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

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

Introduction

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

Prototype

public ArrayNode(JsonNodeFactory paramJsonNodeFactory) 

Source Link

Usage

From source file:org.walkmod.conf.providers.yml.SetReaderYMLAction.java

@Override
public void doAction(JsonNode node) throws Exception {
    if (node.has("chains") && (chain == null || "".equals(chain.trim()))) {
        chain = "default";
    }//from   w w  w .ja  v  a2s  .  co  m
    ObjectNode reader = null;
    ObjectMapper mapper = provider.getObjectMapper();
    if (chain != null && !"".equals(chain.trim())) {

        if (node.has("chains")) {
            JsonNode chainsListNode = node.get("chains");
            if (chainsListNode.isArray()) {
                Iterator<JsonNode> it = chainsListNode.iterator();
                boolean found = false;
                while (it.hasNext() && !found) {
                    JsonNode current = it.next();
                    if (current.has("name")) {
                        String name = current.get("name").asText();
                        found = name.equals(chain);
                        if (found) {
                            if (current.has("reader")) {
                                reader = (ObjectNode) current.get("reader");
                            } else {
                                reader = new ObjectNode(mapper.getNodeFactory());
                            }
                            if (type != null && !"".equals(type.trim())) {
                                reader.set("type", new TextNode(type));
                            }
                            if (path != null && !"".equals(path.trim())) {
                                reader.set("path", new TextNode(path));
                            }
                            if (params != null && !params.isEmpty()) {
                                ObjectNode paramsObject = null;
                                if (reader.has("params")) {
                                    paramsObject = (ObjectNode) reader.get("params");
                                } else {
                                    paramsObject = new ObjectNode(mapper.getNodeFactory());
                                    reader.set("params", paramsObject);
                                }

                                Set<String> keys = params.keySet();
                                for (String key : keys) {
                                    paramsObject.put(key, params.get(key).toString());
                                }

                            }
                        }
                    }
                }
            }
        }
        if (reader != null) {
            provider.write(node);
        }
    } else {
        if (!node.has("chains")) {
            ArrayNode chains = new ArrayNode(mapper.getNodeFactory());
            ObjectNode defaultChain = new ObjectNode(mapper.getNodeFactory());
            defaultChain.set("name", new TextNode("default"));
            ObjectNode readerNode = new ObjectNode(mapper.getNodeFactory());

            if (type != null && !"".equals(type.trim())) {
                readerNode.set("type", new TextNode(type));
            }
            if (path != null && !"".equals(path.trim())) {
                readerNode.set("path", new TextNode(path));
            }
            if (params != null && !params.isEmpty()) {
                ObjectNode paramsObject = new ObjectNode(mapper.getNodeFactory());
                Set<String> keys = params.keySet();
                for (String key : keys) {
                    paramsObject.put(key, params.get(key).toString());
                }
                readerNode.set("params", paramsObject);
            }
            defaultChain.set("reader", readerNode);
            if (node.has("transformations")) {
                defaultChain.set("transformations", node.get("transformations"));
            }
            chains.add(defaultChain);
            provider.write(chains);
        }

    }

}

From source file:org.walkmod.conf.providers.yml.SetWriterYMLAction.java

