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

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

Introduction

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

Prototype

public int size() 

Source Link

Usage

From source file:com.metamx.common.parsers.JSONToLowerParser.java

@Override
public Map<String, Object> parse(String input) {
    try {//from ww  w.jav  a 2s  . c o  m
        Map<String, Object> map = new LinkedHashMap<>();
        JsonNode root = objectMapper.readTree(input);

        Iterator<String> keysIter = (fieldNames == null ? root.fieldNames() : fieldNames.iterator());

        while (keysIter.hasNext()) {
            String key = keysIter.next();

            if (exclude.contains(key.toLowerCase())) {
                continue;
            }

            JsonNode node = root.path(key);

            if (node.isArray()) {
                final List<Object> nodeValue = Lists.newArrayListWithExpectedSize(node.size());
                for (final JsonNode subnode : node) {
                    final Object subnodeValue = valueFunction.apply(subnode);
                    if (subnodeValue != null) {
                        nodeValue.add(subnodeValue);
                    }
                }
                map.put(key.toLowerCase(), nodeValue); // difference from JSONParser parse()
            } else {
                final Object nodeValue = valueFunction.apply(node);
                if (nodeValue != null) {
                    map.put(key.toLowerCase(), nodeValue); // difference from JSONParser parse()
                }
            }
        }
        return map;
    } catch (Exception e) {
        throw new ParseException(e, "Unable to parse row [%s]", input);
    }
}

From source file:com.arpnetworking.tsdcore.sinks.ReMetSinkTest.java

@Test
public void testSerializeMultiple() throws IOException {
    final AggregatedData datumA = TestBeanFactory.createAggregatedData();
    final AggregatedData datumB = TestBeanFactory.createAggregatedData();
    final List<AggregatedData> data = Lists.newArrayList(datumA, datumB);
    final ReMetSink remetSink = _remetSinkBuilder.build();
    final Collection<String> serializedData = remetSink.serialize(data, Collections.<Condition>emptyList());
    remetSink.close();// w  w w  .j a  v a 2s.  c o m

    Assert.assertEquals(1, serializedData.size());
    final JsonNode jsonArrayNode = OBJECT_MAPPER.readTree(Iterables.getOnlyElement(serializedData));
    Assert.assertTrue(jsonArrayNode.isArray());
    Assert.assertEquals(2, jsonArrayNode.size());
    final JsonNode jsonNodeA = jsonArrayNode.get(0);
    final JsonNode jsonNodeB = jsonArrayNode.get(1);
    assertJsonEqualsDatum(jsonNodeA, datumA);
    assertJsonEqualsDatum(jsonNodeB, datumB);
}

From source file:org.activiti.rest.service.api.runtime.ExecutionActiveActivitiesCollectionResourceTest.java

@Deployment
public void testGetActivities() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("processOne");

    CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls
            .createRelativeResourceUrl(RestUrls.URL_EXECUTION_ACTIVITIES_COLLECTION, processInstance.getId())),
            HttpStatus.SC_OK);/*ww  w .j av a  2  s .  c  om*/

    // Check resulting instance
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertTrue(responseNode.isArray());
    assertEquals(2, responseNode.size());

    Set<String> states = new HashSet<String>();
    states.add(responseNode.get(0).textValue());
    states.add(responseNode.get(1).textValue());

    assertTrue(states.contains("waitState"));
    assertTrue(states.contains("anotherWaitState"));
}

From source file:org.n52.iceland.config.json.JsonSettingsDao.java

@Override
public Set<SettingValue<?>> getSettingValues() {
    readLock().lock();//  w  ww  .  ja  v  a  2 s.  co  m
    try {
        JsonNode node = getConfiguration().path(JsonConstants.SETTINGS);
        Set<SettingValue<?>> values = new HashSet<>(node.size());
        node.fieldNames().forEachRemaining(key -> values.add(createSettingValue(key, node.path(key))));
        return values;
    } finally {
        readLock().unlock();
    }
}

From source file:com.baidubce.services.moladb.model.transform.AttributeValueUnmarshaller.java

@Override
public AttributeValue unmarshall(JsonNode jsonObj) throws Exception {

    if (jsonObj.isNull()) {
        logger.error("Input json obj is null");
        throw new BceClientException("Input json obj is null");
    }//from   w  w w  .ja  v  a  2s .  co  m
    if (!jsonObj.isObject() || 0 == jsonObj.size()) {
        logger.error("Input json node:" + jsonObj.toString() + " is not a object or size is 0");
        throw new BceClientException("Illegal json:" + jsonObj.toString() + " for AttributeValue");
    }

    AttributeValue value = new AttributeValue();
    Iterator<String> fieldNames = jsonObj.fieldNames();
    String type = fieldNames.next();
    String val = jsonObj.get(type).asText();
    value.setValue(type, val);
    return value;
}

From source file:org.activiti.rest.service.api.runtime.ProcessInstanceQueryResourceTest.java

/**
 * Test querying process instance based on variables. POST query/process-instances
 *//*from   w w  w. j a  v a  2 s .  c om*/
