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:org.dswarm.graph.json.deserializer.StatementDeserializer.java

@Override
public Statement deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {

    final ObjectCodec oc = jp.getCodec();

    if (oc == null) {

        return null;
    }/*from w w  w .  j a  va2 s .c om*/

    final JsonNode node = oc.readTree(jp);

    if (node == null) {

        return null;
    }

    final JsonNode idNode = node.get("id");

    Long id = null;

    if (idNode != null) {

        try {

            id = idNode.asLong();
        } catch (final Exception e) {

            id = null;
        }
    }

    final JsonNode uuidNode = node.get("uuid");

    String uuid = null;

    if (uuidNode != null && JsonNodeType.NULL != uuidNode.getNodeType()) {

        uuid = uuidNode.asText();
    }

    final JsonNode subjectNode = node.get("s");

    if (subjectNode == null) {

        throw new JsonParseException("expected JSON node that represents the subject of a statement",
                jp.getCurrentLocation());
    }

    final Node subject;

    if (subjectNode.get("uri") != null) {

        // resource node
        subject = subjectNode.traverse(oc).readValueAs(ResourceNode.class);
    } else {

        // bnode
        subject = subjectNode.traverse(oc).readValueAs(Node.class);
    }

    final JsonNode predicateNode = node.get("p");

    if (predicateNode == null) {

        throw new JsonParseException("expected JSON node that represents the predicate of a statement",
                jp.getCurrentLocation());
    }

    final Predicate predicate = predicateNode.traverse(oc).readValueAs(Predicate.class);

    final JsonNode objectNode = node.get("o");

    if (objectNode == null) {

        throw new JsonParseException("expected JSON node that represents the object of a statement",
                jp.getCurrentLocation());
    }

    final Node object;

    if (objectNode.get("uri") != null) {

        // resource node
        object = objectNode.traverse(oc).readValueAs(ResourceNode.class);
    } else if (objectNode.get("v") != null) {

        // literal node
        object = objectNode.traverse(oc).readValueAs(LiteralNode.class);
    } else {

        // bnode
        object = objectNode.traverse(oc).readValueAs(Node.class);
    }

    final JsonNode orderNode = node.get("order");

    Long order = null;

    if (orderNode != null) {

        try {

            order = orderNode.asLong();
        } catch (final Exception e) {

            order = null;
        }
    }

    final JsonNode evidenceNode = node.get("evidence");

    String evidence = null;

    if (evidenceNode != null) {

        evidence = evidenceNode.asText();
    }

    final JsonNode confidenceNode = node.get("confidence");

    String confidence = null;

    if (confidenceNode != null) {

        confidence = confidenceNode.asText();
    }

    final Statement statement = new Statement(subject, predicate, object);

    if (id != null) {

        statement.setId(id);
    }

    if (uuid != null) {

        statement.setUUID(uuid);
    }

    if (order != null) {

        statement.setOrder(order);
    }

    if (evidence != null) {

        statement.setEvidence(evidence);
    }

    if (confidence != null) {

        statement.setConfidence(confidence);
    }

    return statement;
}

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

protected void parseQueryAttributeNode(@Nonnull Query query, @Nonnull JsonNode attributeNode) {
    if (attributeNode.isMissingNode()) {
    } else if (attributeNode.isValueNode()) {
        query.addAttribute(attributeNode.asText());
    } else if (attributeNode.isObject()) {
        List<String> keys = null;

        JsonNode keysNode = attributeNode.path("keys");
        if (keysNode.isMissingNode()) {
        } else if (keysNode.isArray()) {
            if (keys == null) {
                keys = new ArrayList<String>();
            }//from  ww  w  .  j  av  a2  s  .c o  m
            Iterator<JsonNode> itAttributeNode = keysNode.elements();
            while (itAttributeNode.hasNext()) {
                JsonNode keyNode = itAttributeNode.next();
                if (keyNode.isValueNode()) {
                    keys.add(keyNode.asText());
                } else {
                    logger.warn("Ignore invalid node {}", keyNode);
                }
            }
        } else {
            logger.warn("Ignore invalid node {}", keysNode);
        }

        JsonNode keyNode = attributeNode.path("key");
        if (keyNode.isMissingNode()) {
        } else if (keyNode.isValueNode()) {
            if (keys == null) {
                keys = new ArrayList<String>();
            }
            keys.add(keyNode.asText());
        } else {
            logger.warn("Ignore invalid node {}", keyNode);
        }

        String name = attributeNode.path("name").asText();
        JsonNode resultAliasNode = attributeNode.path("resultAlias");
        String resultAlias = resultAliasNode.isMissingNode() ? null : resultAliasNode.asText();
        JsonNode typeNode = attributeNode.path("type");
        String type = typeNode.isMissingNode() ? null : typeNode.asText();
        if (keys == null) {
            query.addAttribute(new QueryAttribute(name, type, resultAlias));
        } else {
            query.addAttribute(new QueryAttribute(name, type, resultAlias, keys));
        }
    } else {
        logger.warn("Ignore invalid node {}", attributeNode);
    }
}

