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:DocumentSerializationTest.java

protected Result createDocumentWithVersion(String sAddress) throws JsonProcessingException, IOException {
    FakeRequest request = new FakeRequest(POST, sAddress);
    request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
    request = request.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
    ObjectMapper om = new ObjectMapper();
    JsonNode node = om.readTree("{\"k\":0,\"@version\":2}");
    request = request.withJsonBody(node);
    return routeAndCall(request);
}

From source file:com.galenframework.tests.integration.GalenFullJsProjectIT.java

private void assertReports(String htmlReportPath, String jsonReportPath) throws IOException {
    try {/*from  w w  w  .j a va  2  s.  c om*/
        ObjectMapper mapper = new ObjectMapper();

        JsonNode jsonTree = mapper
                .readTree(FileUtils.readFileToString(new File(jsonReportPath + "/report.json")));

        assertMap(toMap(jsonTree), new HashMap<String, TestStatistic>() {
            {
                put("Add note page on desktop emulation device", new TestStatistic(74, 0, 0, 74));
                put("Add note page on mobile emulation device", new TestStatistic(73, 0, 0, 73));
                put("Add note page on tablet emulation device", new TestStatistic(74, 0, 0, 74));
                put("Login page on desktop emulation device", new TestStatistic(80, 0, 0, 80));
                put("Login page on mobile emulation device", new TestStatistic(84, 0, 0, 84));
                put("Login page on tablet emulation device", new TestStatistic(79, 0, 0, 79));
                put("My notes page on desktop emulation device", new TestStatistic(81, 0, 0, 81));
                put("My notes page on mobile emulation device", new TestStatistic(83, 0, 0, 83));
                put("My notes page on tablet emulation device", new TestStatistic(81, 0, 0, 81));
                put("Welcome page on desktop emulation device", new TestStatistic(70, 1, 0, 71));
                put("Welcome page on mobile emulation device", new TestStatistic(68, 0, 0, 68));
                put("Welcome page on tablet emulation device", new TestStatistic(70, 1, 0, 71));

            }
        });

        List<String> errorMessages = collectAllErrorMessages(jsonTree, jsonReportPath);
        assertErrorMessages(errorMessages, asList(
                regex().exact("\"login_button\" width is ").digits(2).exact("px instead of 20px").toString(),
                regex().exact("\"login_button\" width is ").digits(2).exact("px instead of 20px").toString()));
    } catch (Exception ex) {
        throw new RuntimeException("Report validation failed:\n" + "Html Report: " + htmlReportPath
                + "/report.html\n" + "Json Report: " + jsonReportPath + "/report.json", ex);
    }
}

From source file:org.apache.tika.language.translate.YandexTranslator.java

@Override
public String translate(String text, String sourceLanguage, String targetLanguage)
        throws TikaException, IOException {
    if (!this.isAvailable()) {
        return text;
    }//from   w  ww  .  j a  v  a  2s .  co  m

    WebClient client = WebClient.create(YANDEX_TRANSLATE_URL_BASE);

    String langCode;

    if (sourceLanguage == null) {
        //Translate Service will identify source language
        langCode = targetLanguage;
    } else {
        //Source language is well known
        langCode = sourceLanguage + '-' + targetLanguage;
    }

    //TODO Add support for text over 10k characters
    Response response = client.accept(MediaType.APPLICATION_JSON).query("key", this.apiKey)
            .query("lang", langCode).query("text", text).get();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader((InputStream) response.getEntity(), UTF_8));
    String line = null;
    StringBuffer responseText = new StringBuffer();
    while ((line = reader.readLine()) != null) {
        responseText.append(line);
    }

    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonResp = mapper.readTree(responseText.toString());

        if (!jsonResp.findValuesAsText("code").isEmpty()) {
            String code = jsonResp.findValuesAsText("code").get(0);
            if (code.equals("200")) {
                return jsonResp.findValue("text").get(0).asText();
            } else {
                throw new TikaException(jsonResp.findValue("message").get(0).asText());
            }
        } else {
            throw new TikaException("Return message not recognized: "
                    + responseText.toString().substring(0, Math.min(responseText.length(), 100)));
        }
    } catch (JsonParseException e) {
        throw new TikaException(
                "Error requesting translation from '" + sourceLanguage + "' to '" + targetLanguage
                        + "', JSON response from Lingo24 is not well formatted: " + responseText.toString());
    }
}