@Override
public void doAction(JsonNode node) throws Exception {

    ObjectNode writer = null;// ww  w  .  ja v  a  2s  . co  m

    ObjectMapper mapper = provider.getObjectMapper();

    if (node.has("chains") && (chain == null || "".equals(chain.trim()))) {
        chain = "default";
    }

    if (chain != null && !"".equals(chain.trim())) {

        if (node.has("chains")) {
            JsonNode chainsListNode = node.get("chains");
            if (chainsListNode.isArray()) {
                Iterator<JsonNode> it = chainsListNode.iterator();
                boolean found = false;
                while (it.hasNext() && !found) {
                    JsonNode current = it.next();
                    if (current.has("name")) {
                        String name = current.get("name").asText();
                        found = name.equals(chain);
                        if (found) {
                            if (current.has("writer")) {
                                writer = (ObjectNode) current.get("writer");
                            } else {
                                writer = new ObjectNode(mapper.getNodeFactory());
                            }

                            if (type != null && !"".equals(type.trim())) {
                                writer.set("type", new TextNode(type));
                            }
                            if (path != null && !"".equals(path.trim())) {
                                writer.set("path", new TextNode(path));
                            }
                            if (params != null && !params.isEmpty()) {
                                ObjectNode paramsObject = null;
                                if (writer.has("params")) {
                                    paramsObject = (ObjectNode) writer.get("params");
                                } else {
                                    paramsObject = new ObjectNode(mapper.getNodeFactory());
                                    writer.set("params", paramsObject);
                                }

                                Set<String> keys = params.keySet();
                                for (String key : keys) {
                                    paramsObject.put(key, params.get(key).toString());
                                }

                            }
                        }
                    }
                }
            }
        }
        if (writer != null) {
            provider.write(node);
        }
    } else {
        if (!node.has("chains")) {
            ArrayNode chains = new ArrayNode(mapper.getNodeFactory());
            ObjectNode defaultChain = new ObjectNode(mapper.getNodeFactory());
            defaultChain.set("name", new TextNode("default"));
            ObjectNode writerNode = new ObjectNode(mapper.getNodeFactory());

            if (type != null && !"".equals(type.trim())) {
                writerNode.set("type", new TextNode(type));
            }
            if (path != null && !"".equals(path.trim())) {
                writerNode.set("path", new TextNode(path));
            }
            if (params != null && !params.isEmpty()) {
                ObjectNode paramsObject = new ObjectNode(mapper.getNodeFactory());
                Set<String> keys = params.keySet();
                for (String key : keys) {
                    paramsObject.put(key, params.get(key).toString());
                }
                writerNode.set("params", paramsObject);
            }

            if (node.has("transformations")) {
                defaultChain.set("transformations", node.get("transformations"));
            }
            defaultChain.set("writer", writerNode);
            chains.add(defaultChain);
            ObjectNode root = new ObjectNode(mapper.getNodeFactory());

            root.set("chains", chains);
            provider.write(root);
        }
    }

}

From source file:com.redhat.lightblue.Response.java

/**
 * Returns the entity data resulting from the call.
 *//*from ww  w  .ja  v  a  2 s . co m*/
public void setEntityData(JsonNode node) {
    // if the node is not an array then wrap it in an array
    if (node != null && !node.isArray()) {
        ArrayNode arrayNode = new ArrayNode(jsonNodeFactory);
        arrayNode.add(node);
        entityData = arrayNode;
    } else {
        entityData = node;
    }
}

From source file:services.GoogleComputeEngineService.java

public static JsonNode listInstances(List<String> tags) throws GoogleComputeEngineException {
    checkAuthentication();//from   w w  w.  ja  va2s  .c  o m
    ObjectNode instances = Json.newObject();
    for (Instance i : client.getInstances(tags)) {
        ObjectNode instance = Json.newObject().put("name", i.getName()).put("description", i.getDescription())
                .put("type", i.getMachineType()).put("status", i.getStatus());
        ObjectNode disks = Json.newObject();
        for (AttachedDisk d : i.getDisks()) {
            disks.set(String.valueOf(d.getIndex()),
                    Json.newObject().put("name", d.getDeviceName()).put("type", d.getType())
                            .put("mode", d.getMode()).put("boot", d.getBoot())
                            .put("autodelete", d.getAutoDelete()));
        }
        instance.set("disks", disks);
        ObjectNode interfaces = Json.newObject();
        for (NetworkInterface n : i.getNetworkInterfaces()) {
            interfaces.set(n.getName(),
                    Json.newObject().put("network", n.getNetwork()).put("address", n.getNetworkIP()));
        }
        instance.set("network-interfaces", interfaces);
        instance.set("disks", disks);
        ArrayNode tagList = new ArrayNode(JsonNodeFactory.instance);
        if (i.getTags() != null && i.getTags().getItems() != null) {
            i.getTags().getItems().forEach(tagList::add);
        }
        instance.set("tags", tagList);
        instances.set(i.getId().toString(), instance);
    }
    return Json.newObject().set("instances", instances);
}

From source file:com.msopentech.odatajclient.testservice.utils.Commons.java

