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.marklogic.client.impl.CombinedQueryBuilderImpl.java

@SuppressWarnings("rawtypes")
private String makeJSONCombinedQuery(CombinedQueryDefinitionImpl qdef) {
    try {//from www  .  ja v  a  2  s . c  om
        ObjectMapper mapper = new ObjectMapper().configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
                .configure(Feature.ALLOW_SINGLE_QUOTES, true);
        ObjectNode rootNode = mapper.createObjectNode();
        ObjectNode searchNode = mapper.createObjectNode();
        rootNode.replace("search", searchNode);
        if (qdef.sparql != null)
            searchNode.put("sparql", qdef.sparql);
        if (qdef.qtext != null)
            searchNode.put("qtext", qdef.qtext);
        if (qdef.options != null) {
            HandleImplementation optionsBase = HandleAccessor.as(qdef.options);
            if (Format.JSON != optionsBase.getFormat()) {
                throw new IllegalStateException("Cannot combine a JSON-format structured " + "query with "
                        + optionsBase.getFormat() + "-format options");
            }
            String json = HandleAccessor.contentAsString(qdef.options);
            JsonNode optionsNode = mapper.readTree(json);
            searchNode.replace("options", optionsNode.get("options"));
        }
        if (qdef.rawQuery != null) {
            String json = HandleAccessor.contentAsString(qdef.rawQuery.getHandle());
            JsonNode rawQueryNode = mapper.readTree(json);
            JsonNode queryNode = rawQueryNode.get("query");
            if (queryNode == null)
                queryNode = rawQueryNode.path("search").get("query");
            if (queryNode != null)
                searchNode.replace("query", queryNode);
            if (qdef.options == null) {
                JsonNode optionsNode = rawQueryNode.path("search").get("options");
                if (optionsNode != null)
                    searchNode.replace("options", optionsNode);
            }
            if (qdef.qtext == null) {
                JsonNode qtextNode = rawQueryNode.path("search").get("qtext");
                if (qtextNode != null)
                    searchNode.replace("qtext", qtextNode);
            }
            if (qdef.sparql == null) {
                JsonNode sparqlNode = rawQueryNode.path("search").get("sparql");
                if (sparqlNode != null)
                    searchNode.replace("sparql", sparqlNode);
            }
        }
        return rootNode.toString();
    } catch (Exception e) {
        throw new MarkLogicIOException(e);
    }
}

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

private ObjectNode createOptionsForNode(NodeType nodeType, ObjectMapper mapper) {
    //        if (nodeType.isPrimaryKey() && nodeType.getEntityType().getKeyGenSpec() == KeyGenSpec.FRAMEWORK) {
    //            ObjectNode opt = mapper.createObjectNode();
    //            opt.put("hidden", true);
    //            return opt;
    //        }/* w w  w .j a  v  a  2 s.c o  m*/
    if (nodeType.getEnumSpec() != null && nodeType.isMandatory()) {
        ObjectNode opt = mapper.createObjectNode();
        opt.put("nullOption", false);
        return opt;
    }
    return null;
}

From source file:la.alsocan.jsonshapeshifter.Transformation.java

private void resolveNode(ObjectMapper om, SchemaNode node, JsonNode parentNode, JsonNode payload,
        List<Integer> pointerContext) {
    switch (node.getType()) {
    case OBJECT://from w ww.j a  v  a2  s .  c  o  m
        ObjectNode oNode = om.createObjectNode();
        ((SchemaObjectNode) node).getChildren().stream().forEach((tChildNode) -> {
            resolveNode(om, tChildNode, oNode, payload, pointerContext);
        });
        if (parentNode.isObject()) {
            ((ObjectNode) parentNode).set(node.getName(), oNode);
        } else {
            ((ArrayNode) parentNode).add(oNode);
        }
        break;
    case ARRAY:
        ArrayNode aNode = om.createArrayNode();
        SchemaNode tChildNode = ((SchemaArrayNode) node).getChild();
        int index = 0;
        pointerContext.add(index);
        Iterator<JsonNode> it = (Iterator<JsonNode>) resolveValue(node, payload, pointerContext);
        while (it.hasNext()) {
            it.next();
            resolveNode(om, tChildNode, aNode, payload, pointerContext);
            pointerContext.set(pointerContext.size() - 1, ++index);
        }
        pointerContext.remove(pointerContext.size() - 1);
        if (parentNode.isObject()) {
            ((ObjectNode) parentNode).set(node.getName(), aNode);
        } else {
            ((ArrayNode) parentNode).add(aNode);
        }
        break;
    case BOOLEAN:
        if (parentNode.isObject()) {
            ((ObjectNode) parentNode).put(node.getName(),
                    (Boolean) resolveValue(node, payload, pointerContext));
        } else {
            ((ArrayNode) parentNode).add((Boolean) resolveValue(node, payload, pointerContext));
        }
        break;
    case INTEGER:
        if (parentNode.isObject()) {
            ((ObjectNode) parentNode).put(node.getName(),
                    (Integer) resolveValue(node, payload, pointerContext));
        } else {
            ((ArrayNode) parentNode).add((Integer) resolveValue(node, payload, pointerContext));
        }
        break;
    case NUMBER:
        if (parentNode.isObject()) {
            ((ObjectNode) parentNode).put(node.getName(), (Double) resolveValue(node, payload, pointerContext));
        } else {
            ((ArrayNode) parentNode).add((Double) resolveValue(node, payload, pointerContext));
        }
        break;
    case NULL:
        if (parentNode.isObject()) {
            ((ObjectNode) parentNode).putNull(node.getName());
        } else {
            ((ArrayNode) parentNode).addNull();
        }
        break;
    case STRING:
        if (parentNode.isObject()) {
            ((ObjectNode) parentNode).put(node.getName(), (String) resolveValue(node, payload, pointerContext));
        } else {
            ((ArrayNode) parentNode).add((String) resolveValue(node, payload, pointerContext));
        }
        break;
    }
}

