Example usage for com.fasterxml.jackson.databind.node ObjectNode ObjectNode

List of usage examples for com.fasterxml.jackson.databind.node ObjectNode ObjectNode

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node ObjectNode ObjectNode.

Prototype

ObjectNode

Source Link

Usage

From source file:com.msopentech.odatajclient.engine.data.impl.JSONPropertyDeserializer.java

@Override
protected JSONProperty doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);

    final JSONProperty property = new JSONProperty();

    if (tree.hasNonNull(ODataConstants.JSON_METADATA)) {
        property.setMetadata(URI.create(tree.get(ODataConstants.JSON_METADATA).textValue()));
        tree.remove(ODataConstants.JSON_METADATA);
    }/*from   www.ja  v  a  2 s.  c  o  m*/

    try {
        final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
        final Document document = builder.newDocument();

        Element content = document.createElement(ODataConstants.ELEM_PROPERTY);

        if (property.getMetadata() != null) {
            final String metadataURI = property.getMetadata().toASCIIString();
            final int dashIdx = metadataURI.lastIndexOf('#');
            if (dashIdx != -1) {
                content.setAttribute(ODataConstants.ATTR_M_TYPE, metadataURI.substring(dashIdx + 1));
            }
        }

        JsonNode subtree = null;
        if (tree.has(ODataConstants.JSON_VALUE)) {
            if (tree.has(ODataConstants.JSON_TYPE)
                    && StringUtils.isBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {

                content.setAttribute(ODataConstants.ATTR_M_TYPE, tree.get(ODataConstants.JSON_TYPE).asText());
            }

            final JsonNode value = tree.get(ODataConstants.JSON_VALUE);
            if (value.isValueNode()) {
                content.appendChild(document.createTextNode(value.asText()));
            } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                subtree = tree.objectNode();
                ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE, tree.get(ODataConstants.JSON_VALUE));
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE + "@" + ODataConstants.JSON_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
            } else {
                subtree = tree.get(ODataConstants.JSON_VALUE);
            }
        } else {
            subtree = tree;
        }

        if (subtree != null) {
            JSONDOMTreeUtils.buildSubtree(client, content, subtree);
        }

        final List<Node> children = XMLUtils.getChildNodes(content, Node.ELEMENT_NODE);
        if (children.size() == 1) {
            final Element value = (Element) children.iterator().next();
            if (ODataConstants.JSON_VALUE.equals(XMLUtils.getSimpleName(value))) {
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    value.setAttribute(ODataConstants.ATTR_M_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
                content = value;
            }
        }

        property.setContent(content);
    } catch (ParserConfigurationException e) {
        throw new JsonParseException("Cannot build property", parser.getCurrentLocation(), e);
    }

    return property;
}

From source file:com.msopentech.odatajclient.engine.data.json.JSONPropertyDeserializer.java

@Override
protected JSONProperty doDeserializeV3(final JsonParser parser, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);

    final JSONProperty property = new JSONProperty();

    if (tree.hasNonNull(ODataConstants.JSON_METADATA)) {
        property.setMetadata(URI.create(tree.get(ODataConstants.JSON_METADATA).textValue()));
        tree.remove(ODataConstants.JSON_METADATA);
    }/*  w  w w.j  a v a 2  s.  c o  m*/

    try {
        final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
        final Document document = builder.newDocument();

        Element content = document.createElement(ODataConstants.ELEM_PROPERTY);

        if (property.getMetadata() != null) {
            final String metadataURI = property.getMetadata().toASCIIString();
            final int dashIdx = metadataURI.lastIndexOf('#');
            if (dashIdx != -1) {
                content.setAttribute(ODataConstants.ATTR_M_TYPE, metadataURI.substring(dashIdx + 1));
            }
        }

        JsonNode subtree = null;
        if (tree.has(ODataConstants.JSON_VALUE)) {
            if (tree.has(ODataConstants.JSON_TYPE)
                    && StringUtils.isBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {

                content.setAttribute(ODataConstants.ATTR_M_TYPE, tree.get(ODataConstants.JSON_TYPE).asText());
            }

            final JsonNode value = tree.get(ODataConstants.JSON_VALUE);
            if (value.isValueNode()) {
                content.appendChild(document.createTextNode(value.asText()));
            } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                subtree = tree.objectNode();
                ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE, tree.get(ODataConstants.JSON_VALUE));
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE + "@" + ODataConstants.JSON_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
            } else {
                subtree = tree.get(ODataConstants.JSON_VALUE);
            }
        } else {
            subtree = tree;
        }

        if (subtree != null) {
            DOMTreeUtilsV3.buildSubtree(content, subtree);
        }

        final List<Node> children = XMLUtils.getChildNodes(content, Node.ELEMENT_NODE);
        if (children.size() == 1) {
            final Element value = (Element) children.iterator().next();
            if (ODataConstants.JSON_VALUE.equals(XMLUtils.getSimpleName(value))) {
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    value.setAttribute(ODataConstants.ATTR_M_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
                content = value;
            }
        }

        property.setContent(content);
    } catch (ParserConfigurationException e) {
        throw new JsonParseException("Cannot build property", parser.getCurrentLocation(), e);
    }

    return property;
}