public static InputStream getLinksAsJSON(final String entitySetName,
        final Map.Entry<String, Collection<String>> link) throws IOException {
    final ObjectNode links = new ObjectNode(JsonNodeFactory.instance);
    links.put(JSON_ODATAMETADATA_NAME, ODATA_METADATA_PREFIX + entitySetName + "/$links/" + link.getKey());

    final ArrayNode uris = new ArrayNode(JsonNodeFactory.instance);

    for (String uri : link.getValue()) {
        final String absoluteURI;
        if (URI.create(uri).isAbsolute()) {
            absoluteURI = uri;/*w  w  w.j av  a 2  s . c om*/
        } else {
            absoluteURI = DEFAULT_SERVICE_URL + uri;
        }
        uris.add(new ObjectNode(JsonNodeFactory.instance).put("url", absoluteURI));
    }

    if (uris.size() == 1) {
        links.setAll((ObjectNode) uris.get(0));
    } else {
        links.set("value", uris);
    }

    return IOUtils.toInputStream(links.toString());
}

From source file:org.walkmod.conf.providers.yml.AddIncludesOrExcludesYMLAction.java

@Override
public void doAction(JsonNode node) throws Exception {
    if (chain == null) {
        chain = "default";
    }/*from   w  w  w.j a  v  a2 s.  co  m*/
    ObjectMapper mapper = provider.getObjectMapper();
    if (node.has("chains")) {
        JsonNode chains = node.get("chains");
        if (chains.isArray()) {
            ArrayNode chainsArray = (ArrayNode) chains;
            int limit = chainsArray.size();
            ObjectNode selectedChain = null;
            for (int i = 0; i < limit && selectedChain == null; i++) {
                JsonNode chainNode = chainsArray.get(i);
                if (chainNode.has("name")) {
                    if (chainNode.get("name").asText().equals(chain)) {
                        selectedChain = (ObjectNode) chainNode;
                    }
                }
            }
            if (selectedChain == null) {
                selectedChain = new ObjectNode(mapper.getNodeFactory());
                selectedChain.set("name", new TextNode(chain));
                chainsArray.add(selectedChain);
            }

            if (setToReader) {
                JsonNode reader = null;
                if (selectedChain.has("reader")) {
                    reader = selectedChain.get("reader");
                } else {
                    reader = new ObjectNode(mapper.getNodeFactory());
                    selectedChain.set("reader", reader);
                }
                setIncludesOrExcludesList((ObjectNode) reader);

            }
            if (setToWriter) {
                JsonNode reader = null;
                if (selectedChain.has("writer")) {
                    reader = selectedChain.get("writer");
                } else {
                    reader = new ObjectNode(mapper.getNodeFactory());
                    selectedChain.set("writer", reader);
                }
                setIncludesOrExcludesList((ObjectNode) reader);
            }

        }
    } else {
        ObjectNode root = (ObjectNode) node;
        if (node.has("transformations")) {
            JsonNode transformations = node.get("transformations");

            root.remove("transformations");
            ObjectNode chainNode = new ObjectNode(mapper.getNodeFactory());
            chainNode.set("name", new TextNode("default"));
            chainNode.set("transformations", transformations);
            ArrayNode chains = new ArrayNode(mapper.getNodeFactory());
            chains.add(chainNode);
            if (!chain.equals("default")) {
                chainNode = new ObjectNode(mapper.getNodeFactory());
                chainNode.set("name", new TextNode(chain));
                chains.add(chainNode);
            }
            ObjectNode reader = new ObjectNode(mapper.getNodeFactory());
            setIncludesOrExcludesList(reader);

            chainNode.set("reader", reader);
            ObjectNode writer = new ObjectNode(mapper.getNodeFactory());
            setIncludesOrExcludesList(writer);
            chainNode.set("writer", writer);

            root.set("chains", chains);
        } else if (!node.has("modules")) {
            ObjectNode chainNode = new ObjectNode(mapper.getNodeFactory());
            chainNode.set("name", new TextNode("default"));
            ArrayNode chains = new ArrayNode(mapper.getNodeFactory());
            chains.add(chainNode);

            ObjectNode reader = new ObjectNode(mapper.getNodeFactory());
            setIncludesOrExcludesList(reader);

            chainNode.set("reader", reader);
            ObjectNode writer = new ObjectNode(mapper.getNodeFactory());
            setIncludesOrExcludesList(writer);
            chainNode.set("writer", writer);

            root.set("chains", chains);
        }

    }
    provider.write(node);
}

