Search in sources :

Example 6 with JsonRepresentation

use of org.restlet.ext.json.JsonRepresentation in project Xponents by OpenSextant.

the class XponentsGeotagger method format.

private Representation format(List<TextMatch> matches, RequestParameters jobParams) throws JSONException {
    Representation result = null;
    int tagCount = 0;
    JSONObject resultContent = new JSONObject();
    JSONObject resultMeta = new JSONObject();
    resultMeta.put("status", "ok");
    resultMeta.put("numfound", 0);
    JSONArray resultArray = new JSONArray();
    /*
		 * Super loop: Iterate through all found entities. record Taxons as
		 * person or orgs record Geo tags as country, place, or geo. geo =
		 * geocoded place or parsed coordinate (MGRS, DMS, etc)
		 * 
		 */
    for (TextMatch name : matches) {
        /*            
			 * ==========================
			 * ANNOTATIONS: non-geographic entities that are filtered out, but worth tracking
			 * ==========================             
			 */
        if (name instanceof TaxonMatch) {
            if (jobParams.output_taxons) {
                TaxonMatch match = (TaxonMatch) name;
                ++tagCount;
                for (Taxon n : match.getTaxons()) {
                    JSONObject node = populateMatch(name);
                    String t = "taxon";
                    String taxon_name = n.name.toLowerCase();
                    if (taxon_name.startsWith("org.")) {
                        t = "org";
                    } else if (taxon_name.startsWith("person.")) {
                        t = "person";
                    }
                    node.put("type", t);
                    // Name of taxon
                    node.put("taxon", n.name);
                    // Name of catalog or source
                    node.put("catalog", n.catalog);
                    // node.put("filtered-out", true);
                    resultArray.put(node);
                    break;
                }
            }
            continue;
        }
        // Ignore non-place tags
        if (name.isFilteredOut() || !(name instanceof PlaceCandidate || name instanceof GeocoordMatch)) {
            continue;
        }
        JSONObject node = populateMatch(name);
        /*
			 * ==========================
			 * ANNOTATIONS: coordinates
			 * ==========================
			 */
        if (name instanceof GeocoordMatch) {
            ++tagCount;
            GeocoordMatch geo = (GeocoordMatch) name;
            node.put("type", "coordinate");
            Transforms.createGeocoding(geo, node);
            resultArray.put(node);
            continue;
        }
        if (name.isFilteredOut()) {
            debug("Filtered out " + name.getText());
            continue;
        }
        PlaceCandidate place = (PlaceCandidate) name;
        Place resolvedPlace = place.getChosen();
        /*
			 * ==========================
			 * ANNOTATIONS: countries, places, etc.
			 * ==========================
			 */
        /*
			 * Accept all country names as potential geotags Else if name can be
			 * filtered out, do it now. Otherwise it is a valid place name to
			 * consider
			 */
        ++tagCount;
        if (place.isCountry) {
            node.put("name", resolvedPlace.getPlaceName());
            node.put("type", "country");
            node.put("cc", resolvedPlace.getCountryCode());
            node.put("confidence", place.getConfidence());
        } else {
            /*
				 * Conf = 20 or greater to be geocoded.
				 */
            Transforms.createGeocoding(resolvedPlace, node);
            node.put("name", resolvedPlace.getPlaceName());
            node.put("type", "place");
            node.put("confidence", place.getConfidence());
            if (place.getConfidence() <= 10) {
                node.put("filtered-out", true);
            }
        }
        resultArray.put(node);
    }
    resultMeta.put("numfound", tagCount);
    resultContent.put("response", resultMeta);
    resultContent.put("annotations", resultArray);
    result = new JsonRepresentation(resultContent.toString(2));
    result.setCharacterSet(CharacterSet.UTF_8);
    return result;
}
Also used : GeocoordMatch(org.opensextant.extractors.xcoord.GeocoordMatch) JSONObject(org.json.JSONObject) Taxon(org.opensextant.data.Taxon) JSONArray(org.json.JSONArray) Representation(org.restlet.representation.Representation) JsonRepresentation(org.restlet.ext.json.JsonRepresentation) TextMatch(org.opensextant.extraction.TextMatch) TaxonMatch(org.opensextant.extractors.xtax.TaxonMatch) JsonRepresentation(org.restlet.ext.json.JsonRepresentation) Place(org.opensextant.data.Place) PlaceCandidate(org.opensextant.extractors.geo.PlaceCandidate)

Example 7 with JsonRepresentation

use of org.restlet.ext.json.JsonRepresentation in project OpenAM by OpenRock.

the class ResourceSetRegistrationEndpoint method createResourceSet.

