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

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

Introduction

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

Prototype

@Override
public ObjectNode createObjectNode() 

Source Link

Document

Note: return type is co-variant, as basic ObjectCodec abstraction can not refer to concrete node types (as it's part of core package, whereas impls are part of mapper package)

Usage

From source file:com.randstad.rest.editor.model.ModelEditorJsonRestResource.java

@RequestMapping(value = "/service/model/{modelId}/json", method = RequestMethod.GET, produces = "application/json")
public ObjectNode getEditorJson(@PathVariable String modelId) {
    ObjectNode modelNode = null;//from w w w .j  a  v  a 2s .co  m

    Model model = repositoryService.getModel(modelId);

    if (model != null) {
        try {

            ObjectMapper objectMapper = new ObjectMapper();

            if (StringUtils.isNotEmpty(model.getMetaInfo())) {
                modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
            } else {
                modelNode = objectMapper.createObjectNode();
                modelNode.put(MODEL_NAME, model.getName());
            }
            modelNode.put(MODEL_ID, model.getId());
            ObjectNode editorJsonNode = (ObjectNode) objectMapper
                    .readTree(new String(repositoryService.getModelEditorSource(model.getId()), "utf-8"));
            modelNode.put("model", editorJsonNode);

        } catch (Exception e) {
            logger.error("Error creating model JSON", e);
            throw new ActivitiException("Error creating model JSON", e);
        }
    }
    return modelNode;
}

From source file:org.dswarm.graph.gdm.test.BaseGDMResourceTest.java

protected void readGDMFromDB(final String recordClassURI, final String dataModelURI,
        final int numberOfStatements, final Optional<Integer> optionalAtMost) throws IOException {

    final ObjectMapper objectMapper = Util.getJSONObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    final ObjectNode requestJson = objectMapper.createObjectNode();

    requestJson.put(DMPStatics.RECORD_CLASS_URI_IDENTIFIER, recordClassURI);
    requestJson.put(DMPStatics.DATA_MODEL_URI_IDENTIFIER, dataModelURI);

    if (optionalAtMost.isPresent()) {

        requestJson.put(DMPStatics.AT_MOST_IDENTIFIER, optionalAtMost.get());
    }//from   ww w  .  j av  a2 s .co  m

    final String requestJsonString = objectMapper.writeValueAsString(requestJson);

    // POST the request
    final ClientResponse response = target().path("/get").type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, requestJsonString);

    Assert.assertEquals("expected 200", 200, response.getStatus());

    final InputStream actualResult = response.getEntity(InputStream.class);
    final BufferedInputStream bis = new BufferedInputStream(actualResult, 1024);
    final ModelParser modelParser = new ModelParser(bis);
    final org.dswarm.graph.json.Model model = new org.dswarm.graph.json.Model();

    final Observable<Void> parseObservable = modelParser.parse().map(resource1 -> {

        model.addResource(resource1);

        return null;
    });

    parseObservable.toBlocking().lastOrDefault(null);

    bis.close();
    actualResult.close();

    LOG.debug("read '{}' statements", model.size());

    Assert.assertEquals("the number of statements should be " + numberOfStatements, numberOfStatements,
            model.size());
}

From source file:com.gsma.mobileconnect.cache.DiscoveryCacheHashMapImplTest.java

@Test
public void get_shouldReturnCopiesOfData() {
    // GIVEN//from  w  w  w.  j a  v a2s . c  o m
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode root = mapper.createObjectNode();

    String field1 = "field1";
    String expectedFieldValue1 = "value1";
    String expectedNewFieldValue1 = "new_value1";
    root.put(field1, expectedFieldValue1);

    String field2 = "field2";
    String expectedFieldValue2 = "value2";
    root.put(field2, expectedFieldValue2);

    DiscoveryCacheKey key = DiscoveryCacheKey.newWithDetails("a", "a");
    IDiscoveryCache cache = Factory.getDefaultDiscoveryCache();

    DiscoveryCacheValue value = new DiscoveryCacheValue(new Date(Long.MAX_VALUE), root);

    // WHEN
    cache.add(key, value);

    // Change the returned value
    DiscoveryCacheValue cachedValue1 = cache.get(key);
    ObjectNode cachedRoot = (ObjectNode) cachedValue1.getValue();
    cachedRoot.remove(field2);
    cachedRoot.put(field1, expectedNewFieldValue1);
    cachedValue1.getTtl().setTime(Long.MIN_VALUE);

    // Get from the cache again
    DiscoveryCacheValue cachedValue2 = cache.get(key);

    // THEN
    // cacheValue1 should reflect the changes
    assertNotNull(cachedValue1);
    assertEquals(expectedNewFieldValue1, cachedValue1.getValue().get(field1).textValue());
    assertNull(cachedValue1.getValue().get(field2));
    assertEquals(Long.MIN_VALUE, cachedValue1.getTtl().getTime());

    // cacheValue2 should not reflect the changes
    assertNotNull(cachedValue2);
    assertEquals(expectedFieldValue1, cachedValue2.getValue().get(field1).textValue());
    assertEquals(expectedFieldValue2, cachedValue2.getValue().get(field2).textValue());
    assertEquals(Long.MAX_VALUE, cachedValue2.getTtl().getTime());
}

From source file:com.kumuluz.ee.security.KeycloakSecurityConfigurationUtilImpl.java

