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:org.apache.drill.exec.ref.rse.JSONRecordReader.java

private DataValue convert(JsonNode node) {
    if (node == null || node.isNull() || node.isMissingNode()) {
        return DataValue.NULL_VALUE;
    } else if (node.isArray()) {
        SimpleArrayValue arr = new SimpleArrayValue(node.size());
        for (int i = 0; i < node.size(); i++) {
            arr.addToArray(i, convert(node.get(i)));
        }/*from w w  w. ja v a2  s  .  co  m*/
        return arr;
    } else if (node.isObject()) {
        SimpleMapValue map = new SimpleMapValue();
        String name;
        for (Iterator<String> iter = node.fieldNames(); iter.hasNext();) {
            name = iter.next();
            map.setByName(name, convert(node.get(name)));
        }
        return map;
    } else if (node.isBinary()) {
        try {
            return new BytesScalar(node.binaryValue());
        } catch (IOException e) {
            throw new RuntimeException("Failure converting binary value.", e);
        }
    } else if (node.isBigDecimal()) {
        throw new UnsupportedOperationException();
        //      return new BigDecimalScalar(node.decimalValue());
    } else if (node.isBigInteger()) {
        throw new UnsupportedOperationException();
        //      return new BigIntegerScalar(node.bigIntegerValue());
    } else if (node.isBoolean()) {
        return new BooleanScalar(node.asBoolean());
    } else if (node.isFloatingPointNumber()) {
        if (node.isBigDecimal()) {
            throw new UnsupportedOperationException();
            //        return new BigDecimalScalar(node.decimalValue());
        } else {
            return new DoubleScalar(node.asDouble());
        }
    } else if (node.isInt()) {
        return new IntegerScalar(node.asInt());
    } else if (node.isLong()) {
        return new LongScalar(node.asLong());
    } else if (node.isTextual()) {
        return new StringScalar(node.asText());
    } else {
        throw new UnsupportedOperationException(String.format("Don't know how to convert value of type %s.",
                node.getClass().getCanonicalName()));
    }

}

From source file:com.unboundid.scim2.server.utils.ResourceComparator.java

/**
 * Retrieve the value of a complex multi-valued attribute that is marked as
 * primary or the first value in the list. If the provided node is not an
 * array node, then just return the provided node.
 *
 * @param node The JsonNode to retrieve from.
 * @return The primary or first value or {@code null} if the provided array
 * node is empty./*from  w w w  .jav  a  2s  .  co m*/
 */
private JsonNode getPrimaryOrFirst(final JsonNode node) {
    // if it's a multi-valued attribute (see Section 2.4
    // [I-D.ietf - scim - core - schema]), if any, or else the first value in
    // the list, if any.

    if (!node.isArray()) {
        return node;
    }

    if (node.size() == 0) {
        return null;
    }

    Iterator<JsonNode> i = node.elements();
    while (i.hasNext()) {
        JsonNode value = i.next();
        JsonNode primary = value.get("primary");
        if (primary != null && primary.booleanValue()) {
            return value;
        }
    }
    return node.get(0);
}

From source file:com.epam.catgenome.manager.externaldb.ncbi.NCBIGeneManager.java

private void parseJsonFromPubmed(final JsonNode pubmedResultRoot, final JsonNode pubmedEntries,
        final NCBIGeneVO ncbiGeneVO) throws JsonProcessingException {
    if (pubmedResultRoot.isArray()) {
        ncbiGeneVO.setPubNumber(pubmedResultRoot.size());
        for (final JsonNode objNode : pubmedResultRoot) {
            if (ncbiGeneVO.getPubmedReferences().size() >= NUMBER_OF_PUBLICATIONS) {
                break;
            }/*  w  w  w  . ja  v a  2 s  . com*/
            JsonNode jsonNode = pubmedEntries.path(RESULT_PATH).get("" + objNode.asText());
            NCBISummaryVO pubmedReference = mapper.treeToValue(jsonNode, NCBISummaryVO.class);
            pubmedReference.setLink(String.format(NCBI_PUBMED_URL, pubmedReference.getUid()));
            // take first author
            if (pubmedReference.getAuthors() != null) {
                pubmedReference.setMultipleAuthors(pubmedReference.getAuthors().size() > 1);
                NCBISummaryVO.NCBIAuthor ncbiAuthor = pubmedReference.getAuthors().get(0);
                pubmedReference.setAuthor(ncbiAuthor);
                pubmedReference.setAuthors(null);
            }

            ncbiGeneVO.getPubmedReferences().add(pubmedReference);
        }
    }
}

