Example usage for com.fasterxml.jackson.databind.node ObjectNode get

List of usage examples for com.fasterxml.jackson.databind.node ObjectNode get

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node ObjectNode get.

Prototype

public JsonNode get(String paramString) 

Source Link

Usage

From source file:org.agorava.facebook.impl.FeedServiceImpl.java

private String determinePostType(ObjectNode node) {
    if (node.has("type")) {
        try {//www.  j  a  v  a2s .  c  om
            String type = node.get("type").textValue();
            PostType.valueOf(type.toUpperCase());
            return type;
        } catch (IllegalArgumentException e) {
            return "post";
        }
    }
    return "post";
}

From source file:org.apache.streams.data.MoreoverJsonActivitySerializer.java

@Override
public Activity deserialize(String serialized) {
    serialized = serialized.replaceAll("\\[[ ]*\\]", "null");

    System.out.println(serialized);

    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
    mapper.setAnnotationIntrospector(introspector);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
    mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, Boolean.FALSE);
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
    mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);
    mapper.configure(DeserializationFeature.WRAP_EXCEPTIONS, Boolean.TRUE);

    Article article;/*from w w w .j  av  a 2 s. c o m*/
    try {
        ObjectNode node = (ObjectNode) mapper.readTree(serialized);
        node.remove("tags");
        node.remove("locations");
        node.remove("companies");
        node.remove("topics");
        node.remove("media");
        node.remove("outboundUrls");
        ObjectNode jsonNodes = (ObjectNode) node.get("source").get("feed");
        jsonNodes.remove("editorialTopics");
        jsonNodes.remove("tags");
        jsonNodes.remove("autoTopics");
        article = mapper.convertValue(node, Article.class);
    } catch (IOException e) {
        throw new IllegalArgumentException("Unable to deserialize", e);
    }
    return MoreoverUtils.convert(article);
}

From source file:controllers.Rules.java

@Security.Authenticated(Secured.class)
@BodyParser.Of(BodyParser.Json.class)
public static Promise<Result> addFeature(String name) {
    JsonNode json = request().body().asJson();
    final ObjectNode avm = (ObjectNode) json.deepCopy();
    avm.retain("ruleUUID", "uuid");
    final ObjectNode feature = Json.newObject();
    feature.put("name", json.findValue("name").asText());
    feature.put("type", json.findValue("type").asText());
    Promise<Boolean> added = Substructure.nodes.connect(avm, feature);
    Promise<Feature> feat = Feature.nodes.get(feature);
    return added.zip(feat).map(new Function<Tuple<Boolean, Feature>, Result>() {
        ObjectNode result = Json.newObject();

        public Result apply(Tuple<Boolean, Feature> t) {
            Boolean added = t._1;
            if (added) {
                Feature feat = t._2;/*  ww w .  j av a2  s  . c  o  m*/
                if (feat.isComplex()) {
                    String parentUUID = avm.get("uuid").asText();
                    String featureUUID = feat.getUUID();
                    String uuid = UUIDGenerator.from(parentUUID + featureUUID);
                    ObjectNode value = Json.newObject();
                    value.put("uuid", uuid);
                    value.putArray("pairs");
                    result.put("value", value);
                } else {
                    result.put("value", new TextNode("underspecified"));
                }
                result.put("message", "Feature successfully added.");
                return ok(result);
            }
            result.put("message", "Feature not added.");
            return badRequest(result);
        }
    });
}

From source file:org.dswarm.graph.gdm.test.GDMResourceTest.java

