Java Code Examples for com.fasterxml.jackson.databind.JsonNode#forEach()
The following examples show how to use
com.fasterxml.jackson.databind.JsonNode#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: BgpAppConfig.java From onos with Apache License 2.0 | 6 votes |
/** * Returns the set of nodes read from network config. * * @return list of BgpPeerConfig or null */ public List<BgpPeerConfig> bgpPeer() { List<BgpPeerConfig> nodes = new ArrayList<BgpPeerConfig>(); JsonNode jsonNodes = object.get(BGP_PEER); if (jsonNodes == null) { return null; } jsonNodes.forEach(jsonNode -> nodes.add(new BgpPeerConfig( jsonNode.path(PEER_IP).asText(), jsonNode.path(REMOTE_AS).asInt(), jsonNode.path(PEER_HOLD_TIME).asInt(), jsonNode.path(PEER_CONNECT_MODE).asText()))); return nodes; }
Example 2
Source File: SimpleFabricConfig.java From onos with Apache License 2.0 | 6 votes |
/** * Returns all routes in this configuration. * * @return a set of routes. */ public Set<FabricRoute> fabricRoutes() { Set<FabricRoute> routes = Sets.newHashSet(); JsonNode routesNode = object.get(FABRIC_ROUTES); if (routesNode == null) { return routes; } routesNode.forEach(jsonNode -> { try { routes.add(DefaultFabricRoute.builder() .source(FabricRoute.Source.STATIC) .prefix(IpPrefix.valueOf(jsonNode.path(PREFIX).asText())) .nextHop(IpAddress.valueOf(jsonNode.path(NEXT_HOP).asText())) .build()); } catch (IllegalArgumentException e) { log.warn("Fabric router parse error; skip: jsonNode={}", jsonNode); } }); return routes; }
Example 3
Source File: TroubleshootLoadFileCommand.java From onos with Apache License 2.0 | 6 votes |
@Override public void loadEdgePortNib() throws IOException { InputStream stream = new FileInputStream(new File(rootDir + "edge-ports.json")); JsonNode jsonTree = mapper().readTree(stream); Map<DeviceId, Set<ConnectPoint>> edgePorts = new HashMap<>(); // note: the parsing structure depends on EdgePortsListCommand jsonTree.forEach(jsonNode -> { DeviceId deviceId = DeviceId.deviceId(jsonNode.fieldNames().next()); PortNumber portNumber = PortNumber.portNumber( jsonNode.get(deviceId.toString()).asText()); if (!edgePorts.containsKey(deviceId)) { edgePorts.put(deviceId, new HashSet<>()); } edgePorts.get(deviceId).add(new ConnectPoint(deviceId, portNumber)); }); EdgePortNib edgePortNib = EdgePortNib.getInstance(); edgePortNib.setEdgePorts(edgePorts); stream.close(); }
Example 4
Source File: JsonPropertyConverter.java From timbuctoo with GNU General Public License v3.0 | 6 votes |
@Override protected HyperLinksProperty createHyperLinksProperty(String propertyName, JsonNode value) throws IOException { if (value instanceof ArrayNode) { value.forEach(rethrowConsumer(val -> { if (!val.isObject()) { throw new IOException("each item in the array should be an object node"); } else { if (!val.has("url") || !val.get("url").isTextual()) { throw new IOException("each item in the array must have an url property containing a string"); } if (!val.has("label") || !val.get("url").isTextual()) { throw new IOException("each item in the array must have an url property containing a string"); } } })); return new HyperLinksProperty(propertyName, objectMapper.writeValueAsString(value)); } throw new IOException(String.format("'%s' should be an array of hyperlinks.", propertyName)); }
Example 5
Source File: TroubleshootLoadFileCommand.java From onos with Apache License 2.0 | 6 votes |
@Override public void loadMastershipNib() throws IOException { InputStream stream = new FileInputStream(new File(rootDir + "masters.json")); JsonNode jsonTree = mapper().readTree(stream); Map<DeviceId, NodeId> deviceMasterMap = new HashMap<>(); // note: the parsing structure depends on MastersListCommand jsonTree.forEach(jsonNode -> { ArrayNode devicesNode = ((ArrayNode) jsonNode.get("devices")); devicesNode.forEach(deviceNode -> { // a device is connected to only one master node at a time deviceMasterMap.put( DeviceId.deviceId(deviceNode.asText()), NodeId.nodeId(jsonNode.get("id").asText())); }); }); MastershipNib mastershipNib = MastershipNib.getInstance(); mastershipNib.setDeviceMasterMap(deviceMasterMap); stream.close(); }
Example 6
Source File: HyperlinksConverter.java From timbuctoo with GNU General Public License v3.0 | 6 votes |
private void throwIfInvalid(JsonNode json) throws IOException { if (json instanceof ArrayNode) { json.forEach(rethrowConsumer(val -> { if (!val.isObject()) { throw new IOException("each item in the array should be an object node"); } else { if (!val.has("url") || !val.get("url").isTextual()) { throw new IOException("each item in the array must have an url property containing a string"); } if (!val.has("label") || !val.get("url").isTextual()) { throw new IOException("each item in the array must have an url property containing a string"); } } })); } else { throw new IOException("should be an array."); } }
Example 7
Source File: ReactiveRoutingConfig.java From onos with Apache License 2.0 | 6 votes |
/** * Gets the set of configured local IPv4 prefixes. * * @return IPv4 prefixes */ public Set<LocalIpPrefixEntry> localIp4PrefixEntries() { Set<LocalIpPrefixEntry> prefixes = Sets.newHashSet(); JsonNode prefixesNode = object.get(IP4LOCALPREFIXES); if (prefixesNode == null) { log.warn("ip4LocalPrefixes is null!"); return prefixes; } prefixesNode.forEach(jsonNode -> { prefixes.add(new LocalIpPrefixEntry( IpPrefix.valueOf(jsonNode.get(IPPREFIX).asText()), LocalIpPrefixEntry.IpPrefixType.valueOf(jsonNode.get(TYPE).asText()), IpAddress.valueOf(jsonNode.get(GATEWAYIP).asText()))); }); return prefixes; }
Example 8
Source File: GroundUtils.java From ground with Apache License 2.0 | 5 votes |
public static List<Long> getListFromJson(JsonNode jsonNode, String fieldName) { List<Long> parents = new ArrayList<>(); JsonNode listNode = jsonNode.get(fieldName); if (listNode != null) { listNode.forEach(node -> parents.add(node.asLong())); } return parents; }
Example 9
Source File: FlowsWebResource.java From onos with Apache License 2.0 | 5 votes |
/** * Removes a batch of flow rules. * * @param stream stream for posted JSON * @return 204 NO CONTENT */ @DELETE public Response deleteFlows(InputStream stream) { FlowRuleService service = get(FlowRuleService.class); ListMultimap<DeviceId, Long> deviceMap = ArrayListMultimap.create(); List<FlowEntry> rulesToRemove = new ArrayList<>(); try { ObjectNode jsonTree = readTreeFromStream(mapper(), stream); JsonNode jsonFlows = jsonTree.get("flows"); jsonFlows.forEach(node -> { DeviceId deviceId = DeviceId.deviceId( nullIsNotFound(node.get(DEVICE_ID), DEVICE_NOT_FOUND).asText()); long flowId = nullIsNotFound(node.get(FLOW_ID), FLOW_NOT_FOUND).asLong(); deviceMap.put(deviceId, flowId); }); } catch (IOException ex) { throw new IllegalArgumentException(ex); } deviceMap.keySet().forEach(deviceId -> { List<Long> flowIds = deviceMap.get(deviceId); Iterable<FlowEntry> entries = service.getFlowEntries(deviceId); flowIds.forEach(flowId -> { StreamSupport.stream(entries.spliterator(), false) .filter(entry -> flowId == entry.id().value()) .forEach(rulesToRemove::add); }); }); service.removeFlowRules(rulesToRemove.toArray(new FlowEntry[0])); return Response.noContent().build(); }
Example 10
Source File: ThriftDocServiceTest.java From armeria with Apache License 2.0 | 5 votes |
private static void removeDocStrings(JsonNode json) { if (json.isObject()) { ((ObjectNode) json).remove("docString"); } if (json.isObject() || json.isArray()) { json.forEach(ThriftDocServiceTest::removeDocStrings); } }
Example 11
Source File: GrpcDocServiceTest.java From armeria with Apache License 2.0 | 5 votes |
private static void removeDocStrings(JsonNode json) { if (json.isObject()) { ((ObjectNode) json).remove("docString"); } if (json.isObject() || json.isArray()) { json.forEach(GrpcDocServiceTest::removeDocStrings); } }
Example 12
Source File: DeviceDescriptionDiscoveryCiscoImpl.java From onos with Apache License 2.0 | 5 votes |
private List<String> prepareModuleAnnotation(JsonNode modules, JsonNode macs) { List<String> modulesInfo = new ArrayList<>(); if (modules.getNodeType() == JsonNodeType.ARRAY) { modules.forEach(module -> modulesInfo.add(getModuleInfo(module, macs))); } else if (modules.getNodeType() == JsonNodeType.OBJECT) { modulesInfo.add(getModuleInfo(modules, macs)); } return modulesInfo; }
Example 13
Source File: ErrorProcessor.java From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 | 5 votes |
protected String rewriteRequiredProperties(JsonNode error) { JsonNode missing = error.get("missing"); final StringJoiner missingStringJoiner = new StringJoiner(", "); missing.forEach(it -> missingStringJoiner.add(it.toString())); return String.format(Messages.error_missing_property, missingStringJoiner.toString()); }
Example 14
Source File: PostgresNodeVersionDao.java From ground with Apache License 2.0 | 5 votes |
@Override public List<Long> retrieveAdjacentLineageEdgeVersion(long startId) throws GroundException { String sql = String.format(SqlConstants.SELECT_NODE_VERSION_ADJACENT_LINEAGE, startId); JsonNode json = Json.parse(PostgresUtils.executeQueryToJson(this.dbSource, sql)); List<Long> result = new ArrayList<>(); json.forEach(x -> result.add(x.get("id").asLong())); return result; }
Example 15
Source File: GuildSettings.java From SkyBot with GNU Affero General Public License v3.0 | 5 votes |
@JsonProperty("blacklisted_words") public GuildSettings setBlackListedWords(JsonNode blacklistedWords) { if (!blacklistedWords.isArray()) { throw new IllegalArgumentException("Not an array"); } blacklistedWords.forEach( (json) -> this.blacklistedWords.add(json.get("word").asText()) ); return this; }
Example 16
Source File: ArmeriaCentralDogma.java From centraldogma with Apache License 2.0 | 5 votes |
private static List<Change<?>> getPreviewDiffs(AggregatedHttpResponse res) { switch (res.status().code()) { case 200: final JsonNode node = toJson(res, JsonNodeType.ARRAY); final ImmutableList.Builder<Change<?>> builder = ImmutableList.builder(); node.forEach(e -> builder.add(toChange(e))); return builder.build(); case 204: return ImmutableList.of(); } return handleErrorResponse(res); }
Example 17
Source File: TroubleshootLoadFileCommand.java From onos with Apache License 2.0 | 5 votes |
@Override public void loadFlowNib() throws IOException { InputStream stream = new FileInputStream(new File(rootDir + "flows.json")); JsonNode jsonTree = mapper().readTree(stream); Set<FlowEntry> flows = new HashSet<>(); List<ObjectNode> flowNodeList = new ArrayList<>(); jsonTree.forEach(jsonNode -> { ArrayNode flowArrayNode = (ArrayNode) jsonNode.get("flows"); Lists.newArrayList(flowArrayNode.iterator()) .forEach(flowNode -> flowNodeList.add((ObjectNode) flowNode)); }); // TODO: future plan for the new APIs of the flow rule service that returns raw flows or normalized flows flowNodeList.forEach(flowNode -> { FlowEntry flow; try { flow = codec(FlowEntry.class).decode(flowNode, this); } catch (IllegalArgumentException e) { log.warn("T3 in offline mode ignores reading extension fields of this flow to avoid decoding error"); ObjectNode extensionRemoved = removeExtension(flowNode); flow = codec(FlowEntry.class).decode(extensionRemoved, this); } flows.add(flow); }); FlowNib flowNib = FlowNib.getInstance(); flowNib.setFlows(flows); stream.close(); }
Example 18
Source File: SpecificationOptimizer.java From syndesis with Apache License 2.0 | 4 votes |
/** * Removes all properties from the given Swagger document that are not used * by the REST Swagger Camel component in order to minimize the amount of * data stored in the configured properties. */ public static String minimizeForComponent(final OasDocument openApiDoc) { final ObjectNode json = (ObjectNode) Library.writeNode(openApiDoc); json.remove(Arrays.asList("info", "tags", "definitions", "responses", "externalDocs")); final JsonNode components = json.get("components"); if (components != null) { ((ObjectNode)components).remove(Arrays.asList("schemas", "responses", "requestBodies", "examples", "headers", "links", "callbacks")); } final JsonNode paths = json.get("paths"); if (paths != null) { paths.forEach(path -> { JsonNode globalParameters = ((ObjectNode)path).remove("parameters"); final List<JsonNode> globalParametersList = new ArrayList<>(); if (globalParameters != null) { collectPathOrQueryParameters(globalParameters, globalParametersList); ((ArrayNode) globalParameters).removeAll(); ((ArrayNode) globalParameters).addAll(globalParametersList); } StreamSupport.stream(path.spliterator(), false) .filter(JsonNode::isObject) .forEach(operation -> { final ObjectNode operationNode = (ObjectNode) operation; operationNode.remove(Arrays.asList("tags", "summary", "description", "externalDocs", "callbacks", "servers")); final ArrayNode parameters = (ArrayNode) operation.get("parameters"); if (parameters != null && parameters.size() > 0) { final List<JsonNode> parametersList = StreamSupport.stream(parameters.spliterator(), false).collect(Collectors.toList()); for (final ListIterator<JsonNode> i = parametersList.listIterator(); i.hasNext();) { final ObjectNode param = (ObjectNode) i.next(); param.remove(Arrays.asList("description", "type", "required", "format")); if (!isPathOrQueryParameter(param)) { i.remove(); } } if (globalParametersList.isEmpty() && parametersList.isEmpty()) { operationNode.remove("parameters"); } else { parameters.removeAll(); parameters.addAll(parametersList); parameters.addAll(globalParametersList); } } else if (!globalParametersList.isEmpty()) { operationNode.set("parameters", globalParameters); } operationNode.remove(Arrays.asList("requestBody", "responses")); }); }); } try { return JsonUtils.writer().writeValueAsString(json); } catch (final JsonProcessingException e) { throw new IllegalStateException("Unable to serialize minified OpenAPI document", e); } }
Example 19
Source File: RegionJsonMatcher.java From onos with Apache License 2.0 | 4 votes |
private Set<NodeId> jsonToSet(JsonNode nodes) { final Set<NodeId> nodeIds = Sets.newHashSet(); nodes.forEach(node -> nodeIds.add(NodeId.nodeId(node.asText()))); return nodeIds; }
Example 20
Source File: SchemaCleanUpUtils.java From jsonschema-generator with Apache License 2.0 | 4 votes |
/** * Check whether the given schema node and its {@link SchemaKeyword#TAG_ALLOF} elements (if there are any) are distinct. If yes, remove the * {@link SchemaKeyword#TAG_ALLOF} node and merge all its elements with the given schema node instead. * <br> * This makes for more readable schemas being generated but has the side-effect that manually added {@link SchemaKeyword#TAG_ALLOF} (e.g. from a * custom definition or attribute overrides) may be removed as well if it isn't strictly speaking necessary. * * @param schemaNode single node representing a sub-schema to consolidate contained {@link SchemaKeyword#TAG_ALLOF} for (if present) * @param allOfTagName name of the {@link SchemaKeyword#TAG_ALLOF} in the designated JSON Schema version */ private void mergeAllOfPartsIfPossible(JsonNode schemaNode, String allOfTagName) { if (!(schemaNode instanceof ObjectNode)) { return; } JsonNode allOfTag = schemaNode.get(allOfTagName); if (!(allOfTag instanceof ArrayNode)) { return; } allOfTag.forEach(part -> this.mergeAllOfPartsIfPossible(part, allOfTagName)); List<JsonNode> allOfElements = new ArrayList<>(); allOfTag.forEach(allOfElements::add); if (allOfElements.stream().anyMatch(part -> !(part instanceof ObjectNode) && !part.asBoolean())) { return; } List<ObjectNode> parts = allOfElements.stream() .filter(part -> part instanceof ObjectNode) .map(part -> (ObjectNode) part) .collect(Collectors.toList()); // collect all defined attributes from the separate parts and check whether there are incompatible differences Map<String, List<JsonNode>> fieldsFromAllParts = Stream.concat(Stream.of(schemaNode), parts.stream()) .flatMap(part -> StreamSupport.stream(((Iterable<Map.Entry<String, JsonNode>>) () -> part.fields()).spliterator(), false)) .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList()))); if ((this.config.getSchemaVersion() == SchemaVersion.DRAFT_6 || this.config.getSchemaVersion() == SchemaVersion.DRAFT_7) && fieldsFromAllParts.containsKey(this.config.getKeyword(SchemaKeyword.TAG_REF))) { // in Draft 7, any other attributes besides the $ref keyword were ignored return; } String ifTagName = this.config.getKeyword(SchemaKeyword.TAG_IF); for (Map.Entry<String, List<JsonNode>> fieldEntries : fieldsFromAllParts.entrySet()) { if (fieldEntries.getValue().size() == 1) { // no conflicts, no further checks continue; } if (ifTagName.equals(fieldEntries.getKey())) { // "if"/"then"/"else" tags should remain isolated in their sub-schemas return; } int offset; if (!allOfTagName.equals(fieldEntries.getKey())) { offset = 0; } else if (fieldEntries.getValue().size() == 2) { // we can ignore the "allOf" tag in the target node (the one we are trying to remove here) continue; } else { offset = 1; } if (!fieldEntries.getValue().stream().skip(offset + 1).allMatch(fieldEntries.getValue().get(offset)::equals)) { // different values for the same tag: be conservative for now and not merge anything // later, we may want to decide based on the tag how to merge them (e.g. take the highest "minLength" and the lowest "maximum") return; } } // all attributes are either distinct or have equal values in all occurrences ObjectNode schemaObjectNode = (ObjectNode) schemaNode; schemaObjectNode.remove(allOfTagName); parts.forEach(schemaObjectNode::setAll); }