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.datamountaineer.streamreactor.connect.json.SimpleJsonConverter.java

/**
 * Convert this object, in the org.apache.kafka.connect.data format, into a JSON object, returning both the schema
 * and the converted object./*w  ww  . ja  v a  2 s  .c o m*/
 */
private static JsonNode convertToJson(Schema schema, Object logicalValue) {
    if (logicalValue == null) {
        if (schema == null) // Any schema is valid and we don't have a default, so treat this as an optional schema
            return null;
        if (schema.defaultValue() != null)
            return convertToJson(schema, schema.defaultValue());
        if (schema.isOptional())
            return JsonNodeFactory.instance.nullNode();
        throw new DataException(
                "Conversion error: null value for field that is required and has no default value");
    }

    Object value = logicalValue;
    try {
        final Schema.Type schemaType;
        if (schema == null) {
            schemaType = ConnectSchema.schemaType(value.getClass());
            if (schemaType == null)
                throw new DataException(
                        "Java class " + value.getClass() + " does not have corresponding schema type.");
        } else {
            schemaType = schema.type();
        }
        switch (schemaType) {
        case INT8:
            return JsonNodeFactory.instance.numberNode((Byte) value);
        case INT16:
            return JsonNodeFactory.instance.numberNode((Short) value);
        case INT32:
            if (schema != null && Date.LOGICAL_NAME.equals(schema.name())) {
                return JsonNodeFactory.instance.textNode(ISO_DATE_FORMAT.format((java.util.Date) value));
            }
            if (schema != null && Time.LOGICAL_NAME.equals(schema.name())) {
                return JsonNodeFactory.instance.textNode(TIME_FORMAT.format((java.util.Date) value));
            }
            return JsonNodeFactory.instance.numberNode((Integer) value);
        case INT64:
            String schemaName = schema.name();
            if (Timestamp.LOGICAL_NAME.equals(schemaName)) {
                return JsonNodeFactory.instance
                        .numberNode(Timestamp.fromLogical(schema, (java.util.Date) value));
            }
            return JsonNodeFactory.instance.numberNode((Long) value);
        case FLOAT32:
            return JsonNodeFactory.instance.numberNode((Float) value);
        case FLOAT64:
            return JsonNodeFactory.instance.numberNode((Double) value);
        case BOOLEAN:
            return JsonNodeFactory.instance.booleanNode((Boolean) value);
        case STRING:
            CharSequence charSeq = (CharSequence) value;
            return JsonNodeFactory.instance.textNode(charSeq.toString());
        case BYTES:
            if (Decimal.LOGICAL_NAME.equals(schema.name())) {
                return JsonNodeFactory.instance.numberNode((BigDecimal) value);
            }

            byte[] valueArr = null;
            if (value instanceof byte[])
                valueArr = (byte[]) value;
            else if (value instanceof ByteBuffer)
                valueArr = ((ByteBuffer) value).array();

            if (valueArr == null)
                throw new DataException("Invalid type for bytes type: " + value.getClass());

            return JsonNodeFactory.instance.binaryNode(valueArr);

        case ARRAY: {
            Collection collection = (Collection) value;
            ArrayNode list = JsonNodeFactory.instance.arrayNode();
            for (Object elem : collection) {
                Schema valueSchema = schema == null ? null : schema.valueSchema();
                JsonNode fieldValue = convertToJson(valueSchema, elem);
                list.add(fieldValue);
            }
            return list;
        }
        case MAP: {
            Map<?, ?> map = (Map<?, ?>) value;
            // If true, using string keys and JSON object; if false, using non-string keys and Array-encoding
            boolean objectMode;
            if (schema == null) {
                objectMode = true;
                for (Map.Entry<?, ?> entry : map.entrySet()) {
                    if (!(entry.getKey() instanceof String)) {
                        objectMode = false;
                        break;
                    }
                }
            } else {
                objectMode = schema.keySchema().type() == Schema.Type.STRING;
            }
            ObjectNode obj = null;
            ArrayNode list = null;
            if (objectMode)
                obj = JsonNodeFactory.instance.objectNode();
            else
                list = JsonNodeFactory.instance.arrayNode();
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                Schema keySchema = schema == null ? null : schema.keySchema();
                Schema valueSchema = schema == null ? null : schema.valueSchema();
                JsonNode mapKey = convertToJson(keySchema, entry.getKey());
                JsonNode mapValue = convertToJson(valueSchema, entry.getValue());

                if (objectMode)
                    obj.set(mapKey.asText(), mapValue);
                else
                    list.add(JsonNodeFactory.instance.arrayNode().add(mapKey).add(mapValue));
            }
            return objectMode ? obj : list;
        }
        case STRUCT: {
            Struct struct = (Struct) value;
            if (struct.schema() != schema)
                throw new DataException("Mismatching schema.");
            ObjectNode obj = JsonNodeFactory.instance.objectNode();
            for (Field field : schema.fields()) {
                obj.set(field.name(), convertToJson(field.schema(), struct.get(field)));
            }
            return obj;
        }
        }

        throw new DataException("Couldn't convert " + value + " to JSON.");
    } catch (ClassCastException e) {
        throw new DataException("Invalid type for " + schema.type() + ": " + value.getClass());
    }
}

