Search in sources :

Example 26 with JSONArray

use of net.minidev.json.JSONArray in project c4sg-services by Code4SocialGood.

the class GeoCodeUtil method getGeoCode.

public Map<String, BigDecimal> getGeoCode() throws Exception {
    Map<String, BigDecimal> geocode = new HashMap<String, BigDecimal>();
    try {
        URL url = getRequestUrl();
        String response = getResponse(url);
        if (response != null) {
            Object obj = JSONValue.parse(response);
            if (obj instanceof JSONArray) {
                JSONArray array = (JSONArray) obj;
                if (array.size() > 0) {
                    JSONObject jsonObject = (JSONObject) array.get(0);
                    String lon = (String) jsonObject.get("lon");
                    String lat = (String) jsonObject.get("lat");
                    geocode.put("lon", new BigDecimal(lon));
                    geocode.put("lat", new BigDecimal(lat));
                }
            }
            return geocode;
        } else {
            throw new Exception("Fail to convert to geocode");
        }
    } catch (Exception ex) {
        throw new Exception(ex.getMessage());
    }
}
Also used : JSONObject(net.minidev.json.JSONObject) HashMap(java.util.HashMap) JSONArray(net.minidev.json.JSONArray) JSONObject(net.minidev.json.JSONObject) BigDecimal(java.math.BigDecimal) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 27 with JSONArray

use of net.minidev.json.JSONArray in project ddf by codice.

the class TestRestEndpoint method testGetDocumentSourcesSuccess.

/**
     * Tests getting source information
     *
     * @throws Exception
     */
@Test
public void testGetDocumentSourcesSuccess() throws Exception {
    final String localSourceId = "local";
    final String fed1SourceId = "fed1";
    final String fed2SourceId = "fed2";
    final String version = "4.0";
    final String jsonMimeTypeString = "application/json";
    Set<ContentType> contentTypes = new HashSet<ContentType>();
    contentTypes.add(new ContentTypeImpl("ct1", "v1"));
    contentTypes.add(new ContentTypeImpl("ct2", "v2"));
    contentTypes.add(new ContentTypeImpl("ct3", null));
    JSONArray contentTypesInJSON = new JSONArray();
    for (ContentType ct : contentTypes) {
        JSONObject ob = new JSONObject();
        ob.put("name", ct.getName());
        ob.put("version", ct.getVersion() != null ? ct.getVersion() : "");
        contentTypesInJSON.add(ob);
    }
    Set<SourceDescriptor> sourceDescriptors = new HashSet<SourceDescriptor>();
    SourceDescriptorImpl localDescriptor = new SourceDescriptorImpl(localSourceId, contentTypes);
    localDescriptor.setVersion(version);
    localDescriptor.setAvailable(true);
    SourceDescriptorImpl fed1Descriptor = new SourceDescriptorImpl(fed1SourceId, contentTypes);
    fed1Descriptor.setVersion(version);
    fed1Descriptor.setAvailable(true);
    SourceDescriptorImpl fed2Descriptor = new SourceDescriptorImpl(fed2SourceId, null);
    fed2Descriptor.setAvailable(true);
    sourceDescriptors.add(localDescriptor);
    sourceDescriptors.add(fed1Descriptor);
    sourceDescriptors.add(fed2Descriptor);
    SourceInfoResponse sourceInfoResponse = new SourceInfoResponseImpl(null, null, sourceDescriptors);
    CatalogFramework framework = mock(CatalogFramework.class);
    when(framework.getSourceInfo(isA(SourceInfoRequestEnterprise.class))).thenReturn(sourceInfoResponse);
    RESTEndpoint restEndpoint = new RESTEndpoint(framework);
    Response response = restEndpoint.getDocument(null, null);
    assertEquals(OK, response.getStatus());
    assertEquals(jsonMimeTypeString, response.getMetadata().get("Content-Type").get(0));
    String responseMessage = IOUtils.toString((ByteArrayInputStream) response.getEntity());
    JSONArray srcList = (JSONArray) new JSONParser().parse(responseMessage);
    assertEquals(3, srcList.size());
    for (Object o : srcList) {
        JSONObject src = (JSONObject) o;
        assertEquals(true, src.get("available"));
        String id = (String) src.get("id");
        if (id.equals(localSourceId)) {
            assertThat((Iterable<Object>) src.get("contentTypes"), hasItems(contentTypesInJSON.toArray()));
            assertEquals(contentTypes.size(), ((JSONArray) src.get("contentTypes")).size());
            assertEquals(version, src.get("version"));
        } else if (id.equals(fed1SourceId)) {
            assertThat((Iterable<Object>) src.get("contentTypes"), hasItems(contentTypesInJSON.toArray()));
            assertEquals(contentTypes.size(), ((JSONArray) src.get("contentTypes")).size());
            assertEquals(version, src.get("version"));
        } else if (id.equals(fed2SourceId)) {
            assertEquals(0, ((JSONArray) src.get("contentTypes")).size());
            assertEquals("", src.get("version"));
        } else {
            fail("Invalid ID returned");
        }
    }
}
Also used : ContentTypeImpl(ddf.catalog.data.impl.ContentTypeImpl) SourceDescriptor(ddf.catalog.source.SourceDescriptor) ContentType(ddf.catalog.data.ContentType) SourceDescriptorImpl(ddf.catalog.source.impl.SourceDescriptorImpl) JSONArray(net.minidev.json.JSONArray) Matchers.anyString(org.mockito.Matchers.anyString) SourceInfoRequestEnterprise(ddf.catalog.operation.impl.SourceInfoRequestEnterprise) QueryResponse(ddf.catalog.operation.QueryResponse) Response(javax.ws.rs.core.Response) SourceInfoResponse(ddf.catalog.operation.SourceInfoResponse) JSONObject(net.minidev.json.JSONObject) CatalogFramework(ddf.catalog.CatalogFramework) SourceInfoResponseImpl(ddf.catalog.operation.impl.SourceInfoResponseImpl) JSONParser(net.minidev.json.parser.JSONParser) JSONObject(net.minidev.json.JSONObject) SourceInfoResponse(ddf.catalog.operation.SourceInfoResponse) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 28 with JSONArray

