Java Code Examples for com.fasterxml.jackson.databind.JsonNode#elements()
The following examples show how to use
com.fasterxml.jackson.databind.JsonNode#elements() .
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: Service.java From hypergraphql with Apache License 2.0 | 6 votes |
private void getQueryPathsRecursive(JsonNode query, Set<LinkedList<QueryNode>> paths, LinkedList<QueryNode> path, HGQLSchema schema) { Model model = ModelFactory.createDefaultModel(); if (path == null) { path = new LinkedList<>(); } else { paths.remove(path); } if (query.isArray()) { Iterator<JsonNode> iterator = query.elements(); while (iterator.hasNext()) { JsonNode currentNode = iterator.next(); getFieldPath(paths, path, schema, model, currentNode); } } else { getFieldPath(paths, path, schema, model, query); } }
Example 2
Source File: JsonUtils.java From aws-xray-sdk-java with Apache License 2.0 | 6 votes |
/** * Finds all immediate children entries mapped to a given field name in a JSON object. * @param rootNode - The node to search for entries. Must be an array node. * @param fieldName - The name of the key to search for in rootNode's children. * @return A list of values that were mapped to the given field name. */ public static List<String> getMatchingListFromJsonArrayNode(JsonNode rootNode, String fieldName) { List<String> retList = new ArrayList<>(); Iterator<JsonNode> ite = rootNode.elements(); if (ite == null || !ite.hasNext()) { return retList; } ite.forEachRemaining(field -> { JsonNode stringNode = field.get(fieldName); // Check if fieldName is present and a valid string if (stringNode != null && !stringNode.textValue().isEmpty()) { retList.add(stringNode.textValue()); } }); return retList; }
Example 3
Source File: ConfigUtilsTopLevelTests.java From vscode-as3mxml with Apache License 2.0 | 6 votes |
@Test void testFilesWithBaseOnly() throws IOException { String baseValue = "src/Base.as"; ObjectMapper mapper = new ObjectMapper(); JsonNode baseConfigData = mapper.readTree( "{" + "\"files\": [\"" + baseValue + "\"]" + "}" ); JsonNode configData = mapper.readTree("{}"); JsonNode result = ConfigUtils.mergeConfigs(configData, baseConfigData); Assertions.assertTrue(result.has(TopLevelFields.FILES)); JsonNode resultValue = result.get(TopLevelFields.FILES); Assertions.assertTrue(resultValue.isArray()); Iterator<JsonNode> elements = resultValue.elements(); Assertions.assertTrue(elements.hasNext()); String resultValue0 = elements.next().asText(); Assertions.assertEquals(baseValue, resultValue0); Assertions.assertFalse(elements.hasNext()); }
Example 4
Source File: BatchGetRowResponseUnmarshaller.java From bce-sdk-java with Apache License 2.0 | 6 votes |
/** * Unmarshal the result of response from TableStorage. * * @param in The input stream of content to be unmarshalled. * @return The batch get row response object. * @throws Exception */ @Override public BatchGetRowResponse unmarshall(InputStream in) throws Exception { String streamContents = Unmarshallers.readStreamContents(in); JsonNode root = JsonUtils.jsonNodeOf(streamContents); if (!root.isObject()) { throw new BceClientException("The input json object:" + root.toString() + " is not an object."); } JsonNode resultsNode = root.get(TableStorageConstants.JSON_RESULT); List<TableStorageResult> results = new ArrayList<TableStorageResult>(); if (resultsNode != null) { Iterator<JsonNode> resultList = resultsNode.elements(); TableStorageResultUnmarshaller unmarshaller = new TableStorageResultUnmarshaller(); while (resultList.hasNext()) { JsonNode resultNode = resultList.next(); TableStorageResult result = unmarshaller.unmarshall(resultNode); results.add(result); } } result.setResults(results); return result; }
Example 5
Source File: RestRequestTandemUseSpringRest.java From activiti-in-action-codes with Apache License 2.0 | 6 votes |
/** * 删除已经部署的请假流程 * * @return * @throws java.io.IOException */ private static void deleteLeaveDeployment() throws IOException { WebClient client = createClient("repository/deployments"); Response response = client.get(); printResult("查询leave.bpmn", response); response = client.get(); InputStream stream = (InputStream) response.getEntity(); JsonNode responseNode = objectMapper.readTree(stream); Iterator<JsonNode> elements = responseNode.elements(); JsonNode next = elements.next(); ArrayNode arrayNode = (ArrayNode) next; for (JsonNode jsonNode : arrayNode) { String deploymentId = jsonNode.get("id").asText(); if (StringUtils.isBlank(deploymentId)) { continue; } String url = "/repository/deployments/" + deploymentId + "?cascade=true"; client = createClient(url); response = client.delete(); printResult("删除deployment", response); } }
Example 6
Source File: CommandLineToolParser.java From cwlexec with Apache License 2.0 | 6 votes |
private static List<CommandLineBinding> toArguments(JsonNode argumentsNode) throws CWLException { List<CommandLineBinding> arguments = null; if (argumentsNode != null) { arguments = new ArrayList<>(); if (argumentsNode.isArray()) { Iterator<JsonNode> elements = argumentsNode.elements(); while (elements.hasNext()) { JsonNode element = elements.next(); if (element.isTextual()) { arguments.add(toArgument(element)); } else if (element.isObject()) { arguments.add(processCommandLineBinding(null, element)); } else { throw new CWLException( ResourceLoader.getMessage("cwl.parser.invalid.array.type", ARGUMENTS), 251); } } } else { throw new CWLException(ResourceLoader.getMessage(CWL_PARSER_INVALID_TYPE, ARGUMENTS, "array"), 251); } } return arguments; }
Example 7
Source File: ListKeyRangesResponseUnmarshaller.java From bce-sdk-java with Apache License 2.0 | 6 votes |
/** * Unmarshal the result of response from TableStorage. * * @param in The input stream of content to be unmarshalled. * @return The list tables response object. * @throws Exception */ @Override public ListKeyRangesResponse unmarshall(InputStream in) throws Exception { String streamContents = Unmarshallers.readStreamContents(in); JsonNode root = JsonUtils.jsonNodeOf(streamContents); if (!root.isObject()) { throw new BceClientException("The input json object:" + root.toString() + " is not an object."); } JsonNode keyRangesObj = root.get(TableStorageConstants.JSON_KEY_RANGES); List<Pair<String, String>> keyRanges = new ArrayList<Pair<String, String>>(); if (keyRangesObj != null) { Iterator<JsonNode> keyRangeList = keyRangesObj.elements(); while (keyRangeList.hasNext()) { JsonNode table = keyRangeList.next(); String startKey = table.get(TableStorageConstants.JSON_START_KEY).asText(); String stopKey = table.get(TableStorageConstants.JSON_END_KEY).asText(); keyRanges.add(new ImmutablePair<String, String>(startKey, stopKey)); } } result.setKeyRanges(keyRanges); return result; }
Example 8
Source File: TableStorageResultUnmarshaller.java From bce-sdk-java with Apache License 2.0 | 6 votes |
/** * Unmarshal the result of JsonNode * * @param resultNode result JsonNode which can be unmarshalled to TableStorageResult object. * @return The TableStorageResult object unmarshalled from resultNode. * @throws Exception */ @Override public TableStorageResult unmarshall(JsonNode resultNode) throws Exception { String rowkey = resultNode.get(TableStorageConstants.JSON_ROWKEY).asText(); JsonNode cellsNode = resultNode.get(TableStorageConstants.JSON_CELLS); List<TableStorageCell> cells = new ArrayList<TableStorageCell>(); if (cells != null) { Iterator<JsonNode> cellList = cellsNode.elements(); while (cellList.hasNext()) { JsonNode cellNode = cellList.next(); String column = cellNode.get(TableStorageConstants.JSON_COLUMN).asText(); String value = cellNode.get(TableStorageConstants.JSON_VALUE).asText(); String decodeValue = URLDecoder.decode(value, TableStorageConstants.DEFAULT_ENCODING); int timestamp = 0; if (cellNode.has(TableStorageConstants.JSON_TIMESTAMP)) { timestamp = cellNode.get(TableStorageConstants.JSON_TIMESTAMP).asInt(); } TableStorageCell cell = new TableStorageCell(CellType.ResultCell, column, decodeValue, timestamp); cells.add(cell); } } String decodeRowkey = URLDecoder.decode(rowkey, TableStorageConstants.DEFAULT_ENCODING); return new TableStorageResult(decodeRowkey, cells); }
Example 9
Source File: InputSettingsParser.java From cwlexec with Apache License 2.0 | 5 votes |
private static List<CWLFile> processCWLFileArrayField(String parentPath, String key, JsonNode arrayNode) throws CWLException { List<CWLFile> array = new ArrayList<>(); Iterator<JsonNode> elements = arrayNode.elements(); while (elements.hasNext()) { JsonNode element = elements.next(); array.add(processCWLFile(parentPath, key, element, true)); } return array; }
Example 10
Source File: HGraphQLConverter.java From hypergraphql with Apache License 2.0 | 5 votes |
private String getSubQuery(JsonNode fieldsJson, String parentType) { Set<String> subQueryStrings = new HashSet<>(); if (schema.getTypes().containsKey(parentType)) { subQueryStrings.add("_id"); subQueryStrings.add("_type"); } if (fieldsJson==null || fieldsJson.isNull()) { if (subQueryStrings.isEmpty()) { return ""; } else { return querySTR(String.join(" ", subQueryStrings)); } } else { Iterator<JsonNode> fields = fieldsJson.elements(); fields.forEachRemaining(field -> { ArrayNode fieldsArray = (field.get("fields").isNull()) ? null : (ArrayNode) field.get("fields"); String arg = (field.get("args").isNull()) ? "" : langSTR((ObjectNode) field.get("args")); String fieldString = field.get("name").asText() + arg + " " + getSubQuery(fieldsArray, field.get("targetName").asText()); subQueryStrings.add(fieldString); }); } if (!subQueryStrings.isEmpty()) { return querySTR(String.join(" ", subQueryStrings)); } else { return ""; } }
Example 11
Source File: TestSparqlQueryManager.java From java-client-api with Apache License 2.0 | 5 votes |
@Test public void testDefaultExecuteSelectQuery() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException { System.out.println("In SPARQL Query Manager Test testDefaultExecuteSelectQuery method"); SPARQLQueryManager sparqlQmgr = readclient.newSPARQLQueryManager(); StringBuffer sparqlQuery = new StringBuffer().append("select ?name ?lives ?city from <http://marklogic.com/semantics#default-graph>{ ?name ?lives ?city } ORDER BY ?name"); SPARQLQueryDefinition qdef = sparqlQmgr.newQueryDefinition(sparqlQuery.toString()); JsonNode jsonResults = sparqlQmgr.executeSelect(qdef, new JacksonHandle()).get(); JsonNode jsonBindingsNodes = jsonResults.path("results").path("bindings"); // Should have 3 nodes returned. assertEquals("Three results not returned from testDefaultExecuteSelectQuery method ", 3, jsonBindingsNodes.size()); Iterator<JsonNode> nameNodesItr = jsonBindingsNodes.elements(); JsonNode jsonNameNode = null; if (nameNodesItr.hasNext()) { jsonNameNode = nameNodesItr.next(); // Verify result 1 values. assertEquals("Element 1 name value incorrect", "http://example.org/ml/people/Jack_Smith", jsonNameNode.path("name").path("value").asText()); assertEquals("Element 1 lives is incorrect", "livesIn", jsonNameNode.path("lives").path("value").asText()); assertEquals("Element 1 city is incorrect", "Glasgow", jsonNameNode.path("city").path("value").asText()); } if (nameNodesItr.hasNext()) { // Verify result 2 values. jsonNameNode = nameNodesItr.next(); assertEquals("Element 2 name value incorrect", "http://example.org/ml/people/Jane_Smith", jsonNameNode.path("name").path("value").asText()); assertEquals("Element 2 lives is incorrect", "livesIn", jsonNameNode.path("lives").path("value").asText()); assertEquals("Element 2 city is incorrect", "London", jsonNameNode.path("city").path("value").asText()); } if (nameNodesItr.hasNext()) { // Verify result 3 values. jsonNameNode = nameNodesItr.next(); assertEquals("Element 3 name value incorrect", "http://example.org/ml/people/John_Smith", jsonNameNode.path("name").path("value").asText()); assertEquals("Element 3 lives is incorrect", "livesIn", jsonNameNode.path("lives").path("value").asText()); assertEquals("Element 3 city is incorrect", "London", jsonNameNode.path("city").path("value").asText()); } }
Example 12
Source File: BaseParser.java From cwlexec with Apache License 2.0 | 5 votes |
protected static List<Object> processAnyArrayField(JsonNode arrayNode) { List<Object> array = new ArrayList<>(); Iterator<JsonNode> elements = arrayNode.elements(); while (elements.hasNext()) { array.add(processAnyFiled(elements.next())); } return array; }
Example 13
Source File: JsonFrameworkDeserializer.java From zeno with Apache License 2.0 | 5 votes |
private <T> void deserializeCollection(JsonNode nodes, NFTypeSerializer<T> itemSerializer, Collection<T> elements) { try { for (Iterator<JsonNode> it = nodes.elements(); it.hasNext();) { JsonNode node = it.next(); T element = itemSerializer.deserialize(new JsonReadGenericRecord(itemSerializer.getFastBlobSchema(), node)); elements.add(element); } } catch (Exception ex) { throw new RuntimeException(ex); } }
Example 14
Source File: ServiceNowMetaDataExtension.java From syndesis with Apache License 2.0 | 5 votes |
private static void processResult(JsonNode node, Consumer<JsonNode> consumer) { if (node.isArray()) { Iterator<JsonNode> it = node.elements(); while (it.hasNext()) { consumer.accept(it.next()); } } else { consumer.accept(node); } }
Example 15
Source File: JsonFrameworkDeserializer.java From zeno with Apache License 2.0 | 5 votes |
private <K, V, M extends Map<K, V>> M deserializeIntoMap(JsonReadGenericRecord rec, String fieldName, NFTypeSerializer<K> keySerializer, NFTypeSerializer<V> valueSerializer, M map) { JsonNode node = getJsonNode(rec, fieldName); if (node == null) { return null; } for (Iterator<JsonNode> it = node.elements(); it.hasNext();) { JsonNode element = it.next(); K key = keySerializer.deserialize(new JsonReadGenericRecord(keySerializer.getFastBlobSchema(), element.get("key"))); V value = valueSerializer.deserialize(new JsonReadGenericRecord(valueSerializer.getFastBlobSchema(), element.get("value"))); map.put(key, value); } return map; }
Example 16
Source File: VariantReferenceReplacementUtils.java From commercetools-sync-java with Apache License 2.0 | 5 votes |
static boolean isProductReferenceSet(@Nonnull final Attribute attribute) { final JsonNode valueAsJsonNode = attribute.getValueAsJsonNode(); if (valueAsJsonNode instanceof ArrayNode) { final Iterator<JsonNode> setIterator = valueAsJsonNode.elements(); if (setIterator.hasNext()) { return isValueAProductReference(setIterator.next()); } } return false; }
Example 17
Source File: LinkDiscoveryCiscoImpl.java From onos with Apache License 2.0 | 4 votes |
@Override public Set<LinkDescription> getLinks() { String response = retrieveResponse(SHOW_LLDP_NEIGHBOR_DETAIL_CMD); DeviceId localDeviceId = this.handler().data().deviceId(); DeviceService deviceService = this.handler().get(DeviceService.class); Set<LinkDescription> linkDescriptions = Sets.newHashSet(); List<Port> ports = deviceService.getPorts(localDeviceId); if (ports.size() == 0 || Objects.isNull(response)) { return linkDescriptions; } try { ObjectMapper om = new ObjectMapper(); JsonNode json = om.readTree(response); if (json == null) { return linkDescriptions; } JsonNode res = json.at("/" + JSON_RESULT); if (res.isMissingNode()) { return linkDescriptions; } JsonNode lldpNeighborsRow = res.at("/" + TABLE_NBOR_DETAIL); if (lldpNeighborsRow.isMissingNode()) { return linkDescriptions; } JsonNode lldpNeighbors = lldpNeighborsRow.at("/" + ROW_NBOR_DETAIL); if (lldpNeighbors.isMissingNode()) { return linkDescriptions; } Iterator<JsonNode> iterator = lldpNeighbors.elements(); while (iterator.hasNext()) { JsonNode neighbors = iterator.next(); String remoteChassisId = neighbors.get(CHASSIS_ID).asText(); String remotePortName = neighbors.get(PORT_ID).asText(); String remotePortDesc = neighbors.get(PORT_DESC).asText(); String lldpLocalPort = neighbors.get(LOCAL_PORT_ID).asText() .replaceAll("(Eth.{0,5})(.\\d{0,5}/\\d{0,5})", "Ethernet$2"); Port localPort = findLocalPortByName(ports, lldpLocalPort); if (localPort == null) { log.warn("local port not found. LldpLocalPort value: {}", lldpLocalPort); continue; } Device remoteDevice = findRemoteDeviceByChassisId(deviceService, remoteChassisId); Port remotePort = findDestinationPortByName(remotePortName, remotePortDesc, deviceService, remoteDevice); if (!localPort.isEnabled() || !remotePort.isEnabled()) { log.debug("Ports are disabled. Cannot create a link between {}/{} and {}/{}", localDeviceId, localPort, remoteDevice.id(), remotePort); continue; } linkDescriptions.addAll(buildLinkPair(localDeviceId, localPort, remoteDevice.id(), remotePort)); } } catch (IOException e) { log.error("Failed to get links ", e); } log.debug("Returning linkDescriptions: {}", linkDescriptions); return linkDescriptions; }
Example 18
Source File: TableMetadataParser.java From iceberg with Apache License 2.0 | 4 votes |
static TableMetadata fromJson(TableOperations ops, InputFile file, JsonNode node) { Preconditions.checkArgument(node.isObject(), "Cannot parse metadata from a non-object: %s", node); int formatVersion = JsonUtil.getInt(FORMAT_VERSION, node); Preconditions.checkArgument(formatVersion == TableMetadata.TABLE_FORMAT_VERSION, "Cannot read unsupported version %d", formatVersion); String location = JsonUtil.getString(LOCATION, node); int lastAssignedColumnId = JsonUtil.getInt(LAST_COLUMN_ID, node); Schema schema = SchemaParser.fromJson(node.get(SCHEMA)); JsonNode specArray = node.get(PARTITION_SPECS); List<PartitionSpec> specs; int defaultSpecId; if (specArray != null) { Preconditions.checkArgument(specArray.isArray(), "Cannot parse partition specs from non-array: %s", specArray); // default spec ID is required when the spec array is present defaultSpecId = JsonUtil.getInt(DEFAULT_SPEC_ID, node); // parse the spec array ImmutableList.Builder<PartitionSpec> builder = ImmutableList.builder(); for (JsonNode spec : specArray) { builder.add(PartitionSpecParser.fromJson(schema, spec)); } specs = builder.build(); } else { // partition spec is required for older readers, but is always set to the default if the spec // array is set. it is only used to default the spec map is missing, indicating that the // table metadata was written by an older writer. defaultSpecId = TableMetadata.INITIAL_SPEC_ID; specs = ImmutableList.of(PartitionSpecParser.fromJsonFields( schema, TableMetadata.INITIAL_SPEC_ID, node.get(PARTITION_SPEC))); } Map<String, String> properties = JsonUtil.getStringMap(PROPERTIES, node); long currentVersionId = JsonUtil.getLong(CURRENT_SNAPSHOT_ID, node); long lastUpdatedMillis = JsonUtil.getLong(LAST_UPDATED_MILLIS, node); JsonNode snapshotArray = node.get(SNAPSHOTS); Preconditions.checkArgument(snapshotArray.isArray(), "Cannot parse snapshots from non-array: %s", snapshotArray); List<Snapshot> snapshots = Lists.newArrayListWithExpectedSize(snapshotArray.size()); Iterator<JsonNode> iterator = snapshotArray.elements(); while (iterator.hasNext()) { snapshots.add(SnapshotParser.fromJson(ops, iterator.next())); } SortedSet<SnapshotLogEntry> entries = Sets.newTreeSet(Comparator.comparingLong(SnapshotLogEntry::timestampMillis)); if (node.has(SNAPSHOT_LOG)) { Iterator<JsonNode> logIterator = node.get(SNAPSHOT_LOG).elements(); while (logIterator.hasNext()) { JsonNode entryNode = logIterator.next(); entries.add(new SnapshotLogEntry( JsonUtil.getLong(TIMESTAMP_MS, entryNode), JsonUtil.getLong(SNAPSHOT_ID, entryNode))); } } return new TableMetadata(ops, file, location, lastUpdatedMillis, lastAssignedColumnId, schema, defaultSpecId, specs, properties, currentVersionId, snapshots, ImmutableList.copyOf(entries.iterator())); }
Example 19
Source File: ConfigUtilsAirOptionsTests.java From vscode-as3mxml with Apache License 2.0 | 4 votes |
@Test void testFilesMergeDuplicate() throws IOException { String baseFile = "assets/base.png"; String newFile = "assets/new.png"; String duplicatePath = "duplicate.png"; ObjectMapper mapper = new ObjectMapper(); JsonNode baseConfigData = mapper.readTree( "{" + "\"airOptions\": {" + "\"files\": [" + "{" + "\"file\": \"" + baseFile + "\"," + "\"path\": \"" + duplicatePath + "\"" + "}" + "]" + "}" + "}" ); JsonNode configData = mapper.readTree( "{" + "\"airOptions\": {" + "\"files\": [" + "{" + "\"file\": \"" + newFile + "\"," + "\"path\": \"" + duplicatePath + "\"" + "}" + "]" + "}" + "}" ); JsonNode result = ConfigUtils.mergeConfigs(configData, baseConfigData); Assertions.assertTrue(result.has(TopLevelFields.AIR_OPTIONS)); JsonNode airOptions = result.get(TopLevelFields.AIR_OPTIONS); Assertions.assertTrue(airOptions.isObject()); Assertions.assertTrue(airOptions.has(AIROptions.FILES)); JsonNode resultValue = airOptions.get(AIROptions.FILES); Assertions.assertTrue(resultValue.isArray()); Iterator<JsonNode> elements = resultValue.elements(); Assertions.assertTrue(elements.hasNext()); JsonNode resultValue0 = elements.next(); Assertions.assertTrue(resultValue0.has(AIROptions.FILES__FILE)); Assertions.assertTrue(resultValue0.has(AIROptions.FILES__PATH)); String result0File = resultValue0.get(AIROptions.FILES__FILE).asText(); String result0Path = resultValue0.get(AIROptions.FILES__PATH).asText(); Assertions.assertEquals(newFile, result0File); Assertions.assertEquals(duplicatePath, result0Path); Assertions.assertFalse(elements.hasNext()); }
Example 20
Source File: SequenceContext.java From armeria with Apache License 2.0 | 2 votes |
/** * Create an iterator over the children. May be constructed with a null * JsonArray if we only use it for writing. */ protected SequenceContext(@Nullable JsonNode json) { children = null != json ? json.elements() : null; }