Example usage for com.fasterxml.jackson.databind JsonNode elements

List of usage examples for com.fasterxml.jackson.databind JsonNode elements

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode elements.

Prototype

public Iterator<JsonNode> elements() 

Source Link

Usage

From source file:org.kiji.rest.resources.RowsResource.java

/**
 * POSTs JSON body to row(s): performs create and update.
 * The input JSON blob can either represent a single KijiRestRow or a list of KijiRestRows.
 *
 * For example, a single KijiRestRow:/*from   w w w.j  a v  a  2  s .c o m*/
 * {
 *   "entityId":"hbase=hex:8c2d2fcc2c150efb49ce0817e1823d46",
 *   "cells":{
 *       "info":{
 *          "firstname":[
 *             {
 *                "timestamp":123,
 *                "value":"John"
 *             }
 *          ]
 *       },
 *       "info":{
 *          "lastname":[
 *             {
 *                "timestamp":123,
 *                "value":"Smith"
 *             }
 *          ]
 *       }
 *    }
 * }
 *
 * A list of KijiRestRows:
 * [
 *    {
 *       "entityId":"hbase=hex:8c2d2fcc2c150efb49ce0817e1823d46",
 *       "cells":{
 *          "info":{
 *             "firstname":[
 *                {
 *                   "timestamp":123,
 *                   "value":"John"
 *                }
 *             ]
 *          }
 *       }
 *    },
 *    {
 *       "entityId":"hbase=hex:acfbe1234567890987654321abcfdega",
 *       "cells":{
 *          "info":{
 *             "firstname":[
 *                {
 *                   "timestamp":12312345,
 *                   "value":"Jane"
 *                }
 *             ]
 *          }
 *       }
 *    }
 * ]
 *
 * Note that the user-formatted entityId is required.
 * Also note that writer schema is not considered as of the latest version.
 *
 * @param instance in which the table resides
 * @param table in which the row resides
 * @param kijiRestRows POST-ed json data
 * @return a message containing the rowkey of interest
 * @throws IOException when post fails
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@ApiStability.Experimental
public Map<String, List<String>> postRows(@PathParam(INSTANCE_PARAMETER) final String instance,
        @PathParam(TABLE_PARAMETER) final String table, final JsonNode kijiRestRows) throws IOException {
    // We intend to return a JSON blob listing the row keys we are putting to.
    // i.e. {targets : [..., ..., ...]}
    final List<String> results = Lists.newLinkedList();

    final Iterator<JsonNode> rowIterator;
    if (kijiRestRows.isArray()) {
        rowIterator = kijiRestRows.elements();
    } else {
        rowIterator = Iterators.singletonIterator(kijiRestRows);
    }

    // Put each row.
    while (rowIterator.hasNext()) {
        final KijiRestRow kijiRestRow = mJsonObjectMapper.treeToValue(rowIterator.next(), KijiRestRow.class);
        final Map<String, String> result = postRow(instance, table, kijiRestRow);
        results.add(result.get("target"));
    }

    final Map<String, List<String>> returnedResults = Maps.newHashMap();
    returnedResults.put("targets", results);
    return returnedResults;
}

From source file:com.tango.elasticsearch.rest.action.unique.UniqueTermsAction.java

/**
 * Parse date request information and validates that request has expected format
 * <p/>/*from  w  w  w  . java  2s  .  c  o m*/
 * Example of input:
 * <code> {"facets": { "terms": { "terms": { "field": "@fields.uid", "size": 10000000, "order": "count", "exclude":
 * [] }, "facet_filter": { "fquery": { "query": { "filtered": { "query": { "bool": { "should": [ { "query_string": {
 * "query": "*" } } ] } }, "filter": { "bool": { "must": [ { "range": { "@timestamp": { "from": 1395275639569, "to":
 * "now" } } }, { "fquery": { "query": { "query_string": { "query": "@fields.tracer.service.name:(\"Like\")" } },
 * "_cache": true } }, { "terms": { "@fields.tracer.ip.country.name": ["UNITED STATES"] } } ] } } } } } } } },
 * "size": 0} }
 * </code>
 * 
 * @param requestSource source of request
 * @return parsed information
 * @throws IOException
 */
