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.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   w w  w . jav  a  2 s  . c om*/

    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.crushpaper.JsonNodeHelper.java

/**
 * Returns the string value for the key, null if it does not exist, or
 * throws an exception if the value is not a string.
 * //from  w  ww . j av  a  2s.  c o m
 * @throws IOException
 */
public String getString(String key) throws IOException {
    JsonNode value = node.get(key);
    if (value == null) {
        return null;
    }

    if (!value.isTextual()) {
        throw new IOException();
    }

    return value.asText();
}

From source file:com.redhat.lightblue.config.rdbms.RDBMSDataSourceConfiguration.java

@Override
public void initializeFromJson(JsonNode node) {
    if (node != null) {
        JsonNode x = node.get("metadataDataStoreParser");
        try {/*from www.  j av a 2 s .  c  o m*/
            if (x != null) {
                metadataDataStoreParser = Class.forName(x.asText());
            }
        } catch (Exception e) {
            throw new IllegalArgumentException(node.toString() + ":" + e);
        }
        x = node.get("database");
        if (x != null) {
            databaseName = x.asText();
        }
        JsonNode jsonNodeServers = node.get("connections");
        if (jsonNodeServers != null && jsonNodeServers.isArray()) {
            Iterator<JsonNode> elements = jsonNodeServers.elements();
            while (elements.hasNext()) {
                JsonNode next = elements.next();
                String datasourceName;
                String JNDI;
                x = next.get("datasourceName");
                if (x != null) {
                    datasourceName = x.asText();
                } else {
                    throw new IllegalStateException("No datasourceName was found: " + node.toString());
                }

                x = next.get("JNDI");
                if (x != null) {
                    JNDI = x.asText();
                } else {
                    throw new IllegalStateException("No JNDI was found: " + node.toString());
                }
                dataSourceJDNIMap.put(datasourceName, JNDI);
            }
        } else {
            throw new IllegalStateException("No connection was found: " + node.toString());
        }
    }
}

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

/**
 * Loads the entity for the given item/*from  ww w  .j av a  2 s.  c  o m*/
 */
public static Object getEntity(JsonNode item) throws IOException {
    if (item != null) {
        JsonNode kindObject = item.get("kind");
        if (kindObject != null && kindObject.isTextual()) {
            String kind = kindObject.asText();
            if (kind != null) {
                String json = toJson(item);
                byte[] bytes = json.getBytes();
                Object entity = loadEntity(bytes, kind, null);
                return entity;
            }
        }
    }
    return null;
}

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

/**
 * Applies this schema rule to take the required code generation steps.
 * <p>/*from   w ww. ja  va  2 s .  c  o  m*/
 * Default values are implemented by assigning an expression to the given
 * field (so when instances of the generated POJO are created, its fields
 * will then contain their default values).
 * <p>
 * Collections (Lists and Sets) are initialized to an empty collection, even
 * when no default value is present in the schema (node is null).
 * 
 * @param nodeName
 *            the name of the property which has (or may have) a default
 * @param node
 *            the default node (may be null if no default node was present
 *            for this property)
 * @param field
 *            the Java field that has added to a generated type to represent
 *            this property
 * @return field, which will have an init expression is appropriate
 */
@Override
public JFieldVar apply(String nodeName, JsonNode node, JFieldVar field, Schema currentSchema) {

    boolean defaultPresent = node != null && isNotEmpty(node.asText());

    String fieldType = field.type().fullName();

    if (fieldType.startsWith(List.class.getName())) {
        field.init(getDefaultList(field.type(), node));

    } else if (fieldType.startsWith(Set.class.getName())) {
        field.init(getDefaultSet(field.type(), node));

    } else if (defaultPresent) {
        field.init(getDefaultValue(field.type(), node));

    }

    return field;
}

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

private JExpression getDefaultEnum(JType fieldType, JsonNode node) {

    JInvocation invokeFromValue = ((JClass) fieldType).staticInvoke("fromValue");
    invokeFromValue.arg(node.asText());

    return invokeFromValue;

}

From source file:org.dawnsci.persistence.json.JacksonMarshaller.java

@Override
public Object unmarshal(String json) throws Exception {
    // read JSON like DOM Parser
    JsonNode rootNode = mapper.readTree(json);
    JsonNode typeNode = rootNode.path("type");
    if (typeNode == null) // if no type we return an Object
        return mapper.readValue(json, Object.class);
    if (typeNode.asText() == null)
        return mapper.readValue(json, Object.class);

    String type = typeNode.asText();
    // if the ROI keyword is present we assume the data is a roi
    if (type.contains("ROI")) {
        // Return the corresponding ROIBean class name
        Class<?> clazz = ROIBeanFactory.getClass(type);
        Object bean = mapper.readValue(json, clazz);
        return ROIBeanFactory.decapsulate(bean);
    }//from   www.  j  a  v a  2  s . c  om
    // if the function keyword is present we assume the data is a function
    if (type.contains("function")) {
        if (PersistenceUtils.getInstance(type) instanceof IOperator) {
            FunctionListBean fbean = mapper.readValue(json, FunctionListBean.class);
            return fbean.getIFunction();
        } else {
            FunctionBean fbean = mapper.readValue(json, FunctionBean.class);
            return fbean.getIFunction();
        }
    }
    return null;
}

From source file:com.jaredjstewart.SampleSecurityManager.java

private void readUsers(final Map<String, User> rolesToUsers, final JsonNode node,
        final Map<String, Role> roleMap) {
    for (JsonNode usersNode : node.get("users")) {
        User user = new User();
        user.name = usersNode.get("name").asText();

        if (usersNode.has("password")) {
            user.password = usersNode.get("password").asText();
        } else {//  w w w.jav a 2 s.c o m
            user.password = user.name;
        }

        for (JsonNode rolesNode : usersNode.get("roles")) {
            user.roles.add(roleMap.get(rolesNode.asText()));
        }

        rolesToUsers.put(user.name, user);
    }
}

From source file:com.redhat.lightblue.config.DataSourcesConfiguration.java

@Override
public final void initializeFromJson(JsonNode node) {
    // Node must be an object node
    if (node instanceof ObjectNode) {
        for (Iterator<Map.Entry<String, JsonNode>> fieldItr = node.fields(); fieldItr.hasNext();) {
            Map.Entry<String, JsonNode> field = fieldItr.next();
            String name = field.getKey();
            JsonNode dsNode = field.getValue();
            LOGGER.debug("Parsing {}", name);
            JsonNode typeNode = dsNode.get("type");
            if (typeNode == null) {
                throw new IllegalArgumentException("type expected in " + name);
            }/* w  w w .j  a v a2s .co m*/
            String type = typeNode.asText();
            LOGGER.debug("{} is a {}", name, type);
            try {
                Class clazz = Class.forName(type);
                DataSourceConfiguration ds = (DataSourceConfiguration) clazz.newInstance();
                ds.initializeFromJson(dsNode);
                datasources.put(name, ds);
            } catch (Exception e) {
                throw new IllegalArgumentException(dsNode + ":" + e);
            }
        }
    } else {
        throw new IllegalArgumentException("node must be instanceof ObjectNode: " + node.toString());
    }
}

From source file:org.jsonschema2pojo.rules.EnumRule.java

private void addInterfaces(JDefinedClass jclass, JsonNode javaInterfaces) {
    for (JsonNode i : javaInterfaces) {
        jclass._implements(resolveType(jclass._package(), i.asText()));
    }/*from  w w  w  . j a v  a  2s  . c o  m*/
}