From source file:org.activiti.rest.service.api.history.HistoricProcessInstanceQueryResourceTest.java

/**
 * Test querying historic process instance based on variables. POST query/historic-process-instances
 *//*from w w  w.j  av  a 2  s .  co m*/
@Deployment
public void testQueryProcessInstancesWithVariables() throws Exception {
    HashMap<String, Object> processVariables = new HashMap<String, Object>();
    processVariables.put("stringVar", "Azerty");
    processVariables.put("intVar", 67890);
    processVariables.put("booleanVar", false);

    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
            processVariables);
    Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    taskService.complete(task.getId());

    ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
            processVariables);

    String url = RestUrls.createRelativeResourceUrl(RestUrls.URL_HISTORIC_PROCESS_INSTANCE_QUERY);

    // Process variables
    ObjectNode requestNode = objectMapper.createObjectNode();
    ArrayNode variableArray = objectMapper.createArrayNode();
    ObjectNode variableNode = objectMapper.createObjectNode();
    variableArray.add(variableNode);
    requestNode.put("variables", variableArray);

    // String equals
    variableNode.put("name", "stringVar");
    variableNode.put("value", "Azerty");
    variableNode.put("operation", "equals");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // Integer equals
    variableNode.removeAll();
    variableNode.put("name", "intVar");
    variableNode.put("value", 67890);
    variableNode.put("operation", "equals");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // Boolean equals
    variableNode.removeAll();
    variableNode.put("name", "booleanVar");
    variableNode.put("value", false);
    variableNode.put("operation", "equals");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // String not equals
    variableNode.removeAll();
    variableNode.put("name", "stringVar");
    variableNode.put("value", "ghijkl");
    variableNode.put("operation", "notEquals");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // Integer not equals
    variableNode.removeAll();
    variableNode.put("name", "intVar");
    variableNode.put("value", 45678);
    variableNode.put("operation", "notEquals");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // Boolean not equals
    variableNode.removeAll();
    variableNode.put("name", "booleanVar");
    variableNode.put("value", true);
    variableNode.put("operation", "notEquals");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // String equals ignore case
    variableNode.removeAll();
    variableNode.put("name", "stringVar");
    variableNode.put("value", "azeRTY");
    variableNode.put("operation", "equalsIgnoreCase");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // String not equals ignore case (not supported)
    variableNode.removeAll();
    variableNode.put("name", "stringVar");
    variableNode.put("value", "HIJKLm");
    variableNode.put("operation", "notEqualsIgnoreCase");
    assertErrorResult(url, requestNode, HttpStatus.SC_BAD_REQUEST);

    // String equals without value
    variableNode.removeAll();
    variableNode.put("value", "Azerty");
    variableNode.put("operation", "equals");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // String equals with non existing value
    variableNode.removeAll();
    variableNode.put("value", "Azerty2");
    variableNode.put("operation", "equals");
    assertResultsPresentInPostDataResponse(url, requestNode);

    // String like ignore case
    variableNode.removeAll();
    variableNode.put("name", "stringVar");
    variableNode.put("value", "azerty");
    variableNode.put("operation", "likeIgnoreCase");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    variableNode.removeAll();
    variableNode.put("name", "stringVar");
    variableNode.put("value", "azerty2");
    variableNode.put("operation", "likeIgnoreCase");
    assertResultsPresentInPostDataResponse(url, requestNode);

    requestNode = objectMapper.createObjectNode();
    requestNode.put("finished", true);
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId());

    requestNode = objectMapper.createObjectNode();
    requestNode.put("finished", false);
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance2.getId());

    requestNode = objectMapper.createObjectNode();
    requestNode.put("processDefinitionId", processInstance.getProcessDefinitionId());
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    requestNode = objectMapper.createObjectNode();
    requestNode.put("processDefinitionKey", "oneTaskProcess");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    requestNode = objectMapper.createObjectNode();
    requestNode.put("processDefinitionKey", "oneTaskProcess");

    HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + url + "?sort=startTime");
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_OK);

    // Check status and size
    JsonNode dataNode = objectMapper.readTree(response.getEntity().getContent()).get("data");
    closeResponse(response);
    assertEquals(2, dataNode.size());
    assertEquals(processInstance.getId(), dataNode.get(0).get("id").asText());
    assertEquals(processInstance2.getId(), dataNode.get(1).get("id").asText());
}