From source file:com.pros.jsontransform.sort.ArraySortAbstract.java

static void doSort(final ArrayNode arrayNode, final JsonNode sortNode, final ObjectTransformer transformer) {
    // move array nodes to sorted array
    int size = arrayNode.size();
    ArrayList<JsonNode> sortedArray = new ArrayList<JsonNode>(arrayNode.size());
    for (int i = 0; i < size; i++) {
        sortedArray.add(arrayNode.remove(0));
    }//w  w  w  .j a va  2s .c om

    // sort array
    sortedArray.sort(new NodeComparator(sortNode, transformer));

    // move nodes back to targetArray
    for (int i = 0; i < sortedArray.size(); i++) {
        arrayNode.add(sortedArray.get(i));
    }
}

From source file:com.infinities.skyport.util.JsonUtil.java

public static String toLegendJson(Throwable e) {
    StringWriter wtr = new StringWriter();
    try {//from ww w.  j a v a 2s.c o m
        JsonGenerator g = new JsonFactory().createGenerator(wtr);
        g.writeStartArray();
        g.writeStartObject();
        g.writeStringField("RES", "FALSE");
        g.writeStringField("REASON", e.toString());
        // g.writeStringField("REASON", Objects.firstNonNull(e.getMessage(),
        // e.toString()));
        g.writeEndObject();
        g.writeEndArray();
        g.close();
    } catch (Exception ee) {
        ArrayNode array = getObjectMapper().createArrayNode();
        ObjectNode reason = getObjectMapper().createObjectNode();
        ObjectNode status = getObjectMapper().createObjectNode();

        status.put(JsonConstants.STATUS, String.valueOf("FALSE"));
        reason.put(JsonConstants.REASON, "an unexpected error occurred");
        array.add(status).add(reason);

        // "[{\"RES\":\"FALSE\"}, {\"REASON\":\"an unexpected error occurred\"}]";
        return array.toString();
    }

    return wtr.toString();
}

From source file:com.redhat.lightblue.util.JsonDoc.java

/**
 * Combines all Json documents in a list into a single Json document
 *
 * @param docs List of JsonDoc objects//from  w  ww.j ava2 s. c o  m
 * @param nodeFactory Json node factory
 *
 * @return If the list has only one document, returns an ObjectNode,
 * otherwise returns an array node containing each document in array
 * elements
 */
public static JsonNode listToDoc(List<JsonDoc> docs, JsonNodeFactory nodeFactory) {
    if (docs == null) {
        return null;
    } else if (docs.isEmpty()) {
        return nodeFactory.arrayNode();
    } else if (docs.size() == 1) {
        return docs.get(0).getRoot();
    } else {
        ArrayNode node = nodeFactory.arrayNode();
        for (JsonDoc doc : docs) {
            node.add(doc.getRoot());
        }
        return node;
    }
}

From source file:de.thingweb.desc.ThingDescriptionParser.java

