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.googlecode.batchfb.impl.ErrorDetectingWrapper.java

/**
 * The batch call itself seems to have a funky error format:
 * //from   w  ww  .  ja v  a 2s  .  c  o m
 * {"error":190,"error_description":"Invalid OAuth access token signature."}
 */
protected void checkForBatchError(JsonNode root) {
    JsonNode errorCode = root.get("error");
    if (errorCode != null) {

        JsonNode errorDescription = root.get("error_description");
        if (errorDescription != null) {

            int code = errorCode.intValue();
            String msg = errorDescription.asText();

            this.throwCodeAndMessage(code, msg);
        }
    }
}

From source file:com.evrythng.java.wrapper.mapping.BatchPopulatingTaskInputParametersDeserializer.java

private <T> T getFieldValue(final JsonNode node) {

    if (node == null) {
        return null;
    }//from   w w w  . j  ava  2 s .  c  o  m
    Object value = null;
    if (node.isBoolean()) {
        value = node.asBoolean();
    }
    if (node.isNumber()) {
        value = node.asDouble();
    }
    if (node.isTextual()) {
        value = node.asText();
    }
    if (node.isArray()) {
        value = new ArrayList<>();
    }
    if (node.isObject()) {
        value = new HashMap<>();
    }
    return (T) value;
}

From source file:com.evrythng.java.wrapper.mapping.PropertyDeserializer.java

private Object getFieldValue(final JsonNode node) {

    if (node == null) {
        return null;
    }/*from ww  w  . j  a v  a 2  s  .c om*/
    Object value = null;
    if (node.isBoolean()) {
        value = node.asBoolean();
    }
    if (node.isNumber()) {
        value = node.asDouble();
    }
    if (node.isTextual()) {
        value = node.asText();
    }
    if (node.isArray()) {
        value = new ArrayList<>();
    }
    if (node.isObject()) {
        value = new HashMap<>();
    }
    return value;
}

From source file:org.ihtsdo.otf.refset.security.RefsetIdentityService.java

/**
 * @param obj/*w  ww .j  a v a2s  .co m*/
 */
private User populateUser(User user, JsonNode obj) {

    //mandatory values
    JsonNode userJson = obj.get("user");
    String id = userJson.findValue("name").asText();
    String status = userJson.findValue("status").asText();

    boolean authenticated = !StringUtils.isEmpty(status) && status.equalsIgnoreCase("enabled") ? true : false;

    user.setUsername(id);
    user.setPassword(userJson.findValue("token").asText());
    user.setAuthenticated(authenticated);
    user.setEnabled(authenticated);
    //other details
    JsonNode email = userJson.findValue("email");

    if (email != null) {

        user.setEmail(email.asText());

    }
    JsonNode middleName = userJson.findValue("middleName");

    if (middleName != null) {

        user.setMiddlename(middleName.asText());

    }

    JsonNode givenName = userJson.findValue("givenName");

    if (givenName != null) {

        user.setGivenname(givenName.asText());

    }

    JsonNode surname = userJson.findValue("surname");

    if (surname != null) {

        user.setSurname(surname.asText());

    }

    return user;
}

From source file:com.digitalpebble.stormcrawler.filtering.basic.BasicURLNormalizer.java

@Override
public void configure(Map stormConf, JsonNode paramNode) {
    JsonNode node = paramNode.get("removeAnchorPart");
    if (node != null) {
        removeAnchorPart = node.booleanValue();
    }//from ww  w  .  j  a va 2  s.  c o  m

    node = paramNode.get("unmangleQueryString");
    if (node != null) {
        unmangleQueryString = node.booleanValue();
    }

    node = paramNode.get("queryElementsToRemove");
    if (node != null) {
        if (!node.isArray()) {
            LOG.warn("Failed to configure queryElementsToRemove.  Not an array: {}", node.toString());
        } else {
            ArrayNode array = (ArrayNode) node;
            for (JsonNode element : array) {
                queryElementsToRemove.add(element.asText());
            }
        }
    }

    node = paramNode.get("checkValidURI");
    if (node != null) {
        checkValidURI = node.booleanValue();
    }
}

From source file:samza.examples.rss.system.RssFeed.java

/**
 * Reads the url and queues the data/*from   ww  w .  j  a  va2 s. c o m*/
 *
 * @param feedDetail feedDetails object
 * @return set of all article urls that were read from the feed
 * @throws IOException                          when it cannot connect to the url or the url is malformed
 * @throws com.sun.syndication.io.FeedException when it cannot reed the feed.
 */
