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:org.numenta.nupic.algorithms.CLAClassifierDeserializer.java

@Override
public CLAClassifier deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    ObjectCodec oc = jp.getCodec();//from  w w w  . jav a2 s.  c o  m
    JsonNode node = oc.readTree(jp);

    CLAClassifier retVal = new CLAClassifier();
    retVal.alpha = node.get("alpha").asDouble();
    retVal.actValueAlpha = node.get("actValueAlpha").asDouble();
    retVal.learnIteration = node.get("learnIteration").asInt();
    retVal.recordNumMinusLearnIteration = node.get("recordNumMinusLearnIteration").asInt();
    retVal.maxBucketIdx = node.get("maxBucketIdx").asInt();

    String[] steps = node.get("steps").asText().split(",");
    TIntList t = new TIntArrayList();
    for (String step : steps) {
        t.add(Integer.parseInt(step));
    }
    retVal.steps = t;

    String[] tupleStrs = node.get("patternNZHistory").asText().split(";");
    Deque<Tuple> patterns = new Deque<Tuple>(tupleStrs.length);
    for (String tupleStr : tupleStrs) {
        String[] tupleParts = tupleStr.split("-");
        int iteration = Integer.parseInt(tupleParts[0]);
        String pattern = tupleParts[1].substring(1, tupleParts[1].indexOf("]")).trim();
        String[] indexes = pattern.split(",");
        int[] indices = new int[indexes.length];
        for (int i = 0; i < indices.length; i++) {
            indices[i] = Integer.parseInt(indexes[i].trim());
        }
        Tuple tup = new Tuple(iteration, indices);
        patterns.append(tup);
    }
    retVal.patternNZHistory = patterns;

    Map<Tuple, BitHistory> bitHistoryMap = new HashMap<Tuple, BitHistory>();
    String[] bithists = node.get("activeBitHistory").asText().split(";");
    for (String bh : bithists) {
        String[] parts = bh.split("-");

        String[] left = parts[0].split(",");
        Tuple iteration = new Tuple(Integer.parseInt(left[0].trim()), Integer.parseInt(left[1].trim()));

        BitHistory bitHistory = new BitHistory();
        String[] right = parts[1].split("=");
        bitHistory.id = right[0].trim();

        TDoubleList dubs = new TDoubleArrayList();
        String[] stats = right[1].substring(1, right[1].indexOf("}")).trim().split(",");
        for (int i = 0; i < stats.length; i++) {
            dubs.add(Double.parseDouble(stats[i].trim()));
        }
        bitHistory.stats = dubs;

        bitHistory.lastTotalUpdate = Integer.parseInt(right[2].trim());

        bitHistoryMap.put(iteration, bitHistory);
    }
    retVal.activeBitHistory = bitHistoryMap;

    ArrayNode jn = (ArrayNode) node.get("actualValues");
    List<Object> l = new ArrayList<Object>();
    for (int i = 0; i < jn.size(); i++) {
        JsonNode n = jn.get(i);
        try {
            double d = Double.parseDouble(n.asText().trim());
            l.add(d);
        } catch (Exception e) {
            l.add(n.asText().trim());
        }
    }
    retVal.actualValues = l;

    //Go back and set the classifier on the BitHistory objects
    for (Tuple tuple : bitHistoryMap.keySet()) {
        bitHistoryMap.get(tuple).classifier = retVal;
    }

    return retVal;
}

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

@Test
public void sampleSPARQLQuery2() throws JsonGenerationException, JsonMappingException, IOException {
    String assertTypeHasProperties = "PREFIX t: <http://marklogic.com/testing-entity-type/SchemaCompleteEntityType-0.0.1/> "
            + "PREFIX es: <http://marklogic.com/entity-services#> " + "SELECT ?version where {"
            + "t:SchemaCompleteEntityType ?version \"0.0.1\" ." + "}";

    JacksonHandle handle = queryMgr.executeSelect(queryMgr.newQueryDefinition(assertTypeHasProperties),
            new JacksonHandle());
    JsonNode results = handle.get();/*www . ja  v  a2  s  .  c o  m*/

    // to see on System.out
    //new ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(System.out, results);

    ArrayNode bindings = (ArrayNode) results.get("results").get("bindings");
    assertEquals(1, bindings.size());

    assertEquals("http://marklogic.com/entity-services#version",
            bindings.get(0).get("version").get("value").asText());
}

From source file:net.maurerit.zkb.KillParser.java

