Example usage for com.fasterxml.jackson.databind JsonNode asText

List of usage examples for com.fasterxml.jackson.databind JsonNode asText

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode asText.

Prototype

public abstract String asText();

Source Link

Usage

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

/**
 * Recursively builds DOM content out of JSON subtree rooted at given node.
 *
 * @param client OData client.// www.j  ava 2 s  . c  o  m
 * @param document root of the DOM document being built
 * @param parent parent of the nodes being generated during this step
 * @param node JSON node to be used as source for DOM elements
 */
public static void buildSubtree(final ODataClient client, final Element parent, final JsonNode node) {
    final Iterator<String> fieldNameItor = node.fieldNames();
    final Iterator<JsonNode> nodeItor = node.elements();
    while (nodeItor.hasNext()) {
        final JsonNode child = nodeItor.next();
        final String name = fieldNameItor.hasNext() ? fieldNameItor.next() : "";

        // no name? array item
        if (name.isEmpty()) {
            final Element element = parent.getOwnerDocument().createElementNS(
                    client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES),
                    ODataConstants.PREFIX_DATASERVICES + ODataConstants.ELEM_ELEMENT);
            parent.appendChild(element);

            if (child.isValueNode()) {
                if (child.isNull()) {
                    element.setAttributeNS(
                            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                            ODataConstants.ATTR_NULL, Boolean.toString(true));
                } else {
                    element.appendChild(parent.getOwnerDocument().createTextNode(child.asText()));
                }
            }

            if (child.isContainerNode()) {
                buildSubtree(client, element, child);
            }
        } else if (!name.contains("@") && !ODataConstants.JSON_TYPE.equals(name)) {
            final Element property = parent.getOwnerDocument().createElementNS(
                    client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES),
                    ODataConstants.PREFIX_DATASERVICES + name);
            parent.appendChild(property);

            boolean typeSet = false;
            if (node.hasNonNull(name + "@" + ODataConstants.JSON_TYPE)) {
                property.setAttributeNS(
                        client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                        ODataConstants.ATTR_M_TYPE,
                        node.get(name + "@" + ODataConstants.JSON_TYPE).textValue());
                typeSet = true;
            }

            if (child.isNull()) {
                property.setAttributeNS(
                        client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                        ODataConstants.ATTR_NULL, Boolean.toString(true));
            } else if (child.isValueNode()) {
                if (!typeSet) {
                    if (child.isInt()) {
                        property.setAttributeNS(
                                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                                ODataConstants.ATTR_M_TYPE, EdmSimpleType.Int32.toString());
                    }
                    if (child.isLong()) {
                        property.setAttributeNS(
                                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                                ODataConstants.ATTR_M_TYPE, EdmSimpleType.Int64.toString());
                    }
                    if (child.isBigDecimal()) {
                        property.setAttributeNS(
                                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                                ODataConstants.ATTR_M_TYPE, EdmSimpleType.Decimal.toString());
                    }
                    if (child.isDouble()) {
                        property.setAttributeNS(
                                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                                ODataConstants.ATTR_M_TYPE, EdmSimpleType.Double.toString());
                    }
                    if (child.isBoolean()) {
                        property.setAttributeNS(
                                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                                ODataConstants.ATTR_M_TYPE, EdmSimpleType.Boolean.toString());
                    }
                    if (child.isTextual()) {
                        property.setAttributeNS(
                                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                                ODataConstants.ATTR_M_TYPE, EdmSimpleType.String.toString());
                    }
                }

                property.appendChild(parent.getOwnerDocument().createTextNode(child.asText()));
            } else if (child.isContainerNode()) {
                if (!typeSet && child.hasNonNull(ODataConstants.JSON_TYPE)) {
                    property.setAttributeNS(
                            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                            ODataConstants.ATTR_M_TYPE, child.get(ODataConstants.JSON_TYPE).textValue());
                }

                final String type = property.getAttribute(ODataConstants.ATTR_M_TYPE);
                if (StringUtils.isNotBlank(type) && EdmSimpleType.isGeospatial(type)) {
                    if (EdmSimpleType.Geography.toString().equals(type)
                            || EdmSimpleType.Geometry.toString().equals(type)) {

                        final String geoType = child.get(ODataConstants.ATTR_TYPE).textValue();
                        property.setAttributeNS(
                                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA),
                                ODataConstants.ATTR_M_TYPE,
                                geoType.startsWith("Geo") ? EdmSimpleType.namespace() + "." + geoType
                                        : type + geoType);
                    }

                    if (child.has(ODataConstants.JSON_COORDINATES)
                            || child.has(ODataConstants.JSON_GEOMETRIES)) {
                        GeospatialJSONHandler.deserialize(child, property,
                                property.getAttribute(ODataConstants.ATTR_M_TYPE));
                    }
                } else {
                    buildSubtree(client, property, child);
                }
            }
        }
    }
}