From source file:org.apache.taverna.scufl2.translator.t2flow.defaultactivities.BeanshellActivityParser.java

@Override
public Configuration parseConfiguration(T2FlowParser t2FlowParser, ConfigBean configBean,
        ParserState parserState) throws ReaderException {
    BeanshellConfig beanshellConfig = unmarshallConfig(t2FlowParser, configBean, "xstream",
            BeanshellConfig.class);

    Configuration configuration = new Configuration();
    configuration.setParent(parserState.getCurrentProfile());

    ObjectNode json = (ObjectNode) configuration.getJson();
    configuration.setType(ACTIVITY_URI.resolve("#Config"));

    if (beanshellConfig.getLocalworkerName() != null) {
        URI localWorkerURI = LOCAL_WORKER_URI
                .resolve(uriTools.validFilename(beanshellConfig.getLocalworkerName()));
        /*/* w  ww  . j a  v  a 2 s. c  o  m*/
         * FIXME: As we can't read the annotation chain yet, we can't tell
         * whether this local worker has been edited or not, and so can't
         * use #definedBy
         */
        json.put("derivedFrom", localWorkerURI.toString());
    }

    String script = beanshellConfig.getScript();
    json.put("script", script);

    ClassLoaderSharing classLoaderSharing = beanshellConfig.getClassLoaderSharing();
    if (classLoaderSharing == ClassLoaderSharing.SYSTEM)
        json.put("classLoaderSharing", "system");
    else {
        // default is "workflow" but don't need to be expressed
        //          json.put("classLoaderSharing", "workflow");
    }

    if (beanshellConfig.getLocalDependencies() != null) {
        ArrayNode dependencies = json.arrayNode();
        for (String localDep : beanshellConfig.getLocalDependencies().getString())
            dependencies.add(localDep);
        if (dependencies.size() > 0)
            json.put("localDependency", dependencies);
    }

    /*
     * Note: Maven Dependencies are not supported by Taverna 3 - only here
     * for informational purposes and potential t2flow->t2flow scenarios
     */
    if (beanshellConfig.getArtifactDependencies() != null) {
        ArrayNode dependencies = json.arrayNode();
        for (BasicArtifact mavenDep : beanshellConfig.getArtifactDependencies()
                .getNetSfTavernaRavenRepositoryBasicArtifact()) {
            ObjectNode mavenDependency = json.objectNode();
            dependencies.add(mavenDependency);
            mavenDependency.put("groupId", mavenDep.getGroupId());
            mavenDependency.put("artifactId", mavenDep.getArtifactId());
            mavenDependency.put("version", mavenDep.getVersion());
        }
        if (dependencies.size() > 0)
            json.put("mavenDependency", dependencies);
    }

    Activity activity = parserState.getCurrentActivity();
    activity.getInputPorts().clear();
    activity.getOutputPorts().clear();
    for (ActivityPortDefinitionBean portBean : beanshellConfig.getInputs()
            .getNetSfTavernaT2WorkflowmodelProcessorActivityConfigActivityInputPortDefinitionBean())
        parseAndAddInputPortDefinition(portBean, configuration, activity);
    for (ActivityPortDefinitionBean portBean : beanshellConfig.getOutputs()
            .getNetSfTavernaT2WorkflowmodelProcessorActivityConfigActivityOutputPortDefinitionBean())
        parseAndAddOutputPortDefinition(portBean, configuration, activity);
    return configuration;
}

From source file:de.thomaskrille.dropwizard.environment_configuration.EnvironmentConfigurationFactory.java

