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.okta.tools.awscli.java

private static String ProcessPolicyDocument(String policyDoc) {

    String strRoleToAssume = null;
    try {/* www  . ja  v a2 s  .  c  o  m*/
        String policyDocClean = URLDecoder.decode(policyDoc, "UTF-8");
        logger.debug("Clean Policy Document: " + policyDocClean);
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            JsonNode rootNode = objectMapper.readTree(policyDocClean);
            JsonNode statement = rootNode.path("Statement");
            logger.debug("Statement node: " + statement.toString());
            JsonNode resource = null;
            if (statement.isArray()) {
                logger.debug("Statement is array");
                for (int i = 0; i < statement.size(); i++) {
                    String action = statement.get(i).path("Action").textValue();
                    if (action != null && action.equals("sts:AssumeRole")) {
                        resource = statement.get(i).path("Resource");
                        logger.debug("Resource node: " + resource.toString());
                        break;
                    }
                }
            } else {
                logger.debug("Statement is NOT array");
                if (statement.get("Action").textValue().equals("sts:AssumeRole")) {
                    resource = statement.path("Resource");
                    logger.debug("Resource node: " + resource.toString());
                }
            }
            if (resource != null) {
                if (resource.isArray()) { //if we're handling a policy with an array of AssumeRole attributes
                    ArrayList<String> lstRoles = new ArrayList<String>();
                    for (final JsonNode node : resource) {
                        lstRoles.add(node.asText());
                    }
                    strRoleToAssume = SelectRole(lstRoles);
                } else {
                    strRoleToAssume = resource.textValue();
                    logger.debug("Role to assume: " + roleToAssume);
                }
            }
        } catch (IOException ioe) {
        }
    } catch (UnsupportedEncodingException uee) {

    }
    return strRoleToAssume;
}

From source file:nosqltools.JSONUtilities.java

private DefaultMutableTreeNode makeJtree(String name, JsonNode node) {
    //instance of default mutable tree node with the root name of that object
    DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode(name);
    //iterator that stores the fields of the JSON documents in the collection.
    Iterator<Entry<String, JsonNode>> iterator = node.fields();

    while (iterator.hasNext()) {
        //the iterator returns the next entry 
        Entry<String, JsonNode> entry = iterator.next();
        //the entry will be added to the tree node and formatted as key:value
        treeNode.add(makeJtree(entry.getKey() + " : " + entry.getValue(), entry.getValue()));
    }//from  w  w  w .ja va  2  s. c  o  m

    //if an array is found within an object
    if (node.isArray()) {
        for (int i = 0; i < node.size(); i++) {
            //create a child and get the information
            JsonNode child = node.get(i);

            //the isValueNode returns valid String representation of the container value, if the node is a value node else null
            if (child.isValueNode())
                treeNode.add(new DefaultMutableTreeNode(child.asText()));
            else
                treeNode.add(makeJtree(String.format("Node %d", i), child));
        }
    }

    return treeNode;
}

From source file:com.liferay.sync.engine.document.library.handler.BaseJSONHandler.java

@Override
public String getException(String response) {
    String exception = null;//from   ww  w  .  j a  v  a 2  s.  c o m

    JsonNode responseJsonNode = null;

    try {
        response = StringEscapeUtils.unescapeJava(response);

        response = response.replaceAll("\n", "\\n");

        responseJsonNode = JSONUtil.readTree(response);
    } catch (Exception e) {
        return "";
    }

    JsonNode errorJsonNode = responseJsonNode.get("error");

    if (errorJsonNode == null) {
        JsonNode exceptionJsonNode = responseJsonNode.get("exception");

        if (exceptionJsonNode == null) {
            return "";
        }

        exception = exceptionJsonNode.asText();

        if (exception.startsWith("No JSON web service action")) {
            return "NoSuchJSONWebServiceException";
        }
    }

    if (exception == null) {
        JsonNode typeJsonNode = null;

        JsonNode rootCauseJsonNode = responseJsonNode.get("rootCause");

        if (rootCauseJsonNode != null) {
            typeJsonNode = rootCauseJsonNode.get("type");
        } else {
            typeJsonNode = errorJsonNode.get("type");
        }

        exception = typeJsonNode.asText();
    }

    if (exception.equals("java.lang.RuntimeException")) {
        JsonNode messageJsonNode = null;

        if (errorJsonNode != null) {
            messageJsonNode = errorJsonNode.get("message");
        } else {
            messageJsonNode = responseJsonNode.get("message");
        }

        String message = messageJsonNode.asText();

        if (message.startsWith("No JSON web service action")) {
            return "NoSuchJSONWebServiceException";
        }
    }

    return exception;
}

