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

The following examples show how to use com.fasterxml.jackson.databind.node.ArrayNode#forEach() . 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: JsonSchemaGeneratorTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void assertSchema(GeneratedFile file, SchemaVersion schemaVersion) throws IOException {
    ObjectReader reader = new ObjectMapper().reader();
    JsonNode node = reader.readTree(file.contents());
    assertEquals(schemaVersion.getIdentifier(), node.get("$schema").asText());
    assertEquals("object", node.get("type").asText());
    JsonNode properties = node.get("properties");
    assertEquals(4, properties.size());
    assertEquals("integer", properties.get("age").get("type").asText());
    assertEquals("string", properties.get("name").get("type").asText());
    JsonNode color = properties.get("color");
    assertEquals("string", color.get("type").asText());
    assertTrue (color.get("enum") instanceof ArrayNode);
    ArrayNode colors = (ArrayNode) color.get("enum");
    Set<Color> colorValues = EnumSet.noneOf(Color.class);
    colors.forEach(x -> colorValues.add(Color.valueOf(x.asText())));
    assertArrayEquals(Color.values(),colorValues.toArray());
    JsonNode address = properties.get("address");
    assertEquals("object", address.get("type").asText());
    JsonNode addressProperties = address.get("properties");
    assertEquals("string", addressProperties.get("street").get("type").asText());
    JsonNode dateNode = addressProperties.get("date");
    assertEquals("string", dateNode.get("type").asText());
    assertEquals("date-time", dateNode.get("format").asText());
}
 
Example 2
Source File: OpenstackNodeWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
private Set<OpenstackNode> readNodeConfiguration(InputStream input) {
    Set<OpenstackNode> nodeSet = Sets.newHashSet();
    try {
         JsonNode jsonTree = readTreeFromStream(mapper().enable(INDENT_OUTPUT), input);
         ArrayNode nodes = (ArrayNode) jsonTree.path(NODES);
         nodes.forEach(node -> {
                 ObjectNode objectNode = node.deepCopy();
                 OpenstackNode openstackNode =
                         codec(OpenstackNode.class).decode(objectNode, this);

                 nodeSet.add(openstackNode);
         });
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }

    return nodeSet;
}
 
Example 3
Source File: BasicHostConfig.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the auxLocations of the host.
 *
 * @return auxLocations of the host or null if none specified
 * @throws IllegalArgumentException if auxLocations are set but empty or not
 *                                  specified with correct format
 */
public Set<HostLocation> auxLocations() {
    if (!object.has(AUX_LOCATIONS)) {
        return null; //no auxLocations are specified
    }

    ImmutableSet.Builder<HostLocation> auxLocationsSetBuilder = ImmutableSet.<HostLocation>builder();

    ArrayNode auxLocationNodes = (ArrayNode) object.path(AUX_LOCATIONS);
    auxLocationNodes.forEach(n -> {
        ConnectPoint cp = ConnectPoint.deviceConnectPoint((n.asText()));
        auxLocationsSetBuilder.add(new HostLocation(cp, 0));
    });

    return auxLocationsSetBuilder.build();
}
 
Example 4
Source File: TroubleshootLoadFileCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Remove JSON nodes for extension instructions of a flow.
 * This effectively allows T3 in offline mode to ignore extension fields of flows to avoid "device not found" error.
 * See decodeExtension() in {@link org.onosproject.codec.impl.DecodeInstructionCodecHelper}.
 *
 * @param flowNode  the json node representing a flow
 * @return          json node with removed extensions
 */
private ObjectNode removeExtension(ObjectNode flowNode) {

    // TODO: decoding extension instructions of offline (dumped) flows is not supported by T3 for now
    ArrayNode extensionRemoved = mapper().createArrayNode();
    ArrayNode instructionArrayNode = (ArrayNode) flowNode.get("treatment").get("instructions");
    instructionArrayNode.forEach(instrNode -> {
        String instrType = instrNode.get("type").asText();
        if (!instrType.equals(Instruction.Type.EXTENSION.name())) {
            extensionRemoved.add(instrNode);
        }
    });
    ((ObjectNode) flowNode.get("treatment")).replace("instructions", extensionRemoved);

    return flowNode;
}
 
