Example usage for com.fasterxml.jackson.databind.node ArrayNode size

List of usage examples for com.fasterxml.jackson.databind.node ArrayNode size

Introduction

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

Prototype

public int size() 

Source Link

Usage

From source file:com.basho.riak.client.api.commands.itest.ITestBucketMapReduce.java

private void JsBucketMR(String bucketType) throws InterruptedException, ExecutionException {
    initValues(bucketType);/*from  ww  w.  ja  v  a2s .  c  om*/

    Namespace ns = new Namespace(bucketType, mrBucketName);
    BucketMapReduce bmr = new BucketMapReduce.Builder().withNamespace(ns)
            .withMapPhase(Function.newNamedJsFunction("Riak.mapValuesJson"), false)
            .withReducePhase(Function.newNamedJsFunction("Riak.reduceNumericSort"), true).build();

    RiakFuture<MapReduce.Response, BinaryValue> future = client.executeAsync(bmr);

    future.await();
    assertTrue("Map reduce operation Operation failed:" + future.cause(), future.isSuccess());

    MapReduce.Response response = future.get();

    // The query should return one phase result which is a JSON array containing
    // all the values, 0 - 199
    assertEquals(200, response.getResultsFromAllPhases().size());
    ArrayNode result = response.getResultForPhase(1);
    assertEquals(200, result.size());

    assertEquals(42, result.get(42).asInt());
    assertEquals(199, result.get(199).asInt());

    resetAndEmptyBucket(ns);
}

From source file:com.basho.riak.client.api.commands.itest.ITestBucketMapReduce.java

@Test
public void multiPhaseResult() throws InterruptedException, ExecutionException {
    initValues(Namespace.DEFAULT_BUCKET_TYPE);

    Namespace ns = new Namespace(Namespace.DEFAULT_BUCKET_TYPE, mrBucketName);
    BucketMapReduce bmr = new BucketMapReduce.Builder().withNamespace(ns)
            .withMapPhase(Function.newNamedJsFunction("Riak.mapValuesJson"), true)
            .withReducePhase(Function.newNamedJsFunction("Riak.reduceNumericSort"), true).build();

    RiakFuture<MapReduce.Response, BinaryValue> future = client.executeAsync(bmr);

    future.await();//www  .  jav  a2 s . co m
    assertTrue(future.isSuccess());

    MapReduce.Response response = future.get();

    // The query should return two phase results, each a JSON array containing
    // all the values, 0 - 199
    assertEquals(400, response.getResultsFromAllPhases().size());
    assertEquals(200, response.getResultForPhase(0).size());
    ArrayNode result = response.getResultForPhase(1);
    assertEquals(200, result.size());

    assertEquals(42, result.get(42).asInt());
    assertEquals(199, result.get(199).asInt());

    resetAndEmptyBucket(ns);
}

From source file:com.turn.shapeshifter.NamedSchemaSerializer.java

/**
 * {@inheritDoc}//from ww w  .j a  v  a  2s  .co m
 *
 * This variation allows for the inclusion of schemas for serializing
 * sub-objects that may appear in {@code message}. If no suitable schema
 * is found in the registry, a schema with default settings is generated
 * on the fly using {@link
 * SchemaSource#get(com.google.protobuf.Descriptors.Descriptor)}.
 *
 */
@Override
public JsonNode serialize(Message message, ReadableSchemaRegistry registry) throws SerializationException {
    ObjectNode object = new ObjectNode(JsonNodeFactory.instance);
    for (Map.Entry<String, String> constant : schema.getConstants().entrySet()) {
        object.put(constant.getKey(), constant.getValue());
    }
    for (Map.Entry<String, FieldDescriptor> fieldEntry : schema.getFields().entrySet()) {
        if (schema.getSkippedFields().contains(fieldEntry.getKey())) {
            continue;
        }
        FieldDescriptor field = fieldEntry.getValue();
        if (field.isRepeated()) {
            int count = message.getRepeatedFieldCount(field);
            if (count > 0) {
                if (schema.getMappings().containsKey(field.getName())) {
                    ObjectNode objectNode = serializeMappedField(message, registry, field, count);
                    if (objectNode.size() > 0) {
                        object.put(schema.getPropertyName(field.getName()), objectNode);
                    }
                } else {
                    ArrayNode array = serializeRepeatedField(message, registry, field, count);
                    if (array.size() > 0) {
                        object.put(schema.getPropertyName(field.getName()), array);
                    }
                }
            }
        } else if (message.hasField(field)) {
            Object value = message.getField(field);
            JsonNode fieldNode = serializeValue(value, field, registry);
            object.put(schema.getPropertyName(field.getName()), fieldNode);
        }
    }
    if (object.size() == 0) {
        return NullNode.instance;
    }
    return object;
}