private List<Attacker> parseAttackers(TreeNode node) {
    List<Attacker> attackers = new ArrayList<Attacker>();

    if (node instanceof ArrayNode) {
        ArrayNode arrayNode = (ArrayNode) node;

        for (int idx = 0; idx < arrayNode.size(); idx++) {
            JsonNode attackerNode = arrayNode.get(idx);
            Attacker attacker = new Attacker();

            attacker.setCharacterId(intFromText(attackerNode.get(CHAR_ID_KEY)));
            attacker.setCharacterName(attackerNode.get(CHAR_NAME_KEY).asText());
            attacker.setCorporationId(intFromText(attackerNode.get(CORP_ID_KEY)));
            attacker.setCorporationName(attackerNode.get(CORP_NAME_KEY).asText());
            attacker.setAllianceId(intFromText(attackerNode.get(ALLIANCE_ID_KEY)));
            attacker.setAllianceName(attackerNode.get(ALLIANCE_NAME_KEY).asText());
            attacker.setFactionId(intFromText(attackerNode.get(FACTION_ID_KEY)));
            attacker.setFactionName(attackerNode.get(FACTION_NAME_KEY).asText());
            attacker.setSecurityStatus(doubleFromText(attackerNode.get(SEC_STATUS_KEY)));
            attacker.setDamageDone(longFromText(attackerNode.get(DAMAGE_DONE_KEY)));
            attacker.setFinalBlow(booleanFromText(attackerNode.get(FINAL_BLOW_KEY)));
            attacker.setWeaponTypeId(intFromText(attackerNode.get(WEAPON_TYPE_KEY)));
            attacker.setWeaponName(TypeID.getTypeName(intFromText(attackerNode.get(WEAPON_TYPE_KEY))));
            attacker.setShipTypeId(intFromText(attackerNode.get(SHIP_TYPE_KEY)));
            attacker.setShipName(TypeID.getTypeName(intFromText(attackerNode.get(SHIP_TYPE_KEY))));

            attackers.add(attacker);/*from   w  ww  . j av  a 2 s.c o  m*/
        }
    }

    return attackers;
}

From source file:org.apache.streams.json.JsonPathFilter.java

