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:com.github.reinert.jjschema.JsonSchemaGeneratorV4.java

@Override
protected void processSchemaProperty(ObjectNode schema, Attributes props) {
    if (!props.$ref().isEmpty()) {
        schema.put("$ref", props.$ref());
    }/*from  w ww .  ja  v a2  s  . com*/
    if (autoPutVersion) {
        schema.put("$schema", SchemaVersion.DRAFTV4.getLocation().toString());
    }
    if (!props.id().isEmpty()) {
        schema.put("id", props.id());
    }
    if (props.required()) {
        schema.put("selfRequired", true);
    }
    if (!props.description().isEmpty()) {
        schema.put("description", props.description());
    }
    if (!props.pattern().isEmpty()) {
        schema.put("pattern", props.pattern());
    }
    if (!props.format().isEmpty()) {
        schema.put("format", props.format());
    }
    if (!props.title().isEmpty()) {
        schema.put("title", props.title());
    }
    if (props.maximum() > -1) {
        schema.put("maximum", props.maximum());
    }
    if (props.exclusiveMaximum()) {
        schema.put("exclusiveMaximum", true);
    }
    if (props.minimum() > -1) {
        schema.put("minimum", props.minimum());
    }
    if (props.exclusiveMinimum()) {
        schema.put("exclusiveMinimum", true);
    }
    if (props.enums().length > 0) {
        ArrayNode enumArray = schema.putArray("enum");
        String[] enums = props.enums();
        for (String v : enums) {
            enumArray.add(v);
        }
    }
    if (props.uniqueItems()) {
        schema.put("uniqueItems", true);
    }
    if (props.minItems() > 0) {
        schema.put("minItems", props.minItems());
    }
    if (props.maxItems() > -1) {
        schema.put("maxItems", props.maxItems());
    }
    if (props.multipleOf() > 0) {
        schema.put("multipleOf", props.multipleOf());
    }
    if (props.minLength() > 0) {
        schema.put("minLength", props.minLength());
    }
    if (props.maxLength() > -1) {
        schema.put("maxLength", props.maxLength());
    }
    if (props.readonly()) {
        schema.put("readonly", true);
    }
}

From source file:net.pterodactylus.sone.web.ajax.GetNotificationsAjaxPage.java

/**
 * {@inheritDoc}//from  w w  w  .j a  v  a 2 s .c  o m
 */
@Override
protected JsonReturnObject createJsonObject(FreenetRequest request) {
    Sone currentSone = getCurrentSone(request.getToadletContext(), false);
    Collection<Notification> notifications = webInterface.getNotifications().getNotifications();
    List<Notification> filteredNotifications = ListNotificationFilters.filterNotifications(notifications,
            currentSone);
    Collections.sort(filteredNotifications, Notification.CREATED_TIME_SORTER);
    ArrayNode jsonNotifications = new ArrayNode(instance);
    for (Notification notification : filteredNotifications) {
        jsonNotifications.add(createJsonNotification(request, notification));
    }
    return createSuccessJsonObject().put("notificationHash", filteredNotifications.hashCode())
            .put("notifications", jsonNotifications).put("options", createJsonOptions(currentSone));
}

From source file:mobile.vo.result.MobilePage.java

@Override
public JsonNode toJson() {
    ObjectNode objectNode = Json.newObject();
    ArrayNode arrayNode = Json.newObject().arrayNode();
    if (CollectionUtils.isNotEmpty(list)) {
        for (T t : list) {
            JsonNode node = MobileVOUtil.toJson(t);
            arrayNode.add(node);
        }/* www . j  a  v  a 2  s  .  c o m*/
    }

    objectNode.put(totalFieldName, totalRowCount);
    objectNode.set(listFieldName, arrayNode);

    return objectNode;
}

From source file:com.ikanow.aleph2.v1.document_db.utils.TestJsonNodeBsonUtils.java