From source file:com.redhat.lightblue.crud.validator.MinMaxChecker.java

@Override
public void checkConstraint(ConstraintValidator validator, FieldTreeNode fieldMetadata, Path fieldMetadataPath,
        FieldConstraint constraint, Path valuePath, JsonDoc doc, JsonNode fieldValue) {
    Number value = ((MinMaxConstraint) constraint).getValue();
    String type = ((MinMaxConstraint) constraint).getType();
    int cmp = cmp(fieldValue, value);
    // cmp==0: fieldValue=value
    // cmp <0: fieldValue<value
    // cmp >0: fieldValue>value
    if (MinMaxConstraint.MIN.equals(type)) {
        if (cmp < 0) {
            validator.addDocError(Error.get(CrudConstants.ERR_VALUE_TOO_SMALL, fieldValue.asText()));
        }/*from w  w w  .  j av  a 2 s . c om*/
    } else {
        if (cmp > 0) {
            validator.addDocError(Error.get(CrudConstants.ERR_VALUE_TOO_LARGE, fieldValue.asText()));
        }
    }
}

From source file:org.apache.taverna.robundle.manifest.TestManifestJSON.java

public void checkManifestJson(JsonNode json) {
    JsonNode context = json.get("@context");
    assertNotNull("Could not find @context", context);
    assertTrue("@context SHOULD be an array", context.isArray());
    assertTrue("@context SHOULD include a context", context.size() > 0);
    JsonNode lastContext = context.get(context.size() - 1);
    assertEquals("@context SHOULD include https://w3id.org/bundle/context as last item",
            "https://w3id.org/bundle/context", lastContext.asText());

    assertEquals("/", json.get("id").asText());

    JsonNode manifest = json.get("manifest");
    if (manifest.isValueNode()) {
        assertEquals("manifest SHOULD be literal value \"manifest.json\" or list", "manifest.json",
                manifest.asText());/*w w w . j a v  a 2s .  c  o m*/
    } else {
        assertTrue("manifest is neither literal or list", manifest.isArray());
        boolean found = false;
        for (JsonNode n : manifest) {
            found = n.asText().equals("manifest.json");
            if (found) {
                break;
            }
        }
        ;
        assertTrue("Could not find 'manifest.json' in 'manifest' list: " + manifest, found);
    }

    assertEquals("2013-03-05T17:29:03Z", json.get("createdOn").asText());
    JsonNode createdBy = json.get("createdBy");
    assertNotNull("Could not find createdBy", createdBy);
    assertEquals("http://example.com/foaf#alice", createdBy.get("uri").asText());
    assertEquals("http://orcid.org/0000-0002-1825-0097", createdBy.get("orcid").asText());
    assertEquals("Alice W. Land", createdBy.get("name").asText());

    JsonNode history = json.get("history");
    if (history.isValueNode()) {
        assertEquals("evolution.ttl", history.asText());
    } else {
        assertEquals("evolution.ttl", history.get(0).asText());
    }

    JsonNode aggregates = json.get("aggregates");
    assertTrue("aggregates not a list", aggregates.isArray());
    JsonNode soup = aggregates.get(0);
    if (soup.isValueNode()) {
        assertEquals("/folder/soup.jpeg", soup.asText());
    } else {
        assertEquals("/folder/soup.jpeg", soup.get("uri").asText());
    }

    JsonNode blog = aggregates.get(1);
    if (blog.isValueNode()) {
        assertEquals("http://example.com/blog/", blog.asText());
    } else {
        assertEquals("http://example.com/blog/", blog.get("uri").asText());
    }

    JsonNode readme = aggregates.get(2);
    assertEquals("/README.txt", readme.get("uri").asText());
    assertEquals("text/plain", readme.get("mediatype").asText());
    assertEquals("2013-02-12T19:37:32.939Z", readme.get("createdOn").asText());
    JsonNode readmeCreatedBy = readme.get("createdBy");
    assertEquals("http://example.com/foaf#bob", readmeCreatedBy.get("uri").asText());
    assertEquals("Bob Builder", readmeCreatedBy.get("name").asText());

    JsonNode comments = aggregates.get(3);
    assertEquals("http://example.com/comments.txt", comments.get("uri").asText());
    JsonNode bundledAs = comments.get("bundledAs");
    assertEquals("urn:uuid:a0cf8616-bee4-4a71-b21e-c60e6499a644", bundledAs.get("uri").asText());
    assertEquals("/folder/", bundledAs.get("folder").asText());
    assertEquals("external.txt", bundledAs.get("filename").asText());

    JsonNode annotations = json.get("annotations");
    assertTrue("annotations MUST be a list", annotations.isArray());

    JsonNode ann0 = annotations.get(0);
    assertEquals("urn:uuid:d67466b4-3aeb-4855-8203-90febe71abdf", ann0.get("uri").asText());
    assertEquals("/folder/soup.jpeg", ann0.get("about").asText());
    assertEquals("annotations/soup-properties.ttl", ann0.get("content").asText());

    JsonNode ann1 = annotations.get(1);
    assertNull(ann1.get("annotation"));
    assertEquals("urn:uuid:a0cf8616-bee4-4a71-b21e-c60e6499a644", ann1.get("about").asText());
    assertEquals("http://example.com/blog/they-aggregated-our-file", ann1.get("content").asText());

    JsonNode ann2 = annotations.get(2);
    assertNull(ann2.get("annotation"));
    JsonNode about = ann2.get("about");
    assertTrue("about was not a list", about.isArray());
    assertEquals("/", about.get(0).asText());
    assertEquals("urn:uuid:d67466b4-3aeb-4855-8203-90febe71abdf", about.get(1).asText());
    assertEquals("annotations/a-meta-annotation-in-this-ro.txt", ann2.get("content").asText());

}