protected Set<String> queueFeedEntries(FeedDetails feedDetail, List<Datum> dataQueue)
        throws IOException, FeedException {
    URL feedUrl = new URL(feedDetail.getUrl());
    URLConnection connection = feedUrl.openConnection();
    connection.setConnectTimeout(this.timeOut);
    SyndFeedInput input = new SyndFeedInput();
    SyndFeed feed = input.build(new InputStreamReader(connection.getInputStream()));
    Set<String> batch = Sets.newConcurrentHashSet();
    for (Object entryObj : feed.getEntries()) {
        SyndEntry entry = (SyndEntry) entryObj;
        ObjectNode nodeEntry = this.serializer.deserialize(entry);
        nodeEntry.put(RSS_KEY, feedDetail.getUrl());
        String entryId = determineId(nodeEntry);
        batch.add(entryId);
        Datum datum = new Datum(nodeEntry, entryId, DateTime.now());
        JsonNode published = nodeEntry.get(DATE_KEY);
        if (published != null) {
            try {
                DateTime date = RFC3339Utils.parseToUTC(published.asText());
                if (date.isAfter(this.publishedSince) && (!seenBefore(entryId, feedDetail.getUrl()))) {
                    dataQueue.add(datum);
                    log.debug("Added entry, {}, to provider queue.", entryId);
                }
            } catch (Exception e) {
                log.trace("Failed to parse date from object node, attempting to add node to queue by default.");
                if (!seenBefore(entryId, feedDetail.getUrl())) {
                    dataQueue.add(datum);
                    log.debug("Added entry, {}, to provider queue.", entryId);
                }
            }
        } else {
            log.debug("No published date present, attempting to add node to queue by default.");
            if (!seenBefore(entryId, feedDetail.getUrl())) {
                dataQueue.add(datum);
                log.debug("Added entry, {}, to provider queue.", entryId);
            }
        }
    }
    return batch;
}

From source file:com.ocdsoft.bacta.soe.json.schema.SoeDefaultRule.java

private JExpression getDefaultValue(JType fieldType, JsonNode node) {

    fieldType = fieldType.unboxify();/*from  ww w.  j  av  a 2 s. c  om*/

    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(short.class.getName())) {
        return JExpr.lit(Short.parseShort(node.asText()));

    } else if (fieldType.fullName().equals(byte.class.getName())) {
        return JExpr.lit(Byte.parseByte(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(getDateType().getName())) {
        long millisecs = parseDateToMillisecs(node.asText());

        JInvocation newDate = JExpr._new(fieldType);
        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.fullName().equals(float.class.getName())) {
        return JExpr.lit(Float.parseFloat(node.asText()));

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

        return getDefaultEnum(fieldType, node);

    } else {
        return JExpr._null();

    }

}

From source file:org.opendaylight.alto.core.northbound.route.costmap.impl.AltoNorthboundCostmapTest.java

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

    AltoModelCostmapService costmapService = mock(AltoModelCostmapService.class);
    Future<RpcResult<QueryOutput>> future = mock(Future.class);
    RpcResult<QueryOutput> rpcResult = mock(RpcResult.class);
    //build QueryOutput
    int order = 0;
    LinkedList<CostmapSource> costmapSources = new LinkedList<CostmapSource>();
    for (String src : pid_source) {
        LinkedList<CostmapDestination> costmapDestinations = new LinkedList<CostmapDestination>();

        for (String dst : pid_destination) {
            CostmapDestinationBuilder costmapDestinationBuilder = new CostmapDestinationBuilder();
            costmapDestinationBuilder.setPidDestination(new PidName(dst));
            costmapDestinationBuilder.setCost(createOrdinalCost(++order));
            costmapDestinations.add(costmapDestinationBuilder.build());
        }/*from  w  w w  .j a v a2 s.  c om*/
        CostmapSourceBuilder costmapSourceBuilder = new CostmapSourceBuilder();
        costmapSourceBuilder.setPidSource(new PidName(src));
        costmapSourceBuilder.setCostmapDestination(costmapDestinations);
        costmapSources.add(costmapSourceBuilder.build());
    }
    CostTypeBuilder costType = new CostTypeBuilder();
    costType.setCostMode(costmode);
    costType.setCostMetric(new CostMetric(costmetri));
    CostmapResponseDataBuilder costmapResponseDataBuilder = new CostmapResponseDataBuilder();
    costmapResponseDataBuilder.setCostType(costType.build());
    costmapResponseDataBuilder.setCostmapSource(costmapSources);

    CostmapResponseBuilder costmapResponseBuilder = new CostmapResponseBuilder();
    costmapResponseBuilder.setCostmapResponseData(costmapResponseDataBuilder.build());

    QueryOutputBuilder queryOutput = new QueryOutputBuilder();
    queryOutput.setResponse(costmapResponseBuilder.build());
    when(rpcResult.getResult()).thenReturn(queryOutput.build());
    when(future.get()).thenReturn(rpcResult);
    when(costmapService.query((QueryInput) anyObject())).thenReturn(future);

    costmapSpy.setMapService(costmapService);

    costmapSpy.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;
        }
    });
    doReturn(ctagIID).when(costmapSpy).getResourceByPath(eq(path), (ReadOnlyTransaction) anyObject());
    RFC7285CostMap.Meta meta = new RFC7285CostMap.Meta();
    RFC7285CostType rfc7285costType = new RFC7285CostType();
    rfc7285costType.metric = costmetri;
    rfc7285costType.mode = costmode;
    meta.costType = rfc7285costType;
    doReturn(meta).when(costmapSpy).buildMeta((InstanceIdentifier<?>) anyObject(),
            (RFC7285CostType) anyObject());

    //start test
    costmapSpy.init();
    Response response = costmapSpy.getFilteredMap(path, filter);
    String responseStr = response.getEntity().toString();
    ObjectMapper mapper = new ObjectMapper();
    JsonNode responseNode = mapper.readTree(responseStr);
    JsonNode costmapNode = responseNode.get("cost-map");
    JsonNode PID1Node = costmapNode.get("PID1");
    JsonNode PID2Node = PID1Node.get("PID2");
    assertEquals("2", PID2Node.asText());

    //        assertEquals(responseStr,surex);
}