From source file:org.onosproject.openstacknetworkingui.OpenstackNetworkingUiMessageHandler.java

private ObjectNode getFlowTraceRequestAsJson(String srcIp, String dstIp) {
    ObjectMapper mapper = new ObjectMapper();
    String controllerUrl = HTTP + clusterService.getLocalNode().ip() + OPENSTACK_NETWORKING_UI_RESULT;

    ObjectNode objectNode = mapper.createObjectNode();

    objectNode.put(COMMAND, FLOW_TRACE).put(REVERSE, false).put(TRANSACTION_ID, TRANSACTION_VALUE)
            .put(APP_REST_URL, controllerUrl);

    if (srcIp.equals(dstIp)) {
        objectNode.putObject(MATCHING_FIELDS).put(SOURCE_IP, srcIp).put(DESTINATION_IP, dstIp)
                .put(TO_GATEWAY, true).put(IP_PROTOCOL, 1);

    } else {//from   www  . j a  v a  2s  .  co  m
        objectNode.putObject(MATCHING_FIELDS).put(SOURCE_IP, srcIp).put(DESTINATION_IP, dstIp);
    }
    return objectNode;
}

From source file:org.onosproject.openstackinterface.impl.OpenstackInterfaceManager.java

private ObjectNode createFloatingIpObject(String portId, Optional<Ip4Address> fixedIpAddress) {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode objectNode = mapper.createObjectNode();

    objectNode.putObject(FLOATINGIP).put(PORT_ID, portId);

    if (portId != null) {
        objectNode.put(FIXED_IP_ADDRESS, fixedIpAddress.get().toString());
    }/* w  w w  . j  av  a2s .  c  o  m*/

    return objectNode;
}

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

@Test
public void get_withInvalidKey_shouldReturnNull() {
    // GIVEN/*from  w  w  w. j a  v  a 2s .  c o m*/
    ObjectMapper objectMapper = new ObjectMapper();
    DiscoveryCacheKey key1 = DiscoveryCacheKey.newWithDetails("a", "a");
    DiscoveryCacheKey key2 = DiscoveryCacheKey.newWithDetails("a", "b");
    IDiscoveryCache cache = Factory.getDefaultDiscoveryCache();
    DiscoveryCacheValue value = new DiscoveryCacheValue(new Date(Long.MAX_VALUE),
            objectMapper.createObjectNode());
    cache.add(key1, value);

    // WHEN
    DiscoveryCacheValue cachedValue1 = cache.get(key1);
    DiscoveryCacheValue cachedValue2 = cache.get(key2);

    // THEN
    assertNotNull(cachedValue1);
    assertNull(cachedValue2);
}

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

@Test
public void remove_withInvalidKey_shouldNotFail() {
    // GIVEN//  w  w  w.ja  va2s.  c om
    ObjectMapper objectMapper = new ObjectMapper();
    DiscoveryCacheKey key1 = DiscoveryCacheKey.newWithDetails("a", "a");
    DiscoveryCacheKey key2 = DiscoveryCacheKey.newWithDetails("a", "b");
    IDiscoveryCache cache = Factory.getDefaultDiscoveryCache();
    DiscoveryCacheValue value = new DiscoveryCacheValue(new Date(Long.MAX_VALUE),
            objectMapper.createObjectNode());
    cache.add(key1, value);

    // WHEN
    cache.remove(key2);
    DiscoveryCacheValue cachedValue1 = cache.get(key1);
    boolean cacheIsEmpty = cache.isEmpty();

    // THEN
    assertNotNull(cachedValue1);
    assertFalse(cacheIsEmpty);
}

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

