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.modelsolv.kaboom.serializer.SerializerTest.java

private void verifyTaxFilingMessage(String message, boolean resourceRoot, boolean linkedReference,
        boolean embeddedResource, boolean checkMultiValued) {
    assertFalse(StringUtils.isEmpty(message));
    System.out.println("==== TaxFiling ====");
    System.out.println(message);/*from www.j a v a 2  s .  c  o  m*/
    JsonNode root = parseJson(message);
    assertEquals("IRS", root.get("jurisdiction").asText());
    assertEquals("1234", root.get("filingID").asText());
    if (resourceRoot) {
        // check the self-link
        assertEquals("http://modelsolv.com/taxblaster/api/taxFilings/1234",
                root.at("/_links/self/href").asText());
    }
    if (linkedReference) {
        // Verify the reference link to Person.
        assertEquals("http://modelsolv.com/taxBlaster/api/people/555-33-5577",
                root.at("/_links/taxpayer/href").asText());
    } else {
        // Verify the embedded Person resource.
        // try pointer expression
        // JsonNode personNode = root.get("_embedded").get("taxpayer");
        JsonNode personNode = root.at("/_embedded/taxpayer");
        assertNotNull(personNode);
        assertEquals("McDermott", personNode.get("lastName").asText());
        if (checkMultiValued) {
            assertEquals("Paul E. McDermott", personNode.at("/otherNames/0").asText());
            assertEquals("Paul Edward McDermott", personNode.at("/otherNames/1").asText());
            assertEquals("123 Sesame Street", personNode.at("/_embedded/addresses/0/street1").asText());
            assertEquals("425 Dobbs Industrial Court",
                    personNode.at("/_embedded/addresses/1/street1").asText());
        }
        if (embeddedResource) {
            // Verify that the reference is to a resource, having a
            // self-link.
            JsonNode personSelfLink = root.at("/_embedded/taxpayer/_links/self/href");
            assertEquals("http://modelsolv.com/taxBlaster/api/people/555-33-5577", personSelfLink.asText());
        }
    }
}

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

public BigInteger deserializeMoPropertyEnum(JsonNode node, PolicyPropertyInfo ppi) {

    EnumInfo ei = ppi.getEnumInfo();
    return ei.getEnumValue(node.asText());
}

From source file:org.modelmapper.jackson.JsonNodeValueReader.java

public Object get(JsonNode source, String memberName) {
    JsonNode propertyNode = source.get(memberName);
    if (propertyNode == null)
        throw new IllegalArgumentException();

    switch (propertyNode.getNodeType()) {
    case BOOLEAN:
        return propertyNode.asBoolean();
    case NULL:/* w  ww .  j av  a  2s  .com*/
        return null;
    case NUMBER:
        return ((NumericNode) propertyNode).numberValue();
    case POJO:
        return ((POJONode) propertyNode).getPojo();
    case STRING:
        return propertyNode.asText();
    case BINARY:
        try {
            return propertyNode.binaryValue();
        } catch (IOException ignore) {
            return null;
        }

    case ARRAY:
    case OBJECT:
    case MISSING:
    default:
        return propertyNode;
    }
}

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

private synchronized void initializeMetadata(Factory factory) throws IOException, ClassNotFoundException,
        NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    if (metadata == null) {
        LOGGER.debug("Initializing metadata");

        JsonNode root = metadataNode;/*from   w  ww  .  j a  v  a 2s  .  c  o  m*/
        if (root == null) {
            try (InputStream is = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream(MetadataConfiguration.FILENAME)) {
                root = JsonUtils.json(is);
            }
        }
        LOGGER.debug("Config root:{}", root);

        JsonNode cfgClass = root.get("type");
        if (cfgClass == null) {
            throw new IllegalStateException(MetadataConstants.ERR_CONFIG_NOT_FOUND + " - type");
        }

        MetadataConfiguration cfg = (MetadataConfiguration) Class.forName(cfgClass.asText()).newInstance();
        cfg.initializeFromJson(root);

        // Set validation flag for all metadata requests
        getJsonTranslator().setValidation(EntityMetadata.class, cfg.isValidateRequests());
        getJsonTranslator().setValidation(EntitySchema.class, cfg.isValidateRequests());
        getJsonTranslator().setValidation(EntityInfo.class, cfg.isValidateRequests());

        metadata = cfg.createMetadata(datasources, getJSONParser(), this);
        factory.setHookResolver(new SimpleHookResolver(cfg.getHookConfigurationParsers()));
    }
}

