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

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

Introduction

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

Prototype

public ArrayNode add(JsonNode paramJsonNode) 

Source Link

Usage

From source file:lumbermill.api.JsonEvent.java

public JsonEvent add(String field, String... values) {
    for (String value : values) {
        if (jsonNode.has(field)) {
            ArrayNode arrayNode = (ArrayNode) this.jsonNode.get(field);
            arrayNode.add(value);
        } else {//w  ww .  j a  v  a 2  s .  c  o m
            jsonNode.set(field, jsonNode.arrayNode().add(value));
        }
    }
    return this;
}

From source file:org.flowable.rest.dmn.service.api.decision.DmnRuleServiceResourceTest.java

@DmnDeploymentAnnotation(resources = { "org/flowable/rest/dmn/service/api/decision/multi-hit.dmn" })
public void testExecutionDecision() throws Exception {
    // Add decision key
    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("decisionKey", "decision1");

    // add input variable
    ArrayNode variablesNode = objectMapper.createArrayNode();
    ObjectNode variableNode = objectMapper.createObjectNode();
    variableNode.put("name", "inputVariable1");
    variableNode.put("type", "integer");
    variableNode.put("value", 5);
    variablesNode.add(variableNode);

    requestNode.set("inputVariables", variablesNode);

    HttpPost httpPost = new HttpPost(
            SERVER_URL_PREFIX + DmnRestUrls.createRelativeResourceUrl(DmnRestUrls.URL_RULE_SERVICE_EXECUTE));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);

    // Check response
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);/* ww w .  j  av  a  2  s .  co  m*/

    ArrayNode resultVariables = (ArrayNode) responseNode.get("resultVariables");

    assertEquals(3, resultVariables.size());
}

From source file:org.envirocar.server.rest.util.GeoJSON.java

protected ArrayNode encodeCoordinate(Coordinate coordinate) throws GeometryConverterException {
    ArrayNode list = getJsonFactory().arrayNode();
    list.add(coordinate.x);
    list.add(coordinate.y);//from   w  w  w .j  a  v a 2s. co m
    return list;
}

From source file:com.baasbox.controllers.actions.filters.WrapResponse.java

private ObjectNode prepareError(RequestHeader request, String error) {
    //List<StackTraceElement> st = this.tryToExtractTheStackTrace(error);
    List<String> st = this.tryToExtractTheStackTrace(error);

    com.fasterxml.jackson.databind.ObjectMapper mapper = com.baasbox.service.scripting.js.Json.mapper();
    ObjectNode result = Json.newObject();
    result.put("result", "error");

    //the error is an exception or a plain message?
    if (st.size() == 0) {
        result.put("message", error);
    } else {// w ww  .j a  v  a 2 s  .c  o m
        Matcher headLineMatcher = headLinePattern.matcher(error);
        StringBuilder message = new StringBuilder();
        if (headLineMatcher.find()) {
            message.append(headLineMatcher.group(1));
            if (headLineMatcher.group(2) != null) {
                message.append(" ").append(headLineMatcher.group(2));
            }
        }
        result.put("message", message.toString());
        ArrayNode ston = result.putArray("stacktrace");
        st.forEach(x -> {
            ston.add(x);
        });
        result.put("full_stacktrace", error);
    }
    result.put("resource", request.path());
    result.put("method", request.method());
    result.put("request_header", (JsonNode) mapper.valueToTree(request.headers()));
    result.put("API_version", BBConfiguration.configuration.getString(BBConfiguration.API_VERSION));
    this.setCallIdOnResult(request, result);
    return result;
}

From source file:org.commonjava.indy.metrics.zabbix.api.IndyZabbixApi.java

/**
 *
 * @param host// w w w .  ja va 2s  .  c o  m
 * @param groupId
 * @param ip
 * @return hostid
 */
public String hostCreate(String host, String groupId, String ip) throws IOException {
    // host not exists, create it.
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode groups = mapper.createArrayNode();
    ObjectNode group = mapper.createObjectNode();
    group.put("groupid", groupId);
    groups.add(group);

    // "interfaces": [
    // {
    // "type": 1,
    // "main": 1,
    // "useip": 1,
    // "ip": "192.168.3.1",
    // "dns": "",
    // "port": "10050"
    // }
    // ],

    ObjectNode interface1 = mapper.createObjectNode();
    //        JSONObject interface1 = new JSONObject();
    interface1.put("type", 1);
    interface1.put("main", 1);
    interface1.put("useip", 1);
    interface1.put("ip", ip);
    interface1.put("dns", "");
    interface1.put("port", "10050");

    Request request = RequestBuilder.newBuilder().method("host.create").paramEntry("host", host)
            .paramEntry("groups", groups).paramEntry("interfaces", new Object[] { interface1 }).build();
    JsonNode response = call(request);
    return response.get("result").get("hostids").get(0).asText();
}