From source file:com.reprezen.swagedit.json.references.JsonReferenceFactory.java

public JsonReference create(JsonNode node) {
    if (node == null || node.isMissingNode()) {
        return new JsonReference(null, null, false, false, false, node);
    }/*from  www .j a v a 2s . c o  m*/

    String text = node.isTextual() ? node.asText() : node.get(PROPERTY).asText();

    return doCreate(text, node);
}

From source file:de.thingweb.client.ClientFactory.java

protected Client pickClient() throws UnsupportedException, URISyntaxException {
    // check for right protocol&encoding
    List<Client> clients = new ArrayList<>(); // it is assumed URIs are ordered by priority

    JsonNode uris = thing.getMetadata().get("uris");
    if (uris != null) {
        if (uris.getNodeType() == JsonNodeType.STRING) {
            checkUri(uris.asText(), clients);
        } else if (uris.getNodeType() == JsonNodeType.ARRAY) {
            ArrayNode an = (ArrayNode) uris;
            for (int i = 0; i < an.size(); i++) {
                checkUri(an.get(i).asText(), i, clients);
            }// w  w w.j a v  a2  s  .com
        }

        // int prio = 1;
        //      for (JsonNode juri : uris) {
        //       String suri = juri.asText();
        //        URI uri = new URI(suri);
        //        if(isCoapScheme(uri.getScheme())) {
        //          clients.add(new CoapClientImpl(suri, thing));
        //          log.info("Found matching client '" + CoapClientImpl.class.getName() + "' with priority " + prio++);
        //        } else if(isHttpScheme(uri.getScheme())) {
        //          clients.add(new HttpClientImpl(suri, thing));
        //          log.info("Found matching client '" + HttpClientImpl.class.getName() + "' with priority " + prio++);
        //        } 
        //      }
    }

    // take priority into account
    if (clients.isEmpty()) {
        log.warn("No fitting client implementation found!");
        throw new UnsupportedException("No fitting client implementation found!");
        // return null;
    } else {
        // pick first one with highest priority
        Client c = clients.get(0);
        log.info("Use '" + c.getClass().getName() + "' according to priority");
        return c;
    }

}

From source file:com.activiti.service.activiti.TaskService.java

/**
 * @return true, if the task was deleted. False, if deleting the task failed.
 *///from  www .j a v  a  2 s  . c  om
public void deleteTask(ServerConfig serverConfig, String taskId) {
    if (taskId == null) {
        throw new IllegalArgumentException("Task id is required");
    }

    JsonNode taskNode = getTask(serverConfig, taskId, false);
    if (taskNode.has("endTime")) {

        JsonNode endTimeNode = taskNode.get("endTime");
        if (endTimeNode != null && !endTimeNode.isNull() && StringUtils.isNotEmpty(endTimeNode.asText())) {

            // Completed task
            URIBuilder builder = clientUtil.createUriBuilder(MessageFormat.format(HISTORIC_TASK_URL, taskId));
            HttpDelete delete = new HttpDelete(clientUtil.getServerUrl(serverConfig, builder));
            clientUtil.executeRequestNoResponseBody(delete, serverConfig, HttpStatus.SC_NO_CONTENT);

        } else {

            // Not completed task
            URIBuilder builder = clientUtil
                    .createUriBuilder(MessageFormat.format(RUNTIME_TASK_URL, taskId) + "?cascadeHistory=true");
            HttpDelete delete = new HttpDelete(clientUtil.getServerUrl(serverConfig, builder));
            clientUtil.executeRequestNoResponseBody(delete, serverConfig, HttpStatus.SC_NO_CONTENT);

        }
    }

}

From source file:org.springframework.data.rest.webmvc.json.patch.JsonPatchPatchConverter.java

private Object valueFromJsonNode(String path, JsonNode valueNode) {
    if (valueNode == null || valueNode.isNull()) {
        return null;
    } else if (valueNode.isTextual()) {
        return valueNode.asText();
    } else if (valueNode.isFloatingPointNumber()) {
        return valueNode.asDouble();
    } else if (valueNode.isBoolean()) {
        return valueNode.asBoolean();
    } else if (valueNode.isInt()) {
        return valueNode.asInt();
    } else if (valueNode.isLong()) {
        return valueNode.asLong();
    } else if (valueNode.isObject()) {
        return new JsonLateObjectEvaluator(valueNode);
    } else if (valueNode.isArray()) {
        // TODO: Convert valueNode to array
    }/*from   ww  w  . ja va  2s .c  o  m*/

    return null;
}

From source file:com.googlecode.jsonschema2pojo.rules.ObjectRule.java