@Test
public void test_mapWritableWrapper() {
    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());

    final BasicDBObject m1 = new BasicDBObject();

    m1.put("test1", true);

    final BasicDBObject m2 = new BasicDBObject();
    m2.put("nested", m1);
    m2.put("test2", "test2");

    final BasicDBList a1 = new BasicDBList();
    a1.add(4);// w w w  . ja va 2s.c  o  m
    a1.add(5);

    final BasicDBList a2 = new BasicDBList();
    a2.add(m1);
    a2.add(m1);

    m2.put("array", a2);
    m1.put("array", a1);

    final JsonNode j2 = JsonNodeBsonUtils.from(m2);

    assertEquals(3, j2.size());

    // Check j's contents
    assertEquals(Stream.of("nested", "test2", "array").sorted().collect(Collectors.toList()),
            Optionals.streamOf(j2.fieldNames(), false).sorted().collect(Collectors.toList()));
    assertEquals("test2", j2.get("test2").asText());

    final JsonNode j1 = j2.get("nested");
    assertEquals(2, j1.size());
    final JsonNode j1b = JsonNodeBsonUtils.from(m1);
    assertTrue("entrySet wrong: " + j1b.toString(), "{\"test1\":true,\"array\":[4,5]}".equals(j1b.toString())
            || "{\"array\":[4,5],\"test1\":true}".equals(j1b.toString())); //(tests entrySet)
    final ArrayNode an = mapper.createArrayNode();
    an.add(mapper.convertValue(4, JsonNode.class));
    an.add(mapper.convertValue(5, JsonNode.class));
    assertEquals(Arrays.asList(mapper.convertValue(true, JsonNode.class), an),
            Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList()));

    // OK, now test adding:

    assertEquals(2, j1.size());

    final ObjectNode o1 = (ObjectNode) j1;
    o1.put("added", "added_this");

    final ObjectNodeWrapper o1c = (ObjectNodeWrapper) o1;
    assertFalse(o1c.containsKey("not_present"));
    assertTrue(o1c.containsKey("added"));
    assertTrue(o1c.containsKey("test1"));

    assertEquals(Stream.of("test1", "array", "added").sorted().collect(Collectors.toList()),
            Optionals.streamOf(j1.fieldNames(), false).sorted().collect(Collectors.toList()));
    assertEquals(
            Arrays.asList(mapper.convertValue(true, JsonNode.class), an,
                    mapper.convertValue("added_this", JsonNode.class)),
            Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList()));
    assertTrue(j1.toString().contains("added_this"));
    assertTrue(j1.toString().contains("4,5"));

    assertEquals(mapper.convertValue("added_this", JsonNode.class), j1.get("added"));

    assertEquals(3, j1.size());

    // OK now test removing:

    assertEquals(null, o1.remove("not_present"));
    assertEquals(mapper.convertValue(true, JsonNode.class), o1.remove("test1"));
    assertEquals(2, o1.size());
    ObjectNode o1b = o1.remove(Arrays.asList("added", "array"));
    assertEquals(0, o1.size());
    assertEquals(0, o1b.size());

    o1.setAll(JsonNodeBsonUtils.from(m1)); // will be minus one object
    assertEquals(2, o1.size());
    assertTrue(o1c.containsValue(mapper.convertValue(true, JsonNode.class)));
    assertFalse(o1c.containsValue("banana"));

    final ObjectNodeWrapper o2 = (ObjectNodeWrapper) JsonNodeBsonUtils.from(m2);
    assertFalse(o2.isEmpty());
    assertTrue(o2.containsKey("array"));
    assertFalse(o2.containsValue("array"));
    assertTrue(o2.containsValue(mapper.convertValue("test2", JsonNode.class)));
    assertEquals(TextNode.class, o2.remove("test2").getClass());
    assertEquals(2, o2.size());
    o2.removeAll();
    assertEquals(0, o2.size());
}

From source file:org.apache.taverna.scufl2.translator.t2flow.defaultactivities.ApiConsomerActivityParser.java

@Override
public Configuration parseConfiguration(T2FlowParser t2FlowParser, ConfigBean configBean,
        ParserState parserState) throws ReaderException {
    ApiConsumerConfig config = unmarshallConfig(t2FlowParser, configBean, "xstream", ApiConsumerConfig.class);

    Configuration configuration = new Configuration();
    configuration.setParent(parserState.getCurrentProfile());

    ObjectNode json = (ObjectNode) configuration.getJson();
    configuration.setType(ACTIVITY_URI.resolve("#Config"));

    json.put("apiConsumerDescription", config.getApiConsumerDescription());
    json.put("apiConsumerName", config.getApiConsumerName());
    json.put("description", config.getDescription());
    json.put("className", config.getClassName());
    json.put("methodName", config.getMethodName());

    ArrayNode parameterNames = json.arrayNode();
    json.put("parameterNames", parameterNames);
    for (String parameterName : config.getParameterNames().getString())
        parameterNames.add(parameterName);

    ArrayNode parameterDimensions = json.arrayNode();
    json.put("parameterDimensions", parameterDimensions);
    for (BigInteger parameterDimension : config.getParameterDimensions().getInt())
        parameterDimensions.add(parameterDimension.intValue());

    ArrayNode parameterTypes = json.arrayNode();
    json.put("parameterTypes", parameterTypes);
    for (String parameterType : config.getParameterTypes().getString())
        parameterTypes.add(parameterType);

    json.put("returnType", config.getReturnType());
    json.put("returnDimension", config.getReturnDimension().intValue());
    json.put("isMethodConstructor", config.isIsMethodConstructor());
    json.put("isMethodStatic", config.isIsMethodStatic());

    return configuration;
}