From source file:com.vaushell.superpipes.tools.scribe.tumblr.TumblrClient.java

private TB_Post convertJsonToPost(final JsonNode node, final TB_Blog blog) {
    final Tags tags = new Tags();
    final JsonNode nodeTags = node.get("tags");
    for (final JsonNode nodeTag : nodeTags) {
        tags.add(nodeTag.asText());
    }/* w  ww. j  a va  2s. c o  m*/

    final String message;
    final String urlName;
    final String type = node.get("type").asText();
    if ("link".equalsIgnoreCase(type)) {
        message = null;
        urlName = convertNodeToString(node.get("title"));
    } else {
        message = convertNodeToString(node.get("title"));
        urlName = null;
    }

    return new TB_Post(node.get("id").asLong(), message,

            convertNodeToString(node.get("url")), urlName, convertNodeToString(node.get("description")), type,
            node.get("slug").asText(), new DateTime(node.get("timestamp").asLong() * 1000L), tags, blog);
}

From source file:io.apicurio.hub.editing.EditApiDesignEndpoint.java

/**
 * Called when a message is received on a web socket connection.  All messages must
 * be of the following (JSON) format://from  ww w.  j a v a  2  s . c  om
 * 
 * <pre>
 * {
 *    "type": "command|...",
 *    "command": {
 *       &lt;marshalled OAI command goes here>
 *    }
 * }
 * </pre>
 * 
 * @param session
 * @param message
 */
@OnMessage
public void onMessage(Session session, JsonNode message) {
    String designId = session.getPathParameters().get("designId");
    ApiDesignEditingSession editingSession = editingSessionManager.getEditingSession(designId);
    String msgType = message.get("type").asText();

    logger.debug("Received a \"{}\" message from a client.", msgType);
    logger.debug("\tdesignId: {}", designId);

    if (msgType.equals("command")) {
        String user = editingSession.getUser(session);
        long localCommandId = -1;
        if (message.has("commandId")) {
            localCommandId = message.get("commandId").asLong();
        }
        String content;
        long cmdContentVersion;

        this.metrics.contentCommand(designId);

        logger.debug("\tuser:" + user);
        try {
            content = mapper.writeValueAsString(message.get("command"));
        } catch (JsonProcessingException e) {
            logger.error("Error writing command as string.", e);
            // TODO do something sensible here - send a msg to the client?
            return;
        }
        try {
            cmdContentVersion = storage.addContent(user, designId, ApiContentType.Command, content);
        } catch (StorageException e) {
            logger.error("Error storing the command.", e);
            // TODO do something sensible here - send a msg to the client?
            return;
        }

        // Send an ack message back to the user
        ApiDesignCommandAck ack = new ApiDesignCommandAck();
        ack.setCommandId(localCommandId);
        ack.setContentVersion(cmdContentVersion);
        editingSession.sendAckTo(session, ack);
        logger.debug("ACK sent back to client.");

        // Now propagate the command to all other clients
        ApiDesignCommand command = new ApiDesignCommand();
        command.setCommand(content);
        command.setContentVersion(cmdContentVersion);
        editingSession.sendCommandToOthers(session, user, command);
        logger.debug("Command propagated to 'other' clients.");

        return;
    } else if (msgType.equals("selection")) {
        String user = editingSession.getUser(session);
        String selection = null;
        if (message.has("selection")) {
            JsonNode node = message.get("selection");
            if (node != null) {
                selection = node.asText();
            }
        }
        logger.debug("\tuser:" + user);
        logger.debug("\tselection:" + selection);
        editingSession.sendUserSelectionToOthers(session, user, selection);
        logger.debug("User selection propagated to 'other' clients.");
        return;
    } else if (msgType.equals("ping")) {
        logger.debug("PING message received.");
        return;
    }
    logger.error("Unknown message type: {}", msgType);
    // TODO something went wrong if we got here - report an error of some kind
}

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