From source file:com.blackberry.bdp.common.versioned.ZkVersioned.java

/**
 * Iterates over json1 which is intended to be a full representation of a complete JSON 
 * structure.  It compares nodes on json1 against nodes on json2 which should contain 
 * either the same identical structure of json1 or a subset of JSON structure contained 
 * in json1./*  w  w  w  . jav a  2 s. c o m*/
 * 
 * If identically named nodes on json1 and json2 vary in type (ObjectNode vs ArrayNode
 * for example) then an exception is thrown since json2 must not contain any additional 
 * structure than what is found in json1.
 * 
 * Explicit Null Node Handling Regardless of Node type:
 * 
 * This pertains to the value of a node being explicity equal to null.  See further below 
 * for handling of non-existent nodes
 * 
 * If a node is null on json1 and not null on json2 then the node on json1 is set to the 
 * value of the node on json2.
 * 
 * If a node is not null on json1 and is null on json2 then the node on json1 is made null.
 * 
 * Non-existent Node Handling:
 *
 * Since json1 is intended to be a full representation of a  complete JSON structure 
 * nodes on json2 that don't exist on json1 are completely ignored.  Only if the same
 * node exists on both json1 and json2 will the structures be merged.
 * 
 * ArrayNode Handling
 * 
 * If the node being compared is an ArrayNode then the elements on json2 are iterated
 * over.  If the index on json1 exists on json1 then the two elements are merged.  If the 
 * index doesn't exist on json1 then the element is added to the ArrayNode on json1.
 * Note: The existence of the element on json1 is determined by index and when an 
 * element is added to json1 it's index increases by one.  That shouldn't be a problem 
 * though as for there to ever be more elements in json2, the index pointer will always 
 * be one larger than the max index of json1.
 * 
 * ArrayNode Handling when json1 contains more elements than json2:
 * 
 * Elements are removed from json1 if they have higher indexes than the size of json2
 * minus 1
 *
 * @param json1
 * @param json2
 * @return
 * @throws com.blackberry.bdp.common.exception.JsonMergeException
 */
public static JsonNode merge(JsonNode json1, JsonNode json2) throws JsonMergeException {
    Iterator<String> json1Fields = json1.fieldNames();
    LOG.info("Merged called on json1 ({}), json2 ({})", json1.getNodeType(), json2.getNodeType());

    while (json1Fields.hasNext()) {
        String nodeName = json1Fields.next();
        JsonNode json1Node = json1.get(nodeName);

        // Check if json2 has the node and run explicit null checks         
        if (!json2.has(nodeName)) {
            LOG.info("Not comparing {} since it doesn't exist on json2", nodeName);
            continue;
        } else if (json1Node.isNull() && json2.hasNonNull(nodeName)) {
            ((ObjectNode) json1).replace(nodeName, json2.get(nodeName));
            LOG.info("explicit null {} on json1 replaced with non-null from json2", nodeName);
            continue;
        } else if (json1.hasNonNull(nodeName) && json2.get(nodeName).isNull()) {
            ((ObjectNode) json1).replace(nodeName, json2.get(nodeName));
            LOG.info("non-null {} on json1 replaced with explicitly null on json2", nodeName);
            continue;
        }

        JsonNode json2Node = json2.get(nodeName);

        if (json1Node.getNodeType().equals(json2Node.getNodeType()) == false) {
            throw new JsonMergeException(String.format("json1 (%s) cannot be merged with json2 (%s)",
                    json1.getNodeType(), json2.getNodeType()));
        }

        LOG.info("need to compare \"{}\" which is a {}", nodeName, json1Node.getNodeType());

        if (json1Node.isObject()) {
            LOG.info("Calling merge on object {}", nodeName);
            merge(json1Node, json2.get(nodeName));
        } else if (json1Node instanceof ObjectNode) {
            throw new JsonMergeException("{} is instance of ObjectNode and wasn't isObject()--what gives?!");
        } else if (json1Node.isArray()) {
            ArrayNode json1Array = (ArrayNode) json1Node;
            ArrayNode json2Array = (ArrayNode) json2Node;
            LOG.info("ArrayNode {} json1 has {} elements and json2 has {} elements", nodeName,
                    json1Array.size(), json2Array.size());
            int indexNo = 0;
            Iterator<JsonNode> json2Iter = json2Array.iterator();
            while (json2Iter.hasNext()) {
                JsonNode json2Element = json2Iter.next();
                if (json1Array.has(indexNo)) {
                    LOG.info("Need to merge ArrayNode {} element {}", nodeName, indexNo);
                    merge(json1Node.get(indexNo), json2Element);
                } else {
                    LOG.info("ArrayNode {} element {} not found on json1, adding", nodeName, indexNo);
                    json1Array.add(json2Element);
                }
                indexNo++;
            }
            while (json1Array.size() > json2Array.size()) {
                int indexToRemove = json1Array.size() - 1;
                json1Array.remove(indexToRemove);
                LOG.info("ArrayNode {} index {} on json1 removed since greater than size of json2 ({})",
                        nodeName, indexToRemove, json2Array.size());
            }
        } else {
            LOG.info("{} ({}) has fallen through known merge types", nodeName, json1Node.getNodeType());
            ((ObjectNode) json1).replace(nodeName, json2Node);
            LOG.info("json1 node {} replaced with json2's node", nodeName);
        }
    }
    return json1;
}

