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.vmware.photon.controller.clustermanager.clients.SwarmClient.java

/**
 * This method calls into the Swarm API endpoint to retrieve the node ip addresses.
 *
 * @param connectionString          connectionString of the master Node in the Cluster
 * @param callback                  callback that is invoked on completion of the operation.
 * @param nodeProperty              specify the property of the node to return.
 * @throws IOException/*w  w w  .  j  a  v a2  s .  c om*/
 */
private void getNodeStatusAsync(final String connectionString, final FutureCallback<Set<String>> callback,
        final NodeProperty nodeProperty) throws IOException {

    final RestClient restClient = new RestClient(connectionString, this.httpClient);

    org.apache.http.concurrent.FutureCallback<HttpResponse> futureCallback = new org.apache.http.concurrent.FutureCallback<HttpResponse>() {
        @Override
        public void completed(HttpResponse result) {

            ArrayNode driverStatus;
            try {
                restClient.checkResponse(result, HttpStatus.SC_OK);
                JsonNode response = objectMapper.readTree(result.getEntity().getContent());
                driverStatus = (ArrayNode) response.get("DriverStatus");
            } catch (Throwable e) {
                callback.onFailure(e);
                return;
            }

            Set<String> nodes = new HashSet<>();

            for (JsonNode entry : driverStatus) {
                ArrayNode kv = (ArrayNode) entry;
                if (kv.size() == 2) {
                    try {
                        String key = kv.get(0).asText();
                        if (key.startsWith(MASTER_VM_NAME_PREFIX) || key.startsWith(WORKER_VM_NAME_PREFIX)) {
                            switch (nodeProperty) {
                            case IP_ADDRESS:
                                String nodeAddress = kv.get(1).asText().split(":")[0];
                                nodes.add(nodeAddress);
                                break;
                            case HOSTNAME:
                                nodes.add(key);
                                break;
                            default:
                                new UnsupportedOperationException(
                                        "NodeProperty is not supported. NodeProperty: " + nodeProperty);
                            }
                        }
                    } catch (Exception ex) {
                        logger.error("malformed node value", ex);
                    }
                }
            }

            callback.onSuccess(nodes);
        }

        @Override
        public void failed(Exception ex) {
            callback.onFailure(ex);
        }

        @Override
        public void cancelled() {
            callback.onFailure(new RuntimeException("getNodeStatusAsync was cancelled"));
        }
    };

    restClient.performAsync(RestClient.Method.GET, SWARM_STATUS_PATH, null, futureCallback);
}

From source file:io.wcm.caravan.pipeline.impl.JsonPathSelectorTest.java

@Test
public void testExtractArrayQueryNoResults() {

    // if no selection matches the expression, but the property in the query exists, no results are returned
    ArrayNode result = new JsonPathSelector("$..book[?(@.title=='No such title')]").call(booksJson);

    assertEquals(0, result.size());
}

From source file:org.gitana.platform.client.changeset.ChangesetImpl.java

@Override
public List<String> getParentChangesetIds() {
    List<String> parentChangesetIds = new ArrayList<String>();

    if (has(FIELD_PARENTS)) {
        ArrayNode parents = getArray(FIELD_PARENTS);
        if (parents.size() > 0) {
            for (int i = 0; i < parents.size(); i++) {
                parentChangesetIds.add(parents.get(i).textValue());
            }/*from w ww  .j a v  a 2  s  .  c o m*/
        }
    }

    return parentChangesetIds;
}

From source file:la.alsocan.jsonshapeshifter.transformations.SimpleCollectionTransformationTest.java

@Test
public void collectionBindingShouldProduceTheRightNumberOfElements() throws IOException {

    Schema source = Schema.buildSchema(new ObjectMapper().readTree(DataSet.SIMPLE_COLLECTION_SCHEMA));
    Schema target = Schema.buildSchema(new ObjectMapper().readTree(DataSet.SIMPLE_COLLECTION_SCHEMA));
    Transformation t = new Transformation(source, target);

    Iterator<SchemaNode> it = t.toBind();
    it.next();/*from   ww  w.ja  v  a2s . c  o  m*/
    t.bind(it.next(), new ArrayNodeBinding((SchemaArrayNode) source.at("/someStringArray")));
    it.next();
    t.bind(it.next(), new ArrayNodeBinding((SchemaArrayNode) source.at("/someIntegerArray")));

    JsonNode payload = new ObjectMapper().readTree(DataSet.SIMPLE_COLLECTION_PAYLOAD);
    JsonNode result = t.apply(payload);

    ArrayNode stringCollection = (ArrayNode) result.at("/someStringArray");
    assertThat(stringCollection.size(), is(5));

    ArrayNode integerCollection = (ArrayNode) result.at("/someIntegerArray");
    assertThat(integerCollection.size(), is(8));
}

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 ww  w.  jav a 2 s. c om*/
        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.apache.solr.kelvin.App.java