@Deployment
public void testQueryProcessInstancesPagingAndSorting() throws Exception {
    ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("aOneTaskProcess");
    ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("bOneTaskProcess");
    ProcessInstance processInstance3 = runtimeService.startProcessInstanceByKey("cOneTaskProcess");

    // Create request node
    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("order", "desc");
    requestNode.put("sort", "processDefinitionKey");

    String url = RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_QUERY);
    HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + url);
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_OK);

    // Check order
    JsonNode rootNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    JsonNode dataNode = rootNode.get("data");
    assertEquals(3, dataNode.size());

    assertEquals(processInstance3.getId(), dataNode.get(0).get("id").asText());
    assertEquals(processInstance2.getId(), dataNode.get(1).get("id").asText());
    assertEquals(processInstance1.getId(), dataNode.get(2).get("id").asText());

    // Check paging size
    requestNode = objectMapper.createObjectNode();
    requestNode.put("start", 0);
    requestNode.put("size", 1);

    httpPost.setEntity(new StringEntity(requestNode.toString()));
    response = executeRequest(httpPost, HttpStatus.SC_OK);
    rootNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    dataNode = rootNode.get("data");
    assertEquals(1, dataNode.size());

    // Check paging start and size
    requestNode = objectMapper.createObjectNode();
    requestNode.put("start", 1);
    requestNode.put("size", 1);
    requestNode.put("order", "desc");
    requestNode.put("sort", "processDefinitionKey");

    httpPost.setEntity(new StringEntity(requestNode.toString()));
    response = executeRequest(httpPost, HttpStatus.SC_OK);
    rootNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    dataNode = rootNode.get("data");
    assertEquals(1, dataNode.size());
    assertEquals(processInstance2.getId(), dataNode.get(0).get("id").asText());
}

From source file:cat.calidos.morfeu.model.transform.TransformNoValueIntTest.java

@Test
public void testTransformJSONToYAML() throws Exception {

    Document doc = produceDocumentFromPath("test-resources/documents/document4.json");
    assertNotNull(doc);/* w w  w .  j  a v  a  2 s.  c o m*/

    Map<String, Object> values = new HashMap<String, Object>(2);
    values.put("cells", doc.getContent().asList());
    values.put("model", doc.getModel());

    String transformed = DaggerViewComponent.builder().withTemplate("templates/transform/content-to-yaml.twig")
            .withValue(values).build().render();
    //System.err.println(transformed);

    YAMLMapper mapper = new YAMLMapper();
    JsonNode yaml = mapper.readTree(transformed);
    assertNotNull(yaml);
    assertTrue(yaml.isObject());
    assertTrue(yaml.has("rows"));

    JsonNode col = yaml.get("rows").get(0).get("cols").get(0); //rows/cols/col
    assertNotNull(col);
    assertTrue(col.isObject());
    assertTrue(col.has("stuff"));
    assertTrue(col.has("data4"));

    JsonNode stuff = col.get("stuff");
    assertTrue(stuff.isArray());
    assertEquals("stuff : [] in transformed yaml should have no elements", 0, stuff.size());

    JsonNode data4 = col.get("data4");
    assertTrue(data4.isObject());
    assertEquals("data4: {} in transformed yaml should be empty", 0, data4.size());

}

From source file:com.infinities.keystone4j.admin.v3.credential.CredentialResourceTest.java

@Test
public void testListCredentials() throws JsonProcessingException, IOException {
    String blobStr = JsonUtils.toJsonWithoutPrettyPrint(blob);
    System.err.println("blob: " + blobStr);
    Response response = target("/v3/credentials").register(JacksonFeature.class)
            .register(ObjectMapperResolver.class).request()
            .header("X-Auth-Token", Config.Instance.getOpt(Config.Type.DEFAULT, "admin_token").asText()).get();
    assertEquals(200, response.getStatus());
    String ret = response.readEntity(String.class);
    JsonNode node = JsonUtils.convertToJsonNode(ret);
    System.err.println(ret);/*from w ww .  java 2 s . c  o  m*/
    JsonNode credentialsJ = node.get("credentials");
    assertEquals(1, credentialsJ.size());
    JsonNode credentialJ = credentialsJ.get(0);
    assertNotNull(credentialJ.get("id").asText());
    assertEquals(credential.getType(), credentialJ.get("type").asText());
    assertEquals(credential.getProjectId(), credentialJ.get("project_id").asText());
    assertEquals(credential.getUserId(), credentialJ.get("user_id").asText());
    assertEquals(blobStr, credentialJ.get("blob").asText());
    assertNotNull(credentialJ.get("links"));
    assertNotNull(credentialJ.get("links").get("self").asText());
}

From source file:ijfx.service.overlay.io.OverlayDeserializer.java

private double[] getArray(JsonNode node, String fieldName) {
    JsonNode arrayNode = node.get(fieldName);
    if (arrayNode == null)
        return new double[0];
    int arraySize = arrayNode.size();
    if (arraySize < 0)
        return new double[0];
    else {//from  www.  ja v a2s  .co m
        return IntStream.range(0, arraySize).mapToDouble(i -> arrayNode.get(i).asDouble()).toArray();
    }
}

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

@Test
public void testSerializeWithEmptySubObject() throws Exception {
    NamedSchema schema = NamedSchema.of(Union.getDescriptor(), "Union");
    SchemaRegistry registry = new SchemaRegistry();
    registry.register(schema);/*from   www  .j ava  2 s . co  m*/
    Union union = Union.newBuilder().setBoolValue(true).build();
    JsonNode result = new NamedSchemaSerializer(schema).serialize(union, registry);
    Assert.assertTrue(result.isObject());
    Assert.assertEquals(1, result.size());
    Assert.assertNull(result.get("unionValue"));
}