use of net.minidev.json.JSONArray in project ddf by codice.

the class RESTEndpoint method getDocument.

/**
     * REST Get. Retrieves information regarding sources available.
     *
     * @param uriInfo
     * @param httpRequest
     * @return
     */
@GET
@Path(SOURCES_PATH)
public Response getDocument(@Context UriInfo uriInfo, @Context HttpServletRequest httpRequest) {
    BinaryContent content;
    ResponseBuilder responseBuilder;
    String sourcesString = null;
    JSONArray resultsList = new JSONArray();
    SourceInfoResponse sources;
    try {
        SourceInfoRequestEnterprise sourceInfoRequestEnterprise = new SourceInfoRequestEnterprise(true);
        sources = catalogFramework.getSourceInfo(sourceInfoRequestEnterprise);
        for (SourceDescriptor source : sources.getSourceInfo()) {
            JSONObject sourceObj = new JSONObject();
            sourceObj.put("id", source.getSourceId());
            sourceObj.put("version", source.getVersion() != null ? source.getVersion() : "");
            sourceObj.put("available", Boolean.valueOf(source.isAvailable()));
            JSONArray contentTypesObj = new JSONArray();
            if (source.getContentTypes() != null) {
                for (ContentType contentType : source.getContentTypes()) {
                    if (contentType != null && contentType.getName() != null) {
                        JSONObject contentTypeObj = new JSONObject();
                        contentTypeObj.put("name", contentType.getName());
                        contentTypeObj.put("version", contentType.getVersion() != null ? contentType.getVersion() : "");
                        contentTypesObj.add(contentTypeObj);
                    }
                }
            }
            sourceObj.put("contentTypes", contentTypesObj);
            resultsList.add(sourceObj);
        }
    } catch (SourceUnavailableException e) {
        LOGGER.info("Unable to retrieve Sources. {}", e.getMessage());
        LOGGER.debug("Unable to retrieve Sources", e);
    }
    sourcesString = JSONValue.toJSONString(resultsList);
    content = new BinaryContentImpl(new ByteArrayInputStream(sourcesString.getBytes(StandardCharsets.UTF_8)), jsonMimeType);
    responseBuilder = Response.ok(content.getInputStream(), content.getMimeTypeValue());
    // Add the Accept-ranges header to let the client know that we accept ranges in bytes
    responseBuilder.header(HEADER_ACCEPT_RANGES, BYTES);
    return responseBuilder.build();
}
Also used : SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) SourceDescriptor(ddf.catalog.source.SourceDescriptor) JSONObject(net.minidev.json.JSONObject) ContentType(ddf.catalog.data.ContentType) ByteArrayInputStream(java.io.ByteArrayInputStream) JSONArray(net.minidev.json.JSONArray) BinaryContentImpl(ddf.catalog.data.impl.BinaryContentImpl) BinaryContent(ddf.catalog.data.BinaryContent) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) SourceInfoResponse(ddf.catalog.operation.SourceInfoResponse) SourceInfoRequestEnterprise(ddf.catalog.operation.impl.SourceInfoRequestEnterprise) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 29 with JSONArray