From source file:org.flowable.rest.service.api.history.HistoricProcessInstanceQueryResourceTest.java

/**
 * Test querying historic process instance based on variables. POST query/historic-process-instances
 *///from  ww  w. j  a v a 2s. c om
@Deployment
public void testQueryProcessInstancesWithVariables() throws Exception {
    HashMap<String, Object> processVariables = new HashMap<String, Object>();
    processVariables.put("stringVar", "Azerty");
    processVariables.put("intVar", 67890);
    processVariables.put("booleanVar", false);

    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
            processVariables);
    Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    taskService.complete(task.getId());

    ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("oneTaskProcess",
            processVariables);

    String url = RestUrls.createRelativeResourceUrl(RestUrls.URL_HISTORIC_PROCESS_INSTANCE_QUERY);

    // Process variables
    ObjectNode requestNode = objectMapper.createObjectNode();
    ArrayNode variableArray = objectMapper.createArrayNode();
    ObjectNode variableNode = objectMapper.createObjectNode();
    variableArray.add(variableNode);
    requestNode.set("variables", variableArray);

    // String equals
    variableNode.put("name", "stringVar");
    variableNode.put("value", "Azerty");
    variableNode.put("operation", "equals");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // Integer equals
    variableNode.removeAll();
    variableNode.put("name", "intVar");
    variableNode.put("value", 67890);
    variableNode.put("operation", "equals");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // Boolean equals
    variableNode.removeAll();
    variableNode.put("name", "booleanVar");
    variableNode.put("value", false);
    variableNode.put("operation", "equals");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // String not equals
    variableNode.removeAll();
    variableNode.put("name", "stringVar");
    variableNode.put("value", "ghijkl");
    variableNode.put("operation", "notEquals");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // Integer not equals
    variableNode.removeAll();
    variableNode.put("name", "intVar");
    variableNode.put("value", 45678);
    variableNode.put("operation", "notEquals");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // Boolean not equals
    variableNode.removeAll();
    variableNode.put("name", "booleanVar");
    variableNode.put("value", true);
    variableNode.put("operation", "notEquals");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // String equals ignore case
    variableNode.removeAll();
    variableNode.put("name", "stringVar");
    variableNode.put("value", "azeRTY");
    variableNode.put("operation", "equalsIgnoreCase");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // String not equals ignore case (not supported)
    variableNode.removeAll();
    variableNode.put("name", "stringVar");
    variableNode.put("value", "HIJKLm");
    variableNode.put("operation", "notEqualsIgnoreCase");
    assertErrorResult(url, requestNode, HttpStatus.SC_BAD_REQUEST);

    // String equals without value
    variableNode.removeAll();
    variableNode.put("value", "Azerty");
    variableNode.put("operation", "equals");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    // String equals with non existing value
    variableNode.removeAll();
    variableNode.put("value", "Azerty2");
    variableNode.put("operation", "equals");
    assertResultsPresentInPostDataResponse(url, requestNode);

    // String like ignore case
    variableNode.removeAll();
    variableNode.put("name", "stringVar");
    variableNode.put("value", "azerty");
    variableNode.put("operation", "likeIgnoreCase");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    variableNode.removeAll();
    variableNode.put("name", "stringVar");
    variableNode.put("value", "azerty2");
    variableNode.put("operation", "likeIgnoreCase");
    assertResultsPresentInPostDataResponse(url, requestNode);

    requestNode = objectMapper.createObjectNode();
    requestNode.put("finished", true);
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId());

    requestNode = objectMapper.createObjectNode();
    requestNode.put("finished", false);
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance2.getId());

    requestNode = objectMapper.createObjectNode();
    requestNode.put("processDefinitionId", processInstance.getProcessDefinitionId());
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    requestNode = objectMapper.createObjectNode();
    requestNode.put("processDefinitionKey", "oneTaskProcess");
    assertResultsPresentInPostDataResponse(url, requestNode, processInstance.getId(), processInstance2.getId());

    requestNode = objectMapper.createObjectNode();
    requestNode.put("processDefinitionKey", "oneTaskProcess");

    HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + url + "?sort=startTime");
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_OK);

    // Check status and size
    JsonNode dataNode = objectMapper.readTree(response.getEntity().getContent()).get("data");
    closeResponse(response);
    assertEquals(2, dataNode.size());
    assertEquals(processInstance.getId(), dataNode.get(0).get("id").asText());
    assertEquals(processInstance2.getId(), dataNode.get(1).get("id").asText());
}