public static ObjectNode toJsonObject(Thing thing) {

    ObjectNode td = factory.objectNode();
    if (thing.getMetadata().get("@context") == null
            || thing.getMetadata().get("@context").getNodeType() == JsonNodeType.NULL) {
        td.put("@context", factory.textNode(WOT_TD_CONTEXT));
    } else {/*from w  w w  .  j  ava2 s .co  m*/
        td.put("@context", thing.getMetadata().get("@context"));
    }
    td.put("name", thing.getName());
    if (thing.getMetadata().contains("@type")) {
        td.put("@type", thing.getMetadata().get("@type"));
    }

    if (thing.getMetadata().contains("security")) {
        td.put("security", thing.getMetadata().get("security"));
    }

    if (thing.getMetadata().contains("encodings")) {
        // ArrayNode encodings = factory.arrayNode();
        // for (String e : thing.getMetadata().getAll("encodings")) {
        // encodings.add(e);
        // }
        td.put("encodings", thing.getMetadata().get("encodings"));
    }

    if (thing.getMetadata().contains("uris")) {
        //          ArrayNode uris = factory.arrayNode();
        //          for (JsonNode uri : thing.getMetadata().getAll("uris")) {
        //             uris.add(uri);
        //          }
        // // TODO array even if single value?
        // td.put("uris", uris);
        td.put("uris", thing.getMetadata().get("uris"));
    }

    ArrayNode properties = factory.arrayNode();
    for (Property prop : thing.getProperties()) {
        ObjectNode p = factory.objectNode();
        if (prop.getPropertyType() != null && prop.getPropertyType().length() > 0) {
            p.put("@type", prop.getPropertyType());
        }
        p.put("name", prop.getName());
        p.put("writable", prop.isWritable());
        p.put("valueType", prop.getValueType());

        if (prop.getHrefs().size() > 1) {
            ArrayNode hrefs = factory.arrayNode();
            for (String href : prop.getHrefs()) {
                hrefs.add(href);
            }
            p.put("hrefs", hrefs);
        } else if (prop.getHrefs().size() == 1) {
            p.put("hrefs", factory.textNode(prop.getHrefs().get(0)));
        }
        if (prop.getStability() != null) {
            p.put("stability", prop.getStability());
        }

        properties.add(p);
    }
    td.put("properties", properties);

    ArrayNode actions = factory.arrayNode();
    for (Action action : thing.getActions()) {
        ObjectNode a = factory.objectNode();
        if (action.getActionType() != null && action.getActionType().length() > 0) {
            a.put("@type", action.getActionType());
        }
        a.put("name", action.getName());

        if (action.getInputType() != null) {
            ObjectNode in = factory.objectNode();
            in.put("valueType", action.getInputType());
            a.put("inputData", in);
        }

        if (action.getOutputType() != null) {
            ObjectNode out = factory.objectNode();
            out.put("valueType", action.getOutputType());
            a.put("outputData", out);
        }

        if (action.getHrefs().size() > 1) {
            ArrayNode hrefs = factory.arrayNode();
            for (String href : action.getHrefs()) {
                hrefs.add(href);
            }
            a.put("hrefs", hrefs);
        } else if (action.getHrefs().size() == 1) {
            a.put("hrefs", factory.textNode(action.getHrefs().get(0)));
        }

        actions.add(a);
    }
    td.put("actions", actions);

    ArrayNode events = factory.arrayNode();
    for (Event event : thing.getEvents()) {
        ObjectNode a = factory.objectNode();
        if (event.getEventType() != null && event.getEventType().length() > 0) {
            a.put("@type", event.getEventType());
        }
        a.put("name", event.getName());

        if (event.getValueType() != null) {
            a.put("valueType", event.getValueType());
        }

        if (event.getHrefs().size() > 1) {
            ArrayNode hrefs = factory.arrayNode();
            for (String href : event.getHrefs()) {
                hrefs.add(href);
            }
            a.put("hrefs", hrefs);
        } else if (event.getHrefs().size() == 1) {
            a.put("hrefs", factory.textNode(event.getHrefs().get(0)));
        }

        events.add(a);
    }
    td.put("events", events);

    return td;
}

From source file:com.yahoo.elide.extensions.JsonApiPatch.java

/**
 * Merge response documents to create final response.
 *//*from w ww .j a va2  s. co m*/
