Java Code Examples for com.fasterxml.jackson.databind.node.ArrayNode#addArray()

The following examples show how to use com.fasterxml.jackson.databind.node.ArrayNode#addArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonSerializable.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
private <T> void internalSetCollection(String propertyName, Collection<T> collection, ArrayNode targetArray) {
    for (T childValue : collection) {
        if (childValue == null) {
            // Sets null.
            targetArray.addNull();
        } else if (childValue instanceof Collection) {
            // When T is also a Collection, use recursion.
            ArrayNode childArray = targetArray.addArray();
            this.internalSetCollection(propertyName, (Collection) childValue, childArray);
        } else if (childValue instanceof JsonNode) {
            targetArray.add((JsonNode) childValue);
        } else if (childValue instanceof JsonSerializable) {
            // JsonSerializable
            JsonSerializable castedValue = (JsonSerializable) childValue;
            castedValue.populatePropertyBag();
            targetArray.add(castedValue.propertyBag != null ? castedValue.propertyBag : this.getMapper().createObjectNode());
        } else {
            // POJO, JSONObject, Number (includes Int, Float, Double etc),
            // Boolean, and String.
            targetArray.add(this.getMapper().valueToTree(childValue));
        }
    }
}
 
Example 2
Source File: GetGraphValues.java    From constellation with Apache License 2.0 5 votes vote down vote up
@Override
public void callService(final PluginParameters parameters, InputStream in, OutputStream out) throws IOException {
    final String graphId = parameters.getStringValue(GRAPH_ID_PARAMETER_ID);

    final Graph graph = graphId == null ? RestUtilities.getActiveGraph() : GraphNode.getGraph(graphId);
    final ObjectMapper mapper = new ObjectMapper();
    final ObjectNode root = mapper.createObjectNode();
    final ArrayNode columns = root.putArray("columns");
    final ArrayNode data = root.putArray("data");
    final ArrayNode row = data.addArray();
    final ReadableGraph rg = graph.getReadableGraph();
    try {
        final int gCount = rg.getAttributeCount(GraphElementType.GRAPH);
        for (int i = 0; i < gCount; i++) {
            final int attrId = rg.getAttribute(GraphElementType.GRAPH, i);
            final String type = rg.getAttributeType(attrId);
            final String label = rg.getAttributeName(attrId);
            String value = rg.getStringValue(attrId, 0);

            columns.add(String.format("%s|%s", label, type));
            RestUtilities.addData(row, type, value);
        }
    } finally {
        rg.release();
    }

    mapper.writeValue(out, root);
}
 
Example 3
Source File: CopyingFormat.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private static JsonNode getOrCreateNode(JsonNode node, String key, boolean getObjectNode){
    if (node instanceof  ObjectNode) {
        ObjectNode obj = (ObjectNode) node;
        return obj.has(key) ? obj.get(key) : getObjectNode ? obj.putObject(key) : obj.putArray(key);
    } else if (node instanceof ArrayNode) {
        ArrayNode arrayNode = (ArrayNode) node;
        return getObjectNode ? arrayNode.addObject() : arrayNode.addArray();
    }

    return null;
}
 
Example 4
Source File: ObservationEncoder.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
private JsonNode encodeSweDataArrayValue(Value<?> value)
        throws EncodingException {
    SweDataArrayValue sweDataArrayValue = (SweDataArrayValue) value;
    ObjectNode result = nodeFactory().objectNode();
    ArrayNode jfields = result.putArray(JSONConstants.FIELDS);
    ArrayNode jvalues = result.putArray(JSONConstants.VALUES);
    List<SweField> fields = ((SweDataRecord) sweDataArrayValue.getValue().getElementType()).getFields();
    List<List<String>> values = sweDataArrayValue.getValue().getValues();
    TokenConverter[] conv = new TokenConverter[fields.size()];
    int i = 0;
    for (SweField field : fields) {
        try {
            conv[i++] = TokenConverter.forField(field);
        } catch (IllegalArgumentException e) {
            throw new UnsupportedEncoderInputException(this, field);
        }
        jfields.add(encodeObjectToJson(field));
    }

    for (List<String> block : values) {
        ArrayNode jblock = jvalues.addArray();
        i = 0;
        for (String token : block) {
            jblock.add(conv[i++].convert(token));
        }
    }
    return result;
}
 
Example 5
Source File: RestUtilities.java    From constellation with Apache License 2.0 4 votes vote down vote up
/**
 * Add a value to a column.
 *
 * @param row The JSON array representing the column.
 * @param type The type of the value.
 * @param value The (possibly null) value.
 */