@Override
public List<StreamsDatum> process(StreamsDatum entry) {

    List<StreamsDatum> result = Lists.newArrayList();

    String json = null;/*  ww  w .  j a v  a 2  s  . c o m*/

    ObjectNode document = null;

    LOGGER.debug("{} processing {}", STREAMS_ID);

    if (entry.getDocument() instanceof ObjectNode) {
        document = (ObjectNode) entry.getDocument();
        try {
            json = mapper.writeValueAsString(document);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    } else if (entry.getDocument() instanceof String) {
        json = (String) entry.getDocument();
        try {
            document = mapper.readValue(json, ObjectNode.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    Preconditions.checkNotNull(document);

    if (StringUtils.isNotEmpty(json)) {

        Object srcResult = null;
        try {
            srcResult = jsonPath.read(json);

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.warn(e.getMessage());
        }

        Preconditions.checkNotNull(srcResult);

        String[] path = StringUtils.split(pathExpression, '.');
        ObjectNode node = document;
        for (int i = 1; i < path.length - 1; i++) {
            node = (ObjectNode) document.get(path[i]);
        }

        Preconditions.checkNotNull(node);

        if (srcResult instanceof JSONArray) {
            try {
                ArrayNode jsonNode = mapper.convertValue(srcResult, ArrayNode.class);
                if (jsonNode.size() == 1) {
                    JsonNode item = jsonNode.get(0);
                    node.set(destNodeName, item);
                } else {
                    node.set(destNodeName, jsonNode);
                }
            } catch (Exception e) {
                LOGGER.warn(e.getMessage());
            }
        } else if (srcResult instanceof JSONObject) {
            try {
                ObjectNode jsonNode = mapper.convertValue(srcResult, ObjectNode.class);
                node.set(destNodeName, jsonNode);
            } catch (Exception e) {
                LOGGER.warn(e.getMessage());
            }
        } else if (srcResult instanceof String) {
            try {
                node.put(destNodeName, (String) srcResult);
            } catch (Exception e) {
                LOGGER.warn(e.getMessage());
            }
        }

    }

    result.add(new StreamsDatum(document));

    return result;

}

From source file:com.datamountaineer.streamreactor.connect.json.SimpleJsonConverterTest.java

@Test
public void mapToJsonNonStringKeys() {
    Schema intIntMap = SchemaBuilder.map(Schema.INT32_SCHEMA, Schema.INT32_SCHEMA).build();
    Map<Integer, Integer> input = new HashMap<>();
    input.put(1, 12);//from w  ww .  j  a  v  a 2  s .co m
    input.put(2, 15);
    JsonNode converted = converter.fromConnectData(intIntMap, input);

    assertTrue(converted.isArray());
    ArrayNode payload = (ArrayNode) converted;
    assertEquals(2, payload.size());
    Set<JsonNode> payloadEntries = new HashSet<>();
    for (JsonNode elem : payload)
        payloadEntries.add(elem);
    assertEquals(new HashSet<>(Arrays.asList(JsonNodeFactory.instance.arrayNode().add(1).add(12),
            JsonNodeFactory.instance.arrayNode().add(2).add(15))), payloadEntries);
}

From source file:com.datamountaineer.streamreactor.connect.json.SimpleJsonConverterTest.java

@Test
public void nullSchemaAndMapNonStringKeysToJson() {
    // This still needs to do conversion of data, null schema means "anything goes". Make sure we mix and match
    // types to verify conversion still works.
    Map<Object, Object> input = new HashMap<>();
    input.put("string", 12);
    input.put(52, "string");
    input.put(false, true);/*from   w ww. j  ava  2 s .  co  m*/
    JsonNode converted = converter.fromConnectData(null, input);
    assertTrue(converted.isArray());
    ArrayNode payload = (ArrayNode) converted;
    assertEquals(3, payload.size());
    Set<JsonNode> payloadEntries = new HashSet<>();
    for (JsonNode elem : payload)
        payloadEntries.add(elem);
    assertEquals(new HashSet<>(Arrays.asList(JsonNodeFactory.instance.arrayNode().add("string").add(12),
            JsonNodeFactory.instance.arrayNode().add(52).add("string"),
            JsonNodeFactory.instance.arrayNode().add(false).add(true))), payloadEntries);
}

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

private void erlangBucketMR(String bucketType) throws InterruptedException, ExecutionException {
    initValues(bucketType);//  ww w. j a  v a2s . c  o  m
    Namespace ns = new Namespace(bucketType, mrBucketName);
    BucketMapReduce bmr = new BucketMapReduce.Builder().withNamespace(ns)
            .withMapPhase(Function.newErlangFunction("riak_kv_mapreduce", "map_object_value"), false)
            .withReducePhase(Function.newErlangFunction("riak_kv_mapreduce", "reduce_string_to_integer"), false)
            .withReducePhase(Function.newErlangFunction("riak_kv_mapreduce", "reduce_sort"), true).build();

    MapReduce.Response response = client.execute(bmr);

    // 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(2);
    assertEquals(200, result.size());

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

    resetAndEmptyBucket(ns);
}

From source file:org.waarp.common.json.AdaptativeJsonHandlerTest.java

/**
 * Test method for {@link org.waarp.common.json.AdaptativeJsonHandler#createArrayNode()}.
 *//*from ww  w . j a  v a 2s . c  o  m*/
@Test
public void testCreateArrayNode() {
    ArrayNode node = handler.createArrayNode();
    node.add(true);
    node.add("bytes".getBytes());
    node.add(2.0);
    node.add(3);
    node.add(5L);
    node.add("string");
    assertTrue(node.size() == 6);
    String result = handler.writeAsString(node);
    ArrayNode node2;
    try {
        node2 = (ArrayNode) handler.mapper.readTree(result);
    } catch (JsonProcessingException e) {
        fail(e.getMessage());
        return;
    } catch (IOException e) {
        fail(e.getMessage());
        return;
    }
    assertTrue(result.equals(handler.writeAsString(node2)));
}

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

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

    // This test verifies that property has RDFtype,title and data type
    String assertPropertyHasRDFtitledatatype = "PREFIX t: <http://marklogic.com/testing-entity-type/SchemaCompleteEntityType-0.0.1/SchemaCompleteEntityType/>"
            + "SELECT ?p ?o " + "WHERE { t:base64BinaryKey ?p ?o }" + "order by ?s";

    JacksonHandle handle = queryMgr//from  w w w.  jav a 2  s  .  co m
            .executeSelect(queryMgr.newQueryDefinition(assertPropertyHasRDFtitledatatype), 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(3, bindings.size());
    //Property has 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#Property",
            bindings.get(0).get("o").get("value").asText());

    //Property has data type 
    assertEquals("http://marklogic.com/entity-services#datatype",
            bindings.get(1).get("p").get("value").asText());
    assertEquals("http://www.w3.org/2001/XMLSchema#base64Binary",
            bindings.get(1).get("o").get("value").asText());

    //Property has title
    assertEquals("http://marklogic.com/entity-services#title", bindings.get(2).get("p").get("value").asText());
    assertEquals("base64BinaryKey", bindings.get(2).get("o").get("value").asText());

}

From source file:org.waarp.common.json.JsonHandlerTest.java

/**
 * Test method for {@link org.waarp.common.json.JsonHandler#createArrayNode()}.
 *///from  w  ww  .  j ava 2  s  .  c o m
@Test
public void testCreateArrayNode() {
    ArrayNode node = JsonHandler.createArrayNode();
    node.add(true);
    node.add("bytes".getBytes());
    node.add(2.0);
    node.add(3);
    node.add(5L);
    node.add("string");
    assertTrue(node.size() == 6);
    String result = JsonHandler.writeAsString(node);
    ArrayNode node2;
    try {
        node2 = (ArrayNode) JsonHandler.mapper.readTree(result);
    } catch (JsonProcessingException e) {
        fail(e.getMessage());
        return;
    } catch (IOException e) {
        fail(e.getMessage());
        return;
    }
    assertTrue(result.equals(JsonHandler.writeAsString(node2)));
}