/**
     * <p>Creates or updates a resource set description.</p>
     *
     * <p>If the request contains a If-Match header an update is performed, otherwise a create is performed.</p>
     *
     * <p>An update will replace the current description of the resource set with the contents of the request body.</p>
     *
     * @param entity The new resource set description.
     * @return A JSON object containing the authorization server's unique id for the resource set and, optionally,
     * a policy uri.
     * @throws NotFoundException If the requested resource set description does not exist.
     * @throws ServerException When an error occurs during creating or updating.
     * @throws BadRequestException If the request JSON is invalid.
     */
@Post
public Representation createResourceSet(JsonRepresentation entity) throws NotFoundException, ServerException, BadRequestException {
    ResourceSetDescription resourceSetDescription = new ResourceSetDescription(null, getClientId(), getResourceOwnerId(), validator.validate(toMap(entity)));
    OAuth2Request oAuth2Request = requestFactory.create(getRequest());
    ResourceSetStore store = providerSettingsFactory.get(oAuth2Request).getResourceSetStore();
    QueryFilter<String> query = QueryFilter.and(QueryFilter.equalTo(ResourceSetTokenField.NAME, resourceSetDescription.getName()), QueryFilter.equalTo(ResourceSetTokenField.CLIENT_ID, getClientId()), QueryFilter.equalTo(ResourceSetTokenField.RESOURCE_OWNER_ID, getResourceOwnerId()));
    if (!store.query(query).isEmpty()) {
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        Map<String, Object> response = new HashMap<String, Object>();
        response.put(OAuth2Constants.Params.ERROR, Status.CLIENT_ERROR_BAD_REQUEST.getReasonPhrase());
        response.put(OAuth2Constants.Params.ERROR_DESCRIPTION, "A shared item with the name '" + resourceSetDescription.getName() + "' already exists");
        return new JsonRepresentation(response);
    }
    JsonValue labels = resourceSetDescription.getDescription().get(OAuth2Constants.ResourceSets.LABELS);
    resourceSetDescription.getDescription().remove(OAuth2Constants.ResourceSets.LABELS);
    for (ResourceRegistrationFilter filter : extensionFilterManager.getFilters(ResourceRegistrationFilter.class)) {
        filter.beforeResourceRegistration(resourceSetDescription);
    }
    store.create(oAuth2Request, resourceSetDescription);
    if (labels.isNotNull()) {
        resourceSetDescription.getDescription().add(OAuth2Constants.ResourceSets.LABELS, labels.asSet());
    }
    labelRegistration.updateLabelsForNewResourceSet(resourceSetDescription);
    for (ResourceRegistrationFilter filter : extensionFilterManager.getFilters(ResourceRegistrationFilter.class)) {
        filter.afterResourceRegistration(resourceSetDescription);
    }
    for (ResourceSetRegistrationHook hook : hooks) {
        hook.resourceSetCreated(oAuth2Request.<String>getParameter("realm"), resourceSetDescription);
    }
    getResponse().setStatus(Status.SUCCESS_CREATED);
    return createJsonResponse(resourceSetDescription, false, true);
}
Also used : OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) HashMap(java.util.HashMap) ResourceSetStore(org.forgerock.oauth2.resources.ResourceSetStore) ResourceSetRegistrationHook(org.forgerock.oauth2.restlet.resources.ResourceSetRegistrationHook) JsonValue(org.forgerock.json.JsonValue) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) JsonRepresentation(org.restlet.ext.json.JsonRepresentation) ResourceRegistrationFilter(org.forgerock.openam.oauth2.extensions.ResourceRegistrationFilter) Post(org.restlet.resource.Post)

Example 8 with JsonRepresentation

use of org.restlet.ext.json.JsonRepresentation in project OpenAM by OpenRock.

the class OpenIDConnectConfiguration method getConfiguration.

/**
     * Handles GET requests to the OpenId Connect .well-known endpoint for retrieving the OpenId Connect provider
     * configuration.
     *
     * @return The representation of the OpenId Connect provider configuration.
     * @throws OAuth2RestletException If an error occurs whilst retrieving the OpenId Connect provider configuration.
     */
@Get
public Representation getConfiguration() throws OAuth2RestletException {
    try {
        final OAuth2Request request = requestFactory.create(getRequest());
        final JsonValue configuration = providerConfiguration.getConfiguration(request);
        return new JsonRepresentation(configuration.asMap());
    } catch (OAuth2Exception e) {
        throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), null);
    }
}
Also used : OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) OAuth2RestletException(org.forgerock.oauth2.restlet.OAuth2RestletException) JsonValue(org.forgerock.json.JsonValue) JsonRepresentation(org.restlet.ext.json.JsonRepresentation) OAuth2Exception(org.forgerock.oauth2.core.exceptions.OAuth2Exception) Get(org.restlet.resource.Get)

Example 9 with JsonRepresentation

use of org.restlet.ext.json.JsonRepresentation in project OpenAM by OpenRock.