use of net.minidev.json.JSONArray in project ddf by codice.

the class GeoCoderEndpoint method doQuery.

JSONObject doQuery(String query) {
    GeoCoder geoCoder = geoCoderFactory.getService();
    GeoResult geoResult = null;
    if (geoCoder != null) {
        geoResult = geoCoder.getLocation(query);
    }
    JSONObject jsonObject = new JSONObject();
    JSONArray resourceSets = new JSONArray();
    JSONObject resourceSet = new JSONObject();
    jsonObject.put("resourceSets", resourceSets);
    resourceSets.add(resourceSet);
    JSONArray resources = new JSONArray();
    resourceSet.put("resources", resources);
    if (geoResult != null) {
        transformGeoResult(geoResult, resources);
    }
    return jsonObject;
}
Also used : GeoCoder(org.codice.ddf.spatial.geocoder.GeoCoder) JSONObject(net.minidev.json.JSONObject) JSONArray(net.minidev.json.JSONArray) GeoResult(org.codice.ddf.spatial.geocoder.GeoResult)

Example 30 with JSONArray

use of net.minidev.json.JSONArray in project ddf by codice.

the class GeoCoderEndpoint method transformGeoResult.

void transformGeoResult(GeoResult geoResult, JSONArray resources) {
    DirectPosition directPosition = geoResult.getPoint().getDirectPosition();
    double[] coords = directPosition.getCoordinate();
    double longitude = coords[0];
    double latitude = coords[1];
    JSONObject resource = new JSONObject();
    JSONArray bbox = new JSONArray();
    List<Point> points = geoResult.getBbox();
    DirectPosition upperCorner = points.get(0).getDirectPosition();
    DirectPosition lowerCorner = points.get(1).getDirectPosition();
    bbox.add(upperCorner.getCoordinate()[1]);
    bbox.add(upperCorner.getCoordinate()[0]);
    bbox.add(lowerCorner.getCoordinate()[1]);
    bbox.add(lowerCorner.getCoordinate()[0]);
    resource.put("bbox", bbox);
    JSONObject point = new JSONObject();
    point.put("type", "Point");
    JSONArray coordinates = new JSONArray();
    coordinates.add(latitude);
    coordinates.add(longitude);
    point.put("coordinates", coordinates);
    resource.put("point", point);
    resource.put("name", geoResult.getFullName());
    resources.add(resource);
}
Also used : DirectPosition(org.opengis.geometry.DirectPosition) JSONObject(net.minidev.json.JSONObject) JSONArray(net.minidev.json.JSONArray) Point(org.opengis.geometry.primitive.Point)

Aggregations

JSONArray (net.minidev.json.JSONArray)55 JSONObject (net.minidev.json.JSONObject)41 Test (org.junit.Test)9 HashMap (java.util.HashMap)8 Map (java.util.Map)6 ArrayList (java.util.ArrayList)5 JSONParser (net.minidev.json.parser.JSONParser)5 Test (org.testng.annotations.Test)5 DocumentContext (com.jayway.jsonpath.DocumentContext)3 HashSet (java.util.HashSet)3 LinkedHashMap (java.util.LinkedHashMap)3 JSONConverterException (org.btrplace.json.JSONConverterException)3 VM (org.btrplace.model.VM)3 PathNotFoundException (com.jayway.jsonpath.PathNotFoundException)2 ContentType (ddf.catalog.data.ContentType)2 BinaryContentImpl (ddf.catalog.data.impl.BinaryContentImpl)2 SourceInfoResponse (ddf.catalog.operation.SourceInfoResponse)2 SourceInfoRequestEnterprise (ddf.catalog.operation.impl.SourceInfoRequestEnterprise)2 SourceDescriptor (ddf.catalog.source.SourceDescriptor)2 TIntObjectHashMap (gnu.trove.map.hash.TIntObjectHashMap)2