protected RequestParamsInfo getRequestInfo(String requestSource) throws IOException {
    RequestParamsInfo result = null;
    if (requestSource != null) {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(requestSource);
        JsonNode facets = jsonNode.findValue("facets");
        {
            if (facets.isMissingNode()) {
                throw new IllegalArgumentException("No facets found in requests");
            }
            Iterator<String> iterator = facets.fieldNames();
            while (iterator.hasNext()) {
                String facetName = iterator.next();
                if (!TARGET_FACET_NAME.equals(facetName)) {
                    throw new IllegalArgumentException("Unexpected facet name: " + facetName);
                }
            }
        }
        JsonNode terms = facets.path(TARGET_FACET_NAME);
        if (terms.isMissingNode()) {
            throw new IllegalArgumentException(
                    String.format("No facet with name '%s' found in requests", TARGET_FACET_NAME));
        }
        JsonNode range = jsonNode.findValue("@timestamp");
        if (range.isMissingNode()) {
            throw new IllegalArgumentException("No @timestamp found in requests");
        }
        String from = range.path("from").asText();
        String to = range.path("to").asText();
        if (from.length() > 0 && to.length() > 0) {
            long currentTime = System.currentTimeMillis();
            long fromLong = "now".equals(from) ? currentTime : Long.parseLong(from);
            long toLong = "now".equals(to) ? currentTime : Long.parseLong(to);
            Iterator<JsonNode> iterator = range.elements();
            while (iterator.hasNext()) {
                iterator.next();
                iterator.remove();
            }
            result = new RequestParamsInfo(fromLong, toLong, objectMapper.writeValueAsString(jsonNode));
        }
    }
    return result;
}

From source file:clearfacts.cds.JsonDataSource.java

public void moveFirst() throws JRException {
    if (jsonTree == null || jsonTree.isMissingNode()) {
        throw new JRException("No JSON data to operate on!");
    }//from  w  w  w .  j a  v a2s .  c  o  m

    currentJsonNode = null;
    JsonNode result = getJsonData(jsonTree, selectExpression);
    if (result != null && result.isObject()) {
        final List<JsonNode> list = new ArrayList<JsonNode>();
        list.add(result);
        jsonNodesIterator = new Iterator<JsonNode>() {
            private int count = -1;

            public void remove() {
                list.remove(count);
            }

            public JsonNode next() {
                count++;
                return list.get(count);
            }

            public boolean hasNext() {
                return count < list.size() - 1;
            }
        };
    } else if (result != null && result.isArray()) {
        jsonNodesIterator = result.elements();
    }
}

From source file:org.apache.olingo.commons.core.serialization.JsonDeserializer.java

protected String setInline(final String name, final String suffix, final JsonNode tree, final ObjectCodec codec,
        final LinkImpl link) throws IOException {

    final String entityNamePrefix = name.substring(0, name.indexOf(suffix));
    if (tree.has(entityNamePrefix)) {
        final JsonNode inline = tree.path(entityNamePrefix);
        JsonEntityDeserializer entityDeserializer = new JsonEntityDeserializer(version, serverMode);

        if (inline instanceof ObjectNode) {
            link.setType(ODataLinkType.ENTITY_NAVIGATION.toString());
            link.setInlineEntity(entityDeserializer.doDeserialize(inline.traverse(codec)).getPayload());

        } else if (inline instanceof ArrayNode) {
            link.setType(ODataLinkType.ENTITY_SET_NAVIGATION.toString());

            final EntitySet entitySet = new EntitySetImpl();
            for (final Iterator<JsonNode> entries = inline.elements(); entries.hasNext();) {
                entitySet.getEntities()/*from   w w  w  .ja  v a2  s  .co m*/
                        .add(entityDeserializer.doDeserialize(entries.next().traverse(codec)).getPayload());
            }

            link.setInlineEntitySet(entitySet);
        }
    }
    return entityNamePrefix;
}

From source file:controllers.AnyplaceMapping.java

private static boolean isBuildingCoOwner(ObjectNode building, String userId) {

    JsonNode cws = null;

    if (building != null && (cws = building.get("co_owners")) != null) {
        Iterator<JsonNode> it = cws.elements();
        while (it.hasNext()) {
            if (it.next().textValue().equals(userId)) {
                return true;
            }//  ww w.ja  va 2 s. c  o m
        }
    }

    return false;
}

From source file:tests.SearchTests.java

@Test
public void searchViaApiShort() {
    running(TEST_SERVER, new Runnable() {
        @Override/*  w w w. ja v  a 2 s . c om*/
        public void run() {
            final JsonNode jsonObject = Json.parse(call("resource?author=abraham&format=short"));
            assertThat(jsonObject.isArray()).isTrue();
            assertThat(jsonObject.size()).isGreaterThan(5).isLessThan(10);
            assertThat(jsonObject.elements().next().isContainerNode()).isFalse();
        }
    });
}

From source file:org.apache.olingo.client.core.serialization.JsonDeserializer.java

protected String setInline(final String name, final String suffix, final JsonNode tree, final ObjectCodec codec,
        final Link link) throws IOException {

    final String entityNamePrefix = name.substring(0, name.indexOf(suffix));

    Integer count = null;/*from www  .  jav a 2s .co  m*/
    if (tree.hasNonNull(entityNamePrefix + Constants.JSON_COUNT)) {
        count = tree.get(entityNamePrefix + Constants.JSON_COUNT).asInt();
    }

    if (tree.has(entityNamePrefix)) {
        final JsonNode inline = tree.path(entityNamePrefix);
        JsonEntityDeserializer entityDeserializer = new JsonEntityDeserializer(serverMode);

        if (inline instanceof ObjectNode) {
            link.setType(Constants.ENTITY_NAVIGATION_LINK_TYPE);
            link.setInlineEntity(entityDeserializer.doDeserialize(inline.traverse(codec)).getPayload());

        } else if (inline instanceof ArrayNode) {
            link.setType(Constants.ENTITY_SET_NAVIGATION_LINK_TYPE);

            final EntityCollection entitySet = new EntityCollection();
            if (count != null) {
                entitySet.setCount(count);
            }
            for (final Iterator<JsonNode> entries = inline.elements(); entries.hasNext();) {
                entitySet.getEntities()
                        .add(entityDeserializer.doDeserialize(entries.next().traverse(codec)).getPayload());
            }

            link.setInlineEntitySet(entitySet);
        }
    }
    return entityNamePrefix;
}