From source file:com.baasbox.commands.UsersResource.java

private String getUsername(JsonNode command) throws CommandException {
    JsonNode params = command.get(ScriptCommand.PARAMS);
    JsonNode id = params.get("username");
    if (id == null || !id.isTextual()) {
        throw new CommandParsingException(command, "missing user username");
    }/*from  w w  w  .j a va 2  s .  c  o  m*/

    String username = id.asText();
    boolean internalUsername = UserService.isInternalUsername(username);
    if (internalUsername) {
        throw new CommandExecutionException(command, "invalid user: " + username);
    }
    return username;
}

From source file:org.opendaylight.nemo.renderer.cli.physicalnetwork.PhysicalResourceLoaderTest.java

@Test
public void testBuildPortAttributes() throws Exception {
    Class<PhysicalResourceLoader> class1 = PhysicalResourceLoader.class;
    Method method = class1.getDeclaredMethod("buildPortAttributes", new Class[] { JsonNode.class });
    method.setAccessible(true);// ww  w. j a  v a  2s.c om

    List<Attribute> attributeList;
    JsonNode attributes = mock(JsonNode.class);
    JsonNode portAttribute = mock(JsonNode.class);
    JsonNode jsonNode_temp = mock(JsonNode.class);

    when(attributes.size()).thenReturn(1);
    when(attributes.get(any(Integer.class))).thenReturn(portAttribute);
    //get into method "buildPortAttribute"
    when(portAttribute.path(any(String.class))).thenReturn(jsonNode_temp);
    when(jsonNode_temp.asText()).thenReturn(new String(""))//branch null
            .thenReturn(new String("zm"));
    attributeList = (List<Attribute>) method.invoke(physicalResourceLoader, attributes);
    Assert.assertTrue(attributeList.size() == 0);
    //new AttributeName("zm");
    attributeList = (List<Attribute>) method.invoke(physicalResourceLoader, attributes);
    Assert.assertTrue(attributeList.size() == 1);
    verify(portAttribute, times(3)).path(any(String.class));
    verify(jsonNode_temp, times(3)).asText();
}

From source file:org.agatom.springatom.cmp.action.DefaultActionsModelReader.java

private ActionRole resolveSecurityRoles(final JsonNode roles, final ActionRoleMap.Connector[] connectors) {
    if (JsonNodeType.STRING.equals(roles.getNodeType())) {
        return new DefaultActionRole().appendRole(roles.asText());
    }//from www. ja  v  a2  s .  com
    final Iterator<JsonNode> iterator = roles.iterator();
    ActionRole actionRole = null;

    while (iterator.hasNext()) {
        final JsonNode node = iterator.next();
        final JsonNodeType type = node.getNodeType();
        if (JsonNodeType.STRING.equals(type)) {
            actionRole = new DefaultActionRole().appendRole(node.asText());
        } else if (JsonNodeType.ARRAY.equals(type)) {

            final ArrayNode arrayNode = (ArrayNode) node;
            final DefaultActionRole role = new DefaultActionRole();
            for (JsonNode textRoleNode : arrayNode) {
                role.appendRole(textRoleNode.asText());
            }
            actionRole = role;

        } else if (JsonNodeType.OBJECT.equals(type)) {

            final ActionRoleMap actionRoleMap = new ActionRoleMap();
            final Map<ActionRoleMap.Connector, DefaultActionRole> map = Maps
                    .newHashMapWithExpectedSize(node.size());
            String strConnector;
            for (final ActionRoleMap.Connector connector : connectors) {
                strConnector = connector.toString().toLowerCase();
                if (node.has(strConnector)) {
                    final DefaultActionRole role = new DefaultActionRole();
                    for (JsonNode textRoleNode : node.get(strConnector)) {
                        role.appendRole(textRoleNode.asText());
                    }
                    map.put(connector, role);
                }
            }
            actionRoleMap.setRoles(map);
            actionRole = actionRoleMap;

        }
    }

    return actionRole;
}

From source file:com.baasbox.commands.DocumentsResource.java

private String getDocumentId(JsonNode command) throws CommandException {
    JsonNode params = command.get(ScriptCommand.PARAMS);
    JsonNode id = params.get("id");
    if (id == null || !id.isTextual()) {
        throw new CommandParsingException(command, "missing document id");
    }//w ww.j  a  v  a 2s.  co  m
    String idString = id.asText();
    return idString;
}

From source file:io.gravitee.definition.jackson.datatype.api.deser.FailoverDeserializer.java