Example 5
Source File: GitLabSourceConnector.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
/**
 * Queries the given endpoint, reads the resulting branches, adds all of the branches it finds
 * to the collection of branches, and then returns a URL of the next page of results.
 * @param httpClient
 * @param endpoint
 * @param branches
 * @throws IOException
 * @throws SourceConnectorException
 */
private String addBranches(CloseableHttpClient httpClient, Endpoint endpoint,
        Collection<SourceCodeBranch> branches) throws IOException, SourceConnectorException {
    HttpGet get = new HttpGet(endpoint.toString());
    get.addHeader("Accept", "application/json");
    addSecurity(get);

    try (CloseableHttpResponse response = httpClient.execute(get)) {
        try (InputStream contentStream = response.getEntity().getContent()) {
            JsonNode node = mapper.readTree(contentStream);
            if (node.isArray()) {
                ArrayNode array = (ArrayNode) node;
                array.forEach(obj -> {
                    JsonNode branch = (JsonNode) obj;
                    SourceCodeBranch glBranch = new SourceCodeBranch();
                    glBranch.setName(branch.get("name").asText());
                    glBranch.setCommitId(branch.get("commit").get("id").asText());
                    branches.add(glBranch);
                });
            }
        }
        Header linkHeader = response.getFirstHeader("Link");
        return getNextPage(linkHeader);
    }
}
 
Example 6
Source File: VplsWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Add new interfaces. Add new interfaces to a Vpls.<br>
 *
 * @param stream interfaces JSON
 * @param vplsName Vpls name
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 * @onos.rsModel InterfacesPost
 */
