Example usage for com.fasterxml.jackson.databind ObjectMapper readTree

List of usage examples for com.fasterxml.jackson.databind ObjectMapper readTree

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper readTree.

Prototype

public JsonNode readTree(URL source) throws IOException, JsonProcessingException 

Source Link

Document

Method to deserialize JSON content as tree expressed using set of JsonNode instances.

Usage

From source file:com.marklogic.client.functionaltest.TestPOJOWithStringQD.java

@Test
public void testPOJOSearchWithStringHandle() throws JsonProcessingException, IOException {
    PojoRepository<Artifact, Long> products = client.newPojoRepository(Artifact.class, Long.class);
    PojoPage<Artifact> p;/*  w w w .  j a v a 2  s  . c o m*/
    this.loadSimplePojos(products);
    QueryManager queryMgr = client.newQueryManager();
    StringQueryDefinition qd = queryMgr.newStringDefinition();
    qd.setCriteria("5");
    StringHandle results = new StringHandle();
    JacksonHandle jh = new JacksonHandle();
    p = products.search(qd, 1, jh);

    long pageNo = 1, count = 0;
    do {
        count = 0;
        p = products.search(qd, pageNo, results.withFormat(Format.JSON));

        while (p.iterator().hasNext()) {
            Artifact a = p.iterator().next();
            validateArtifact(a);
            count++;
            //            System.out.println(a.getId()+" "+a.getManufacturer().getName() +"  "+count);
        }
        assertEquals("Page total results", 0, p.getTotalSize());
        pageNo = pageNo + p.getPageSize();
        //            System.out.println(results.get().toString());
    } while (!p.isLastPage() && pageNo < p.getTotalSize());
    assertFalse("String handle is not empty", results.get().isEmpty());
    assertTrue("String handle contains results", results.get().contains("results"));
    assertFalse("String handle contains format", results.get().contains("\"format\":\"json\""));

    ObjectMapper mapper = new ObjectMapper();
    JsonNode actNode = mapper.readTree(results.get()).get("total");
    //      System.out.println(expNode.equals(actNode)+"\n"+ expNode.toString()+"\n"+actNode.toString());

    assertEquals("Total search results resulted are ", actNode.asInt(), 0);
}

From source file:ArmTests.java

@Test
public void createVm() throws IOException, CloudException, InterruptedException {
    final ResourceManagementClient client = getResourceManagementClient();

    // Create deployment if not exists
    final DeploymentsOperations deployments = client.getDeployments();
    final Deployment deploymentParameters = new Deployment();

    // Set deployment parameters
    final String template = FileUtils.readText(FileUtils.getResourcePath("arm-template.json"));
    final String templateParams = FileUtils.readText(FileUtils.getResourcePath("arm-template.params.json"));
    final String parameters = String.format(templateParams, STORAGE_ID, IMAGE_PATH, VM_NAME, VNET_ID, USERNAME,
            PASSWORD, OS_TYPE, VM_SIZE);
    ObjectMapper mapper = new ObjectMapper();

    final DeploymentProperties deploymentProperties = new DeploymentProperties();
    deploymentProperties.setMode(DeploymentMode.INCREMENTAL);
    deploymentProperties.setTemplate(mapper.readTree(template));
    deploymentProperties.setParameters(mapper.readTree(parameters));
    deploymentParameters.setProperties(deploymentProperties);

    // Update deployment
    final ServiceResponse<DeploymentExtended> deploymentResponse = deployments.createOrUpdate(GROUP_ID,
            DEPLOYMENT_ID, deploymentParameters);

    Assert.assertTrue(deploymentResponse.getResponse().isSuccess());
}

From source file:com.salmon.security.xacml.demo.springmvc.rest.controller.MarketPlacePopulatorController.java