private void readGDMFromDBThatWasWrittenAsGDM(final Optional<ObjectNode> optionalContentSchemaRequestJSON,
        final String resourcePathV1, final String resourcePathV2, final String dataModelURI,
        final String recordClassURI, final long statementCountCurrentVersion, final long statementCountV1,
        final boolean deprecateMissingRecords, final Optional<String> optionalRecordClassUri)
        throws IOException {

    LOG.debug("start read test for GDM resource at {} DB", dbType);

    writeGDMToDBInternal(dataModelURI, resourcePathV1);
    writeGDMToDBInternalWithContentSchema(resourcePathV2, dataModelURI, optionalContentSchemaRequestJSON,
            deprecateMissingRecords, optionalRecordClassUri);

    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);

    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);//from  ww  w  .j  a v  a 2 s.com

        return null;
    });

    final Iterator<Void> iterator = parseObservable.toBlocking().getIterator();

    Assert.assertTrue(iterator.hasNext());

    while (iterator.hasNext()) {

        iterator.next();
    }

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

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

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

    // read first version
    final ObjectNode requestJson2 = objectMapper.createObjectNode();

    requestJson2.put(DMPStatics.RECORD_CLASS_URI_IDENTIFIER, recordClassURI);
    requestJson2.put(DMPStatics.DATA_MODEL_URI_IDENTIFIER, dataModelURI);
    requestJson2.put(DMPStatics.VERSION_IDENTIFIER, 1);

    final String requestJsonString2 = objectMapper.writeValueAsString(requestJson2);

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

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

    final InputStream actualResult2 = response2.getEntity(InputStream.class);
    final BufferedInputStream bis2 = new BufferedInputStream(actualResult2, 1024);
    final ModelParser modelParser2 = new ModelParser(bis2);
    final org.dswarm.graph.json.Model model2 = new org.dswarm.graph.json.Model();

    final Observable<Void> parseObservable2 = modelParser2.parse().map(resource1 -> {

        model2.addResource(resource1);

        return null;
    });

    final Iterator<Void> iterator2 = parseObservable2.toBlocking().getIterator();

    Assert.assertTrue(iterator2.hasNext());

    while (iterator2.hasNext()) {

        iterator2.next();
    }

    bis2.close();
    actualResult2.close();

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

    Assert.assertEquals("the number of statements should be " + statementCountV1, statementCountV1,
            model2.size());

    LOG.debug("finished read test for GDM resource at {} DB", dbType);
}

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

@Test
public void clear_shouldEmptyCache() {
    // GIVEN//w w w . j a  v a  2 s  . com
    ObjectMapper objectMapper = new ObjectMapper();
    DiscoveryCacheKey key1 = DiscoveryCacheKey.newWithDetails("a", "a");
    DiscoveryCacheKey key2 = DiscoveryCacheKey.newWithDetails("a", "b");
    IDiscoveryCache cache = Factory.getDefaultDiscoveryCache();
    DiscoveryCacheValue value = new DiscoveryCacheValue(new Date(Long.MAX_VALUE),
            objectMapper.createObjectNode());
    cache.add(key1, value);
    cache.add(key2, value);

    // WHEN
    cache.clear();
    DiscoveryCacheValue cachedValue1 = cache.get(key1);
    DiscoveryCacheValue cachedValue2 = cache.get(key2);
    boolean cacheIsEmpty = cache.isEmpty();

    // THEN
    assertNull(cachedValue1);
    assertNull(cachedValue2);
    assertTrue(cacheIsEmpty);
}

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

@Test
public void remove_withValidKey_shouldRemoveEntry() {
    // GIVEN/*  ww w . j a  v a  2 s.co  m*/
    ObjectMapper objectMapper = new ObjectMapper();
    DiscoveryCacheKey key1 = DiscoveryCacheKey.newWithDetails("a", "a");
    DiscoveryCacheKey key2 = DiscoveryCacheKey.newWithDetails("a", "b");
    IDiscoveryCache cache = Factory.getDefaultDiscoveryCache();
    DiscoveryCacheValue value = new DiscoveryCacheValue(new Date(Long.MAX_VALUE),
            objectMapper.createObjectNode());
    cache.add(key1, value);
    cache.add(key2, value);

    // WHEN
    cache.remove(key1);
    DiscoveryCacheValue cachedValue1 = cache.get(key1);
    DiscoveryCacheValue cachedValue2 = cache.get(key2);
    boolean cacheIsEmpty = cache.isEmpty();

    // THEN
    assertNull(cachedValue1);
    assertNotNull(cachedValue2);
    assertFalse(cacheIsEmpty);
}