From source file:DocumentSerializationTest.java

protected Result createDocumentWithJustOneElementAsString(String sAddress)
        throws JsonProcessingException, IOException {
    FakeRequest request = new FakeRequest(POST, sAddress);
    request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
    request = request.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
    ObjectMapper om = new ObjectMapper();
    JsonNode node = om.readTree("\"element\"");
    request = request.withJsonBody(node);
    return routeAndCall(request);
}

From source file:DocumentSerializationTest.java

public Result modifyDocumentWithVersionNUll(String sAddress) throws JsonProcessingException, IOException {
    // Modify created document
    FakeRequest request = new FakeRequest(PUT, sAddress);
    request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
    request = request.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
    ObjectMapper om = new ObjectMapper();
    JsonNode node = om.readTree("{\"k\":0,\"@version\":12}");
    request = request.withJsonBody(node, PUT);
    return routeAndCall(request);
}

From source file:org.springframework.data.rest.webmvc.json.DomainObjectReaderUnitTests.java

/**
 * @see DATAREST-701/*from   w  w  w  .ja v a 2s  . co  m*/
 */
@Test
public void mergesNestedMapWithoutTypeInformation() throws Exception {

    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.readTree("{\"map\" : {\"a\": \"1\", \"b\": {\"c\": \"2\"}}}");

    TypeWithGenericMap target = new TypeWithGenericMap();
    target.map = new HashMap<String, Object>();
    target.map.put("b", new HashMap<String, Object>());

    reader.readPut((ObjectNode) node, target, mapper);
}

From source file:org.apache.airavata.db.AbstractThriftDeserializer.java

@Override
public T deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    final T instance = newInstance();
    final ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    final ObjectNode rootNode = mapper.readTree(jp);
    final Iterator<Map.Entry<String, JsonNode>> iterator = rootNode.fields();

    while (iterator.hasNext()) {
        final Map.Entry<String, JsonNode> currentField = iterator.next();
        try {//from  w  w  w  .  j  a  v a 2 s .c  o  m
            /*
             * If the current node is not a null value, process it.  Otherwise,
             * skip it.  Jackson will treat the null as a 0 for primitive
             * number types, which in turn will make Thrift think the field
             * has been set. Also we ignore the MongoDB specific _id field
             */
            if (!currentField.getKey().equalsIgnoreCase("_id")
                    && currentField.getValue().getNodeType() != JsonNodeType.NULL) {
                final E field = getField(
                        CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, currentField.getKey()));
                final JsonParser parser = currentField.getValue().traverse();
                parser.setCodec(mapper);
                final Object value = mapper.readValue(parser, generateValueType(instance, field));
                if (value != null) {
                    log.debug(String.format("Field %s produced value %s of type %s.", currentField.getKey(),
                            value, value.getClass().getName()));
                    instance.setFieldValue(field, value);
                } else {
                    log.debug("Field {} contains a null value.  Skipping...", currentField.getKey());
                }
            } else {
                log.debug("Field {} contains a null value.  Skipping...", currentField.getKey());
            }
        } catch (final NoSuchFieldException | IllegalArgumentException e) {
            log.error("Unable to de-serialize field '{}'.", currentField.getKey(), e);
            ctxt.mappingException(e.getMessage());
        }
    }

    try {
        // Validate that the instance contains all required fields.
        validate(instance);
    } catch (final TException e) {
        log.error(String.format("Unable to deserialize JSON '%s' to type '%s'.", jp.getValueAsString(),
                instance.getClass().getName(), e));
        ctxt.mappingException(e.getMessage());
    }

    return instance;
}