@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)/*from w  w  w.  ja v  a 2s.c  om*/
public void whenPayloadIsStrange(HttpServletRequest request, HttpMessageNotReadableException ex) {

    StringBuilder sb = new StringBuilder("REQUEST PARTS: ");

    LOG.info("************************ JSON ERROR  ************************ ");
    LOG.info("ContentType " + request.getContentType());
    LOG.info("ContentLength " + request.getContentLength());

    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
            jb.append(line);
    } catch (Exception e) {
        /*report an error*/ }

    LOG.info("************************ JSON PARSING  ************************ ");
    LOG.info("Payload: " + jb.toString());
    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        JsonParser jp = factory.createParser(jb.toString());
        JsonNode actualObj = mapper.readTree(jp);
        LOG.info("JSON OBJECT CREATED: " + actualObj.toString());

        ObjectMapper driverMapper = new ObjectMapper();
        Driver jsonDriver = driverMapper.readValue(actualObj.toString(), Driver.class);

        LOG.info("DRIVER OBJECT CREATED: " + jsonDriver.toString());

    } catch (Exception e) {
        LOG.error("JSON Parsing Exception " + e.getMessage());
    }

}

From source file:de.tudarmstadt.ukp.dkpro.wsd.wsi.si.InducedSenseInventory.java

/**
 * Loads a serialized sense inventory from a json file
 *
 * @param fileName// w ww  .j a  va2  s . c o m
 * @throws WSDException
 */
public void loadInventory(String fileName) throws WSDException {
    ObjectMapper mapper = new ObjectMapper();
    try {
        BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
        JsonNode root = mapper.readTree(fileReader);
        Iterator<JsonNode> it = root.elements();
        while (it.hasNext()) {
            JsonNode termNode = it.next();
            if (termNode.has("term")) {
                String term = termNode.get("term").textValue();
                Iterator<JsonNode> it2 = termNode.get("clusters").elements();
                int senseIndex = 0;
                while (it2.hasNext()) {
                    String senseId = term + "_" + senseIndex++;
                    JsonNode clusterNode = it2.next();
                    Iterator<JsonNode> it3 = clusterNode.elements();
                    Collection<String> cluster = new LinkedList<String>();
                    while (it3.hasNext()) {

                        Iterator<JsonNode> it4 = it3.next().elements();
                        while (it4.hasNext()) {
                            JsonNode wordNode = it4.next();
                            cluster.add(wordNode.textValue());
                        }

                    }
                    addSense(term, senseId, cluster);

                }

            }
        }
        System.out.println("loaded " + inventory.size() + " terms and " + clusters.size() + " sense clusters");
    } catch (Exception e) {
        throw new WSDException(e);
    }

}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.ConsistentHashTest.java

License:asdf

@Test
public void itAppliesConsistentHashingToSteeringDeliveryService() throws Exception {
    CloseableHttpResponse response = null;
    try {/*from  w w  w .  java  2 s  .c o m*/
        String requestPath = URLEncoder.encode("/some/path/thing", "UTF-8");
        HttpGet httpGet = new HttpGet(
                "http://localhost:3333/crs/consistenthash/deliveryservice?ip=98.76.54.123&deliveryServiceId="
                        + steeringDeliveryServiceId + "&requestPath=" + requestPath);
        response = closeableHttpClient.execute(httpGet);

        ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
        JsonNode deliveryServiceNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));
        assertThat(deliveryServiceNode.get("id").asText(), isIn(steeredDeliveryServices));

    } finally {
        if (response != null)
            response.close();
    }
}

From source file:com.almende.eve.rpc.jsonrpc.JSONRequest.java

/**
 * Instantiates a new jSON request.//from  ww  w . j a va 2  s.  co  m
 *
 * @param json the json
 * @throws JSONRPCException the jSONRPC exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public JSONRequest(final String json) throws JSONRPCException, IOException {
    final ObjectMapper mapper = JOM.getInstance();
    init(mapper.readTree(json));
}

From source file:org.duracloud.snapshot.rest.GeneralResourceTest.java

@Test
public void testVersion() throws JsonParseException, IOException {

    replayAll();/*from  w ww .  jav  a  2s  .c  om*/

    Response response = resource.version();

    String message = (String) response.getEntity();

    ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getFactory();
    JsonParser jp = factory.createJsonParser(message);
    JsonNode obj = mapper.readTree(jp);
    Assert.assertNotNull(obj);
    Assert.assertNotNull(obj.get("version"));

}

From source file:com.chenchengzhi.windtalkers.server.WindMessageFactory.java

