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

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
@Override
public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException 

Source Link

Document

Convenience conversion method that will bind data given JSON tree contains into specific value (usually bean) type.

Usage

From source file:org.onosproject.ospf.controller.impl.Controller.java

/**
 * Get the area configuration from a json file.
 *
 * @return areas List<OSPFArea>/*from w ww .j  a va 2  s  .co m*/
 */
private List getConfiguration() {
    List<OSPFArea> areas = null;
    try {
        // Read network configuration from area-config.json
        // read the configuration area wise .
        File configFile = new File(CONFIG_DIR, configFileName);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(configFile);
        Configuration config = mapper.treeToValue(node, Configuration.class);
        log.debug("OSPF area Configuration : {}", config);
        areas = config.getOspfAreas();
        return areas;

    } catch (Exception e) {
        log.debug("Error::Controller:: {}", e.getMessage());
        return areas;
    }

}

From source file:cc.arduino.packages.discoverers.PluggableDiscovery.java

private BoardPort mapJsonNodeToBoardPort(ObjectMapper mapper, JsonNode node) {
    try {//from  www  .ja  v  a 2 s .c  o  m
        BoardPort port = mapper.treeToValue(node.get("port"), BoardPort.class);
        // if no label, use address
        if (port.getLabel() == null || port.getLabel().isEmpty()) {
            port.setLabel(port.getAddress());
        }
        port.searchMatchingBoard();
        return port;
    } catch (JsonProcessingException e) {
        System.err.println(format("{0}: Invalid BoardPort message", discoveryName));
        e.printStackTrace();
        return null;
    }
}

From source file:com.hp.autonomy.frontend.find.core.search.QueryRestrictionsDeserializer.java

protected <T> T parseAs(final ObjectMapper objectMapper,
        @SuppressWarnings("TypeMayBeWeakened") final JsonNode node, final String fieldName, final Class<T> type)
        throws JsonProcessingException {
    final JsonNode childNode = node.get(fieldName);
    return childNode == null ? null : objectMapper.treeToValue(childNode, type);
}

From source file:de.upb.wdqa.wdvd.datamodel.oldjson.jackson.deserializers.OldJacksonSnakDeserializer.java

@Override
public OldJacksonSnak deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    OldJacksonSnak result = null;//from w  w  w  . j  av a2 s  .com

    if (!p.getCurrentToken().equals(JsonToken.START_ARRAY)) {
        logger.warn("Token " + JsonToken.START_ARRAY + " expected");
    }

    p.nextToken();
    String type = p.getText();
    p.nextToken();

    // determine type
    if (type.equals("value")) {
        OldJacksonValueSnak valuesnak = new OldJacksonValueSnak();
        valuesnak.setProperty("P" + p.getIntValue());
        p.nextToken();
        valuesnak.setDatatype(p.getText());
        p.nextToken();

        ObjectMapper mapper = (ObjectMapper) p.getCodec();
        JsonNode root = mapper.readTree(p);
        Class<? extends OldJacksonValue> valueClass = getValueClass(valuesnak.getDatatype());
        if (valueClass != null) {
            valuesnak.setDatavalue(mapper.treeToValue(root, valueClass));
        }

        p.nextToken();

        result = valuesnak;
    } else if (type.equals("novalue")) {
        result = new OldJacksonNoValueSnak();
        result.setProperty("P" + p.getIntValue());
        p.nextToken();
    } else if (type.equals("somevalue")) {
        result = new OldJacksonSomeValueSnak();
        result.setProperty("P" + p.getIntValue());
        p.nextToken();
    } else {
        logger.warn("Unknown value type: " + type);
    }

    if (!p.getCurrentToken().equals(JsonToken.END_ARRAY)) {
        logger.warn("Token " + JsonToken.END_ARRAY + " expected");
    }

    return result;
}

From source file:com.apteligent.ApteligentJavaClient.java

/**
 * @param hash The crash hash to retrieve
 * @param diagnostics include detailed diagnostics information for crash
 * @param getOtherCrashes include other crashes and legacy crash groups now part of this group
 * @return Crash object//from  www.  ja  v a2 s.c  o m
 */