From source file:es.bsc.amon.controller.AppsDBMapper.java

/**
 *
 * @param start//from  w w w . jav a2s  . c o  m
 * @param end
 * @param showInstances if true, shows instances information instead of nodes information
 * @return
 */
public ObjectNode getAllApps(long start, long end, boolean showInstances) {
    DBObject query = (DBObject) JSON.parse("{ '$or' : [" + "{ '$and' : [ { timestamp : { '$gte' : " + start
            + " }}, { timestamp : {'$lte' : " + end + "}} ] }," + "{ '$and' : [ { endtime : { '$gte' : " + start
            + " }}, { endtime : {'$lte' : " + end + "}} ] }" + "]}");
    //DBObject orderby = new BasicDBObject("timestamp":-1);
    BasicDBList ret = DBManager.instance.find(EventsDBMapper.COLL_NAME, query);

    Map<String, Set<String>> appsInfo = new HashMap<>();

    Iterator<Object> iter = ret.iterator();
    while (iter.hasNext()) {
        DBObject event = (DBObject) iter.next();
        try {
            String appName = event.get(EventsDBMapper.APPID).toString();
            Object node = event.get(showInstances ? EventsDBMapper.INSTANCEID : EventsDBMapper.NODEID);
            String nodeName = node == null ? "" : node.toString();
            Set<String> appSet = appsInfo.get(appName);
            if (appSet == null) {
                appSet = new TreeSet<String>();
                appsInfo.put(appName, appSet);
            }
            appSet.add(nodeName);
        } catch (NullPointerException ex) {
            Logger.warn("This element did not parsed as an application: " + event.toString()
                    + ". Removing it from DB...");
            try {
                EventsDBMapper.getInstance().remove(event);
            } catch (Exception e) {
                Logger.error("Cannot remove it from database");
            }
        }
    }

    ObjectNode all = new ObjectNode(JsonNodeFactory.instance);
    for (Map.Entry<String, Set<String>> entry : appsInfo.entrySet()) {
        ArrayNode nodes = new ArrayNode(JsonNodeFactory.instance);
        for (String n : entry.getValue()) {
            nodes.add(n);
        }
        all.put(entry.getKey(), nodes);
    }
    return all;
}

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

/**
 * This operation merge the contents of two JSON arrays. This operation does not modify either of the input arrays.
 * The result is the contents or array1 and array2, merged into a single array. The merge operation add into the result
 * the first array and then the second array.
 *
 * @param array1 The string representation of a JSON array object.
 *               Arrays in JSON are comma separated lists of objects, enclosed in square brackets [ ].
 *               Examples: [1,2,3] or ["one","two","three"] or [{"one":1, "two":2}, 3, "four"]
 * @param array2 The string representation of a JSON array object.
 *               Arrays in JSON are comma separated lists of objects, enclosed in square brackets [ ].
 *               Examples: [1,2,3] or ["one","two","three"] or [{"one":1, "two":2}, 3, "four"]
 * @return a map containing the output of the operation. Keys present in the map are:
 * <p/>//ww  w  . j av  a2s.  c o m
 * <br><br><b>returnResult</b> - This will contain the string representation of the new JSON array with the contents
 * of array1 and array2.
 * <br><b>exception</b> - In case of success response, this result is empty. In case of failure response,
 * this result contains the java stack trace of the runtime exception.
 * <br><br><b>returnCode</b> - The returnCode of the operation: 0 for success, -1 for failure.
 */