From source file:org.envirocar.server.rest.util.GeoJSON.java

protected ArrayNode encodeCoordinates(Polygon geometry) throws GeometryConverterException {
    ArrayNode list = getJsonFactory().arrayNode();
    list.add(encodeCoordinates(geometry.getExteriorRing()));
    for (int i = 0; i < geometry.getNumInteriorRing(); ++i) {
        list.add(encodeCoordinates(geometry.getInteriorRingN(i)));
    }/* w  w w  .  j a v  a  2s  .c  om*/
    return list;
}

From source file:org.apache.taverna.examples.JsonExport.java

public ObjectNode toJson(WorkflowBundle wfBundle) {

    ObjectNode root = mapper.createObjectNode();
    ArrayNode contextList = root.arrayNode();
    root.put("@context", contextList);
    ObjectNode context = root.objectNode();
    contextList.add("https://w3id.org/scufl2/context");
    contextList.add(context);/*  ww w  . j a  v a 2 s.c  o m*/
    URI base = wfBundle.getGlobalBaseURI();
    context.put("@base", base.toASCIIString());
    root.put("id", base.toASCIIString());

    //        root.put("name", wfBundle.getName());
    //        root.put("revisions", toJson(wfBundle.getCurrentRevision()));

    root.put("workflow", toJson(wfBundle.getMainWorkflow()));
    root.put("profile", toJson(wfBundle.getMainProfile()));

    return root;
}

From source file:com.syncedsynapse.kore2.jsonrpc.ApiMethod.java

/**
 * Adds a parameter to the request/*from www  . j a va 2 s .co  m*/
 * @param parameter Parameter name
 * @param values Values to add
 */
protected void addParameterToRequest(String parameter, String[] values) {
    if (values != null) {
        final ArrayNode arrayNode = objectMapper.createArrayNode();
        for (int i = 0; i < values.length; i++) {
            arrayNode.add(values[i]);
        }
        getParametersNode().put(parameter, arrayNode);
    }
}

From source file:org.flowable.rest.dmn.service.api.decision.DmnRuleServiceResourceTest.java

@DmnDeploymentAnnotation(resources = { "org/flowable/rest/dmn/service/api/decision/single-hit.dmn" })
public void testExecutionDecisionSingleResult() throws Exception {
    // Add decision key
    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("decisionKey", "decision");

    // add input variable
    ArrayNode variablesNode = objectMapper.createArrayNode();
    ObjectNode variableNode1 = objectMapper.createObjectNode();
    variableNode1.put("name", "inputVariable1");
    variableNode1.put("type", "integer");
    variableNode1.put("value", 5);
    variablesNode.add(variableNode1);

    ObjectNode variableNode2 = objectMapper.createObjectNode();
    variableNode2.put("name", "inputVariable2");
    variableNode2.put("type", "string");
    variableNode2.put("value", "test2");
    variablesNode.add(variableNode2);//from  w w  w  .ja v  a  2  s. c  o m

    requestNode.set("inputVariables", variablesNode);

    HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX
            + DmnRestUrls.createRelativeResourceUrl(DmnRestUrls.URL_RULE_SERVICE_EXECUTE_SINGLE_RESULT));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);

    // Check response
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);

    ArrayNode resultVariables = (ArrayNode) responseNode.get("resultVariables");

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