private JExpression getDefaultValue(JType fieldType, JsonNode node) {

    if (!fieldType.isPrimitive() && node.isNull()) {
        return JExpr._null();
    }//  w  ww .j  a  v  a 2  s .c  o m

    fieldType = fieldType.unboxify();

    if (fieldType.fullName().equals(String.class.getName())) {
        return JExpr.lit(node.asText());

    } else if (fieldType.fullName().equals(int.class.getName())) {
        return JExpr.lit(Integer.parseInt(node.asText()));

    } else if (fieldType.fullName().equals(double.class.getName())) {
        return JExpr.lit(Double.parseDouble(node.asText()));

    } else if (fieldType.fullName().equals(boolean.class.getName())) {
        return JExpr.lit(Boolean.parseBoolean(node.asText()));

    } else if (fieldType.fullName().equals(Date.class.getName())) {
        long millisecs = parseDateToMillisecs(node.asText());

        JInvocation newDate = JExpr._new(fieldType.owner().ref(Date.class));
        newDate.arg(JExpr.lit(millisecs));

        return newDate;

    } else if (fieldType.fullName().equals(long.class.getName())) {
        return JExpr.lit(Long.parseLong(node.asText()));

    } else if (fieldType instanceof JDefinedClass
            && ((JDefinedClass) fieldType).getClassType().equals(ClassType.ENUM)) {

        return getDefaultEnum(fieldType, node);

    } else {
        return JExpr._null();

    }

}

From source file:com.vaushell.superpipes.tools.scribe.tumblr.TumblrClient.java

private void checkErrors(final Response response, final JsonNode root, final int validResponseCode)
        throws TumblrException {
    final JsonNode res = root.get("response");
    if (response.getCode() != validResponseCode) {
        final JsonNode meta = root.get("meta");

        final List<String> listErrors = new ArrayList<>();
        final JsonNode errors = res.get("errors");
        if (errors != null) {
            for (final JsonNode error : errors) {
                listErrors.add(error.asText());
            }//from   w  w w  .  j av  a2  s  . c o  m
        }

        throw new TumblrException(response.getCode(), meta.get("status").asInt(), meta.get("msg").asText(),
                listErrors);
    }
}

From source file:twg2.dependency.models.PackageJson.java

public String getLicense() {
    if (license != null) {
        JsonNode type;
        if (license.isTextual()) {
            return license.asText();
        } else if ((type = license.get("type")) != null) {
            if (!type.isTextual()) {
                throw new IllegalArgumentException(
                        "expected text node, '" + name + "' is a " + type.getNodeType() + " node");
            }/*from  w ww .  j ava 2s.  c o  m*/
            return type.asText();
        }
    }
    return null;
}

From source file:com.yahoo.ycsb.db.CouchbaseClient.java

/**
 * Decode the object from server into the storable result.
 *
 * @param source the loaded object./*  w w  w  .jav  a2 s  . co m*/
 * @param fields the fields to check.
 * @param dest the result passed back to the ycsb core.
 */