@Action(name = "Merge Arrays", outputs = { @Output(OutputNames.RETURN_RESULT), @Output(OutputNames.RETURN_CODE),
        @Output(OutputNames.EXCEPTION) }, responses = {
                @Response(text = ResponseNames.SUCCESS, field = OutputNames.RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
                @Response(text = ResponseNames.FAILURE, field = OutputNames.RETURN_CODE, value = ReturnCodes.FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) })
public Map<String, String> execute(@Param(value = Constants.InputNames.ARRAY, required = true) String array1,
        @Param(value = Constants.InputNames.ARRAY, required = true) String array2) {

    Map<String, String> returnResult = new HashMap<>();
    if (StringUtilities.isBlank(array1)) {
        final String exceptionValue = NOT_A_VALID_JSON_ARRAY_MESSAGE
                + ARRAY1_MESSAGE.replaceFirst("=", EMPTY_STRING);
        return populateResult(returnResult, exceptionValue, new Exception(exceptionValue));
    }

    if (StringUtilities.isBlank(array2)) {
        final String exceptionValue = NOT_A_VALID_JSON_ARRAY_MESSAGE
                + ARRAY2_MESSAGE.replaceFirst("=", EMPTY_STRING);
        return populateResult(returnResult, new Exception(exceptionValue));
    }

    JsonNode jsonNode1;
    JsonNode jsonNode2;
    ObjectMapper mapper = new ObjectMapper();
    try {
        jsonNode1 = mapper.readTree(array1);
    } catch (IOException exception) {
        final String value = INVALID_JSON_OBJECT_PROVIDED_EXCEPTION_MESSAGE + ARRAY1_MESSAGE + array1;
        return populateResult(returnResult, value, exception);
    }
    try {
        jsonNode2 = mapper.readTree(array2);
    } catch (IOException exception) {
        final String value = INVALID_JSON_OBJECT_PROVIDED_EXCEPTION_MESSAGE + ARRAY2_MESSAGE + array2;
        return populateResult(returnResult, value, exception);
    }

    final String result;
    if (jsonNode1 instanceof ArrayNode && jsonNode2 instanceof ArrayNode) {
        final ArrayNode asJsonArray1 = (ArrayNode) jsonNode1;
        final ArrayNode asJsonArray2 = (ArrayNode) jsonNode2;
        final ArrayNode asJsonArrayResult = new ArrayNode(mapper.getNodeFactory());

        asJsonArrayResult.addAll(asJsonArray1);
        asJsonArrayResult.addAll(asJsonArray2);
        result = asJsonArrayResult.toString();
    } else {
        result = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY1_MESSAGE + array1 + ARRAY2_MESSAGE + array2;
        return populateResult(returnResult, new Exception(result));
    }
    return populateResult(returnResult, result, null);
}

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

/**
 * Serializes a repeated field./*from   w w  w  . j  a va  2  s  .c  o  m*/
 *
 * @param message the message being serialized
 * @param registry a registry of schemas, for enclosed object types
 * @param field the descriptor of the repeated field to serialize
 * @param count the count of repeated items in the field
 * @return the JSON representation of the serialized
 * @throws SerializationException
 */
private ArrayNode serializeRepeatedField(Message message, ReadableSchemaRegistry registry,
        FieldDescriptor field, int count) throws SerializationException {
    ArrayNode array = new ArrayNode(JsonNodeFactory.instance);
    for (int i = 0; i < count; i++) {
        Object value = message.getRepeatedField(field, i);
        JsonNode valueNode = serializeValue(value, field, registry);
        if (!valueNode.isNull()) {
            array.add(valueNode);
        }
    }
    return array;
}

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

@Test
public void testParseWithEmptyRepeated() throws Exception {
    NamedSchema schema = NamedSchema.of(Union.getDescriptor(), "Union").useSchema("union_repeated", "Union");
    SchemaRegistry registry = new SchemaRegistry();
    registry.register(schema);//from  w  w w  . j  a  v a2  s. c  om
    Union union = Union.newBuilder().setBoolValue(true).addUnionRepeated(Union.getDefaultInstance()).build();
    ObjectNode result = (ObjectNode) new NamedSchemaSerializer(schema).serialize(union, registry);
    result.put("unionRepeated", new ArrayNode(JsonNodeFactory.instance));
    Union parsed = Union.newBuilder().mergeFrom(new NamedSchemaParser(schema).parse(result, registry)).build();
    Assert.assertTrue(parsed.getBoolValue());
    Assert.assertEquals(0, parsed.getUnionRepeatedCount());
}