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:org.apache.asterix.test.common.TestExecutor.java

protected HttpUriRequest constructPostMethodJson(String statement, URI uri, String stmtParam,
        List<CompilationUnit.Parameter> otherParams) {
    if (stmtParam == null) {
        throw new NullPointerException("Statement parameter required.");
    }//from   w w w  . j a v a2  s . co m
    RequestBuilder builder = RequestBuilder.post(uri);
    ObjectMapper om = new ObjectMapper();
    ObjectNode content = om.createObjectNode();
    for (CompilationUnit.Parameter param : upsertParam(otherParams, stmtParam, statement)) {
        content.put(param.getName(), param.getValue());
    }
    try {
        builder.setEntity(new StringEntity(om.writeValueAsString(content), ContentType.APPLICATION_JSON));
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    builder.setCharset(StandardCharsets.UTF_8);
    return builder.build();
}

From source file:org.openecomp.sdnc.dmaapclient.SdncFlatJsonDmaapConsumer.java

public void processMsg(String msg, String mapDirName) throws InvalidMessageException {

    if (msg == null) {
        throw new InvalidMessageException("Null message");
    }/*  w  ww .j ava 2 s.c  om*/

    ObjectMapper oMapper = new ObjectMapper();
    JsonNode instarRootNode = null;
    ObjectNode sdncRootNode = null;

    String instarMsgName = null;

    try {
        instarRootNode = oMapper.readTree(msg);
    } catch (Exception e) {
        throw new InvalidMessageException("Cannot parse json object", e);
    }

    Iterator<Map.Entry<String, JsonNode>> instarFields = instarRootNode.fields();

    while (instarFields.hasNext()) {
        Map.Entry<String, JsonNode> entry = instarFields.next();

        instarMsgName = entry.getKey();
        instarRootNode = entry.getValue();
        break;
    }

    Map<String, String> fieldMap = loadMap(instarMsgName, mapDirName);

    if (fieldMap == null) {
        throw new InvalidMessageException("Unable to process message - cannot load field mappings");
    }

    if (!fieldMap.containsKey(SDNC_ENDPOINT)) {
        throw new InvalidMessageException("No SDNC endpoint known for message " + instarMsgName);
    }

    String sdncEndpoint = fieldMap.get(SDNC_ENDPOINT);

    sdncRootNode = oMapper.createObjectNode();
    ObjectNode inputNode = oMapper.createObjectNode();

    for (String fromField : fieldMap.keySet()) {

        if (!SDNC_ENDPOINT.equals(fromField)) {
            JsonNode curNode = instarRootNode.get(fromField);
            if (curNode != null) {
                String fromValue = curNode.textValue();

                inputNode.put(fieldMap.get(fromField), fromValue);
            }
        }
    }
    sdncRootNode.put("input", inputNode);

    try {
        String rpcMsgbody = oMapper.writeValueAsString(sdncRootNode);
        String odlUrlBase = getProperty("sdnc.odl.url-base");
        String odlUser = getProperty("sdnc.odl.user");
        String odlPassword = getProperty("sdnc.odl.password");

        if ((odlUrlBase != null) && (odlUrlBase.length() > 0)) {
            SdncOdlConnection conn = SdncOdlConnection.newInstance(odlUrlBase + sdncEndpoint, odlUser,
                    odlPassword);

            conn.send("POST", "application/json", rpcMsgbody);
        } else {
            LOG.info("POST message body would be:\n" + rpcMsgbody);
        }
    } catch (Exception e) {

    }

}

From source file:org.wrml.runtime.format.text.html.WrmldocFormatter.java

protected ObjectNode buildLinksNode(final ObjectMapper objectMapper, final Map<URI, ObjectNode> schemaNodes,
        final Map<URI, LinkRelation> linkRelationCache, final ApiNavigator apiNavigator,
        final Resource resource, final Prototype defaultPrototype) {

    final Context context = getContext();
    final SchemaLoader schemaLoader = context.getSchemaLoader();
    final SyntaxLoader syntaxLoader = context.getSyntaxLoader();

    final URI defaultSchemaUri = (defaultPrototype != null) ? defaultPrototype.getSchemaUri() : null;

    final ObjectNode linksNode = objectMapper.createObjectNode();

    final Set<URI> responseSchemaUris = new HashSet<>();
    if (defaultSchemaUri != null) {
        responseSchemaUris.add(defaultSchemaUri);
    }/*  w w w  .j  a va2 s  .c o  m*/

    for (final Method method : Method.values()) {
        final Set<URI> methodResponseSchemaUris = resource.getResponseSchemaUris(method);
        if (methodResponseSchemaUris != null && !methodResponseSchemaUris.isEmpty()) {
            responseSchemaUris.addAll(methodResponseSchemaUris);
        }
    }

    final ConcurrentHashMap<URI, LinkTemplate> linkTemplates = resource.getLinkTemplates();

    for (final URI schemaUri : responseSchemaUris) {
        final Prototype prototype = schemaLoader.getPrototype(schemaUri);
        final SortedMap<URI, LinkProtoSlot> linkProtoSlots = prototype.getLinkProtoSlots();
        if (linkProtoSlots == null || linkProtoSlots.isEmpty()) {
            continue;
        }

        final ObjectNode linkTemplatesNode = objectMapper.createObjectNode();

        final Set<URI> linkRelationUris = linkProtoSlots.keySet();
        for (final URI linkRelationUri : linkRelationUris) {
            final LinkProtoSlot linkProtoSlot = linkProtoSlots.get(linkRelationUri);

            if (schemaLoader.getDocumentSchemaUri().equals(linkProtoSlot.getDeclaringSchemaUri())) {
                // Skip over the built-in system-level link relations (which are all self-referential).
                continue;
            }

            final ObjectNode linkTemplateNode = objectMapper.createObjectNode();
            final String linkSlotName = linkProtoSlot.getName();
            linkTemplatesNode.put(linkSlotName, linkTemplateNode);

            final LinkRelation linkRelation = getLinkRelation(linkRelationCache, linkRelationUri);
            final Method method = linkRelation.getMethod();

            linkTemplateNode.put(PropertyName.method.name(), method.getProtocolGivenName());
            linkTemplateNode.put(PropertyName.rel.name(), syntaxLoader.formatSyntaxValue(linkRelationUri));
            linkTemplateNode.put(PropertyName.relationTitle.name(), linkRelation.getTitle());

            final URI responseSchemaUri;
            final URI requestSchemaUri;

            if (linkTemplates.containsKey(linkRelationUri)) {
                final LinkTemplate linkTemplate = linkTemplates.get(linkRelationUri);
                responseSchemaUri = linkTemplate.getResponseSchemaUri();
                requestSchemaUri = linkTemplate.getRequestSchemaUri();

                final UUID endPointId = linkTemplate.getEndPointId();
                if (endPointId != null) {
                    final Resource endPointResource = apiNavigator.getResource(endPointId);

                    final ObjectNode endPointNode = objectMapper.createObjectNode();

                    endPointNode.put(PropertyName.id.name(), syntaxLoader.formatSyntaxValue(endPointId));
                    endPointNode.put(PropertyName.pathSegment.name(), endPointResource.getPathSegment());
                    endPointNode.put(PropertyName.fullPath.name(), endPointResource.getPathText());
                    endPointNode.put(PropertyName.uriTemplate.name(),
                            endPointResource.getUriTemplate().getUriTemplateString());

                    linkTemplateNode.put(PropertyName.endpoint.name(), endPointNode);
                }

            } else {
                responseSchemaUri = linkProtoSlot.getResponseSchemaUri();
                requestSchemaUri = linkProtoSlot.getRequestSchemaUri();
            }

            if (responseSchemaUri != null) {
                final ObjectNode responseSchemaNode = getSchemaNode(objectMapper, schemaNodes,
                        responseSchemaUri, schemaLoader);
                linkTemplateNode.put(PropertyName.responseSchema.name(), responseSchemaNode);
            }

            if (requestSchemaUri != null) {
                final ObjectNode requestSchemaNode = getSchemaNode(objectMapper, schemaNodes, requestSchemaUri,
                        schemaLoader);
                linkTemplateNode.put(PropertyName.requestSchema.name(), requestSchemaNode);
            }

            final String signature = buildLinkSignature(linkSlotName, responseSchemaUri, requestSchemaUri,
                    schemaUri);
            linkTemplateNode.put(PropertyName.signature.name(), signature);
        }

        if (linkTemplatesNode.size() > 0) {
            final ObjectNode schemaNode = objectMapper.createObjectNode();
            final ObjectNode schemaDetailsNode = getSchemaNode(objectMapper, schemaNodes, schemaUri,
                    schemaLoader);
            schemaNode.put(PropertyName.schema.name(), schemaDetailsNode);
            schemaNode.put(PropertyName.linkTemplates.name(), linkTemplatesNode);
            linksNode.put(prototype.getUniqueName().getLocalName(), schemaNode);
        }
    }

    return linksNode;
}

From source file:com.microsoft.azure.vmagent.AzureVMManagementServiceDelegate.java

private static void AddNSGNode(final JsonNode template, final ObjectMapper mapper, final String nsgName)
        throws IOException {

    ObjectNode.class.cast(template.get("variables")).put("nsgName", nsgName);

    ArrayNode resourcesNodes = ArrayNode.class.cast(template.get("resources"));
    Iterator<JsonNode> resourcesNodesIter = resourcesNodes.elements();
    while (resourcesNodesIter.hasNext()) {
        JsonNode resourcesNode = resourcesNodesIter.next();
        JsonNode typeNode = resourcesNode.get("type");
        if (typeNode == null || !typeNode.asText().equals("Microsoft.Network/networkInterfaces")) {
            continue;
        }//from  w w  w .  j a va2  s . co  m

        ObjectNode nsgNode = mapper.createObjectNode();
        nsgNode.put("id", "[resourceId('Microsoft.Network/networkSecurityGroups', variables('nsgName'))]");

        // Find the properties node
        // We will attach the provided NSG and not check if it's valid because that's done in the verification step
        ObjectNode propertiesNode = ObjectNode.class.cast(resourcesNode.get("properties"));
        propertiesNode.set("networkSecurityGroup", nsgNode);
        break;
    }
}

From source file:com.marklogic.client.functionaltest.TestPartialUpdate.java

@Test
public void testPartialUpdateJSON() throws IOException {
    System.out.println("Running testPartialUpdateJSON");

    String[] filenames = { "json-original.json" };

    DatabaseClient client = DatabaseClientFactory.newClient("localhost", uberPort, dbName, "eval-user", "x",
            Authentication.DIGEST);//from  w ww.  ja  v  a 2  s .  c  om

    // write docs
    for (String filename : filenames) {
        writeDocumentUsingInputStreamHandle(client, filename, "/partial-update/", "JSON");
    }

    ObjectMapper mapper = new ObjectMapper();

    String docId = "/partial-update/json-original.json";
    JSONDocumentManager docMgr = client.newJSONDocumentManager();
    DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
    patchBldr.pathLanguage(PathLanguage.JSONPATH);

    ObjectNode fragmentNode = mapper.createObjectNode();
    ObjectNode fragmentNode1 = mapper.createObjectNode();
    ObjectNode fragmentNode2 = mapper.createObjectNode();

    fragmentNode.put("insertedKey", 9);
    fragmentNode1.put("original", true);
    fragmentNode2.put("modified", false);

    String fragment = mapper.writeValueAsString(fragmentNode);
    String fragment1 = mapper.writeValueAsString(fragmentNode1);
    String fragment2 = mapper.writeValueAsString(fragmentNode2);

    String jsonpath = new String("$.employees[2]");
    patchBldr.insertFragment(jsonpath, Position.AFTER, fragment);
    patchBldr.insertFragment("$.employees[2]", Position.AFTER, fragment1);
    patchBldr.insertFragment("$.employees[0]", Position.AFTER, fragment2);

    DocumentPatchHandle patchHandle = patchBldr.build();
    docMgr.patch(docId, patchHandle);

    String content = docMgr.read(docId, new StringHandle()).get();

    System.out.println(content);

    assertTrue("fragment is not inserted", content.contains("{\"insertedKey\":9}"));
    assertTrue("Original fragment is not inserted or incorrect", content.contains("{\"original\":true}"));
    assertTrue("Modified fragment is not inserted or incorrect", content.contains("{\"modified\":false}"));

    // Test for replaceValue with booleans.
    DocumentPatchBuilder patchBldrBool = docMgr.newPatchBuilder();
    patchBldrBool.pathLanguage(PathLanguage.JSONPATH);

    //Replace original to false and modified to true.
    patchBldrBool.replaceValue("$.employees[5].original", false);
    patchBldrBool.replaceValue("$.employees[1].modified", new Boolean(true));

    DocumentPatchHandle patchHandleBool = patchBldrBool.build();
    docMgr.patch(docId, patchHandleBool);

    String content1 = docMgr.read(docId, new StringHandle()).get();

    System.out.println(content1);
    // Make sure the inserted content is present.
    assertTrue("Original fragment is not replaced", content1.contains("{\"original\":false}"));
    assertTrue("Modified fragment is not replaced", content1.contains("{\"modified\":true}"));

    // release client
    client.release();
}

From source file:com.marklogic.client.functionaltest.TestPartialUpdate.java

@Test
public void testPartialUpdateCombinationJSON() throws Exception {
    System.out.println("Running testPartialUpdateCombinationJSON");
    DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x",
            Authentication.DIGEST);/*ww  w.j av a 2 s  .  c om*/

    // write docs
    String[] filenames = { "json-original.json" };
    for (String filename : filenames) {
        writeDocumentUsingInputStreamHandle(client, filename, "/partial-update/", "JSON");
    }
    String docId = "/partial-update/json-original.json";

    ObjectMapper mapper = new ObjectMapper();

    JSONDocumentManager docMgr = client.newJSONDocumentManager();
    DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
    patchBldr.pathLanguage(PathLanguage.JSONPATH);
    String content1 = docMgr.read(docId, new StringHandle()).get();

    System.out.println("Before" + content1);
    ObjectNode fragmentNode = mapper.createObjectNode();
    fragmentNode = mapper.createObjectNode();
    fragmentNode.put("insertedKey", 9);
    String fragment = mapper.writeValueAsString(fragmentNode);
    // Original - patchBldr.insertFragment("$.employees", Position.LAST_CHILD, fragment).delete("$.employees[2]").replaceApply("$.employees[1].firstName", patchBldr.call().concatenateAfter("Hi"));
    patchBldr.insertFragment("$.employees[0]", Position.AFTER, fragment).delete("$.employees[2]")
            .replaceApply("$.employees[1].firstName", patchBldr.call().concatenateAfter("Hi"));
    DocumentPatchHandle patchHandle = patchBldr.build();
    docMgr.patch(docId, patchHandle);

    String content = docMgr.read(docId, new StringHandle()).get();

    System.out.println("After" + content);

    assertTrue("fragment is not inserted", content.contains("{\"insertedKey\":9}"));
    assertTrue("fragment is not inserted",
            content.contains("{\"firstName\":\"AnnHi\", \"lastName\":\"Smith\"}"));
    assertFalse("fragment is not deleted", content.contains("{\"firstName\":\"Bob\", \"lastName\":\"Foo\"}"));

    // release client
    client.release();

}