public Crash getCrash(String hash, boolean diagnostics, boolean getOtherCrashes) {
    String params = "?diagnostics=" + diagnostics + "&get_other_crashes=" + getOtherCrashes;
    Crash crash = null;
    try {
        HttpsURLConnection conn = sendGetRequest(API_CRASH_DETAILS.replace("{hash}", hash), params);
        JsonFactory jsonFactory = new JsonFactory();
        JsonParser jp = jsonFactory.createParser(conn.getInputStream());
        ObjectMapper mapper = getObjectMapper();
        TreeNode node = mapper.readTree(jp);
        crash = mapper.treeToValue(node, Crash.class);
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
    return crash;
}

From source file:org.jmxtrans.embedded.config.ConfigurationParser.java

private List<OutputWriter> parseOutputWritersNode(@Nonnull JsonNode outputWritersParentNode) {
    JsonNode outputWritersNode = outputWritersParentNode.path("outputWriters");
    List<OutputWriter> outputWriters = new ArrayList<OutputWriter>();
    if (outputWritersNode.isMissingNode()) {
    } else if (outputWritersNode.isArray()) {
        for (JsonNode outputWriterNode : outputWritersNode) {
            try {
                String className = outputWriterNode.path("@class").asText();
                OutputWriter outputWriter = (OutputWriter) Class.forName(className).newInstance();
                JsonNode deprecatedEnabledNode = outputWriterNode.path("enabled");
                if (!deprecatedEnabledNode.isMissingNode()) {
                    logger.warn(/*from  w ww .  j av a  2 s  .c  om*/
                            "OutputWriter {}, deprecated usage of attribute 'enabled', settings{ \"enabled\":... } should be used instead");
                    outputWriter.setEnabled(deprecatedEnabledNode.asBoolean());
                }
                JsonNode settingsNode = outputWriterNode.path("settings");
                if (settingsNode.isMissingNode()) {
                } else if (settingsNode.isObject()) {
                    ObjectMapper mapper = new ObjectMapper();
                    @SuppressWarnings("unchecked")
                    Map<String, Object> settings = mapper.treeToValue(settingsNode, Map.class);
                    outputWriter.setSettings(settings);
                    if (settings.containsKey("enabled")) {
                        outputWriter.setEnabled(Boolean.valueOf(String.valueOf(settings.get("enabled"))));
                    }
                } else {
                    logger.warn("Ignore invalid node {}", outputWriterNode);
                }
                logger.trace("Add {}", outputWriter);
                outputWriters.add(outputWriter);
            } catch (Exception e) {
                throw new EmbeddedJmxTransException("Exception converting settings " + outputWritersNode, e);
            }
        }
    } else {
        logger.warn("Ignore invalid node {}", outputWritersNode);
    }
    return outputWriters;
}

From source file:com.apteligent.ApteligentJavaClient.java

/**
 * @param appID appId (string, optional): The app to retrieve data about,
 * @param metricType The metric to retrieve
 * @param duration can only be 1440 (24 hours) or 43200 (1 month)
 * @param groupBy TODO FILL IN THIS COMMENT
 * @return/*from  w  w w  . jav  a 2  s . co  m*/
 */
public CrashSummary getErrorPie(String appID, CrashSummary.MetricType metricType, int duration,
        Pie.GroupBy groupBy) {

    String params = "{ \"params\": " + "{\"duration\": " + duration + "," + " \"graph\": \""
            + metricType.toString() + "\"," + " \"appId\": \"" + appID + "\"" + ",\"groupBy\": \""
            + groupBy.toString() + "\"}" + "}";

    CrashSummary crashSummary = null;
    try {
        HttpsURLConnection conn = sendPostRequest(API_ERROR_PIE, params);
        JsonFactory jsonFactory = new JsonFactory();
        JsonParser jp = jsonFactory.createParser(conn.getInputStream());
        ObjectMapper mapper = getObjectMapper();
        TreeNode node = mapper.readTree(jp);
        crashSummary = mapper.treeToValue(node.get("data"), CrashSummary.class);
        if (crashSummary != null) {
            crashSummary.setParams(appID, metricType, duration);
        }
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
    return crashSummary;
}

From source file:com.apteligent.ApteligentJavaClient.java

/**
 * @param appID appId (string, optional): The app to retrieve data about,
 * @param metricType The metric to retrieve
 * @param duration can only be 1440 (24 hours) or 43200 (1 month)
 * @param groupBy TODO FILL IN THIS COMMENT
 * @return/* w  w  w .  ja v a2 s  .  c o m*/
 */
public CrashSummary getErrorSparklines(String appID, CrashSummary.MetricType metricType, int duration,
        Sparklines.GroupBy groupBy) {

    String params = "{ \"params\": " + "{\"duration\": " + duration + "," + " \"graph\": \""
            + metricType.toString() + "\"," + " \"appId\": \"" + appID + "\"" + ",\"groupBy\": \""
            + groupBy.toString() + "\"}" + "}";

    CrashSummary crashSummary = null;
    try {
        HttpsURLConnection conn = sendPostRequest(API_ERROR_SPARKLINES, params);
        JsonFactory jsonFactory = new JsonFactory();
        JsonParser jp = jsonFactory.createParser(conn.getInputStream());
        ObjectMapper mapper = getObjectMapper();
        TreeNode node = mapper.readTree(jp);
        crashSummary = mapper.treeToValue(node.get("data"), CrashSummary.class);
        if (crashSummary != null) {
            crashSummary.setParams(appID, metricType, duration);
        }
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
    return crashSummary;
}

From source file:com.apteligent.ApteligentJavaClient.java

/**
 * @param appID appId (string, optional): The app to retrieve data about,
 * @param metricType The metric to retrieve
 * @param duration can only be 1440 (24 hours) or 43200 (1 month)
 * @return Error object//  w  w w .j  av a  2 s .co m
 */
public CrashSummary getErrorGraph(String appID, CrashSummary.MetricType metricType, int duration) {

    // { "params": {"duration": 43200, "graph": "crashes", "appId": "4f2cc6dfb09315234e000639"}}
    //String responseStr = "{\"data\": {\"start\": \"2014-11-13T00:00:00\", \"interval\": 86400, \"end\": \"2014-12-13T00:00:00\", \"series\": [{\"points\": [0, 3, 2, 0, 2, 3, 2, 3, 0, 6, 0, 0, 0, 1, 0, 0, 6, 2, 0, 1, 0, 0, 4, 1, 0, 0, 1, 2, 0, 0], \"name\": \"crashes\"}]}, \"params\": {\"duration\": 43200, \"graph\": \"crashes\", \"appId\": \"4f2cc6dfb09315234e000639\"}}";

    String params = "{ \"params\": " + "{\"duration\": " + duration + "," + " \"graph\": \""
            + metricType.toString() + "\"," + " \"appId\": \"" + appID + "\"}" + "}";

    System.out.println(params);
    CrashSummary crashSummary = null;
    try {
        HttpsURLConnection conn = sendPostRequest(API_ERROR_GRAPH, params);
        JsonFactory jsonFactory = new JsonFactory();
        JsonParser jp = jsonFactory.createParser(conn.getInputStream());
        ObjectMapper mapper = getObjectMapper();
        TreeNode node = mapper.readTree(jp);
        crashSummary = mapper.treeToValue(node.get("data"), CrashSummary.class);
        if (crashSummary != null) {
            crashSummary.setParams(appID, metricType, duration);
        }
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
    return crashSummary;
}

From source file:org.jsonschema2pojo.integration.CustomDateTimeFormatIT.java

/**
 * This tests the class generated when formatDateTimes config option is set to TRUE
 * The field should have @JsonFormat annotation with pattern and timezone defined in json schema
 * It also tests the serialization and deserialization process
 * /*from  ww w . j a v  a2s. c  o m*/
 * @throws Exception
 */
@Test
public void testCustomDateTimePatternWithCustomTimezoneWhenFormatDateTimesConfigIsTrue() throws Exception {
    Field field = classWhenConfigIsTrue.getDeclaredField("customFormatCustomTZ");
    JsonFormat annotation = field.getAnnotation(JsonFormat.class);

    assertThat(annotation, notNullValue());
    // Assert that the patterns match
    assertEquals("yyyy-MM-dd", annotation.pattern());
    // Assert that the timezones match
    assertEquals("PST", annotation.timezone());

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setTimeZone(TimeZone.getTimeZone("PST"));

    ObjectNode node = objectMapper.createObjectNode();
    node.put("customFormatCustomTZ", "2016-11-06");

    Object pojo = objectMapper.treeToValue(node, classWhenConfigIsTrue);

    Method getter = new PropertyDescriptor("customFormatCustomTZ", classWhenConfigIsTrue).getReadMethod();

    // Assert that the Date object in the deserialized class is as expected
    assertEquals(dateFormatter.parse("2016-11-06").toString(), getter.invoke(pojo).toString());

    JsonNode jsonVersion = objectMapper.valueToTree(pojo);

    // Assert that when the class is serialized, the date object is serialized as expected 
    assertEquals("2016-11-06", jsonVersion.get("customFormatCustomTZ").asText());
}