From source file:com.spoiledmilk.ibikecph.map.SMHttpRequest.java

public void findPlacesForLocation(final Location loc, final SMHttpRequestListener listener) {
    new Thread(new Runnable() {
        @Override//from w  w w .j  a  va 2s .  c  om
        public void run() {
            String url = String.format(Locale.US, "%s/%f,%f.json", Config.GEOCODER, loc.getLatitude(),
                    loc.getLongitude()); // ,%d
                                                                                                                                    // ,
                                                                                                                                    // GEOCODER_SEARCH_RADIUS
            JsonNode response = HttpUtils.get(url);
            Address a = null;
            if (response != null) {
                if (response.size() > 0) {
                    a = new Address(response.path("vejnavn").path("navn").asText(),
                            response.path("husnr").asText(), response.path("postnummer").path("nr").asText(),
                            response.path("kommune").path("navn").asText(), loc.getLatitude(),
                            loc.getLongitude());
                } else {
                    a = new Address(
                            Util.limitDecimalPlaces(loc.getLatitude(), 4) + "\n"
                                    + Util.limitDecimalPlaces(loc.getLongitude(), 4),
                            "", "", "", loc.getLatitude(), loc.getLongitude());
                }
            } else {
                a = new Address(
                        Util.limitDecimalPlaces(loc.getLatitude(), 4) + "\n"
                                + Util.limitDecimalPlaces(loc.getLongitude(), 4),
                        "", "", "", loc.getLatitude(), loc.getLongitude());
            }
            sendMsg(REQUEST_FIND_PLACES_FOR_LOC, a, listener);
        }
    }).start();
}

From source file:org.eel.kitchen.jsonschema.validator.InstanceValidator.java

@Override
public void validate(final ValidationContext context, final ValidationReport report, final JsonNode instance) {
    final SchemaContainer orig = context.getContainer();
    context.setContainer(schemaNode.getContainer());

    for (final KeywordValidator validator : validators) {
        validator.validateInstance(context, report, instance);
        if (report.hasFatalError())
            return;
    }//www . j  a v  a 2  s  .  c  om

    if (instance.size() > 0) {
        final JsonValidator validator = instance.isArray() ? new ArrayValidator(schemaNode.getNode())
                : new ObjectValidator(schemaNode.getNode());

        validator.validate(context, report, instance);
    }
    context.setContainer(orig);
}

From source file:com.ning.metrics.serialization.hadoop.pig.SmileStorage.java

/**
 * Retrieves the next tuple to be processed. Implementations should NOT reuse
 * tuple objects (or inner member objects) they return across calls and
 * should return a different tuple object in each call.
 *
 * @return the next tuple to be processed or null if there are no more tuples
 *         to be processed./*from   w  ww  .j  a v  a 2 s.  co  m*/
 * @throws java.io.IOException if there is an exception while retrieving the next
 *                             tuple
 */