private void addInterfaces(JDefinedClass jclass, JsonNode javaInterfaces) {
    for (JsonNode i : javaInterfaces) {
        jclass._implements(jclass.owner().ref(i.asText()));
    }// w w  w  . j  a  v a2  s  .  co m
}

From source file:org.keycloak.authz.server.services.common.KeycloakIdentity.java

@Override
public Attributes getAttributes() {
    HashMap<String, Collection<String>> attributes = new HashMap<>();

    try {/*from  ww w. j  a  v a  2s. c  o m*/
        ObjectNode objectNode = JsonSerialization.createObjectNode(this.accessToken);
        Iterator<String> iterator = objectNode.fieldNames();
        List<String> roleNames = new ArrayList<>();

        while (iterator.hasNext()) {
            String fieldName = iterator.next();
            JsonNode fieldValue = objectNode.get(fieldName);
            List<String> values = new ArrayList<>();

            values.add(fieldValue.asText());

            if (fieldName.equals("realm_access")) {
                JsonNode grantedRoles = fieldValue.get("roles");

                if (grantedRoles != null) {
                    Iterator<JsonNode> rolesIt = grantedRoles.iterator();

                    while (rolesIt.hasNext()) {
                        roleNames.add(rolesIt.next().asText());
                    }
                }
            }

            if (fieldName.equals("resource_access")) {
                Iterator<JsonNode> resourceAccessIt = fieldValue.iterator();

                while (resourceAccessIt.hasNext()) {
                    JsonNode grantedRoles = resourceAccessIt.next().get("roles");

                    if (grantedRoles != null) {
                        Iterator<JsonNode> rolesIt = grantedRoles.iterator();

                        while (rolesIt.hasNext()) {
                            roleNames.add(rolesIt.next().asText());
                        }
                    }
                }
            }

            attributes.put(fieldName, values);
        }

        attributes.put("roles", roleNames);
    } catch (Exception e) {
        throw new RuntimeException("Error while reading attributes from security token.", e);
    }

    return Attributes.from(attributes);
}

From source file:io.fabric8.kubernetes.api.KubernetesHelper.java

/**
 * Returns the given json data as a DTO such as
 * {@link Pod}, {@link ReplicationController} or
 * {@link io.fabric8.kubernetes.api.model.Service}
 * from the Kubernetes REST API or/*from w  w w . j  a  va 2s  .c o  m*/
 * {@link JsonNode} if it cannot be recognised.
 */
public static Object loadJson(byte[] json) throws IOException {
    if (json != null && json.length > 0) {
        ObjectReader reader = objectMapper.reader();
        JsonNode tree = reader.readTree(new ByteArrayInputStream(json));
        if (tree != null) {
            JsonNode kindNode = tree.get("kind");
            if (kindNode != null) {
                String kind = kindNode.asText();
                return loadEntity(json, kind, tree);
            } else {
                LOG.warn("No JSON type for: " + tree);
            }
            return tree;
        }
    }
    return null;
}

From source file:com.epam.catgenome.manager.externaldb.ncbi.NCBIGeneManager.java

private void parseJsonFromHomolog(JsonNode homologsResultRoot, JsonNode homologEntries, NCBIGeneVO ncbiGeneVO)
        throws JsonProcessingException {
    if (homologsResultRoot.isArray() && homologsResultRoot.size() != 0) {
        final JsonNode objNode = homologsResultRoot.get(0);
        JsonNode jsonNode = homologEntries.path(RESULT_PATH).get("" + objNode.asText());
        NCBISummaryVO summary = mapper.treeToValue(jsonNode, NCBISummaryVO.class);
        ncbiGeneVO.setLinkToHomologsCitations(String.format(NCBI_PUBMED_HOMOLOG_URL, summary.getUid()));
    }//from  w  ww .  j a  v a 2 s  .c om
}

From source file:org.flowable.app.service.idm.RemoteIdmServiceImpl.java

protected RemoteUser parseUserInfo(JsonNode json) {
    RemoteUser user = new RemoteUser();
    user.setId(json.get("id").asText());
    user.setFirstName(json.get("firstName").asText());
    user.setLastName(json.get("lastName").asText());
    user.setEmail(json.get("email").asText());
    user.setFullName(json.get("fullName").asText());

    if (json.has("groups")) {
        for (JsonNode groupNode : ((ArrayNode) json.get("groups"))) {
            user.getGroups().add(new RemoteGroup(groupNode.get("id").asText(), groupNode.get("name").asText()));
        }//from w w  w .ja v a2 s .co  m
    }

    if (json.has("privileges")) {
        for (JsonNode privilegeNode : ((ArrayNode) json.get("privileges"))) {
            user.getPrivileges().add(privilegeNode.asText());
        }
    }

    return user;
}