From source file:org.jmxtrans.embedded.config.ConfigurationParser.java

private void mergeEmbeddedJmxTransConfiguration(@Nonnull JsonNode configurationRootNode,
        @Nonnull EmbeddedJmxTrans embeddedJmxTrans) {
    for (JsonNode queryNode : configurationRootNode.path("queries")) {

        String objectName = queryNode.path("objectName").asText();
        Query query = new Query(objectName);
        embeddedJmxTrans.addQuery(query);
        JsonNode resultAliasNode = queryNode.path("resultAlias");
        if (resultAliasNode.isMissingNode()) {
        } else if (resultAliasNode.isValueNode()) {
            query.setResultAlias(resultAliasNode.asText());
        } else {/*  w  w  w  .java 2  s  .  c  o m*/
            logger.warn("Ignore invalid node {}", resultAliasNode);
        }

        JsonNode attributesNode = queryNode.path("attributes");
        if (attributesNode.isMissingNode()) {
        } else if (attributesNode.isArray()) {
            Iterator<JsonNode> itAttributeNode = attributesNode.elements();
            while (itAttributeNode.hasNext()) {
                JsonNode attributeNode = itAttributeNode.next();
                parseQueryAttributeNode(query, attributeNode);
            }
        } else {
            logger.warn("Ignore invalid node {}", resultAliasNode);
        }

        JsonNode attributeNode = queryNode.path("attribute");
        parseQueryAttributeNode(query, attributeNode);
        List<OutputWriter> outputWriters = parseOutputWritersNode(queryNode);
        query.getOutputWriters().addAll(outputWriters);
        logger.trace("Add {}", query);
    }

    List<OutputWriter> outputWriters = parseOutputWritersNode(configurationRootNode);
    embeddedJmxTrans.getOutputWriters().addAll(outputWriters);
    logger.trace("Add global output writers: {}", outputWriters);

    JsonNode queryIntervalInSecondsNode = configurationRootNode.path("queryIntervalInSeconds");
    if (!queryIntervalInSecondsNode.isMissingNode()) {
        embeddedJmxTrans.setQueryIntervalInSeconds(queryIntervalInSecondsNode.asInt());
    }

    JsonNode exportBatchSizeNode = configurationRootNode.path("exportBatchSize");
    if (!exportBatchSizeNode.isMissingNode()) {
        embeddedJmxTrans.setExportBatchSize(exportBatchSizeNode.asInt());
    }

    JsonNode numQueryThreadsNode = configurationRootNode.path("numQueryThreads");
    if (!numQueryThreadsNode.isMissingNode()) {
        embeddedJmxTrans.setNumQueryThreads(numQueryThreadsNode.asInt());
    }

    JsonNode exportIntervalInSecondsNode = configurationRootNode.path("exportIntervalInSeconds");
    if (!exportIntervalInSecondsNode.isMissingNode()) {
        embeddedJmxTrans.setExportIntervalInSeconds(exportIntervalInSecondsNode.asInt());
    }

    JsonNode numExportThreadsNode = configurationRootNode.path("numExportThreads");
    if (!numExportThreadsNode.isMissingNode()) {
        embeddedJmxTrans.setNumExportThreads(numExportThreadsNode.asInt());
    }

    logger.info("Loaded {}", embeddedJmxTrans);
}