private void addOverride(JsonNode root, String name, String value) {
    JsonNode node = root;//from w ww. ja  v  a  2s  . c om
    final Iterable<String> split = Splitter.on('.').trimResults().split(name);
    final String[] parts = Iterables.toArray(split, String.class);

    for (int i = 0; i < parts.length; i++) {
        String key = parts[i];

        if (!(node instanceof ObjectNode)) {
            throw new IllegalArgumentException("Unable to override " + name + "; it's not a valid path.");
        }
        final ObjectNode obj = (ObjectNode) node;

        final String remainingPath = Joiner.on('.').join(Arrays.copyOfRange(parts, i, parts.length));
        if (obj.has(remainingPath) && !remainingPath.equals(key)) {
            if (obj.get(remainingPath).isValueNode()) {
                obj.put(remainingPath, value);
                return;
            }
        }

        JsonNode child;
        final boolean moreParts = i < parts.length - 1;

        if (key.matches(".+\\[\\d+\\]$")) {
            final int s = key.indexOf('[');
            final int index = Integer.parseInt(key.substring(s + 1, key.length() - 1));
            key = key.substring(0, s);
            child = obj.get(key);
            if (child == null) {
                throw new IllegalArgumentException(
                        "Unable to override " + name + "; node with index not found.");
            }
            if (!child.isArray()) {
                throw new IllegalArgumentException(
                        "Unable to override " + name + "; node with index is not an array.");
            } else if (index >= child.size()) {
                throw new ArrayIndexOutOfBoundsException(
                        "Unable to override " + name + "; index is greater than size of array.");
            }
            if (moreParts) {
                child = child.get(index);
                node = child;
            } else {
                ArrayNode array = (ArrayNode) child;
                array.set(index, TextNode.valueOf(value));
                return;
            }
        } else if (moreParts) {
            child = obj.get(key);
            if (child == null) {
                child = obj.objectNode();
                obj.put(key, child);
            }
            if (child.isArray()) {
                throw new IllegalArgumentException(
                        "Unable to override " + name + "; target is an array but no index specified");
            }
            node = child;
        }

        if (!moreParts) {
            if (node.get(key) != null && node.get(key).isArray()) {
                ArrayNode arrayNode = (ArrayNode) obj.get(key);
                arrayNode.removeAll();
                Pattern escapedComma = Pattern.compile("\\\\,");
                for (String val : Splitter.on(Pattern.compile("(?<!\\\\),")).trimResults().split(value)) {
                    arrayNode.add(escapedComma.matcher(val).replaceAll(","));
                }
            } else {
                obj.put(key, value);
            }
        }
    }
}

From source file:org.apache.taverna.scufl2.translator.t2flow.T2FlowParser.java

protected void parseDispatchStack(DispatchLayer dispatchLayer) throws ReaderException {
    URI typeUri = mapTypeFromRaven(dispatchLayer.getRaven(), dispatchLayer.getClazz());
    ObjectNode procConfig = parserState.get().getCurrentConfiguration().getJsonAsObjectNode();

    try {//  w  w  w  . jav a2s . c om
        Configuration dispatchConfig = parseConfiguration(dispatchLayer.getConfigBean());
        URI relUri = INTERNAL_DISPATCH_PREFIX.relativize(typeUri);
        String name;
        if (!relUri.isAbsolute()) {
            /*
             * It's an internal layer. We'll put it under the name which
             * we'll cleverly fish out of the URI path, eg. "retry" or
             * "parallelize"
             */
            name = relUri.getPath().toLowerCase();
            if (dispatchConfig != null && dispatchConfig.getJson().size() > 0)
                // But only if non-empty (non-default)
                procConfig.put(name, dispatchConfig.getJson());
        } else {
            ObjectNode json;
            if (dispatchConfig != null && dispatchConfig.getJson().isObject())
                json = dispatchConfig.getJsonAsObjectNode();
            else {
                /*
                 * We'll still need to create an objectNode to keep _type
                 * and _below
                 */
                json = procConfig.objectNode();
                if (dispatchConfig != null)
                    // We'll put the non-objectnode here
                    json.put("_config", dispatchConfig.getJson());
            }

            /*
             * Not really much to go from here, we don't want to use the
             * typeUri as the name as third-party layers in theory could be
             * added several times for same type
             */
            name = randomUUID().toString();
            json.put("_type", typeUri.toString());
            // Might be null - meaning "top"
            json.put("_below", parserState.get().getPreviousDispatchLayerName());
            procConfig.put(name, json);
        }
        parserState.get().setPreviousDispatchLayerName(name);
    } catch (JAXBException ex) {
        String message = "Can't parse configuration for dispatch layer in "
                + parserState.get().getCurrentProcessor();
        if (isStrict())
            throw new ReaderException(message, ex);
        logger.log(WARNING, message, ex);
    }
}