@Test
public void testResourceTypeNodeUniqueness() throws IOException {

    writeGDMToDBInternal("http://data.slub-dresden.de/resources/1", DEFAULT_GDM_FILE_NAME);
    writeGDMToDBInternal("http://data.slub-dresden.de/resources/2", DEFAULT_GDM_FILE_NAME);

    final String typeQuery = "MATCH (n:TYPE_RESOURCE) RETURN id(n) AS node_id, n.uri AS node_uri;";

    final ObjectMapper objectMapper = Util.getJSONObjectMapper();

    final ObjectNode requestJson = objectMapper.createObjectNode();

    requestJson.put("query", typeQuery);

    final String requestJsonString = objectMapper.writeValueAsString(requestJson);

    final ClientResponse response = cypher().type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, requestJsonString);

    Assert.assertEquals("expected 200", 200, response.getStatus());

    final String body = response.getEntity(String.class);

    final ObjectNode bodyJson = objectMapper.readValue(body, ObjectNode.class);

    Assert.assertNotNull(bodyJson);//  www.j  a va 2 s . c  o  m

    final JsonNode dataNode = bodyJson.get("data");

    Assert.assertNotNull(dataNode);
    Assert.assertTrue(dataNode.size() > 0);

    final Map<String, Long> resourceTypeMap = Maps.newHashMap();

    for (final JsonNode entry : dataNode) {

        final String resourceType = entry.get(1).textValue();
        final long nodeId = entry.get(0).longValue();

        if (resourceTypeMap.containsKey(resourceType)) {

            final Long existingNodeId = resourceTypeMap.get(resourceType);

            Assert.assertTrue("resource node map already contains a node for resource type '" + resourceType
                    + "' with the id '" + existingNodeId + "', but found another node with id '" + nodeId
                    + "' for this resource type", false);
        }

        resourceTypeMap.put(resourceType, nodeId);
    }
}

From source file:com.ikanow.aleph2.graph.titan.utils.TitanGraphBuildingUtils.java

/** Quick/fast validation of user generated elements (vertices and edges)
 * @param o//w  w  w  . jav a 2  s.  c  o  m
 * @return
 */
public static Validation<BasicMessageBean, ObjectNode> validateUserElement(final ObjectNode o,
        GraphSchemaBean config) {
    // Same as validation for merged elements, and in addition:
    // - For vertices:
    //   - id is set and is consistent with dedup fields
    // - For edges
    //   - "properties" are valid, and don't have illegal permissions

    return validateMergedElement(o, config).bind(success -> {

        final JsonNode type = o.get(GraphAnnotationBean.type); // (exists and is valid by construction of validateMergedElement)

        final Stream<String> keys_to_check = Patterns.match(type.asText()).<Stream<String>>andReturn()
                .when(t -> GraphAnnotationBean.ElementType.edge.toString().equals(t),
                        __ -> Stream.of(GraphAnnotationBean.inV, GraphAnnotationBean.outV))
                .otherwise(__ -> Stream.of(GraphAnnotationBean.id));

        final Optional<BasicMessageBean> first_error = keys_to_check.<BasicMessageBean>map(k -> {
            final JsonNode key = o.get(k);

            if (null == key) {
                return ErrorUtils.buildErrorMessage("GraphBuilderEnrichmentService", "system.onObjectBatch",
                        ErrorUtils.MISSING_OR_BADLY_FORMED_FIELD, k, "missing");
            } else if (!key.isIntegralNumber() && !key.isObject()) {
                return ErrorUtils.buildErrorMessage("GraphBuilderEnrichmentService", "system.onObjectBatch",
                        ErrorUtils.MISSING_OR_BADLY_FORMED_FIELD, k, "not_long_or_object");
            }

            if (key.isObject()) { // user specified id, check its format is valid               
                if (!config.deduplication_fields().stream().allMatch(f -> key.has(f))) {
                    return ErrorUtils.buildErrorMessage("GraphBuilderEnrichmentService", "system.onObjectBatch",
                            ErrorUtils.MISSING_OR_BADLY_FORMED_FIELD, k, "missing_key_subfield");
                }
            }
            return null;
        }).filter(b -> null != b).findFirst();

        return first_error.<Validation<BasicMessageBean, ObjectNode>>map(b -> Validation.fail(b))
                .orElseGet(() -> Validation.success(o));
    });
}

From source file:net.sf.jasperreports.web.util.RequirejsTemplateConfigContributor.java

protected void mergeObject(ObjectNode dest, ObjectNode source) {
    for (Iterator<Entry<String, JsonNode>> it = source.fields(); it.hasNext();) {
        Entry<String, JsonNode> fieldEntry = it.next();
        String field = fieldEntry.getKey();
        JsonNode sourceValue = fieldEntry.getValue();
        JsonNode destValue = dest.get(field);
        // only recursively merging if both dest and source fields are objects
        // otherwise we overwrite the field, not appending arrays for now
        if (sourceValue instanceof ObjectNode && destValue instanceof ObjectNode) {
            mergeObject((ObjectNode) destValue, (ObjectNode) sourceValue);
        } else {/*w ww . ja v  a 2s. co  m*/
            dest.put(field, sourceValue);
        }
    }
}

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

