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:br.com.criativasoft.opendevice.core.json.CommandDeserialize.java

@Override
public Command deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    ObjectNode root = (ObjectNode) mapper.readTree(jp);
    Class<? extends Command> commandClass = null;

    JsonNode jsonType = root.get("type");
    int type = jsonType.intValue();

    CommandType commandType = CommandType.getByCode(type);

    if (commandType == null)
        throw new IllegalArgumentException("type of command must be provided !");

    if (DeviceCommand.isCompatible(commandType)) {
        return mapper.readValue(root.toString(), DeviceCommand.class);
    } else {// w  w  w .  j ava2s .co m

        Class<? extends Command> cmdClass = registry.get(commandType);

        if (cmdClass == null) {
            throw new IllegalArgumentException(
                    "Command type not supported!! You need configure in CommandDeserialize");
        }

        return mapper.readValue(root.toString(), cmdClass);

    }

}

From source file:org.wikidata.wdtk.datamodel.json.jackson.datavalues.JacksonValueDeserializer.java

@Override
public JacksonValue deserialize(JsonParser jsonParser, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec();
    JsonNode root = mapper.readTree(jsonParser);
    Class<? extends JacksonValue> valueClass = getValueClass(root);

    return mapper.treeToValue(root, valueClass);
}

From source file:org.onosproject.segmentrouting.web.PolicyWebResource.java

/**
 * Delete a segment routing policy./*from w  w  w.j a  v a2  s  .c  o  m*/
 *
 * @param input JSON stream for policy to delete
 * @return status of the request - OK if the policy is removed,
 * INTERNAL_SERVER_ERROR otherwise
 * @throws IOException if JSON is invalid
 */
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
public Response removePolicy(InputStream input) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode policyJson = (ObjectNode) mapper.readTree(input);
    SegmentRoutingService srService = get(SegmentRoutingService.class);
    Policy policyInfo = POLICY_CODEC.decode(policyJson, this);
    // TODO: Check the result
    srService.removePolicy(policyInfo);

    return Response.ok().build();

}

From source file:com.googlecode.jmxtrans.util.ProcessConfigUtils.java

/**
 * Uses jackson to load json configuration from a File into a full object
 * tree representation of that json.//from  ww  w .  j av a2  s.c om
 */
public JmxProcess parseProcess(File file) throws IOException {
    String fileName = file.getName();
    ObjectMapper mapper = fileName.endsWith(".yml") || fileName.endsWith(".yaml") ? yamlMapper : jsonMapper;
    JsonNode jsonNode = mapper.readTree(file);
    JmxProcess jmx = mapper.treeToValue(jsonNode, JmxProcess.class);
    jmx.setName(fileName);
    return jmx;
}

From source file:net.mostlyharmless.jghservice.connector.jira.SearchIssues.java

@Override
public List<JiraEvent.Issue> processResponse(String jsonResponse) throws IOException {
    ObjectMapper m = new ObjectMapperProvider().getContext(JiraEvent.Issue.class);
    ObjectNode root = (ObjectNode) m.readTree(jsonResponse);
    JavaType t = m.getTypeFactory().constructCollectionType(List.class, JiraEvent.Issue.class);
    return m.convertValue(root.get("issues"), t);
}

From source file:org.opendaylight.ovsdb.plugin.shell.PrintCacheTest.java

@Test
public void testDoExecute() throws Exception {
    // Read in schema and create the DatabaseSchema
    InputStream resourceAsStream = PrintCacheTest.class.getResourceAsStream("test_schema.json");
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree(resourceAsStream);
    DatabaseSchema schema = DatabaseSchema.fromJson("some", jsonNode.get("result"));
    assertNotNull(schema);/*from  w w  w .  j av  a 2s .  c  o  m*/
    assertEquals(Version.fromString("6.12.0"), schema.getVersion());

    // Add params to PrintCache
    PrintCache printCacheTest = new PrintCache();
    Field cNField = printCacheTest.getClass().getDeclaredField("nodeName");
    cNField.setAccessible(true);
    cNField.set(printCacheTest, NODESTRING);
    InventoryServiceImpl inventoryService = new InventoryServiceImpl();
    inventoryService.init();
    printCacheTest.setOvsdbInventory(inventoryService);

    // Test that an empty cache prints nothing
    // Capture the output from PrintCache and compare it to what is expected
    PrintStream originalBaos = System.out;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    System.setOut(new PrintStream(baos));
    printCacheTest.doExecute();
    assertEquals("PrintCache output does not match expected output:", "", baos.toString());

    // Add some data to the bridges row in the Open_vSwitch table
    GenericTableSchema ovsTable = schema.table(OPENVSWITCH, GenericTableSchema.class);
    ColumnSchema<GenericTableSchema, Set<UUID>> bridges = ovsTable.multiValuedColumn(BRIDGES, UUID.class);
    Column column = new Column(bridges, new UUID(BRIDGE).toString());
    Row row = new Row(ovsTable);
    row.addColumn(BRIDGES, column);

    NodeId nodeId = new NodeId(NODESTRING);
    NodeKey nodeKey = new NodeKey(nodeId);
    Node node = new NodeBuilder().setId(nodeId).setKey(nodeKey).build();
    inventoryService.updateRow(node, OvsVswitchdSchemaConstants.DATABASE_NAME, OPENVSWITCH,
            new UUID("1").toString(), row);

    // Test that a populated cache is printed correctly
    // Capture the output from PrintCache and compare it to what is expected
    printCacheTest.doExecute();
    System.setOut(originalBaos);
    assertEquals("PrintCache output does not match expected output:", CACHE, baos.toString());
}

