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.activiti5.engine.impl.bpmn.deployer.BpmnDeployer.java

protected void addDefinitionInfoToCache(ProcessDefinitionEntity processDefinition,
        ProcessEngineConfigurationImpl processEngineConfiguration, CommandContext commandContext) {

    if (processEngineConfiguration.isEnableProcessDefinitionInfoCache() == false) {
        return;//from  w  w  w .  j a va 2 s . c  o  m
    }

    DeploymentManager deploymentManager = processEngineConfiguration.getDeploymentManager();
    ProcessDefinitionInfoEntityManager definitionInfoEntityManager = commandContext
            .getProcessDefinitionInfoEntityManager();
    ObjectMapper objectMapper = commandContext.getProcessEngineConfiguration().getObjectMapper();
    ProcessDefinitionInfoEntity definitionInfoEntity = definitionInfoEntityManager
            .findProcessDefinitionInfoByProcessDefinitionId(processDefinition.getId());

    ObjectNode infoNode = null;
    if (definitionInfoEntity != null && definitionInfoEntity.getInfoJsonId() != null) {
        byte[] infoBytes = definitionInfoEntityManager.findInfoJsonById(definitionInfoEntity.getInfoJsonId());
        if (infoBytes != null) {
            try {
                infoNode = (ObjectNode) objectMapper.readTree(infoBytes);
            } catch (Exception e) {
                throw new ActivitiException(
                        "Error deserializing json info for process definition " + processDefinition.getId());
            }
        }
    }

    ProcessDefinitionInfoCacheObject definitionCacheObject = new ProcessDefinitionInfoCacheObject();
    if (definitionInfoEntity == null) {
        definitionCacheObject.setRevision(0);
    } else {
        definitionCacheObject.setId(definitionInfoEntity.getId());
        definitionCacheObject.setRevision(definitionInfoEntity.getRevision());
    }

    if (infoNode == null) {
        infoNode = objectMapper.createObjectNode();
    }
    definitionCacheObject.setInfoNode(infoNode);

    deploymentManager.getProcessDefinitionInfoCache().add(processDefinition.getId(), definitionCacheObject);
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Creates a list of JsonNodes containing the mapping for fields that will _enable_ or _disable_ field data depending on fielddata_info is present 
 *  (note this can convert a property to a dynamic template, but never the other way round)
 * @param instream/*from www . j a v  a2s . co m*/
 * @param f
 * @param field_lookups
 * @param fielddata_info 3tuple containing not_analyzed, analyzed, and override
 * @param mapper
 * @return
 */
protected static Stream<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>> createFieldLookups(
        final Stream<String> instream, final Function<String, Either<String, Tuple2<String, String>>> f,
        final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> field_lookups,
        final Optional<Tuple3<JsonNode, JsonNode, Boolean>> fielddata_info,
        final SearchIndexSchemaDefaultBean search_index_schema_override,
        final Map<Either<String, Tuple2<String, String>>, String> type_override, final ObjectMapper mapper,
        final String index_type) {
    return instream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>map(Lambdas.wrap_u(fn -> {
        final Either<String, Tuple2<String, String>> either_tmp = f.apply(fn);
        final Optional<String> maybe_type = Optional.ofNullable(type_override.get(either_tmp));

        // add type if present
        final Either<String, Tuple2<String, String>> either = maybe_type
                .<Either<String, Tuple2<String, String>>>map(type -> {
                    return either_tmp.<Either<String, Tuple2<String, String>>>either(s -> Either.left(s),
                            t2 -> Either.right(Tuples._2T(t2._1(), type)));
                }).orElse(either_tmp);

        final ObjectNode mutable_field_metadata = (ObjectNode) Optional.ofNullable(field_lookups.get(either))
                .map(j -> j.deepCopy())
                .orElse(either.either(Lambdas.wrap_fj_u(__ -> mapper.readTree(BACKUP_FIELD_MAPPING_PROPERTIES)),
                        Lambdas.wrap_fj_u(__ -> mapper.readTree(BACKUP_FIELD_MAPPING_TEMPLATES))));
        //(note that these 2 mappings don't have "type"s - therefore they will result in default_templates not properties - you need the type to generate a property)

        final ObjectNode mutable_field_mapping_tmp = either.isLeft() ? mutable_field_metadata
                : (ObjectNode) mutable_field_metadata.get("mapping");

        //(override with type if set)
        maybe_type.ifPresent(type -> mutable_field_mapping_tmp.put("type", type));

        final boolean has_type = mutable_field_mapping_tmp.has("type");

        final Tuple2<ObjectNode, Either<String, Tuple2<String, String>>> toplevel_eithermod = Lambdas
                .get(() -> {
                    if (either.isLeft() && !has_type) {
                        final ObjectNode top_level = (ObjectNode) mapper.createObjectNode().set("mapping",
                                mutable_field_metadata);
                        return Tuples._2T(top_level,
                                Either.<String, Tuple2<String, String>>right(Tuples._2T(fn, "*")));
                    } else { // right[dynamic] *OR* (left[properties] and has-type)
                        return Tuples._2T(mutable_field_metadata, either);
                    }
                });

        final ObjectNode mutable_field_mapping = toplevel_eithermod._2().isLeft() ? toplevel_eithermod._1()
                : (ObjectNode) toplevel_eithermod._1().get("mapping");

        // Special case ... if we're columnar and we're merging with tokenized and non-dual then convert to untokenized instead 
        if (fielddata_info.filter(t3 -> t3._3()).isPresent() && mutable_field_mapping.equals(
                mapper.convertValue(search_index_schema_override.tokenized_string_field(), JsonNode.class))) {
            mutable_field_mapping.removeAll();
            mutable_field_mapping.setAll((ObjectNode) mapper
                    .convertValue(search_index_schema_override.untokenized_string_field(), ObjectNode.class));
        }

        if (toplevel_eithermod._2().isRight()) {
            if (!toplevel_eithermod._1().has(PATH_MATCH_NAME) && !toplevel_eithermod._1().has(RAW_MATCH_NAME)) {
                toplevel_eithermod._1().put(PATH_MATCH_NAME, toplevel_eithermod._2().right().value()._1());

                if (!toplevel_eithermod._1().has(TYPE_MATCH_NAME))
                    toplevel_eithermod._1().put(TYPE_MATCH_NAME, toplevel_eithermod._2().right().value()._2());
            }
            if (!has_type) {
                if (toplevel_eithermod._2().right().value()._2().equals("*")) { // type is mandatory
                    mutable_field_mapping.put("type", "{dynamic_type}");
                } else {
                    mutable_field_mapping.put("type", toplevel_eithermod._2().right().value()._2());
                }
            }
        }
        handleMappingFields(mutable_field_mapping, fielddata_info, mapper, index_type);
        setMapping(mutable_field_mapping, fielddata_info, mapper, index_type);
        return Tuples._2T(toplevel_eithermod._2(), toplevel_eithermod._1());
    }));

}

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

@javax.ws.rs.Path("/graph")
@GET/*from w  w w . j a  v  a 2  s.c  o m*/
@Produces("application/json")
public Response graph() {
    ObjectMapper mapper = new ObjectMapper();

    // Fetch the services we'll be using.
    DeviceService deviceService = get(DeviceService.class);
    HostService hostService = get(HostService.class);
    TopologyService topologyService = get(TopologyService.class);

    // Fetch the current topology and its graph that we'll use to render.
    Topology topo = topologyService.currentTopology();
    TopologyGraph graph = topologyService.getGraph(topo);

    // Build all interior vertexes, i.e. no end-station hosts yet
    ArrayNode vertexesNode = mapper.createArrayNode();
    for (TopologyVertex vertex : graph.getVertexes()) {
        vertexesNode.add(json(mapper, vertex.deviceId(), 2, vertex.deviceId().uri().getSchemeSpecificPart(),
                deviceService.isAvailable(vertex.deviceId())));
    }

    // Now scan all links and count number of them between the same devices
    // using a normalized link key.
    Map<String, AggLink> linkRecords = aggregateLinks();

    // Now build all interior edges using the aggregated links.
    ArrayNode edgesNode = mapper.createArrayNode();
    for (AggLink lr : linkRecords.values()) {
        edgesNode.add(json(mapper, lr.links.size(), lr.link.src(), lr.link.dst()));
    }

    // Merge the exterior and interior vertexes and inject host links as
    // the exterior edges.
    for (Host host : hostService.getHosts()) {
        Set<IpAddress> ipAddresses = host.ipAddresses();
        IpAddress ipAddress = ipAddresses.isEmpty() ? null : ipAddresses.iterator().next();
        String label = ipAddress != null ? ipAddress.toString() : host.mac().toString();
        vertexesNode.add(json(mapper, host.id(), 3, label, true));
        edgesNode.add(json(mapper, 1, host.location(), new ConnectPoint(host.id(), portNumber(-1))));
    }

    // Now put the vertexes and edges into a root node and ship them off
    ObjectNode rootNode = mapper.createObjectNode();
    rootNode.set("vertexes", vertexesNode);
    rootNode.set("edges", edgesNode);
    return Response.ok(rootNode.toString()).build();
}

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

private JacksonDatabindHandle<ObjectNode> getJSONDocumentHandle(String startValidTime, String endValidTime,
        String address, String uri) throws Exception {

    // Setup for JSON document
    /**/*from w w w .  ja  v  a 2  s . c o m*/
     * 
     { "System": { systemStartERIName : "", systemEndERIName : "", }, "Valid":
     * { validStartERIName: "2001-01-01T00:00:00", validEndERIName:
     * "2011-12-31T23:59:59" }, "Address": "999 Skyway Park", "uri":
     * "javaSingleDoc1.json" }
     */

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode rootNode = mapper.createObjectNode();

    // Set system time values
    ObjectNode system = mapper.createObjectNode();

    system.put(systemStartERIName, "");
    system.put(systemEndERIName, "");
    rootNode.set(systemNodeName, system);

    // Set valid time values
    ObjectNode valid = mapper.createObjectNode();

    valid.put(validStartERIName, startValidTime);
    valid.put(validEndERIName, endValidTime);
    rootNode.set(validNodeName, valid);

    // Set Address
    rootNode.put(addressNodeName, address);

    // Set uri
    rootNode.put(uriNodeName, uri);

    System.out.println(rootNode.toString());

    JacksonDatabindHandle<ObjectNode> handle = new JacksonDatabindHandle<ObjectNode>(ObjectNode.class)
            .withFormat(Format.JSON);
    handle.set(rootNode);

    return handle;
}

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

private static void AddPublicIPResourceNode(final JsonNode template, final ObjectMapper mapper)
        throws IOException {

    final String ipName = "variables('vmName'), copyIndex(), 'IPName'";
    try (InputStream fragmentStream = AzureVMManagementServiceDelegate.class
            .getResourceAsStream(PUBLIC_IP_FRAGMENT_FILENAME)) {

        final JsonNode publicIPFragment = mapper.readTree(fragmentStream);
        // Add the virtual network fragment
        ArrayNode.class.cast(template.get("resources")).add(publicIPFragment);

        // Because we created/updated this in the template, we need to add the appropriate
        // dependsOn node to the networkInterface and the ipConfigurations properties
        // "[concat('Microsoft.Network/publicIPAddresses/', variables('vmName'), copyIndex(), 'IPName')]"
        // Find the network interfaces node
        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 v a 2  s  .  com
            // Find the dependsOn node
            ArrayNode dependsOnNode = ArrayNode.class.cast(resourcesNode.get("dependsOn"));
            // Add to the depends on node.
            dependsOnNode.add("[concat('Microsoft.Network/publicIPAddresses/'," + ipName + ")]");

            //Find the ipConfigurations/ipconfig1 node
            ArrayNode ipConfigurationsNode = ArrayNode.class
                    .cast(resourcesNode.get("properties").get("ipConfigurations"));
            Iterator<JsonNode> ipConfigNodeIter = ipConfigurationsNode.elements();
            while (ipConfigNodeIter.hasNext()) {
                JsonNode ipConfigNode = ipConfigNodeIter.next();
                JsonNode nameNode = ipConfigNode.get("name");
                if (nameNode == null || !nameNode.asText().equals("ipconfig1")) {
                    continue;
                }
                //find the properties node
                ObjectNode propertiesNode = ObjectNode.class.cast(ipConfigNode.get("properties"));
                //add the publicIPAddress node
                ObjectNode publicIPIdNode = mapper.createObjectNode();
                publicIPIdNode.put("id",
                        "[resourceId('Microsoft.Network/publicIPAddresses', concat(" + ipName + "))]");
                // propertiesNode.putObject("publicIPAddress").put
                propertiesNode.set("publicIPAddress", publicIPIdNode);
                break;
            }
            break;
        }
    }
}

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