private void configureTestsFromJsonNode(JsonNode node) throws Exception {
    if (testCases == null)
        testCases = new ArrayList<ITestCase>(); //otherwise appends
    ArrayNode list = ConfigurableLoader.assureArray(node);
    for (int i = 0; i < list.size(); i++) {
        JsonNode config = list.get(i);//from  w  ww  .  ja va2 s .  c  o  m
        try {
            ITestCase t = SingletonTestRegistry.instantiate(config);
            t.configure(config);
            testCases.add(t);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "error reading " + config.toString(), e);
        }
    }
}

From source file:io.wcm.caravan.pipeline.impl.JsonPathSelectorTest.java

@Test
public void testExtractArrayQuery2() {

    // find the book by title
    ArrayNode result = new JsonPathSelector("$..book[?(@.title=='The Lord of the Rings')]").call(booksJson);

    assertEquals(1, result.size());
}

From source file:io.cloudslang.content.json.actions.GetValueFromObject.java

private JsonNode getValue(JsonNode jsonElement, String aKey) throws Exception {

    //non JSON array object
    if (!aKey.matches(".*" + ESCAPED_SLASH + "[[0-9]+]$")) {
        if (jsonElement.get(aKey) != null) {
            return jsonElement.get(aKey);
        } else/*  w  w  w. j av a  2  s.  c  o m*/
            throw new Exception("The " + aKey + " key does not exist in JavaScript object!");
    }
    //JSON array object
    else {
        int startIndex = aKey.indexOf("[");
        int endIndex = aKey.indexOf("]");
        String oneKey = aKey.substring(0, startIndex);
        int index = 0;
        try {
            index = Integer.parseInt(aKey.substring(startIndex + 1, endIndex));
        } catch (NumberFormatException e) {
            throw new Exception("Invalid index provided: " + index);
        }
        JsonNode subObject;
        subObject = jsonElement.get(oneKey);
        if (jsonElement.get(oneKey) != null) {
            if (subObject instanceof ArrayNode) {
                final ArrayNode asJsonArray = (ArrayNode) subObject;
                if ((index >= asJsonArray.size()) || (index < 0)) {
                    throw new Exception("The provided " + index
                            + " index is out of range! Provide a valid index value in the provided JSON!");
                } else {
                    return asJsonArray.get(index);
                }
            } else {
                throw new Exception("Invalid json array provided: " + subObject.toString() + " ");
            }
        } else {
            throw new Exception("The " + aKey + " key does not exist in JavaScript object!");
        }
    }
}

From source file:com.github.pjungermann.config.types.json.JsonConverter.java

@NotNull
@SuppressWarnings("unchecked")
protected ArrayList prepareEntries(@NotNull final ArrayNode valueList) {
    final ArrayList list = new ArrayList(valueList.size());

    for (JsonNode entry : valueList) {
        if (entry instanceof ObjectNode) {
            list.add(from((ObjectNode) entry));

        } else {//  w  ww.j av  a2  s.  c  o  m
            list.add(extractValue(entry));
        }
    }

    return list;
}

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

/**
 * {@inheritDoc}//from   www  .  j a v a  2  s .c  om
 * @throws SerializationException
 */
@Override
public JsonNode serialize(Message message, ReadableSchemaRegistry registry) throws SerializationException {
    ObjectNode object = new ObjectNode(JsonNodeFactory.instance);

    for (Descriptors.FieldDescriptor field : descriptor.getFields()) {
        String propertyName = AutoSchema.PROTO_FIELD_CASE_FORMAT.to(AutoSchema.JSON_FIELD_CASE_FORMAT,
                field.getName());
        if (field.isRepeated()) {
            if (message.getRepeatedFieldCount(field) > 0) {
                ArrayNode array = serializeRepeatedField(message, field, registry);
                if (array.size() != 0) {
                    object.put(propertyName, array);
                }
            }
        } else if (message.hasField(field)) {
            Object value = message.getField(field);
            JsonNode fieldNode = serializeValue(value, field, registry);
            if (!fieldNode.isNull()) {
                object.put(propertyName, fieldNode);
            }
        }
    }

    if (object.size() == 0) {
        return NullNode.instance;
    }

    return object;
}