@Override
public Tuple getNext() throws IOException {
    try {
        if (reader == null || !reader.nextKeyValue()) {
            return null;
        }

        final Object value = reader.getCurrentValue();

        if (value instanceof SmileEnvelopeEvent) {
            final SmileEnvelopeEvent envelope = (SmileEnvelopeEvent) value;
            final JsonNode data = (JsonNode) envelope.getData();

            final Tuple tuple = factory.newTuple(data.size());
            int i = 0;
            for (final GoodwillSchemaField field : schema.getSchema()) {
                final JsonNode node = data.get(field.getName());
                tuple.set(i, getJsonValue(field.getType(), node));
                i++;
            }

            return tuple;
        } else {
            throw new IOException(String.format("Expected SmileEnvelopeEvent, not %s", value.getClass()));
        }
    } catch (NullPointerException e) {
        String splitInfo = "<no split info>";
        if (split != null) {
            splitInfo = split.toString();
        }
        log.error(String.format("Corrupt Smile file (%s), ignoring the rest of the input", splitInfo), e);
    } catch (com.fasterxml.jackson.core.JsonParseException e) {
        String splitInfo = "<no split info>";
        if (split != null) {
            splitInfo = split.toString();
        }
        log.error(String.format("Corrupt Smile file (%s), ignoring the rest of the input", splitInfo), e);
        return null;
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }

    return null;
}

From source file:org.lendingclub.mercator.docker.DockerSerializerModule.java

public ObjectNode flatten(JsonNode n) {
    ObjectNode out = vanillaObjectMapper.createObjectNode();
    Converter<String, String> caseFormat = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);

    n.fields().forEachRemaining(it -> {
        JsonNode val = it.getValue();
        String key = it.getKey();
        key = caseFormat.convert(key);/*from   www  . j ava  2  s  .  co m*/
        if (val.isValueNode()) {

            out.set(key, it.getValue());
        } else if (val.isArray()) {
            if (val.size() == 0) {
                out.set(key, val);
            }
            boolean valid = true;
            Class<? extends Object> type = null;
            ArrayNode an = (ArrayNode) val;
            for (int i = 0; valid && i < an.size(); i++) {
                if (!an.get(i).isValueNode()) {
                    valid = false;
                }
                if (type != null && an.get(i).getClass() != type) {
                    valid = false;
                }
            }

        }
    });
    renameAttribute(out, "oSType", "osType");
    renameAttribute(out, "iD", "id");
    renameAttribute(out, "neventsListener", "nEventsListener");
    renameAttribute(out, "cPUSet", "cpuSet");
    renameAttribute(out, "cPUShares", "cpuShares");
    renameAttribute(out, "iPv4Forwarding", "ipv4Forwarding");
    renameAttribute(out, "oOMKilled", "oomKilled");
    renameAttribute(out, "state_oomkilled", "state_oomKilled");
    renameAttribute(out, "bridgeNfIptables", "bridgeNfIpTables");
    renameAttribute(out, "bridgeNfIp6tables", "bridgeNfIp6Tables");
    out.remove("ngoroutines");
    return out;
}

From source file:org.opendaylight.nemo.renderer.cli.physicalnetwork.PhysicalResourceLoaderTest.java

@Test
public void testBuildPortAttributes() throws Exception {
    Class<PhysicalResourceLoader> class1 = PhysicalResourceLoader.class;
    Method method = class1.getDeclaredMethod("buildPortAttributes", new Class[] { JsonNode.class });
    method.setAccessible(true);//from  ww  w  .  j  a  va  2s .  co  m

    List<Attribute> attributeList;
    JsonNode attributes = mock(JsonNode.class);
    JsonNode portAttribute = mock(JsonNode.class);
    JsonNode jsonNode_temp = mock(JsonNode.class);

    when(attributes.size()).thenReturn(1);
    when(attributes.get(any(Integer.class))).thenReturn(portAttribute);
    //get into method "buildPortAttribute"
    when(portAttribute.path(any(String.class))).thenReturn(jsonNode_temp);
    when(jsonNode_temp.asText()).thenReturn(new String(""))//branch null
            .thenReturn(new String("zm"));
    attributeList = (List<Attribute>) method.invoke(physicalResourceLoader, attributes);
    Assert.assertTrue(attributeList.size() == 0);
    //new AttributeName("zm");
    attributeList = (List<Attribute>) method.invoke(physicalResourceLoader, attributes);
    Assert.assertTrue(attributeList.size() == 1);
    verify(portAttribute, times(3)).path(any(String.class));
    verify(jsonNode_temp, times(3)).asText();
}