@Override
public Message parse(HttpRequest httpRequest) {
    WindTalkerID talkerID = pathResolve(httpRequest);
    if (talkerID == null) {
        throw Issue.of(StatusCode.NOT_FOUND, WindMessageFactory.class.getCanonicalName(), "parse",
                "Talker not found!");
    }/*from  w ww  .  j  av a  2 s . c o  m*/

    Message request = new Message(talkerID);

    ChannelBuffer buffer = httpRequest.getContent();
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getJsonFactory();
    byte[] rawRequestBytes = buffer.array();
    String content = new String(rawRequestBytes, Charsets.UTF_8);

    try {
        JsonNode body = mapper.readTree(factory.createJsonParser(content));
        request.setRequestBody(body);
    } catch (JsonProcessingException jpe) {
        throw Issue.of(StatusCode.BAD_REQUEST, WindMessageFactory.class.getCanonicalName(), "parse",
                "JsonProcessingException");
    } catch (IOException ioe) {
        throw Issue.of(StatusCode.BAD_REQUEST, WindMessageFactory.class.getCanonicalName(), "parse",
                "IOException");
    }

    return request;
}

From source file:access.deploy.geoserver.PiazzaEnvironment.java

/**
 * Checks if a GeoServer resource exists (200 OK returns from the server. 404 indicates not exists)
 * /* ww  w. ja  v  a2  s  . co m*/
 * @return True if exists, false if not
 */
private boolean doesResourceExist(String resourceUri) throws HttpStatusCodeException, RestClientException {
    // Check if exists
    HttpEntity<String> request = new HttpEntity<>(authHeaders.get());

    try {
        pzLogger.log(String.format("Checking if GeoServer Resource Exists at %s", resourceUri),
                Severity.INFORMATIONAL, new AuditElement(ACCESS, "checkGeoServerResourceExists", resourceUri));
        ResponseEntity<String> response = restTemplate.exchange(resourceUri, HttpMethod.GET, request,
                String.class);
        // Validate that the response body is JSON. Otherwise, an authentication redirect error may have occurred.
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            objectMapper.readTree(response.getBody());
        } catch (IOException exception) {
            String error = String.format(
                    "Received a non-error response from GeoServer resource check for %s, but it was not valid JSON. Authentication may have failed.",
                    resourceUri);
            LOGGER.error(error, exception);
            pzLogger.log(error, Severity.ERROR);
            return false;
        }
        if (response.getStatusCode().is2xxSuccessful()) {
            return true;
        }
    } catch (HttpClientErrorException | HttpServerErrorException exception) {
        // If it's a 404, then it does not exist. Fall through.
        if (!exception.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
            // If it's anything but a 404, then it's a server error and we should not proceed with creation. Throw
            // an exception.
            LOGGER.error("HTTP Status Error checking GeoServer Resource {} Exists : {}" + resourceUri,
                    exception.getStatusCode().toString(), exception);
            throw exception;
        }
    } catch (RestClientException exception) {
        LOGGER.error("Unexpected Error Checking GeoServer Resource Exists : " + resourceUri, exception);
        throw exception;
    }
    return false;
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.ConsistentHashTest.java

License:asdf

@Test
public void itUsesBypassFiltersWithDeliveryServiceSteering() throws Exception {
    CloseableHttpResponse response = null;
    try {//  w w w. j  av  a2s  .  c o  m
        String requestPath = URLEncoder.encode("/some/path/force-to-target-2/more/asdfasdf", "UTF-8");
        HttpGet httpGet = new HttpGet(
                "http://localhost:3333/crs/consistenthash/deliveryservice?ip=98.76.54.123&deliveryServiceId="
                        + steeringDeliveryServiceId + "&requestPath=" + requestPath);
        response = closeableHttpClient.execute(httpGet);

        ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
        JsonNode deliveryServiceNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));
        assertThat(deliveryServiceNode.get("id").asText(), equalTo("steering-target-2"));

        requestPath = URLEncoder.encode("/some/path/force-to-target-1/more/asdfasdf", "UTF-8");
        httpGet = new HttpGet(
                "http://localhost:3333/crs/consistenthash/deliveryservice?ip=98.76.54.123&deliveryServiceId="
                        + steeringDeliveryServiceId + "&requestPath=" + requestPath);
        response = closeableHttpClient.execute(httpGet);

        deliveryServiceNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));
        assertThat(deliveryServiceNode.get("id").asText(), equalTo("steering-target-1"));
    } finally {
        if (response != null)
            response.close();
    }
}