@POST
@Path("interfaces/{vplsName}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response addInterfaces(@PathParam("vplsName") String vplsName, InputStream stream) {
    Vpls service = get(Vpls.class);
    DeviceService deviceService = get(DeviceService.class);
    InterfaceAdminService interfaceService = get(InterfaceAdminService.class);
    final VplsData vplsData = nullIsNotFound(service.getVpls(vplsName),
            VPLS_NOT_FOUND + vplsName);
    try {
        ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
        ArrayNode routesArray = nullIsIllegal((ArrayNode) jsonTree.get(INTERFACES),
                INTERFACES_KEY_ERROR);
        Collection<Interface> interfaceList = new ArrayList<>();
       routesArray.forEach(interfJson -> {
            Interface inter = codec(Interface.class).decode((ObjectNode) interfJson, this);
            nullIsNotFound(deviceService.getDevice(inter.connectPoint().deviceId()),
                    DEVICE_NOT_FOUND + inter.connectPoint().deviceId());
            nullIsNotFound(deviceService.getPort(inter.connectPoint()),
                    PORT_NOT_FOUND + inter.connectPoint().port());
            interfaceList.add(inter);
            interfaceService.add(inter);
        });
        service.addInterfaces(vplsData, interfaceList);
        UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
                .path(INTERFACES)
                .path(vplsName);
        return Response
                .created(locationBuilder.build())
                .build();

    } catch (IOException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}
 
Example 7
Source File: LmCounterOptionCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public List<CounterOption> decode(ArrayNode json,
        CodecContext context) {
    if (json == null) {
        return null;
    }
    List<CounterOption> moList = new ArrayList<>();
    json.forEach(node -> moList.add(CounterOption.valueOf(node.asText())));
    return moList;
}
 
Example 8
Source File: GitLabSourceConnector.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * Queries the given endpoint, reads the resulting projects, adds all of the projects it finds
 * to the collection of projects, and then returns a URL of the next page of results.
 * @param httpClient
 * @param endpoint
 * @param projects
 * @throws IOException
 * @throws SourceConnectorException
 */
private String addProjects(CloseableHttpClient httpClient, Endpoint endpoint,
        Collection<GitLabProject> projects) throws IOException, SourceConnectorException {
    HttpGet get = new HttpGet(endpoint.toString());
    get.addHeader("Accept", "application/json");
    addSecurity(get);

    try (CloseableHttpResponse response = httpClient.execute(get)) {
        try (InputStream contentStream = response.getEntity().getContent()) {
            JsonNode node = mapper.readTree(contentStream);
            if (node.isArray()) {
                ArrayNode array = (ArrayNode) node;
                array.forEach(obj -> {
                    JsonNode project = (JsonNode) obj;
                    int id = project.get("id").asInt();
                    String name = project.get("name").asText();
                    String path = project.get("path").asText();
                    String fullPath = project.get("path_with_namespace").asText();
                    GitLabProject glp = new GitLabProject();
                    glp.setId(id);
                    glp.setName(name);
                    glp.setPath(path);
                    glp.setFull_path(fullPath);
                    projects.add(glp);
                });
            }
        }
        Header linkHeader = response.getFirstHeader("Link");
        return getNextPage(linkHeader);
    }
}
 
Example 9
Source File: JobSnapshotLoader.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private void readDataTable(String table) {
    ArrayNode jsonTree = (ArrayNode) readJsonTree(table);
    List<Pair<Object, Object>> items = new ArrayList<>();
    jsonTree.forEach(item -> {
        try {
            items.add(Pair.of(item.get("id").textValue(), MAPPER.writeValueAsString(item)));
        } catch (JsonProcessingException e) {
            throw new IllegalStateException(e);
        }
    });
    long written = CassandraUtils.writeIntoTwoColumnTable(session, table, Observable.from(items));
    System.out.println(String.format("Successfully writen %s entries into table %s", written, table));
}
 
Example 10
Source File: YoRCDeserializer.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
private Set<String> getLanguagesFromArrayNode(ArrayNode languagesNode) {
    Set<String> result = new HashSet<>();
    if (languagesNode != null) {
        languagesNode.forEach(e -> result.add(e.asText()));
    }
    return result;
}
 
Example 11
Source File: CollectionConverter.java    From agrest with Apache License 2.0 5 votes vote down vote up
@Override
public T valueNonNull(JsonNode node) {
    if (!node.isArray()) {
        throw new IllegalArgumentException("Node is not an array: " + node.getNodeType().name());
    }

    T container = containerSupplier.get();
    ArrayNode array = (ArrayNode) node;
    array.forEach(child -> container.add(elementConverter.value(child)));
    return container;
}
 
Example 12
Source File: LossMeasurementThresholdCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public List<LossMeasurementThreshold> decode(ArrayNode json, CodecContext context) {
    if (json == null) {
        return null;
    }
    List<LossMeasurementThreshold> thrList = new ArrayList<>();
    json.forEach(node -> thrList.add(decode((ObjectNode) node, context)));
    return thrList;
}
 
Example 13
Source File: FlowTableConfig.java    From onos with Apache License 2.0 5 votes vote down vote up
public Set<FlowRule> flowtable() {
    JsonNode ents = object.path(ENTRIES);
    if (!ents.isArray()) {

        return ImmutableSet.of();
    }
    ArrayNode entries = (ArrayNode) ents;

    Builder<FlowRule> builder = ImmutableSet.builder();
    entries.forEach(entry -> builder.add(decode(entry, FlowRule.class)));
    return builder.build();
}
 
Example 14
Source File: LmThresholdOptionCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public List<ThresholdOption> decode(ArrayNode json,
        CodecContext context) {
    if (json == null) {
        return null;
    }
    List<ThresholdOption> moList = new ArrayList<>();
    json.forEach(node -> moList.add(ThresholdOption.valueOf(node.asText())));
    return moList;
}
 
Example 15
Source File: Swagger2Module.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Consider various remaining aspects.
 * <ul>
 * <li>{@code @Schema(not = ...)}</li>
 * <li>{@code @Schema(allOf = ...)}</li>
 * <li>{@code @Schema(minProperties = ...)}</li>
 * <li>{@code @Schema(maxProperties = ...)}</li>
 * <li>{@code @Schema(requiredProperties = ...)}</li>
 * </ul>
 *
 * @param memberAttributes already collected schema for the field/method
 * @param member targeted field/method
 * @param context generation context
 */
protected void overrideInstanceAttributes(ObjectNode memberAttributes, MemberScope<?, ?> member, SchemaGenerationContext context) {
    Schema annotation = this.getSchemaAnnotationValue(member, Function.identity(), x -> true)
            .orElse(null);
    if (annotation == null) {
        return;
    }
    if (annotation.not() != Void.class) {
        memberAttributes.set("not", context.createDefinitionReference(context.getTypeContext().resolve(annotation.not())));
    }
    if (annotation.allOf().length > 0) {
        Stream.of(annotation.allOf())
                .map(rawType -> context.getTypeContext().resolve(rawType))
                .map(context::createDefinitionReference).forEach(memberAttributes
                .withArray(context.getKeyword(SchemaKeyword.TAG_ALLOF))::add);
    }
    if (annotation.minProperties() > 0) {
        memberAttributes.put("minProperties", annotation.minProperties());
    }
    if (annotation.maxProperties() > 0) {
        memberAttributes.put("maxProperties", annotation.maxProperties());
    }
    if (annotation.requiredProperties().length > 0) {
        Set<String> alreadyMentionedRequiredFields = new HashSet<>();
        ArrayNode requiredFieldNames = memberAttributes
                .withArray(context.getKeyword(SchemaKeyword.TAG_REQUIRED));
        requiredFieldNames
                .forEach(arrayItem -> alreadyMentionedRequiredFields.add(arrayItem.asText()));
        Stream.of(annotation.requiredProperties())
                .filter(field -> !alreadyMentionedRequiredFields.contains(field))
                .forEach(requiredFieldNames::add);
    }
}
 
Example 16
Source File: DmMeasurementOptionCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public List<MeasurementOption> decode(ArrayNode json,
        CodecContext context) {
    if (json == null) {
        return null;
    }
    List<MeasurementOption> moList = new ArrayList<>();
    json.forEach(node -> moList.add(MeasurementOption.valueOf(node.asText())));
    return moList;
}
 
Example 17
Source File: DmnJsonConverter.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
protected void processDRDDecision(DmnDefinition definition, JsonNode decisionServiceChildNode, Map<String, String> decisionEditorJsonMap,
    Map<String, JsonNode> sourceRefMap, Map<String, JsonNode> targetRefMap, List<DmnElementReference> decisionServiceDecissions) {

    ArrayNode decisionsArrayNode = (ArrayNode) decisionServiceChildNode.get(EDITOR_CHILD_SHAPES);
    if (decisionsArrayNode == null || decisionsArrayNode.size() == 0) {
        return;
    }

    decisionsArrayNode.forEach(decisionChildNode -> {
        Decision decision = new Decision();
        decision.setDmnDefinition(definition);
        decision.setId(DmnJsonConverterUtil.getElementId(decisionChildNode));
        decision.setName(DmnJsonConverterUtil.getPropertyValueAsString(PROPERTY_NAME, decisionChildNode));

        JsonNode decisionTableReferenceNode = DmnJsonConverterUtil.getProperty(PROPERTY_DECISION_TABLE_REFERENCE, decisionChildNode);
        if (decisionTableReferenceNode != null && decisionTableReferenceNode.has("key") && !decisionTableReferenceNode.get("key").isNull()) {

            String decisionTableKey = decisionTableReferenceNode.get("key").asText();
            if (decisionEditorJsonMap != null) {
                String decisionTableEditorJson = decisionEditorJsonMap.get(decisionTableKey);
                if (StringUtils.isNotEmpty(decisionTableEditorJson)) {
                    try {
                        JsonNode decisionTableNode = objectMapper.readTree(decisionTableEditorJson);

                        DecisionTable decisionTable = new DecisionTable();
                        decision.setExpression(decisionTable);

                        processDecisionTable(decisionTableNode, decisionTable);
                    } catch (Exception ex) {
                        LOGGER.error("Error while parsing decision table editor JSON: " + decisionTableEditorJson);
                    }
                } else {
                    LOGGER.warn("Could not find decision table for key: " + decisionTableKey);
                }
            }
        }

        if (decisionTableReferenceNode != null && decisionTableReferenceNode.has("name") && !decisionTableReferenceNode.get("name").isNull()) {
            decision.setName(DmnJsonConverterUtil.getValueAsString(PROPERTY_NAME, decisionTableReferenceNode));
        }

        if (targetRefMap.containsKey(decisionChildNode.get("resourceId").asText())) {
            JsonNode informationRequirementNode = targetRefMap.get(decisionChildNode.get("resourceId").asText());

            InformationRequirement informationRequirement = new InformationRequirement();
            informationRequirement.setId(DmnJsonConverterUtil.getElementId(informationRequirementNode));
            informationRequirement.setName(DmnJsonConverterUtil.getPropertyValueAsString(PROPERTY_NAME, informationRequirementNode));

            JsonNode requiredDecisionNode = sourceRefMap.get(DmnJsonConverterUtil.getElementId(informationRequirementNode));

            DmnElementReference requiredDecisionReference = createDmnElementReference(requiredDecisionNode);

            informationRequirement.setRequiredDecision(requiredDecisionReference);
            decision.addRequiredDecision(informationRequirement);
        }

        decisionServiceDecissions.add(createDmnElementReference(decisionChildNode));
        definition.addDecision(decision);
    });
}
 
Example 18
Source File: McastRouteWebResource.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a set of new multicast routes.
 *
 * @param stream multicast routes JSON
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 * @onos.rsModel McastRouteBulk
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("bulk/")
public Response createRoutes(InputStream stream) {
    MulticastRouteService service = get(MulticastRouteService.class);
    try {
        ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
        ArrayNode routesArray = nullIsIllegal((ArrayNode) jsonTree.get(ROUTES),
                ROUTES_KEY_ERROR);
        routesArray.forEach(routeJson -> {
            McastRoute route = codec(McastRoute.class).decode((ObjectNode) routeJson, this);
            service.add(route);

            Set<HostId> sources = new HashSet<>();
            routeJson.path(SOURCES).elements().forEachRemaining(src -> {
                sources.add(HostId.hostId(src.asText()));
            });
            Set<HostId> sinks = new HashSet<>();
            routeJson.path(SINKS).elements().forEachRemaining(sink -> {
                sinks.add(HostId.hostId(sink.asText()));
            });

            if (!sources.isEmpty()) {
                sources.forEach(source -> {
                    service.addSource(route, source);
                });
            }
            if (!sinks.isEmpty()) {
                sinks.forEach(sink -> {
                    service.addSink(route, sink);
                });
            }
        });
    } catch (IOException ex) {
        throw new IllegalArgumentException(ex);
    }

    return Response
            .created(URI.create(""))
            .build();
}
 
Example 19
Source File: RMepCodec.java    From onos with Apache License 2.0 3 votes vote down vote up
/**
 * Decodes the MepId JSON array into a collection of entities.
 *
 * @param json    JSON array to decode
 * @param context decoding context
 * @return collection of decoded MepId
 * @throws java.lang.UnsupportedOperationException if the codec does not
 *                                                 support decode operations
 */
@Override
public List<MepId> decode(ArrayNode json, CodecContext context) {
    List<MepId> rmepList = new ArrayList<>();
    json.forEach(node -> rmepList.add(decode((ObjectNode) node, context)));
    return rmepList;
}
 
Example 20
Source File: VidCodec.java    From onos with Apache License 2.0 3 votes vote down vote up
/**
 * Decodes the VlanId JSON array into a collection of entities.
 *
 * @param json    JSON array to decode
 * @param context decoding context
 * @return collection of decoded VlanId
 * @throws java.lang.UnsupportedOperationException if the codec does not
 *                                                 support decode operations
 */
@Override
public List<VlanId> decode(ArrayNode json, CodecContext context) {
    List<VlanId> vidList = new ArrayList<>();
    json.forEach(node -> vidList.add(decode((ObjectNode) node, context)));
    return vidList;
}