From source file:org.gitana.platform.client.job.JobImpl.java

@Override
public List<JobLogEntry> getLogEntries() {
    List<JobLogEntry> list = new ArrayList<JobLogEntry>();

    ArrayNode entries = getArray(FIELD_LOG_ENTRIES);
    for (int i = 0; i < entries.size(); i++) {
        ObjectNode object = (ObjectNode) entries.get(i);

        JobLogEntry entry = new JobLogEntry(object);
        list.add(entry);/*from   w w  w  .j  a  v a  2 s .com*/
    }

    return list;
}

From source file:com.discover.cls.processors.cls.JSONToAttributes.java

private void addKeys(final String currentPath, final JsonNode jsonNode, final String separator,
        final boolean preserveType, final boolean flattenArrays, final Map<String, String> map) {
    if (jsonNode.isObject()) {
        ObjectNode objectNode = (ObjectNode) jsonNode;
        Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
        String pathPrefix = currentPath.isEmpty() ? "" : currentPath + separator;

        while (iter.hasNext()) {
            Map.Entry<String, JsonNode> entry = iter.next();
            addKeys(pathPrefix + entry.getKey(), entry.getValue(), separator, preserveType, flattenArrays, map);
        }/*from  w w w .  ja va  2  s .  c o m*/
    } else if (jsonNode.isArray()) {
        if (flattenArrays) {
            ArrayNode arrayNode = (ArrayNode) jsonNode;
            for (int i = 0; i < arrayNode.size(); i++) {
                addKeys(currentPath + "[" + i + "]", arrayNode.get(i), separator, preserveType, flattenArrays,
                        map);
            }
        } else {
            map.put(currentPath, jsonNode.toString());
        }
    } else if (jsonNode.isValueNode()) {
        ValueNode valueNode = (ValueNode) jsonNode;
        map.put(currentPath,
                valueNode.isTextual() && preserveType ? valueNode.toString() : valueNode.textValue());
    }
}

From source file:com.marklogic.entityservices.TestEsEntityTypeSPARQL.java

@Test
public void testSPARQLEntityType() throws JsonGenerationException, JsonMappingException, IOException {

    // This test verifies that EntityType doc SchemaCompleteEntityType-0.0.1 has all the ET in it and version and title
    String assertEachEntityTypeHasProperties = "PREFIX t: <http://marklogic.com/testing-entity-type/SchemaCompleteEntityType-0.0.1/>"
            + "SELECT ?p ?o " + "WHERE {  t:OrderDetails ?p ?o    }" + "order by ?s";

    JacksonHandle handle = queryMgr/*from w w  w.j  a  va 2s  . c o m*/
            .executeSelect(queryMgr.newQueryDefinition(assertEachEntityTypeHasProperties), new JacksonHandle());
    JsonNode results = handle.get();
    // to see on System.out
    //new ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(System.out, results);

    ArrayNode bindings = (ArrayNode) results.get("results").get("bindings");
    assertEquals(6, bindings.size());
    //Each Entity Type has a RDF type
    assertEquals("http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
            bindings.get(0).get("p").get("value").asText());
    assertEquals("http://marklogic.com/entity-services#EntityType",
            bindings.get(0).get("o").get("value").asText());

    //Entity type has property ProductName
    assertEquals("http://marklogic.com/entity-services#property",
            bindings.get(1).get("p").get("value").asText());
    assertEquals(
            "http://marklogic.com/testing-entity-type/SchemaCompleteEntityType-0.0.1/OrderDetails/productName",
            bindings.get(1).get("o").get("value").asText());

    //Entity type has property ProductName
    assertEquals("http://marklogic.com/entity-services#primaryKey",
            bindings.get(2).get("p").get("value").asText());
    assertEquals(
            "http://marklogic.com/testing-entity-type/SchemaCompleteEntityType-0.0.1/OrderDetails/quantity",
            bindings.get(2).get("o").get("value").asText());

    //Entity type has property quantity
    assertEquals("http://marklogic.com/entity-services#property",
            bindings.get(3).get("p").get("value").asText());
    assertEquals(
            "http://marklogic.com/testing-entity-type/SchemaCompleteEntityType-0.0.1/OrderDetails/quantity",
            bindings.get(3).get("o").get("value").asText());

    //Entity type has version
    assertEquals("http://marklogic.com/entity-services#version",
            bindings.get(4).get("p").get("value").asText());
    assertEquals("0.0.1", bindings.get(4).get("o").get("value").asText());

    //Entity type has title
    assertEquals("http://marklogic.com/entity-services#title", bindings.get(5).get("p").get("value").asText());
    assertEquals("OrderDetails", bindings.get(5).get("o").get("value").asText());

}