private Action resolveFromAction(final ObjectNode node) {
    final String type = node.get("type").textValue();
    AbstractAction action = null;
    switch (type) {
    case "view": {
        action = new ViewAction();
    }/*from  w w w .j a  v  a2 s.  c o m*/
    }

    if (action != null) {

        action.setName(node.get("name").textValue());
        action.setLabel(this.getLabel(node.get(RESOURCE_BUNDLE_KEY).textValue()));

        this.setCssRule(node, action);
        this.setSecurity(node, action);

        action.setOrder(node.has("index") ? node.get("index").shortValue() : -1);
    } else {
        throw new IllegalStateException(String.format("%s is not supported", type));
    }

    return action;
}

From source file:com.almende.eve.agent.google.GoogleDirectionsAgent.java

/**
 * Retrieve the duration of the directions from origin to destination
 * in seconds./* www.  j av  a 2s . co m*/
 * 
 * @param origin
 *            the origin
 * @param destination
 *            the destination
 * @return duration Duration in seconds
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws InvalidKeyException
 *             the invalid key exception
 * @throws NoSuchAlgorithmException
 *             the no such algorithm exception
 * @throws URISyntaxException
 *             the uRI syntax exception
 */
public Integer getDuration(@Name("origin") final String origin, @Name("destination") final String destination)
        throws IOException, InvalidKeyException, NoSuchAlgorithmException, URISyntaxException {
    final ObjectNode directions = getDirections(origin, destination);

    // TODO: check fields for being null
    final JsonNode routes = directions.get("routes");
    final JsonNode route = routes.get(0);
    final JsonNode legs = route.get("legs");
    final JsonNode leg = legs.get(0);
    final JsonNode jsonDuration = leg.get("duration");

    final Integer duration = jsonDuration.get("value").asInt();
    return duration;
}

From source file:com.almende.eve.agent.google.GoogleDirectionsAgent.java

/**
 * Retrieve the distance between origin to destination in meters.
 * //from  www. jav a  2  s  .co  m
 * @param origin
 *            the origin
 * @param destination
 *            the destination
 * @return duration Distance in meters
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws InvalidKeyException
 *             the invalid key exception
 * @throws NoSuchAlgorithmException
 *             the no such algorithm exception
 * @throws URISyntaxException
 *             the uRI syntax exception
 */
public Integer getDistance(@Name("origin") final String origin, @Name("destination") final String destination)
        throws IOException, InvalidKeyException, NoSuchAlgorithmException, URISyntaxException {
    final ObjectNode directions = getDirections(origin, destination);

    // TODO: check fields for being null
    final JsonNode routes = directions.get("routes");
    final JsonNode route = routes.get(0);
    final JsonNode legs = route.get("legs");
    final JsonNode leg = legs.get(0);
    final JsonNode jsonDistance = leg.get("distance");

    final Integer distance = jsonDistance.get("value").asInt();
    return distance;
}

From source file:com.almende.eve.agent.google.GoogleDirectionsAgent.java

/**
 * Retrieve the duration of the directions from origin to destination
 * in readable text, for example "59 mins".
 * //from  ww w . java  2s .  c  om
 * @param origin
 *            the origin
 * @param destination
 *            the destination
 * @return duration Duration in text
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws InvalidKeyException
 *             the invalid key exception
 * @throws NoSuchAlgorithmException
 *             the no such algorithm exception
 * @throws URISyntaxException
 *             the uRI syntax exception
 */
public String getDurationHuman(@Name("origin") final String origin,
        @Name("destination") final String destination)
        throws IOException, InvalidKeyException, NoSuchAlgorithmException, URISyntaxException {
    final ObjectNode directions = getDirections(origin, destination);

    // TODO: check fields for being null
    final JsonNode routes = directions.get("routes");
    final JsonNode route = routes.get(0);
    final JsonNode legs = route.get("legs");
    final JsonNode leg = legs.get(0);
    final JsonNode jsonDuration = leg.get("duration");

    final String duration = jsonDuration.get("text").asText();
    return duration;
}