private ObjectNode toJSONObject(String jsonString) {
    ObjectMapper mapper = new ObjectMapper();

    ObjectNode json;/*from w w w .  ja v  a  2  s. c o m*/
    try {
        json = mapper.readValue(jsonString, ObjectNode.class);
    } catch (IOException e) {
        json = mapper.createObjectNode();
    }
    return json;
}

From source file:scott.barleyrs.rest.EntityResultMessageBodyWriter.java

private JsonNode toJson(ObjectMapper mapper, Entity entity, Set<Entity> started) {
    if (!started.add(entity)) {
        return null;
    }//from w w w.  ja  va  2s .c o m
    try {
        ObjectNode jsonEntity = mapper.createObjectNode();
        for (Node node : entity.getChildren(Node.class)) {
            putNode(mapper, jsonEntity, node, started);
        }
        return jsonEntity;
    } finally {
        started.remove(entity);
    }
}

From source file:org.commonjava.indy.metrics.zabbix.api.IndyZabbixApi.java

public String getItem(String host, String item, String hostid) throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    ArrayNode groups = mapper.createArrayNode();
    ObjectNode search = mapper.createObjectNode();
    search.put("key_", item);
    Request getRequest = RequestBuilder.newBuilder().method("item.get").paramEntry("hostids", hostid)
            .paramEntry("search", search).build();
    JsonNode response = call(getRequest);
    if (response.get("result").isNull() || response.get("result").get(0) == null) {
        return null;
    }/*from w w  w.  j a va2  s  .c  o m*/
    return response.get("result").get(0).get("itemid").asText();
}

From source file:net.hamnaberg.json.Collection.java

public void writeTo(Writer writer) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode obj = mapper.createObjectNode();
    obj.set("collection", asJson());
    mapper.writeValue(writer, obj);/*from ww w.  j  ava 2  s . c  o  m*/
}

From source file:org.onosproject.tvue.TopologyResource.java

private ArrayNode json(ObjectMapper mapper, Path path) {
    ArrayNode pathNode = mapper.createArrayNode();
    for (Link link : path.links()) {
        ObjectNode linkNode = mapper.createObjectNode().put("src", id(link.src())).put("dst", id(link.dst()));
        pathNode.add(linkNode);/*w  w w.j av  a 2  s .c om*/
    }
    return pathNode;
}

From source file:org.commonjava.indy.metrics.zabbix.api.IndyZabbixApi.java

/**
 *
 * @param host/*from  w w w.  j a v a  2s. c  o  m*/
 * @param groupId
 * @param ip
 * @return hostid
 */
public String hostCreate(String host, String groupId, String ip) throws IOException {
    // host not exists, create it.
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode groups = mapper.createArrayNode();
    ObjectNode group = mapper.createObjectNode();
    group.put("groupid", groupId);
    groups.add(group);

    // "interfaces": [
    // {
    // "type": 1,
    // "main": 1,
    // "useip": 1,
    // "ip": "192.168.3.1",
    // "dns": "",
    // "port": "10050"
    // }
    // ],

    ObjectNode interface1 = mapper.createObjectNode();
    //        JSONObject interface1 = new JSONObject();
    interface1.put("type", 1);
    interface1.put("main", 1);
    interface1.put("useip", 1);
    interface1.put("ip", ip);
    interface1.put("dns", "");
    interface1.put("port", "10050");

    Request request = RequestBuilder.newBuilder().method("host.create").paramEntry("host", host)
            .paramEntry("groups", groups).paramEntry("interfaces", new Object[] { interface1 }).build();
    JsonNode response = call(request);
    return response.get("result").get("hostids").get(0).asText();
}

From source file:org.dswarm.graph.gdm.test.GDMResourceTest.java

@Test
public void testResourceTypeNodeUniqueness() throws IOException {

    writeGDMToDBInternal("http://data.slub-dresden.de/resources/1", DEFAULT_GDM_FILE_NAME);
    writeGDMToDBInternal("http://data.slub-dresden.de/resources/2", DEFAULT_GDM_FILE_NAME);

    final String typeQuery = "MATCH (n:TYPE_RESOURCE) RETURN id(n) AS node_id, n.uri AS node_uri;";

    final ObjectMapper objectMapper = Util.getJSONObjectMapper();

    final ObjectNode requestJson = objectMapper.createObjectNode();

    requestJson.put("query", typeQuery);

    final String requestJsonString = objectMapper.writeValueAsString(requestJson);

    final ClientResponse response = cypher().type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, requestJsonString);

    Assert.assertEquals("expected 200", 200, response.getStatus());

    final String body = response.getEntity(String.class);

    final ObjectNode bodyJson = objectMapper.readValue(body, ObjectNode.class);

    Assert.assertNotNull(bodyJson);/*from  w ww .  java  2s .c  om*/

    final JsonNode dataNode = bodyJson.get("data");

    Assert.assertNotNull(dataNode);
    Assert.assertTrue(dataNode.size() > 0);

    final Map<String, Long> resourceTypeMap = Maps.newHashMap();

    for (final JsonNode entry : dataNode) {

        final String resourceType = entry.get(1).textValue();
        final long nodeId = entry.get(0).longValue();

        if (resourceTypeMap.containsKey(resourceType)) {

            final Long existingNodeId = resourceTypeMap.get(resourceType);

            Assert.assertTrue("resource node map already contains a node for resource type '" + resourceType
                    + "' with the id '" + existingNodeId + "', but found another node with id '" + nodeId
                    + "' for this resource type", false);
        }

        resourceTypeMap.put(resourceType, nodeId);
    }
}