From source file:graphene.dao.es.impl.CombinedDAOESImpl.java

@Override
public G_SearchResults search(final G_EntityQuery pq) {
    // TODO: Use a helper class
    final G_SearchResults results = G_SearchResults.newBuilder().setTotal(0)
            .setResults(new ArrayList<G_SearchResult>()).build();

    final List<G_SearchResult> resultsList = new ArrayList<G_SearchResult>();
    JestResult jestResult = new JestResult(null);
    try {//w  ww  .jav  a 2 s.  co m
        final io.searchbox.core.Search.Builder action = buildSearchAction(pq);
        JestClient jestClient = c.getClient();
        synchronized (jestClient) {
            jestResult = jestClient.execute(action.build());
        }
    } catch (final DataAccessException e) {
        e.printStackTrace();
    } catch (final Exception e) {
        e.printStackTrace();
    }
    // logger.debug(jestResult.getJsonString());
    JsonNode rootNode;
    long totalNumberOfPossibleResults = 0l;
    try {
        rootNode = mapper.readValue(jestResult.getJsonString(), JsonNode.class);

        if ((rootNode != null) && (rootNode.get("hits") != null)
                && (rootNode.get("hits").get("total") != null)) {
            totalNumberOfPossibleResults = rootNode.get("hits").get("total").asLong();
            logger.debug("Found " + totalNumberOfPossibleResults + " hits in hitparent!");
            final ArrayNode actualListOfHits = getListOfHitsFromResult(jestResult);

            for (int i = 0; i < actualListOfHits.size(); i++) {
                final JsonNode currentHit = actualListOfHits.get(i);
                if (ValidationUtils.isValid(currentHit)) {
                    final G_SearchResult result = db.buildSearchResultFromDocument(i, currentHit, pq);
                    if (result == null) {
                        logger.error("could not build search result from hit " + currentHit.toString());
                    }
                    CollectionUtils.addIgnoreNull(resultsList, result);
                } else {
                    logger.error("Invalid search result at index " + i + " for query " + pq.toString());
                }
            }
        }
    } catch (final IOException e) {
        e.printStackTrace();
    }
    results.setResults(resultsList);
    results.setTotal(totalNumberOfPossibleResults);
    return results;
}

From source file:org.thingsboard.server.dao.rule.BaseRuleService.java

private void validateFilters(JsonNode filtersJson) {
    if (filtersJson == null || filtersJson.isNull()) {
        throw new IncorrectParameterException("Rule filters are required!");
    }/*from  w w w .j a va2  s .  co  m*/
    if (!filtersJson.isArray()) {
        throw new IncorrectParameterException("Filters json is not an array!");
    }
    ArrayNode filtersArray = (ArrayNode) filtersJson;
    for (int i = 0; i < filtersArray.size(); i++) {
        validateComponentJson(filtersArray.get(i), ComponentType.FILTER);
    }
}

From source file:com.turn.shapeshifter.NamedSchemaParserTest.java

@Test
public void testParseWithRepeatedTransform() throws Exception {
    NamedSchema schema = NamedSchema.of(Union.getDescriptor(), "Union").transform("int32_repeated", TWO);
    SchemaRegistry registry = new SchemaRegistry();
    registry.register(schema);/*from   w ww  .j  ava 2 s .c o  m*/
    Union fibonacci = Union.newBuilder().addInt32Repeated(1).addInt32Repeated(1).addInt32Repeated(2)
            .addInt32Repeated(3).addInt32Repeated(5).addInt32Repeated(8).build();
    JsonNode result = new NamedSchemaSerializer(schema).serialize(fibonacci, registry);

    ArrayNode repeated = (ArrayNode) result.get("int32Repeated");
    Assert.assertEquals(6, repeated.size());
    Assert.assertEquals(2, repeated.get(0).asInt());
    Assert.assertEquals(2, repeated.get(1).asInt());
    Assert.assertEquals(4, repeated.get(2).asInt());
    Assert.assertEquals(6, repeated.get(3).asInt());
    Assert.assertEquals(10, repeated.get(4).asInt());
    Assert.assertEquals(16, repeated.get(5).asInt());

    Union parsed = Union.newBuilder().mergeFrom(new NamedSchemaParser(schema).parse(result, registry)).build();
    Assert.assertEquals(1, parsed.getInt32Repeated(0));
    Assert.assertEquals(1, parsed.getInt32Repeated(1));
    Assert.assertEquals(2, parsed.getInt32Repeated(2));
    Assert.assertEquals(3, parsed.getInt32Repeated(3));
    Assert.assertEquals(5, parsed.getInt32Repeated(4));
    Assert.assertEquals(8, parsed.getInt32Repeated(5));
}