private static JsonNode mergeResponse(List<Supplier<Pair<Integer, JsonNode>>> results) {
    ArrayNode list = JsonNodeFactory.instance.arrayNode();
    for (Supplier<Pair<Integer, JsonNode>> result : results) {
        JsonNode node = result.get().getRight();
        if (node == null || node instanceof NullNode) {
            node = JsonNodeFactory.instance.objectNode().set("data", null);
        }
        list.add(node);
    }
    return list;
}

From source file:mobile.service.SelfInfoService.java

/**
 * ???/*from   w w w.  j  a v a 2s. co  m*/
 * 
 * @param newJobExp ??
 */
public static ServiceResult addJobExp(JsonNode newJobExp) {
    User user = User.getFromSession(Context.current().session());
    Expert expert = Expert.findByUserId(user.id);

    ArrayNode jobExpArrayNode = null;
    if (null == expert || StringUtils.isBlank(expert.jobExp)) {
        jobExpArrayNode = Json.newObject().arrayNode();
    } else {
        jobExpArrayNode = (ArrayNode) Json.parse(expert.jobExp);
    }
    if (newJobExp.hasNonNull("endYear") && newJobExp.get("endYear").asText().equals("-1")) {
        ((ObjectNode) newJobExp).put("endYear", "");
    }
    jobExpArrayNode.add(newJobExp);

    ObjectNode jobExpNode = Json.newObject();
    jobExpNode.set("jobExp", jobExpArrayNode);

    ObjectNodeResult objectNodeResult = Expert.saveExpertByJson(Context.current().session(), jobExpNode);

    return ServiceResult.create(objectNodeResult);
}

From source file:com.redhat.lightblue.crud.rdbms.RDBMSProcessor.java

private static void convertRecursion(RDBMSContext rdbmsContext, JsonDoc jd, String key, Object values,
        ArrayNode doc) {
    Collection c = values instanceof Collection ? ((Collection) values) : null;
    if (values == null || (c != null && c.isEmpty())) {
        if (doc == null) {
            jd.modify(new Path(key), NullNode.getInstance(), true);
        } else {//from  ww w . ja  va 2  s  . c  om
            doc.add(NullNode.getInstance());
        }
    } else if (c != null && c.size() > 1) {
        if (doc == null) {
            doc = new ArrayNode(rdbmsContext.getJsonNodeFactory());
        }
        for (Object value : c) {
            if (value instanceof Collection) {
                Collection cValue = (Collection) value;
                ArrayNode newDoc = new ArrayNode(rdbmsContext.getJsonNodeFactory());
                for (Object o : cValue) {
                    convertRecursion(rdbmsContext, jd, key, o, newDoc);
                }
                doc.add(newDoc);
            } else {
                doc.add(value.toString());
            }
        }
        jd.modify(new Path(key), doc, true);
    } else {
        if (doc == null) {
            Object o = c.iterator().next();
            jd.modify(new Path(key), new TextNode(o.toString()), true);
        } else {
            doc.add(new TextNode(values.toString()));
        }
    }
}

From source file:de.thingweb.desc.ThingDescriptionParser.java