From source file:org.opendaylight.groupbasedpolicy.renderer.opflex.mit.MitLibTest.java

@Test
public void testSerializeMoProperties() throws Exception {
    PolicyClassInfo pci = null;/*from  w  ww  .  j a  v a2 s  .  c  o m*/
    PolicyObjectInstance poi = null;
    boolean prop2Found = false, prop3Found = false, prop4Found = false, prop5Found = false, prop6Found = false,
            prop7Found = false;

    /*
     * Construct the PolicyObjectInfo object by
     * running it through the deserializer
     */

    testMo = constructClass1Mo();
    poi = lib.deserializeMoProperties(testMo, testMit);
    pci = testMit.getClass(TEST_CLASS_1_NAME);
    lib.serializeMoProperties(pci, poi, testMo, testMit);
    List<Property> props = testMo.getProperties();
    assertTrue(props.size() == 2);
    for (Property prop : props) {

        if (prop.getName().equals(TEST_PROP_2_NAME)) {
            assertTrue(prop.getData().asText().equals(TEST_DATA_2_STRING));
            prop2Found = true;
        }

        if (prop.getName().equals(TEST_PROP_3_NAME)) {
            assertTrue(prop.getName().equals(TEST_PROP_3_NAME));
            assertTrue(prop.getData().has(MitLib.REFERENCE_SUBJECT));
            JsonNode jn = prop.getData().findValue(MitLib.REFERENCE_SUBJECT);
            assertTrue(jn.asText().equals(TEST_CLASS_3_NAME));
            assertTrue(prop.getData().has(MitLib.REFERENCE_URI));
            jn = prop.getData().findValue(MitLib.REFERENCE_URI);
            assertTrue(jn.asText().equals("/" + TEST_CLASS_3_NAME));
            prop3Found = true;
        }
    }
    assertTrue(prop2Found);
    assertTrue(prop3Found);

    testMo = constructClass2Mo();
    poi = lib.deserializeMoProperties(testMo, testMit);
    pci = testMit.getClass(TEST_CLASS_2_NAME);
    lib.serializeMoProperties(pci, poi, testMo, testMit);
    props = testMo.getProperties();
    assertTrue(props.size() == 2);
    for (Property prop : props) {

        if (prop.getName().equals(TEST_PROP_4_NAME)) {
            assertTrue(prop.getData().asText().equals(TEST_DATA_4_STRING));
            prop4Found = true;
        }
        if (prop.getName().equals(TEST_PROP_5_NAME)) {
            assertTrue(prop.getData().asText().equals(TEST_ENUM_VAL_2_NAME));
            prop5Found = true;
        }
    }
    assertTrue(prop4Found);
    assertTrue(prop5Found);

    testMo = constructClass3Mo();
    poi = lib.deserializeMoProperties(testMo, testMit);
    pci = testMit.getClass(TEST_CLASS_3_NAME);
    lib.serializeMoProperties(pci, poi, testMo, testMit);
    props = testMo.getProperties();
    assertTrue(props.size() == 2);
    for (Property prop : props) {
        if (prop.getName().equals(TEST_PROP_6_NAME)) {
            assertTrue(prop.getData().asText().equals(TEST_DATA_6_STRING));
            prop6Found = true;
        }
        if (prop.getName().equals(TEST_PROP_7_NAME)) {
            assertTrue(prop.getData().asText().equals(TEST_DATA_7_STRING));
            prop7Found = true;
        }
    }
    assertTrue(prop6Found);
    assertTrue(prop7Found);

}