From source file:com.almende.pi5.common.agents.LoggerAgent.java

/**
 * Gets the json./*  w  ww  .  j a  v  a 2s .c o  m*/
 *
 * @return the json
 */
@JsonIgnore
public ArrayNode getJson() {
    final ArrayNode result = JOM.createArrayNode();
    synchronized (logs) {
        for (LogLine ll : logs) {
            result.add(JOM.getInstance().valueToTree(ll));
        }
    }
    return result;
}

From source file:org.apache.solr.kelvin.responseanalyzers.XmlDoclistExtractorResponseAnalyzer.java

public void decode(Map<String, Object> previousResponses) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode response = mapper.createArrayNode();

    if (!previousResponses.containsKey(XmlResponseAnalyzer.XML_DOM)) {
        previousResponses.put(DOC_LIST, response); //empty
        return;/*from ww  w  .  ja  va 2 s  . co m*/
    }

    NodeList nodeList = (NodeList) expr.evaluate((Document) previousResponses.get(XmlResponseAnalyzer.XML_DOM),
            XPathConstants.NODESET);

    for (int i = 0; i < nodeList.getLength(); i++) {
        Node doc = nodeList.item(i);
        ObjectNode oDoc = mapper.createObjectNode();
        Node subel = doc.getFirstChild();
        while (subel != null) {
            if (subel.getNodeType() != Node.TEXT_NODE) {
                String fieldName = subel.getAttributes().getNamedItem("name").getNodeValue();
                String elementName = subel.getNodeName();
                if ("arr".equals(elementName)) {
                    ArrayNode multivaluedField = mapper.createArrayNode();
                    Node mvItem = subel.getFirstChild();
                    while (mvItem != null) {
                        multivaluedField.add(mvItem.getTextContent());
                        mvItem = mvItem.getNextSibling();
                    }
                    oDoc.put(fieldName, multivaluedField);
                } else {
                    String value = subel.getTextContent();
                    oDoc.put(fieldName, value);
                }
            }
            subel = subel.getNextSibling();
        }
        response.add(oDoc);
    }
    previousResponses.put(DOC_LIST, response);
}

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

/**
 *
 * @param start/*from  ww w  .j a v a 2s . 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:org.apache.drill.optiq.DrillAggregateRel.java

@Override
public int implement(DrillImplementor implementor) {
    int inputId = implementor.visitChild(this, 0, getChild());
    final List<String> childFields = getChild().getRowType().getFieldNames();
    final List<String> fields = getRowType().getFieldNames();
    /*/*from  www .  ja  v  a  2s  .com*/
     * E.g. { op: "segment", ref: "segment", exprs: ["deptId"] }, { op: "collapsingaggregate", within: "segment",
     * carryovers: ["deptId"], aggregations: [ {ref: "c", expr: "count(1)"} ] }
     */
    final ObjectNode segment = implementor.mapper.createObjectNode();
    segment.put("op", "segment");
    segment.put("input", inputId);
    // TODO: choose different name for field if there is already a field
    // called "segment"
    segment.put("ref", "segment");
    final ArrayNode exprs = implementor.mapper.createArrayNode();
    segment.put("exprs", exprs);
    for (int group : Util.toIter(groupSet)) {
        exprs.add(childFields.get(group));
    }

    final int segmentId = implementor.add(segment);

    final ObjectNode aggregate = implementor.mapper.createObjectNode();
    aggregate.put("op", "collapsingaggregate");
    aggregate.put("input", segmentId);
    aggregate.put("within", "segment");
    final ArrayNode carryovers = implementor.mapper.createArrayNode();
    aggregate.put("carryovers", carryovers);
    for (int group : Util.toIter(groupSet)) {
        carryovers.add(childFields.get(group));
    }
    final ArrayNode aggregations = implementor.mapper.createArrayNode();
    aggregate.put("aggregations", aggregations);
    for (Ord<AggregateCall> aggCall : Ord.zip(aggCalls)) {
        final ObjectNode aggregation = implementor.mapper.createObjectNode();
        aggregation.put("ref", fields.get(groupSet.cardinality() + aggCall.i));
        aggregation.put("expr", toDrill(aggCall.e, childFields));
        aggregations.add(aggregation);
    }

    return implementor.add(aggregate);
}