From source file:org.opendaylight.sfc.sbrest.json.SfExporterTest.java

private boolean testExportSfJson(String expectedResultFile, boolean nameOnly) throws IOException {
    ServiceFunction serviceFunction;//from  w  w w . j  a v a  2s .  c o  m
    String exportedSfString;
    SfExporterFactory sfExporterFactory = new SfExporterFactory();

    if (nameOnly) {
        serviceFunction = this.buildServiceFunctionNameOnly();
        exportedSfString = sfExporterFactory.getExporter().exportJsonNameOnly(serviceFunction);
    } else {
        serviceFunction = this.buildServiceFunction();
        exportedSfString = sfExporterFactory.getExporter().exportJson(serviceFunction);
    }

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode expectedSfJson = objectMapper
            .readTree(this.gatherServiceFunctionJsonStringFromFile(expectedResultFile));
    JsonNode exportedSfJson = objectMapper.readTree(exportedSfString);

    return expectedSfJson.equals(exportedSfJson);
}

From source file:org.onosproject.segmentrouting.config.SegmentRoutingAppConfigTest.java

/**
 * Initialize test related variables./*from   w w  w  . j av a 2s  . com*/
 *
 * @throws Exception
 */
@Before
public void setUp() throws Exception {
    InputStream jsonStream = SegmentRoutingAppConfigTest.class.getResourceAsStream("/sr-app-config.json");
    InputStream invalidJsonStream = SegmentRoutingAppConfigTest.class
            .getResourceAsStream("/sr-app-config-invalid.json");

    ApplicationId subject = APP_ID;
    String key = SegmentRoutingManager.SR_APP_ID;
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree(jsonStream);
    JsonNode invalidJsonNode = mapper.readTree(invalidJsonStream);
    ConfigApplyDelegate delegate = new MockDelegate();

    config = new SegmentRoutingAppConfig();
    config.init(subject, key, jsonNode, mapper, delegate);
    invalidConfig = new SegmentRoutingAppConfig();
    invalidConfig.init(subject, key, invalidJsonNode, mapper, delegate);
}

From source file:ingest.inspect.PointCloudInspector.java

/**
 * Executes POST request to Point Cloud to grab the Payload
 * /*from   w ww  . j  av a 2  s  .c om*/
 * @param url
 *            The URL to post for point cloud api
 * @return The PointCloudResponse object containing metadata.
 */
private PointCloudResponse postPointCloudTemplate(String url, String payload) throws IOException {
    // Setup Basic Headers
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    // Create the Request template and execute post
    HttpEntity<String> request = new HttpEntity<String>(payload, headers);
    String response = "";
    try {
        logger.log("Sending Metadata Request to Point Cloud Service", Severity.INFORMATIONAL,
                new AuditElement(INGEST, "requestPointCloudMetadata", url));
        response = restTemplate.postForObject(url, request, String.class);
    } catch (HttpServerErrorException e) {
        String error = "Error occurred posting to: " + url + "\nPayload: \n" + payload
                + "\nMost likely the payload source file is not accessible.";
        // this exception will be thrown until the s3 file is accessible to external services

        LOG.error(error, e);
        throw new HttpServerErrorException(e.getStatusCode(), error);
    }

    // Parse required fields from point cloud json response
    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = mapper.readTree(response);
    double maxx = root.at("/response/metadata/maxx").asDouble();
    double maxy = root.at("/response/metadata/maxy").asDouble();
    double maxz = root.at("/response/metadata/maxz").asDouble();
    double minx = root.at("/response/metadata/minx").asDouble();
    double miny = root.at("/response/metadata/miny").asDouble();
    double minz = root.at("/response/metadata/minz").asDouble();
    String spatialreference = root.at("/response/metadata/spatialreference").asText();

    // Return the new PointCloudResponse object
    return new PointCloudResponse(spatialreference, maxx, maxy, maxz, minx, miny, minz);
}