the class OpenIDConnectDiscovery method discovery.

/**
     * Handles GET requests to the OpenId Connect discovery endpoint.
     *
     * @return The representation of the OpenId Connect discovery.
     * @throws OAuth2RestletException If an error occurs whilst performing the discovery.
     */
@Get
public Representation discovery() throws OAuth2RestletException {
    final OAuth2Request request = requestFactory.create(getRequest());
    final String resource = request.getParameter("resource");
    final String rel = request.getParameter("rel");
    final String realm = request.getParameter("realm");
    try {
        final String deploymentUrl = baseUrlProviderFactory.get(realm).getRootURL(ServletUtils.getRequest(getRequest()));
        final Map<String, Object> response = providerDiscovery.discover(resource, rel, deploymentUrl, request);
        return new JsonRepresentation(response);
    } catch (OAuth2Exception e) {
        throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), null);
    }
}
Also used : OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) OAuth2RestletException(org.forgerock.oauth2.restlet.OAuth2RestletException) JsonRepresentation(org.restlet.ext.json.JsonRepresentation) OAuth2Exception(org.forgerock.oauth2.core.exceptions.OAuth2Exception) Get(org.restlet.resource.Get)

Example 10 with JsonRepresentation

use of org.restlet.ext.json.JsonRepresentation in project OpenAM by OpenRock.

the class ResourceSetRegistrationEndpointTest method shouldUpdateResourceSetDescription.

@Test
@SuppressWarnings("unchecked")
public void shouldUpdateResourceSetDescription() throws Exception {
    //Given
    JsonRepresentation entity = createUpdateRequestRepresentation();
    ResourceSetDescription resourceSetDescription = new ResourceSetDescription("RESOURCE_SET_ID", "CLIENT_ID", "RESOURCE_OWNER_ID", RESOURCE_SET_DESCRIPTION_CONTENT.asMap());
    setUriResourceSetId();
    addCondition();
    given(store.read("RESOURCE_SET_ID", "RESOURCE_OWNER_ID")).willReturn(resourceSetDescription);
    //When
    Representation responseRep = endpoint.updateResourceSet(entity);
    //Then
    ArgumentCaptor<ResourceSetDescription> resourceSetCaptor = ArgumentCaptor.forClass(ResourceSetDescription.class);
    verify(store).update(resourceSetCaptor.capture());
    assertThat(resourceSetCaptor.getValue().getId()).isEqualTo("RESOURCE_SET_ID");
    assertThat(resourceSetCaptor.getValue().getClientId()).isEqualTo("CLIENT_ID");
    assertThat(resourceSetCaptor.getValue().getName()).isEqualTo("NEW_NAME");
    assertThat(resourceSetCaptor.getValue().getUri()).isEqualTo(URI.create("NEW_URI"));
    assertThat(resourceSetCaptor.getValue().getType()).isEqualTo("NEW_TYPE");
    assertThat(resourceSetCaptor.getValue().getScopes()).containsExactly("NEW_SCOPE");
    assertThat(resourceSetCaptor.getValue().getIconUri()).isEqualTo(URI.create("NEW_ICON_URI"));
    Map<String, Object> responseBody = (Map<String, Object>) new ObjectMapper().readValue(responseRep.getText(), Map.class);
    assertThat(responseBody).containsKey("_id");
    verify(labelRegistration).updateLabelsForExistingResourceSet(any(ResourceSetDescription.class));
}
Also used : JacksonRepresentation(org.restlet.ext.jackson.JacksonRepresentation) JsonRepresentation(org.restlet.ext.json.JsonRepresentation) Representation(org.restlet.representation.Representation) JSONObject(org.json.JSONObject) JsonRepresentation(org.restlet.ext.json.JsonRepresentation) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.testng.annotations.Test)

Aggregations

JsonRepresentation (org.restlet.ext.json.JsonRepresentation)22 JSONObject (org.json.JSONObject)16 Test (org.testng.annotations.Test)13 ResourceSetDescription (org.forgerock.oauth2.resources.ResourceSetDescription)7 Representation (org.restlet.representation.Representation)7 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)5 Map (java.util.Map)5 JacksonRepresentation (org.restlet.ext.jackson.JacksonRepresentation)5 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)4 HashMap (java.util.HashMap)3 IOException (java.io.IOException)2 Date (java.util.Date)2 AuditEvent (org.forgerock.audit.events.AuditEvent)2 JsonValue (org.forgerock.json.JsonValue)2 OAuth2Exception (org.forgerock.oauth2.core.exceptions.OAuth2Exception)2 OAuth2RestletException (org.forgerock.oauth2.restlet.OAuth2RestletException)2 JSONArray (org.json.JSONArray)2 JSONException (org.json.JSONException)2 TextMatch (org.opensextant.extraction.TextMatch)2