From source file:org.apache.olingo.client.core.serialization.JsonDeserializer.java

protected void value(final Valuable valuable, final JsonNode node, final ObjectCodec codec)
        throws IOException, EdmPrimitiveTypeException {

    EdmTypeInfo typeInfo = StringUtils.isBlank(valuable.getType()) ? null
            : new EdmTypeInfo.Builder().setTypeExpression(valuable.getType()).build();

    final Map.Entry<PropertyType, EdmTypeInfo> guessed = guessPropertyType(node);
    if (typeInfo == null) {
        typeInfo = guessed.getValue();//  w ww.  j  a  va 2 s  .  co m
    }

    final PropertyType propType = typeInfo == null ? guessed.getKey()
            : typeInfo.isCollection() ? PropertyType.COLLECTION
                    : typeInfo.isPrimitiveType() ? PropertyType.PRIMITIVE
                            : node.isValueNode() ? PropertyType.ENUM : PropertyType.COMPLEX;

    switch (propType) {
    case COLLECTION:
        fromCollection(valuable, node.elements(), typeInfo, codec);
        break;

    case COMPLEX:
        if (node.has(Constants.JSON_TYPE)) {
            valuable.setType(node.get(Constants.JSON_TYPE).asText());
            ((ObjectNode) node).remove(Constants.JSON_TYPE);
        }
        final Object value = fromComplex((ObjectNode) node, codec);
        valuable.setValue(ValueType.COMPLEX, value);
        break;

    case ENUM:
        valuable.setValue(ValueType.ENUM, node.asText());
        break;

    case PRIMITIVE:
        if (valuable.getType() == null && typeInfo != null) {
            valuable.setType(typeInfo.getFullQualifiedName().toString());
        }
        final Object primitiveValue = fromPrimitive(node, typeInfo);
        valuable.setValue(primitiveValue instanceof Geospatial ? ValueType.GEOSPATIAL : ValueType.PRIMITIVE,
                primitiveValue);
        break;

    case EMPTY:
    default:
        valuable.setValue(ValueType.PRIMITIVE, StringUtils.EMPTY);
    }
}

From source file:org.apache.olingo.commons.core.serialization.JsonDeserializer.java

protected void value(final Valuable valuable, final JsonNode node, final ObjectCodec codec)
        throws IOException, EdmPrimitiveTypeException {

    EdmTypeInfo typeInfo = StringUtils.isBlank(valuable.getType()) ? null
            : new EdmTypeInfo.Builder().setTypeExpression(valuable.getType()).build();

    final Map.Entry<ODataPropertyType, EdmTypeInfo> guessed = guessPropertyType(node);
    if (typeInfo == null) {
        typeInfo = guessed.getValue();/*w w  w  .j av a 2  s .  c  o m*/
    }

    final ODataPropertyType propType = typeInfo == null ? guessed.getKey()
            : typeInfo.isCollection() ? ODataPropertyType.COLLECTION
                    : typeInfo.isPrimitiveType() ? ODataPropertyType.PRIMITIVE
                            : node.isValueNode() ? ODataPropertyType.ENUM : ODataPropertyType.COMPLEX;

    switch (propType) {
    case COLLECTION:
        fromCollection(valuable, node.elements(), typeInfo, codec);
        break;

    case COMPLEX:
        if (node.has(jsonType)) {
            valuable.setType(node.get(jsonType).asText());
            ((ObjectNode) node).remove(jsonType);
        }
        final Object value = fromComplex((ObjectNode) node, codec);
        valuable.setValue(value instanceof LinkedComplexValue ? ValueType.LINKED_COMPLEX : ValueType.COMPLEX,
                value);
        break;

    case ENUM:
        valuable.setValue(ValueType.ENUM, node.asText());
        break;

    case PRIMITIVE:
        if (valuable.getType() == null && typeInfo != null) {
            valuable.setType(typeInfo.getFullQualifiedName().toString());
        }
        final Object primitiveValue = fromPrimitive(node, typeInfo);
        valuable.setValue(primitiveValue instanceof Geospatial ? ValueType.GEOSPATIAL : ValueType.PRIMITIVE,
                primitiveValue);
        break;

    case EMPTY:
    default:
        valuable.setValue(ValueType.PRIMITIVE, StringUtils.EMPTY);
    }
}