@Deprecated
private static Thing parseOld(JsonNode td) throws IOException {
    try {/*from w  ww. ja v  a 2s .  co  m*/
        Thing thing = new Thing(td.get("metadata").get("name").asText());

        Iterator<String> tdIterator = td.fieldNames();
        while (tdIterator.hasNext()) {
            switch (tdIterator.next()) {
            case "metadata":
                Iterator<String> metaIterator = td.get("metadata").fieldNames();
                while (metaIterator.hasNext()) {
                    switch (metaIterator.next()) {
                    case "encodings":
                        for (JsonNode encoding : td.get("metadata").get("encodings")) {
                            thing.getMetadata().add("encodings", encoding);
                        }
                        break;

                    case "protocols":
                        TreeMap<Long, String> orderedURIs = new TreeMap<>();
                        for (JsonNode protocol : td.get("metadata").get("protocols")) {
                            orderedURIs.put(protocol.get("priority").asLong(), protocol.get("uri").asText());
                        }
                        if (orderedURIs.size() == 1) {
                            thing.getMetadata().add("uris", factory.textNode(orderedURIs.get(0)));
                        } else {
                            ArrayNode an = factory.arrayNode();
                            for (String uri : orderedURIs.values()) {
                                // values returned in ascending order
                                an.add(uri);
                            }
                            thing.getMetadata().add("uris", an);
                        }

                        break;
                    }
                }
                break;

            case "interactions":
                for (JsonNode inter : td.get("interactions")) {
                    if (inter.get("@type").asText().equals("Property")) {
                        Property.Builder builder = Property.getBuilder(inter.get("name").asText());
                        Iterator<String> propIterator = inter.fieldNames();
                        while (propIterator.hasNext()) {
                            switch (propIterator.next()) {
                            case "outputData":
                                builder.setValueType(inter.get("outputData"));
                                break;
                            case "writable":
                                builder.setWriteable(inter.get("writable").asBoolean());
                                break;
                            }
                        }
                        thing.addProperty(builder.build());
                    } else if (inter.get("@type").asText().equals("Action")) {
                        Action.Builder builder = Action.getBuilder(inter.get("name").asText());
                        Iterator<String> actionIterator = inter.fieldNames();
                        while (actionIterator.hasNext()) {
                            switch (actionIterator.next()) {
                            case "inputData":
                                builder.setInputType(inter.get("inputData").asText());
                                break;
                            case "outputData":
                                builder.setOutputType(inter.get("outputData").asText());
                                break;
                            }
                        }
                        thing.addAction(builder.build());
                    } else if (inter.get("@type").asText().equals("Event")) {
                        Event.Builder builder = Event.getBuilder(inter.get("name").asText());
                        Iterator<String> actionIterator = inter.fieldNames();
                        while (actionIterator.hasNext()) {
                            switch (actionIterator.next()) {
                            case "outputData":
                                builder.setValueType(inter.get("outputData"));
                                break;
                            }
                        }
                        thing.addEvent(builder.build());
                    }
                }
                break;
            }
        }

        return thing;
    } catch (Exception e) { // anything could happen here
        throw new IOException("unable to parse Thing Description");
    }
}

From source file:com.squarespace.template.plugins.platform.CommerceUtils.java

public static ArrayNode getItemVariantOptions(JsonNode item) {
    JsonNode structuredContent = item.path("structuredContent");
    JsonNode variants = structuredContent.path("variants");
    if (variants.size() <= 1) {
        return EMPTY_ARRAY;
    }//from  w  w  w .ja v  a2s .  com

    ArrayNode userDefinedOptions = JsonUtils.createArrayNode();
    JsonNode ordering = structuredContent.path("variantOptionOrdering");
    for (int i = 0; i < ordering.size(); i++) {
        String optionName = ordering.path(i).asText();
        ObjectNode option = JsonUtils.createObjectNode();
        option.put("name", optionName);
        option.put("values", JsonUtils.createArrayNode());
        userDefinedOptions.add(option);
    }

    for (int i = 0; i < variants.size(); i++) {
        JsonNode variant = variants.path(i);
        JsonNode attributes = variant.get("attributes");
        if (attributes == null) {
            continue;
        }
        Iterator<String> fields = attributes.fieldNames();

        while (fields.hasNext()) {
            String field = fields.next();

            String variantOptionValue = attributes.get(field).asText();
            ObjectNode userDefinedOption = null;

            for (int j = 0; j < userDefinedOptions.size(); j++) {
                ObjectNode current = (ObjectNode) userDefinedOptions.get(j);
                if (current.get("name").asText().equals(field)) {
                    userDefinedOption = current;
                }
            }

            if (userDefinedOption != null) {
                boolean hasOptionValue = false;
                ArrayNode optionValues = (ArrayNode) userDefinedOption.get("values");
                for (int k = 0; k < optionValues.size(); k++) {
                    String optionValue = optionValues.get(k).asText();
                    if (optionValue.equals(variantOptionValue)) {
                        hasOptionValue = true;
                        break;
                    }
                }

                if (!hasOptionValue) {
                    optionValues.add(variantOptionValue);
                }
            }
        }
    }
    return userDefinedOptions;
}