@Override
public Failover deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonNode node = jp.getCodec().readTree(jp);

    Failover failover = new Failover();

    final JsonNode casesNode = node.get("cases");
    if (casesNode != null) {
        if (casesNode.isArray()) {
            List<FailoverCase> cases = new ArrayList<>();

            casesNode.elements().forEachRemaining(
                    jsonNode -> cases.add(FailoverCase.valueOf(jsonNode.asText().toUpperCase())));

            failover.setCases(cases.toArray(new FailoverCase[cases.size()]));
        } else {/*from   w  w  w.  jav  a2  s . c o  m*/
            failover.setCases(new FailoverCase[] { FailoverCase.valueOf(casesNode.asText().toUpperCase()) });
        }
    }

    JsonNode maxAttemptsNode = node.get("maxAttempts");
    if (maxAttemptsNode != null) {
        int maxAttempts = maxAttemptsNode.asInt(Failover.DEFAULT_MAX_ATTEMPTS);
        failover.setMaxAttempts(maxAttempts);
    } else {
        failover.setMaxAttempts(Failover.DEFAULT_MAX_ATTEMPTS);
    }

    JsonNode retryTimeoutNode = node.get("retryTimeout");
    if (retryTimeoutNode != null) {
        long retryTimeout = retryTimeoutNode.asLong(Failover.DEFAULT_RETRY_TIMEOUT);
        failover.setRetryTimeout(retryTimeout);
    } else {
        failover.setRetryTimeout(Failover.DEFAULT_RETRY_TIMEOUT);
    }

    return failover;
}

From source file:com.attribyte.essem.DefaultResponseGenerator.java

protected String parseGraphAggregation(JsonNode sourceParent, List<String> fields, RateUnit rateUnit,
        ObjectNode targetMeta, ArrayNode targetGraph) {

    Iterator<Map.Entry<String, JsonNode>> iter = sourceParent.fields();
    Map.Entry<String, JsonNode> aggregation = null;

    while (iter.hasNext()) {
        aggregation = iter.next();//from ww  w.  j  a  va  2 s .  c om
        if (aggregation.getValue().isObject()) {
            break;
        } else {
            aggregation = null;
        }
    }

    if (aggregation == null) {
        return "Aggregation is invalid";
    }

    String bucketName = aggregation.getKey();

    JsonNode obj = aggregation.getValue();
    JsonNode bucketsObj = obj.get("buckets");
    if (bucketsObj == null || !bucketsObj.isArray()) {
        return "Aggregation is invalid";
    }

    if (keyComponents.contains(bucketName)) {
        for (final JsonNode bucketObj : bucketsObj) {
            if (!bucketObj.isObject()) {
                return "Aggregation is invalid";
            }

            JsonNode keyNode = bucketObj.get(KEY_NODE_KEY);
            if (keyNode == null) {
                return "Aggregation is invalid";
            }

            targetMeta.put(translateBucketName(bucketName), keyNode.asText());
            String error = parseGraphAggregation(bucketObj, fields, rateUnit, targetMeta.deepCopy(),
                    targetGraph);
            if (error != null) {
                return error;
            }
        }
        return null;
    } else {
        ObjectNode graphObj = targetGraph.addObject();
        addAggregationMeta(graphObj, targetMeta);

        ArrayNode samplesArr = graphObj.putArray("samples");

        for (final JsonNode bucketObj : bucketsObj) {
            if (!bucketObj.isObject()) {
                return "Aggregation is invalid";
            }

            JsonNode keyNode = bucketObj.get(KEY_NODE_KEY);
            if (keyNode == null) {
                return "Aggregation is invalid";
            }

            ArrayNode sampleArr = samplesArr.addArray();
            sampleArr.add(keyNode.asLong());
            JsonNode docCountNode = bucketObj.get(SAMPLES_KEY);
            long samples = docCountNode != null ? docCountNode.asLong() : 0L;
            sampleArr.add(samples);

            for (String field : fields) {
                JsonNode fieldObj = bucketObj.get(field);
                if (fieldObj != null) {
                    JsonNode valueNode = fieldObj.get("value");
                    if (rateUnit == RAW_RATE_UNIT || valueNode == null || !rateFields.contains(field)) {
                        if (valueNode != null) {
                            sampleArr.add(valueNode);
                        } else {
                            sampleArr.add(0L);
                        }
                    } else {
                        sampleArr.add(valueNode.doubleValue() * rateUnit.mult);
                    }
                } else {
                    sampleArr.add(0L);
                }
            }
        }

        return null;
    }
}