protected ArrayNode buildReferencesArrayNode(final ObjectMapper objectMapper,
        final Map<URI, ObjectNode> schemaNodes, final Map<URI, LinkRelation> linkRelationCache,
        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 String defaultSchemaName = (defaultPrototype != null)
            ? defaultPrototype.getUniqueName().getLocalName()
            : null;/*from www . j a va 2s. com*/

    final ArrayNode referencesNode = objectMapper.createArrayNode();

    final ConcurrentHashMap<URI, LinkTemplate> referenceTemplates = resource.getReferenceTemplates();
    final Set<URI> referenceRelationUris = referenceTemplates.keySet();

    if (referenceTemplates != null && !referenceTemplates.isEmpty()) {

        String selfResponseSchemaName = null;

        List<String> resourceParameterList = null;
        final UriTemplate uriTemplate = resource.getUriTemplate();
        final String[] parameterNames = uriTemplate.getParameterNames();
        if (parameterNames != null && parameterNames.length > 0) {

            resourceParameterList = new ArrayList<>();

            for (int i = 0; i < parameterNames.length; i++) {
                final String parameterName = parameterNames[i];

                URI keyedSchemaUri = null;

                if (defaultPrototype != null) {
                    final Set<String> allKeySlotNames = defaultPrototype.getAllKeySlotNames();
                    if (allKeySlotNames != null && allKeySlotNames.contains(parameterName)) {
                        keyedSchemaUri = defaultSchemaUri;
                    }
                }

                if (keyedSchemaUri == null) {

                    final Set<URI> referenceLinkRelationUris = resource
                            .getReferenceLinkRelationUris(Method.Get);
                    if (referenceLinkRelationUris != null && !referenceLinkRelationUris.isEmpty()) {
                        for (URI linkRelationUri : referenceLinkRelationUris) {
                            final LinkTemplate referenceTemplate = referenceTemplates.get(linkRelationUri);
                            final URI responseSchemaUri = referenceTemplate.getResponseSchemaUri();
                            final Prototype responseSchemaPrototype = schemaLoader
                                    .getPrototype(responseSchemaUri);
                            if (responseSchemaPrototype != null) {
                                final Set<String> allKeySlotNames = responseSchemaPrototype
                                        .getAllKeySlotNames();
                                if (allKeySlotNames != null && allKeySlotNames.contains(parameterName)) {
                                    keyedSchemaUri = responseSchemaUri;
                                    break;
                                }
                            }
                        }
                    }
                }

                String parameterTypeString = "?";

                if (keyedSchemaUri != null) {

                    final Prototype keyedPrototype = schemaLoader.getPrototype(keyedSchemaUri);
                    final ProtoSlot keyProtoSlot = keyedPrototype.getProtoSlot(parameterName);
                    if (keyProtoSlot instanceof PropertyProtoSlot) {
                        final PropertyProtoSlot keyPropertyProtoSlot = (PropertyProtoSlot) keyProtoSlot;
                        final ValueType parameterValueType = keyPropertyProtoSlot.getValueType();
                        final Type parameterHeapType = keyPropertyProtoSlot.getHeapValueType();
                        switch (parameterValueType) {
                        case Text: {
                            if (!String.class.equals(parameterHeapType)) {
                                final Class<?> syntaxClass = (Class<?>) parameterHeapType;
                                parameterTypeString = syntaxClass.getSimpleName();
                            } else {
                                parameterTypeString = parameterValueType.name();
                            }

                            break;
                        }
                        case SingleSelect: {
                            final Class<?> choicesEnumClass = (Class<?>) parameterHeapType;

                            if (choicesEnumClass.isEnum()) {
                                parameterTypeString = choicesEnumClass.getSimpleName();
                            } else {
                                // ?
                                parameterTypeString = parameterValueType.name();
                            }

                            break;
                        }
                        default: {
                            parameterTypeString = parameterValueType.name();
                            break;
                        }
                        }
                    }

                }

                resourceParameterList.add(parameterTypeString + " " + parameterName);
            }
        }

        for (final Method method : Method.values()) {
            for (final URI linkRelationUri : referenceRelationUris) {

                final LinkTemplate referenceTemplate = referenceTemplates.get(linkRelationUri);
                final LinkRelation linkRelation = getLinkRelation(linkRelationCache, linkRelationUri);

                if (method != linkRelation.getMethod()) {
                    continue;
                }

                final ObjectNode referenceNode = objectMapper.createObjectNode();
                referencesNode.add(referenceNode);

                referenceNode.put(PropertyName.method.name(), method.getProtocolGivenName());
                referenceNode.put(PropertyName.rel.name(), syntaxLoader.formatSyntaxValue(linkRelationUri));

                final String relationTitle = linkRelation.getTitle();
                referenceNode.put(PropertyName.relationTitle.name(), relationTitle);

                final URI responseSchemaUri = referenceTemplate.getResponseSchemaUri();
                String responseSchemaName = null;
                if (responseSchemaUri != null) {
                    final ObjectNode responseSchemaNode = getSchemaNode(objectMapper, schemaNodes,
                            responseSchemaUri, schemaLoader);
                    referenceNode.put(PropertyName.responseSchema.name(), responseSchemaNode);

                    responseSchemaName = responseSchemaNode
                            .get(SchemaDesignFormatter.PropertyName.localName.name()).asText();
                }

                final URI requestSchemaUri = referenceTemplate.getRequestSchemaUri();

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

                    requestSchemaName = requestSchemaNode
                            .get(SchemaDesignFormatter.PropertyName.localName.name()).asText();
                }

                final StringBuilder signatureBuilder = new StringBuilder();

                if (responseSchemaName != null) {
                    signatureBuilder.append(responseSchemaName);
                } else {
                    signatureBuilder.append("void");
                }

                signatureBuilder.append(" ");

                String functionName = relationTitle;

                if (SystemLinkRelation.self.getUri().equals(linkRelationUri)) {
                    functionName = "get" + responseSchemaName;
                    selfResponseSchemaName = responseSchemaName;
                } else if (SystemLinkRelation.save.getUri().equals(linkRelationUri)) {
                    functionName = "save" + responseSchemaName;
                } else if (SystemLinkRelation.delete.getUri().equals(linkRelationUri)) {
                    functionName = "delete";
                    if (defaultSchemaName != null) {
                        functionName += defaultSchemaName;
                    } else if (selfResponseSchemaName != null) {
                        functionName += selfResponseSchemaName;
                    }
                }

                signatureBuilder.append(functionName).append(" ( ");

                String parameterString = null;
                if (resourceParameterList != null) {
                    final StringBuilder parameterStringBuilder = new StringBuilder();
                    final int parameterCount = resourceParameterList.size();
                    for (int i = 0; i < parameterCount; i++) {
                        final String parameter = resourceParameterList.get(i);
                        parameterStringBuilder.append(parameter);
                        if (i < parameterCount - 1) {
                            parameterStringBuilder.append(" , ");
                        }
                    }

                    parameterString = parameterStringBuilder.toString();
                    signatureBuilder.append(parameterString);
                }

                if (requestSchemaName != null) {
                    if (StringUtils.isNotBlank(parameterString)) {
                        signatureBuilder.append(" , ");
                    }

                    signatureBuilder.append(requestSchemaName);

                    signatureBuilder.append(" ");

                    final String parameterName = Character.toLowerCase(requestSchemaName.charAt(0))
                            + requestSchemaName.substring(1);
                    signatureBuilder.append(parameterName);
                }

                signatureBuilder.append(" ) ");

                final String signature = signatureBuilder.toString();
                referenceNode.put(PropertyName.signature.name(), signature);
            }

        }

    }

    return referencesNode;
}