From source file:org.schedoscope.export.kafka.avro.HCatToAvroRecordConverter.java

private List<Object> convertArray(JsonNode json, Schema schema) throws IOException {

    List<Object> res = new ArrayList<>();
    Iterator<JsonNode> it = json.elements();

    while (it.hasNext()) {

        JsonNode n = it.next();
        if (!n.isNull()) {
            for (Schema s : schema.getElementType().getTypes()) {
                if (s.getType().equals(Schema.Type.STRING)) {
                    res.add(n.asText());
                } else if (s.getType().equals(Schema.Type.INT)) {
                    res.add(n.asInt());//from ww  w  .j  a  v  a 2  s . c o m
                } else if (s.getType().equals(Schema.Type.LONG)) {
                    res.add(n.asLong());
                } else if (s.getType().equals(Schema.Type.BOOLEAN)) {
                    res.add(n.asBoolean());
                } else if (s.getType().equals(Schema.Type.DOUBLE)) {
                    res.add(n.asDouble());
                } else if (s.getType().equals(Schema.Type.FLOAT)) {
                    res.add(n.asDouble());
                } else if (s.getType().equals(Schema.Type.RECORD)) {
                    res.add(convertRecord(n, s));
                } else if (s.getType().equals(Schema.Type.ARRAY)) {
                    res.addAll(convertArray(n, s));
                } else if (s.getType().equals(Schema.Type.MAP)) {
                    res.add(convertMap(n, s));
                }
            }
        }
    }
    return res;
}

From source file:com.vz.onosproject.zeromqprovider.AppWebResource.java

/**
 * Installs flows to downstream ZMQ device
 * @param stream blob flowrule/* ww  w .j a v a  2s  . c  o  m*/
 * @return 200 OK
 */
@POST
@Path("flows")
@Consumes(MediaType.APPLICATION_JSON)

public Response persisFlow(InputStream stream) {
    log.info("#### Pushing a flow");
    ObjectNode jsonTree = null;
    List<String> devices = controller.getAvailableDevices();
    try {
        jsonTree = (ObjectNode) mapper().readTree(stream);
        JsonNode devId = jsonTree.get("DeviceId");
        JsonNode payload = jsonTree.get("Payload");
        String sPayload = payload.toString();

        log.info("Device Id" + devId.asText());
        log.info("Payload Text value " + payload.textValue() + " toString " + payload.toString() + "Type "
                + payload.getNodeType().toString());

        if (devId == null || devId.asText().isEmpty() || devices.contains(devId.asText()) == false) {
            throw new IllegalArgumentException(INVALID_DEVICEID);
        }

        if (payload == null || sPayload.isEmpty()) {
            throw new IllegalArgumentException(INVALID_FLOW);
        }

        DeviceId deviceId = DeviceId.deviceId(devId.asText());
        Blob blob = new Blob(sPayload.getBytes());

        store.InsertBlob(deviceId, blob);
        controller.writeToDevice(deviceId, blob);
        incrPostCount();
        log.info("#### Total num of posts :  " + getNumPostRecieved());

        return Response.ok().build();
    } catch (/*IO*/Exception e) {
        e.printStackTrace();
        log.info("###### ERROR " + e.getMessage());
    }
    return Response.noContent().build();
}