From source file:cc.arduino.packages.discoverers.PluggableDiscovery.java

private void processJsonNode(ObjectMapper mapper, JsonNode node) {
    JsonNode eventTypeNode = node.get("eventType");
    if (eventTypeNode == null) {
        System.err.println(format("{0}: Invalid message, missing eventType", discoveryName));
        return;/*w w w .j  av  a 2s .co m*/
    }

    switch (eventTypeNode.asText()) {
    case "error":
        try {
            PluggableDiscoveryMessage msg = mapper.treeToValue(node, PluggableDiscoveryMessage.class);
            debug("error: " + msg.getMessage());
            if (msg.getMessage().contains("START_SYNC")) {
                startPolling();
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return;

    case "list":
        JsonNode portsNode = node.get("ports");
        if (portsNode == null) {
            System.err.println(format("{0}: Invalid message, missing ports list", discoveryName));
            return;
        }
        if (!portsNode.isArray()) {
            System.err.println(format("{0}: Invalid message, ports list should be an array", discoveryName));
            return;
        }

        synchronized (portList) {
            portList.clear();
        }
        portsNode.forEach(portNode -> {
            BoardPort port = mapJsonNodeToBoardPort(mapper, node);
            if (port != null) {
                addOrUpdate(port);
            }
        });
        return;

    // Messages for SYNC updates

    case "add":
        BoardPort addedPort = mapJsonNodeToBoardPort(mapper, node);
        if (addedPort != null) {
            addOrUpdate(addedPort);
        }
        return;

    case "remove":
        BoardPort removedPort = mapJsonNodeToBoardPort(mapper, node);
        if (removedPort != null) {
            remove(removedPort);
        }
        return;

    default:
        debug("Invalid event: " + eventTypeNode.asText());
        return;
    }
}

From source file:org.springframework.tuple.JsonNodeToTupleConverter.java

private List<Object> nodeToList(JsonNode node) {
    List<Object> list = new ArrayList<Object>(node.size());
    for (int i = 0; i < node.size(); i++) {
        JsonNode item = node.get(i);
        if (item.isObject()) {
            list.add(convert(item));/* w ww .j  ava 2s  . c o  m*/
        } else if (item.isArray()) {
            list.add(nodeToList(item));
        } else if (item.isNull()) {
            list.add(null);
        } else if (item.isBoolean()) {
            list.add(item.booleanValue());
        } else if (item.isNumber()) {
            list.add(item.numberValue());
        } else {
            list.add(item.asText());
        }
    }
    return list;
}