private void decode(final Object source, final Set<String> fields, final HashMap<String, ByteIterator> dest) {
    if (useJson) {
        try {
            JsonNode json = JSON_MAPPER.readTree((String) source);
            boolean checkFields = fields != null && fields.size() > 0;
            for (Iterator<Map.Entry<String, JsonNode>> jsonFields = json.fields(); jsonFields.hasNext();) {
                Map.Entry<String, JsonNode> jsonField = jsonFields.next();
                String name = jsonField.getKey();
                if (checkFields && fields.contains(name)) {
                    continue;
                }
                JsonNode jsonValue = jsonField.getValue();
                if (jsonValue != null && !jsonValue.isNull()) {
                    dest.put(name, new StringByteIterator(jsonValue.asText()));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Could not decode JSON");
        }
    } else {
        HashMap<String, String> converted = (HashMap<String, String>) source;
        for (Map.Entry<String, String> entry : converted.entrySet()) {
            dest.put(entry.getKey(), new StringByteIterator(entry.getValue()));
        }
    }
}

From source file:org.opendaylight.alto.core.northbound.route.endpointcost.impl.AltoNorthboundEndpointcostTest.java

@Test
public void testgetFilteredMap() throws ExecutionException, InterruptedException, IOException {
    //mock config
    AltoNorthboundRouteEndpointcost endpointcost = new AltoNorthboundRouteEndpointcost();
    AltoNorthboundRouteEndpointcost endpointcostSpy = spy(endpointcost);
    InstanceIdentifier<ContextTag> ctagIID = InstanceIdentifier.create(ContextTag.class);

    AltoModelEndpointcostService endpointcostService = mock(AltoModelEndpointcostService.class);
    Future<RpcResult<QueryOutput>> future = mock(Future.class);
    RpcResult<QueryOutput> rpcResult = mock(RpcResult.class);
    List<Source> sources = new ArrayList<Source>();
    List<Destination> destinations = new ArrayList<Destination>();

    for (String source : endpoints_source_ipv4) {
        SourceBuilder sourceBuilder = new SourceBuilder();
        Ipv4Builder ipv4 = new Ipv4Builder();
        ipv4.setIpv4(new Ipv4Address(source));
        sourceBuilder.setAddress(ipv4.build());
        sources.add(sourceBuilder.build());
    }/* w w w  . java 2s. c  om*/
    for (String destination : endpoints_destination_ipv4) {
        DestinationBuilder destinationBuilder = new DestinationBuilder();
        Ipv4Builder ipv4 = new Ipv4Builder();
        ipv4.setIpv4(new Ipv4Address(destination));
        destinationBuilder.setAddress(ipv4.build());
        destinations.add(destinationBuilder.build());
    }

    List<? extends TypedAddressData> source = sources;

    List<? extends TypedAddressData> destination = destinations;

    int order = 0;
    LinkedList<EndpointCost> ecList = new LinkedList<EndpointCost>();
    for (TypedAddressData src : source) {
        for (TypedAddressData dst : destination) {
            org.opendaylight.yang.gen.v1.urn.opendaylight.alto.service.model.endpointcost.rfc7285.rev151021.endpointcostmap.response.data.endpoint.cost.map.endpoint.cost.SourceBuilder srcBuilder = new org.opendaylight.yang.gen.v1.urn.opendaylight.alto.service.model.endpointcost.rfc7285.rev151021.endpointcostmap.response.data.endpoint.cost.map.endpoint.cost.SourceBuilder();
            srcBuilder.setAddress(createSourceAddress(src.getAddress()));

            org.opendaylight.yang.gen.v1.urn.opendaylight.alto.service.model.endpointcost.rfc7285.rev151021.endpointcostmap.response.data.endpoint.cost.map.endpoint.cost.DestinationBuilder dstBuilder = new org.opendaylight.yang.gen.v1.urn.opendaylight.alto.service.model.endpointcost.rfc7285.rev151021.endpointcostmap.response.data.endpoint.cost.map.endpoint.cost.DestinationBuilder();
            dstBuilder.setAddress(createDestinationAddress(dst.getAddress()));

            EndpointCostBuilder ecBuilder = new EndpointCostBuilder();
            ecBuilder.setSource(srcBuilder.build());
            ecBuilder.setDestination(dstBuilder.build());
            ecBuilder.setCost(createOrdinalCost(++order));

            ecList.add(ecBuilder.build());
        }
    }

    EndpointCostMapBuilder ecmBuilder = new EndpointCostMapBuilder();
    ecmBuilder.setEndpointCost(ecList);

    EndpointCostmapDataBuilder ecmdBuilder = new EndpointCostmapDataBuilder();
    ecmdBuilder.setEndpointCostMap(ecmBuilder.build());

    EndpointcostResponseBuilder ecrBuilder = new EndpointcostResponseBuilder();
    ecrBuilder.setEndpointcostData(ecmdBuilder.build());
    QueryOutputBuilder queryOutputBuilder = new QueryOutputBuilder();
    queryOutputBuilder.setResponse(ecrBuilder.build());

    when(rpcResult.getResult()).thenReturn(queryOutputBuilder.build());
    when(future.get()).thenReturn(rpcResult);
    when(endpointcostService.query((QueryInput) anyObject())).thenReturn(future);

    endpointcostSpy.setDataBroker(new DataBroker() {
        @Override
        public ReadOnlyTransaction newReadOnlyTransaction() {
            return null;
        }

        @Override
        public ReadWriteTransaction newReadWriteTransaction() {
            return null;
        }

        @Override
        public WriteTransaction newWriteOnlyTransaction() {
            return null;
        }

        @Override
        public ListenerRegistration<DataChangeListener> registerDataChangeListener(
                LogicalDatastoreType logicalDatastoreType, InstanceIdentifier<?> instanceIdentifier,
                DataChangeListener dataChangeListener, DataChangeScope dataChangeScope) {
            return null;
        }

        @Override
        public BindingTransactionChain createTransactionChain(
                TransactionChainListener transactionChainListener) {
            return null;
        }

        @Nonnull
        @Override
        public <T extends DataObject, L extends DataTreeChangeListener<T>> ListenerRegistration<L> registerDataTreeChangeListener(
                @Nonnull DataTreeIdentifier<T> dataTreeIdentifier, @Nonnull L l) {
            return null;
        }
    });
    endpointcostSpy.setMapService(endpointcostService);

    doReturn(ctagIID).when(endpointcostSpy).getResourceByPath(eq(path), (ReadOnlyTransaction) anyObject());

    //start test
    endpointcostSpy.init();
    Response response = endpointcostSpy.getFilteredMap(path, filter);
    String surex = response.getEntity().toString();
    ObjectMapper mapper = new ObjectMapper();
    JsonNode responseTree = mapper.readTree(surex);
    JsonNode endpointcostMapNode = responseTree.get("endpoint-cost-map");
    JsonNode soureceNode = endpointcostMapNode.get("ipv4:192.0.2.2");
    JsonNode destNode = soureceNode.get("ipv4:198.51.100.34");
    assertEquals("2", destNode.asText());
}

From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java

/**
 * {@inheritDoc }/* w  w  w  .  j av a  2s . co m*/
 */
@Override
protected NavigationLinks retrieveNavigationInfo(final String entitySetName, final InputStream is)
        throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final ObjectNode srcNode = (ObjectNode) mapper.readTree(is);
    IOUtils.closeQuietly(is);

    final NavigationLinks links = new NavigationLinks();

    final Iterator<Map.Entry<String, JsonNode>> fieldIter = srcNode.fields();

    while (fieldIter.hasNext()) {
        final Map.Entry<String, JsonNode> field = fieldIter.next();
        if (field.getKey().endsWith(JSON_NAVIGATION_BIND_SUFFIX)) {
            final String title = field.getKey().substring(0, field.getKey().indexOf('@'));
            final List<String> hrefs = new ArrayList<String>();
            if (field.getValue().isArray()) {
                for (JsonNode href : ((ArrayNode) field.getValue())) {
                    final String uri = href.asText();
                    hrefs.add(uri.substring(uri.lastIndexOf('/') + 1));
                }
            } else {
                final String uri = field.getValue().asText();
                hrefs.add(uri.substring(uri.lastIndexOf('/') + 1));
            }

            links.addLinks(title, hrefs);
        } else if (Commons.linkInfo.get(version).exists(entitySetName, field.getKey())) {
            links.addInlines(field.getKey(), IOUtils.toInputStream(field.getValue().toString()));
        }
    }

    return links;
}