From source file:com.marklogic.client.functionaltest.TestPartialUpdate.java

@Test
public void testPartialUpdateJSONDescriptor() throws IOException {
    System.out.println("Running testPartialUpdateJSONDescriptor");

    String[] filenames = { "json-original.json" };

    DatabaseClient client = DatabaseClientFactory.newClient("localhost", uberPort, dbName, "eval-user", "x",
            Authentication.DIGEST);/*from w ww  . java  2 s  .c  o m*/

    // write docs
    for (String filename : filenames) {
        writeDocumentUsingInputStreamHandle(client, filename, "/partial-update/", "JSON");
    }

    ObjectMapper mapper = new ObjectMapper();
    String docId = "/partial-update/json-original.json";
    // create doc manager
    JSONDocumentManager docMgr = client.newJSONDocumentManager();

    //Create Document Descriptor
    DocumentDescriptor desc = docMgr.newDescriptor(docId);

    DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
    patchBldr.pathLanguage(PathLanguage.JSONPATH);
    ObjectNode fragmentNode = mapper.createObjectNode();
    fragmentNode = mapper.createObjectNode();
    fragmentNode.put("insertedKey", 9);
    String fragment = mapper.writeValueAsString(fragmentNode);

    patchBldr.insertFragment("$.employees[2]", Position.AFTER, fragment);
    DocumentPatchHandle patchHandle = patchBldr.build();

    docMgr.patch(desc, patchHandle);

    String content = docMgr.read(docId, new StringHandle()).get();

    System.out.println("After" + content);

    assertTrue("fragment is not inserted", content.contains("{\"insertedKey\":9}]"));

    // release client
    client.release();
}