From source file:com.dhenton9000.jersey.client.CodeBaseClass.java

/**
 * ****************************************************************
 * these classes use fasterxml jackson which is read/write to the
 * DOM-style JSON model// w  w w.  j a va 2s  . c  om
 * 
 */

protected JsonNode getRestaurantJsonNode(int id) throws IOException {
    ClientConfig config = new ClientConfig();
    Client client = ClientBuilder.newClient(config);
    WebTarget target = client.target(getBaseURI());
    Response response = target.path("restaurant").path("" + 4).request().accept(MediaType.APPLICATION_JSON)
            .get(Response.class);

    if (response.getStatus() != 200) {
        fail("status problem for request " + response.getStatus());
    }

    String jsonStringResponse = response.readEntity(String.class);

    ObjectMapper mapper = new ObjectMapper();
    JsonNode sampleTree = mapper.readTree(jsonStringResponse);
    LOG.debug(jsonStringResponse);
    return sampleTree;
}

From source file:com.evrythng.java.wrapper.mapping.CreateActionsJobInputDeserializer.java

@Override
public CreateActionJob.Input deserialize(final JsonParser jp, final DeserializationContext ctx)
        throws IOException {

    ObjectMapper mapper = JSONUtils.OBJECT_MAPPER;
    JsonNode node = mapper.readTree(jp);
    JsonNode typeNode = node.get(CreateActionJob.Input.FIELD_TYPE);
    if (typeNode == null) {
        throw new JsonMappingException("Cannot deserialize create actions job input without type field");
    }/*  ww w . ja va  2  s .c  om*/
    String typeRaw = getFieldValue(typeNode);
    JsonNode contentTypeNode = node.get(CreateActionJob.Input.FIELD_CONTENT_TYPE);
    if (contentTypeNode == null) {
        throw new JsonMappingException("Cannot deserialize create actions job input without contentType field");
    }
    String contentTypeRaw = getFieldValue(contentTypeNode);
    Class<? extends CreateActionJob.Input> subtypeClass = classForType(
            CreateActionJob.Input.Type.valueOf(typeRaw.toUpperCase()),
            CreateActionJob.Input.ContentType.valueOf(contentTypeRaw.toUpperCase()));
    return mapper.readValue(node.toString(), subtypeClass);
}

From source file:org.onosproject.segmentrouting.web.PolicyWebResource.java

/**
 * Create a new segment routing policy./*from   w w  w .  j a  v a 2  s.c o m*/
 *
 * @param input JSON stream for policy to create
 * @return status of the request - OK if the policy is created,
 * INTERNAL_SERVER_ERROR if the JSON is invalid or the policy cannot be created
 * @throws IOException if JSON processing fails
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createPolicy(InputStream input) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode policyJson = (ObjectNode) mapper.readTree(input);
    SegmentRoutingService srService = get(SegmentRoutingService.class);
    Policy policyInfo = POLICY_CODEC.decode(policyJson, this);

    if (policyInfo.type() == Policy.Type.TUNNEL_FLOW) {
        srService.createPolicy(policyInfo);
        return Response.ok().build();
    } else {
        return Response.serverError().build();
    }
}

From source file:org.trustedanalytics.cloud.cc.api.CcAppEnv.java

/**
 * <pre>//from   w w  w  .  jav a 2s .c o m
 * Method to get value by specified filter
 * Example json:
 * {
 * "user-provided": [
 *   {
 *        "name": "sso",
 *        "label": "user-provided",
 *        "tags": [],
 *        "credentials": {
 *          "apiEndpoint": "http://api.example.eu"
 *        }
 *   }]}
 *
 * To get api endpoint from such json we could use this method like:
 * String apiEndpoint = ccAppEnv.getValueByFilter("$..[?(@.name=='sso')]..credentials..apiEndpoint").toString();
 * </pre>
 * @param filter is an expression like: "$..[?(@.name=='sso')]..credentials..apiEndpoint"
 */
public JsonNode getValueByFilter(String filter) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readTree(JsonPath.parse(env).read(filter).toString());
}