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.aol.one.patch.testobj.PatchChildTestObject.java

/**
 * @param field/*  w w  w.  java 2s  . com*/
 * @param newValueNode
 */
public void replaceValue(String field, JsonNode newValueNode) {

    if (field.equals("doubleField")) {
        this.doubleField = newValueNode.asDouble();
    }

    if (field.equals("strField")) {
        this.strField = newValueNode.asText();
    }
}

From source file:com.redhat.lightblue.metadata.types.BigIntegerTypeTest.java

@Test
public void testToJson() {
    JsonNodeFactory jsonNodeFactory = new JsonNodeFactory(true);
    JsonNode jsonNode = bigIntegerType.toJson(jsonNodeFactory, BigInteger.ZERO);
    assertTrue(new BigInteger(jsonNode.asText()).equals(BigInteger.ZERO));
}

From source file:com.easarrive.aws.plugins.common.service.impl.TestSNSService.java

@Test
public void aaa() {
    // String message =
    // "{\"Records\":[{\"eventVersion\":\"2.0\",\"eventSource\":\"aws:s3\",\"awsRegion\":\"us-west-2\",\"eventTime\":\"2016-06-28T12:59:55.700Z\",\"eventName\":\"ObjectCreated:Put\",\"userIdentity\":{\"principalId\":\"AFRDGXV7XRMK5\"},\"requestParameters\":{\"sourceIPAddress\":\"124.205.19.130\"},\"responseElements\":{\"x-amz-request-id\":\"CA17C6B0CA3B9D5B\",\"x-amz-id-2\":\"8OnEzpN3a49R+oHXc+BXDRGEaLRjgM9sygcuNhg+G2g6FNWxK9CkE1vaxJhc+WiW\"},\"s3\":{\"s3SchemaVersion\":\"1.0\",\"configurationId\":\"test\",\"bucket\":{\"name\":\"etago-app-dev\",\"ownerIdentity\":{\"principalId\":\"AFRDGXV7XRMK5\"},\"arn\":\"arn:aws:s3:::etago-app-dev\"},\"object\":{\"key\":\"users/image/22.jpg\",\"size\":4006886,\"eTag\":\"229f0eddc267a22e02d938e294ebd7e5\",\"sequencer\":\"00577274CB93A5D229\"}}}]}";
    String message = "{\"Service\":\"Amazon S3\",\"Event\":\"s3:TestEvent\",\"Time\":\"2016-06-29T09:35:00.087Z\",\"Bucket\":\"etago-app-dev\",\"RequestId\":\"3AFC2B9075E9D4F1\",\"HostId\":\"aNL0geUz8N1uvZwQZ9mEdphu3wOYpvYCt9FiHIDTKzAEUjF6xXuOzybqRItfVtLc\"}";
    ObjectMapper mapper = JsonUtil.getInstance();
    try {//  www. ja  va  2 s. co m
        if (StringUtil.isEmpty(message)) {
            return;
        }
        JsonNode jsonNode = mapper.readTree(message);
        if (jsonNode == null) {
            return;
        }
        JsonNode recordsJsonNode = jsonNode.get("Records");
        if (recordsJsonNode == null) {
            return;
        }
        Iterator<JsonNode> recordsJsonNodeI = recordsJsonNode.elements();
        if (recordsJsonNodeI == null) {
            return;
        }
        while (recordsJsonNodeI.hasNext()) {
            JsonNode recordJsonNode = recordsJsonNodeI.next();
            if (recordJsonNode == null) {
                continue;
            }
            JsonNode eventVersion = recordJsonNode.get("eventVersion");
            System.out.println(eventVersion.asText());
            JsonNode eventSource = recordJsonNode.get("eventSource");
            System.out.println(eventSource.asText());
            JsonNode eventName = recordJsonNode.get("eventName");
            System.out.println(eventName.asText());

        }
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.microsoft.azure.oidc.token.impl.SimpeTokenParser.java

private List<Email> getEmails(final JsonNode node) {
    final List<Email> emails = new ArrayList<Email>();
    for (final JsonNode n : node.get("emails")) {
        emails.add(emailFactory.createEmail(n.asText()));
    }//w w  w .  j a  va  2 s .  c o m
    return emails;
}

From source file:com.forgerock.wisdom.oauth2.info.internal.StandardIntrospectionService.java

@Override
public TokenInfo introspect(final String token) {

    try {//  w w  w  . j  a  va2s .  c  o  m
        HttpURLConnection connection = (HttpURLConnection) new URL(baseUrl).openConnection();
        connection.getOutputStream().write(format("token=%s", token).getBytes());
        connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setDoOutput(true);
        if (bearerToken != null) {
            connection.addRequestProperty("Authorization", format("Bearer %s", bearerToken));
        }
        int code = connection.getResponseCode();
        if (code != 200) {
            return TokenInfo.INVALID;
        }

        try (InputStream stream = connection.getInputStream()) {
            JsonNode node = mapper.readTree(stream);
            if (node.get("active").asBoolean()) {

                JsonNode exp = node.get("exp");
                long expiresIn = 0;
                if (exp != null) {
                    expiresIn = exp.asLong() - System.currentTimeMillis();
                }

                JsonNode scope = node.get("scope");
                String[] scopes = null;
                if (scope != null) {
                    scopes = scope.asText().split(" ");
                }

                return new TokenInfo(true, expiresIn, scopes);
            }
        }

    } catch (IOException e) {
        // Ignored
    }

    return TokenInfo.INVALID;
}

From source file:com.linkedin.pinot.tools.backfill.BackfillSegmentUtils.java

/**
 * Fetches the list of all segment names for a table
 * @param tableName//from w ww.  j  a  v  a 2 s  .  c o  m
 * @return
 * @throws IOException
 */
public List<String> getAllSegments(String tableName, SegmentType segmentType) throws IOException {

    List<String> allSegments = new ArrayList<>();
    String urlString = String.format(SEGMENTS_ENDPOINT, _controllerHttpHost.toURI(), tableName);
    URL url = new URL(urlString);
    InputStream is = url.openConnection().getInputStream();

    String response = IOUtils.toString(is);
    JsonNode segmentsData = new ObjectMapper().readTree(response);

    if (segmentsData != null) {
        if (segmentType == null || SegmentType.OFFLINE.equals(segmentType)) {
            JsonNode offlineSegments = segmentsData.get(0).get(SegmentType.OFFLINE.toString());
            if (offlineSegments != null) {
                for (JsonNode segment : offlineSegments) {
                    allSegments.add(segment.asText());
                }
            }
        }
        if (segmentType == null || SegmentType.REALTIME.equals(segmentType)) {
            JsonNode realtimeSegments = segmentsData.get(0).get(SegmentType.REALTIME.toString());
            if (realtimeSegments != null) {
                for (JsonNode segment : realtimeSegments) {
                    allSegments.add(segment.asText());
                }
            }
        }
    }
    LOGGER.info("All segments : {}", allSegments);

    return allSegments;
}

From source file:eu.cloudwave.wp5.feedbackhandler.metricsources.NewRelicClient.java

/**
 * {@inheritDoc}//  w ww. j  a va2 s .c om
 */
@Override
protected void handleHttpServerException(final HttpStatusCodeException serverError)
        throws MetricSourceClientException, IOException {
    // if the status code is 401 UNAUTHORIZED -> the API key is not valid
    if (serverError.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
        throw new MetricSourceClientException(ErrorType.NEW_RELIC__INVALID_API_KEY,
                Messages.ERRORS__NEW_RELIC__INVALID_API_KEY);
    }

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode errorNode = mapper.readTree(serverError.getResponseBodyAsString());
    final JsonNode titleNode = errorNode.findValue(JSON__TITLE);
    if (titleNode != null) {
        final String message = titleNode.asText();
        ErrorType type = ErrorType.NEW_RELIC__GENERAL;

        if (message.contains(ERROR__INVALID_APPLICATION_ID)
                || message.equals(ERROR__INVALID_PARAMETER_APPLICATION_ID)) {
            type = ErrorType.NEW_RELIC__INVALID_APPLICATION_ID;
        } else if (message.contains(ERROR__UNKNOWN_METRIC)) {
            type = ErrorType.UNKNOWN_METRIC;
        } else if (message.contains(ERROR__INVALID_PARAMETER)) {
            type = ErrorType.INVALID_PARAMETER;
        }
        throw new MetricSourceClientException(type, message);
    }
}

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

@Override
public JFieldVar apply(String nodeName, JsonNode node, JFieldVar field, Schema currentSchema) {

    if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()) {
        JAnnotationUse annotation = field.annotate(Pattern.class);
        annotation.param("regexp", node.asText());
    }//from   w  w  w  .  j a  va 2 s. c  om

    return field;
}

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

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

    Proxy proxy = new Proxy();
    final JsonNode contextPath = node.get("context_path");
    if (contextPath != null) {
        String sContextPath = formatContextPath(contextPath.asText());
        proxy.setContextPath(sContextPath);
    } else {/* www .ja v a 2s  .c  o  m*/
        throw ctxt.mappingException("[api] API must have a valid context path");
    }

    final JsonNode nodeEndpoints = node.get("endpoints");

    if (nodeEndpoints != null && nodeEndpoints.isArray()) {
        nodeEndpoints.elements().forEachRemaining(jsonNode -> {
            try {
                Endpoint endpoint = jsonNode.traverse(jp.getCodec()).readValueAs(Endpoint.class);
                proxy.getEndpoints().add(endpoint);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    JsonNode stripContextNode = node.get("strip_context_path");
    if (stripContextNode != null) {
        proxy.setStripContextPath(stripContextNode.asBoolean(false));
    }

    JsonNode loadBalancingNode = node.get("load_balancing");
    if (loadBalancingNode != null) {
        LoadBalancer loadBalancer = loadBalancingNode.traverse(jp.getCodec()).readValueAs(LoadBalancer.class);
        proxy.setLoadBalancer(loadBalancer);
    }

    JsonNode failoverNode = node.get("failover");
    if (failoverNode != null) {
        Failover failover = failoverNode.traverse(jp.getCodec()).readValueAs(Failover.class);
        proxy.setFailover(failover);
    }

    JsonNode dumpRequestNode = node.get("dumpRequest");
    if (dumpRequestNode != null) {
        boolean dumpRequest = dumpRequestNode.asBoolean(Proxy.DEFAULT_DUMP_REQUEST);
        proxy.setDumpRequest(dumpRequest);
    } else {
        proxy.setDumpRequest(Proxy.DEFAULT_DUMP_REQUEST);
    }

    return proxy;
}

From source file:io.sqp.schemamatcher.typematchers.TypeMatcher.java

@Override
final public boolean isCompatibleTo(JsonNode other) {
    JsonNode typeField = other.get("type");
    if (typeField == null) {
        throw new InvalidMatchingSchemaException("Type field is not set. Expected type '" + _type + "'.");
    }//from   w w  w.j  a  va 2s.  c o  m
    return _type.matches(typeField.asText()) && isTypeCompatibleTo(other);
}