From source file:com.marklogic.client.functionaltest.BasicJavaClientREST.java

public JsonNode constructJSONCollectionMetadata(String... col) {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode mNode = mapper.createObjectNode();
    ArrayNode aNode = mapper.createArrayNode();

    for (String c : col) {
        aNode.add(c);/*  w  ww  .  ja va  2s. co m*/
    }
    mNode.withArray("collections").addAll(aNode);
    return mNode;
}

From source file:com.marklogic.client.functionaltest.BasicJavaClientREST.java

public JsonNode constructJSONPropertiesMetadata(Map prop) {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode mainNode = mapper.createObjectNode();
    ObjectNode cNode = mapper.createObjectNode();

    Iterator keys = prop.keySet().iterator();
    while (keys.hasNext()) {
        String keyvalue = keys.next().toString();
        cNode.put(keyvalue, prop.get(keyvalue).toString());
    }//w w w.ja  v  a 2  s.c  o m
    mainNode.set("properties", cNode);
    return (mainNode);
}

From source file:com.marklogic.client.functionaltest.TestPartialUpdate.java

@Test
public void testPartialUpdateJSONDescriptorTranc() throws IOException {
    System.out.println("Running testPartialUpdateJSONDescriptorTranc");

    String[] filenames = { "json-original.json" };

    DatabaseClient client = DatabaseClientFactory.newClient("localhost", uberPort, dbName, "eval-user", "x",
            Authentication.DIGEST);/*from www. j av  a  2 s . co  m*/

    // write docs
    for (String filename : filenames) {
        writeDocumentUsingInputStreamHandle(client, filename, "/partial-update/", "JSON");
    }
    ObjectMapper mapper = new ObjectMapper();
    String docId = "/partial-update/json-original.json";
    // create doc manager
    JSONDocumentManager docMgr = client.newJSONDocumentManager();
    // create template
    DocumentUriTemplate template = docMgr.newDocumentUriTemplate("JSON");
    template.withDirectory(docId);
    //Create Document Descriptor
    DocumentDescriptor desc = docMgr.newDescriptor(template.getDirectory());
    DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();

    ObjectNode fragmentNode = mapper.createObjectNode();
    fragmentNode = mapper.createObjectNode();
    fragmentNode.put("insertedKey", 9);
    String fragment = mapper.writeValueAsString(fragmentNode);
    patchBldr.pathLanguage(PathLanguage.JSONPATH);
    patchBldr.insertFragment("$.employees[2]", Position.AFTER, fragment);
    DocumentPatchHandle patchHandle = patchBldr.build();
    //      Transaction t = client.openTransaction("Tranc");
    docMgr.patch(desc, patchHandle);//,t);
    //         t.commit();
    String content = docMgr.read(docId, new StringHandle()).get();

    System.out.println("After" + content);

    assertTrue("fragment is not inserted", content.contains("{\"insertedKey\":9}]"));

    // release client
    client.release();
}