public static void addData(final ArrayNode row, final String type, final String value) {
    switch (type) {
        case BooleanAttributeDescription.ATTRIBUTE_NAME:
        case BooleanObjectAttributeDescription.ATTRIBUTE_NAME:
            // A DataFrame will parse [True, False, None] to [1.0, 0.0, Nan],
            // so implicitly convert null to False so the result is all booleans.
            row.add(Boolean.parseBoolean(value));
            break;
        case ColorAttributeDescription.ATTRIBUTE_NAME:
            if (value == null) {
                row.addNull();
            } else {
                final ArrayNode rgb = row.addArray();
                final ConstellationColor cv = ConstellationColor.getColorValue(value);
                rgb.add(cv.getRed());
                rgb.add(cv.getGreen());
                rgb.add(cv.getBlue());
                rgb.add(cv.getAlpha());
            }
            break;
        case ZonedDateTimeAttributeDescription.ATTRIBUTE_NAME:
            // A DataFrame will parse null as NaT.
            if (value == null) {
                row.addNull();
            } else {
                // Remove the trailing tz name if present.
                final int ix = value.lastIndexOf(" [");
                row.add(ix == -1 ? value : value.substring(0, ix));
            }
            break;
        case FloatAttributeDescription.ATTRIBUTE_NAME:
        case FloatObjectAttributeDescription.ATTRIBUTE_NAME:
            // A DataFrame will parse null as NaN.
            if (value == null) {
                row.addNull();
            } else {
                row.add(Float.parseFloat(value));
            }
            break;
        case IntegerAttributeDescription.ATTRIBUTE_NAME:
        case IntegerObjectAttributeDescription.ATTRIBUTE_NAME:
            // A DataFrame will parse null as NaN, but the column will be
            // converted to a float column.
            if (value == null) {
                row.addNull();
            } else {
                row.add(Integer.parseInt(value));
            }
            break;
        default:
            // Everything else we leave as a string; nulls are fine.
            row.add(value);
            break;
    }
}
 
Example 6
Source File: IntentsWebResource.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Gets all related flow entries created by a particular intent.
 * Returns all flow entries of the specified intent.
 *
 * @param appId application identifier
 * @param key   intent key
 * @return 200 OK with intent data
 * @onos.rsModel Relatedflows
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("relatedflows/{appId}/{key}")
public Response getIntentFlowsById(@PathParam("appId") String appId,
                                   @PathParam("key") String key) {
    ApplicationId applicationId = get(CoreService.class).getAppId(appId);
    nullIsNotFound(applicationId, APP_ID_NOT_FOUND);
    IntentService intentService = get(IntentService.class);
    FlowRuleService flowService = get(FlowRuleService.class);

    Intent intent = intentService.getIntent(Key.of(key, applicationId));
    if (intent == null) {
        long numericalKey = Long.decode(key);
        intent = intentService.getIntent(
                Key.of(numericalKey, applicationId));
    }
    nullIsNotFound(intent, INTENT_NOT_FOUND);

    ObjectNode root = mapper().createObjectNode();
    root.put(APP_ID, appId);
    root.put(ID, key);

    IntentFilter intentFilter = new IntentFilter(intentService, flowService);

    List<Intent> installables =
            intentService.getInstallableIntents(intent.key());

    if (intent instanceof HostToHostIntent) {
        root.put(INTENT_TYPE, HOST_TO_HOST_INTENT);
    } else if (intent instanceof PointToPointIntent) {
        root.put(INTENT_TYPE, POINT_TO_POINT_INTENT);
    } else if (intent instanceof SinglePointToMultiPointIntent) {
        root.put(INTENT_TYPE, SINGLE_TO_MULTI_POINT_INTENT);
    } else if (intent instanceof MultiPointToSinglePointIntent) {
        root.put(INTENT_TYPE, MULTI_TO_SINGLE_POINT_INTENT);
    } else {
        root.put(INTENT_TYPE, INTENT);
    }

    ArrayNode pathsNode = root.putArray(INTENT_PATHS);

    for (List<FlowEntry> flowEntries :
            intentFilter.readIntentFlows(installables)) {
        ArrayNode flowNode = pathsNode.addArray();

        for (FlowEntry entry : flowEntries) {
            flowNode.add(codec(FlowEntry.class).encode(entry, this));
        }
    }
    return ok(root).build();
}