public void treeTraversalSolution() { try { ObjectMapper mapper = new ObjectMapper(); // use the ObjectMapper to read the json string and create a tree JsonNode node = mapper.readTree(new File("Persons.json")); Iterator<String> fieldNames = node.fieldNames(); while (fieldNames.hasNext()) { JsonNode personsNode = node.get("persons"); Iterator<JsonNode> elements = personsNode.iterator(); while (elements.hasNext()) { JsonNode element = elements.next(); JsonNodeType nodeType = element.getNodeType(); if (nodeType == JsonNodeType.STRING) { out.println("Group: " + element.textValue()); } if (nodeType == JsonNodeType.ARRAY) { Iterator<JsonNode> fields = element.iterator(); while (fields.hasNext()) { parsePerson(fields.next()); } } } fieldNames.next(); } } catch (IOException ex) { ex.printStackTrace(); } }
@Test public void testGetTasks() throws Exception { Response response = target("/tasks").request().get(); assertResponseStatus(response, Response.Status.OK); assertHeader(response.getHeaders(), HttpHeaders.CONTENT_TYPE, JsonApiMediaType.APPLICATION_JSON_API); JsonNode data = mapper.readTree((InputStream) response.getEntity()).get("data"); assertThat(data.getNodeType(), is(JsonNodeType.ARRAY)); List<Task> tasks = new ArrayList<>(); for (JsonNode node : data) { tasks.add(getTaskFromJson(node)); } assertThat(tasks, hasSize(1)); final Task task = tasks.get(0); assertThat(task.getId(), is(1L)); assertThat(task.getName(), is("First task")); assertThat(task.getProject(), is(nullValue())); }
@Test public void shouldThrowIfAnExtraordinaryExceptionHappensWhenParsingAsGenericMap() throws Exception { JsonNode value = mock(ObjectNode.class); when(value.getNodeType()).thenReturn(JsonNodeType.OBJECT); JsonNodeClaim claim = (JsonNodeClaim) claimFromNode(value); JsonNodeClaim spiedClaim = spy(claim); ObjectMapper mockedMapper = mock(ObjectMapper.class); when(spiedClaim.getObjectMapper()).thenReturn(mockedMapper); JsonParser mockedParser = mock(JsonParser.class); when(mockedMapper.treeAsTokens(value)).thenReturn(mockedParser); when(mockedParser.readValueAs(ArgumentMatchers.any(TypeReference.class))).thenThrow(IOException.class); exception.expect(JWTDecodeException.class); spiedClaim.asMap(); }
@Override public List<GeoCoord> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); if (JsonNodeType.ARRAY != node.getNodeType()) { throw new IOException("Unable to instantiate new GeoCoord Path Lists from JSON!"); } List<GeoCoord> result = new ArrayList<>(node.size()); for (int i = 0; i < node.size(); i++) { JsonNode p = node.get(i); double lon = p.get("longitude").asDouble(); double lat = p.get("latitude").asDouble(); result.add(new GeoCoord(lon, lat)); } return result; }
private Property createSclarProperty(String arrayType, JsonNode node) { Property property = null; Iterator<JsonNode> nodes = node.elements(); while (nodes.hasNext()) { JsonNode leafNode = nodes.next(); JsonNodeType type = leafNode.getNodeType(); switch (type) { case STRING: property = new StringPropertyBuilder().withExample(leafNode.asText()).build(); break; case BOOLEAN: property = new BooleanPropertyBuilder().withExample(leafNode.asBoolean()).build(); break; case NUMBER: if (leafNode.isInt() || leafNode.isLong()) { property = new IntegerPropertyBuilder().withExample(leafNode.asLong()).build(); } else if (leafNode.isFloat() || leafNode.isDouble()) { property = new NumberPropertyBuilder().withExample(leafNode.asDouble()).build(); } break; default: break; } } return property; }
private JsonNode removeNullNodes(JsonNode node) { Iterator<JsonNode> iterator = node.iterator(); while (iterator.hasNext()) { JsonNode next = iterator.next(); if (next.getNodeType().equals(JsonNodeType.NULL)) { iterator.remove(); } if (next.getNodeType().equals(JsonNodeType.ARRAY) || next.getNodeType().equals(JsonNodeType.OBJECT)) { JsonNode jsonNode = removeNullNodes(next); if (!jsonNode.iterator().hasNext()) { iterator.remove(); } } } return node; }
@Test @WithMockUser(authorities={"VIEW_DEVICE_CHART"}) public void shouldLoadMetrics() throws Exception { List<String> listMetrics = eventSchema.getFields() .stream() .filter(schemaField -> schemaField.getKnownTypes().contains(JsonNodeType.NUMBER)) .map(m -> m.getPath()).collect(java.util.stream.Collectors.toList()); when(deviceRegisterService.findByTenantDomainNameAndDeviceGuid(tenant.getDomainName(), DEVICE_GUID)) .thenReturn(Device.builder().application(application).build()); when(eventSchemaService.findKnownIncomingMetricsBy(tenant, application, DEVICE_GUID, CHANNEL, JsonNodeType.NUMBER)) .thenReturn(ServiceResponseBuilder.<List<String>>ok() .withResult(new ArrayList<String>(listMetrics)).build()); getMockMvc().perform(get("/devices/visualization/loading/metrics/").param("deviceGuid", DEVICE_GUID).param("channel", CHANNEL)) .andExpect(model().attribute("metrics", equalTo(listMetrics))) .andExpect(view().name("devices/visualization/metrics")); }
@Before public void setUp() throws Exception { expectedFlattenMap = new HashMap<>(); expectedFlattenMap.put("ts", JsonParsingService.JsonPathData.builder() .value("2016-03-03T18:15:00Z") .types(Arrays.asList(new JsonNodeType[] {JsonNodeType.OBJECT,JsonNodeType.STRING})).build()); expectedFlattenMap.put("value", JsonParsingService.JsonPathData.builder() .value(31.0) .types(Arrays.asList(new JsonNodeType[] {JsonNodeType.OBJECT,JsonNodeType.NUMBER})).build()); expectedFlattenMap.put("command.type", JsonParsingService.JsonPathData.builder() .value("ButtonPressed") .types(Arrays.asList(new JsonNodeType[] {JsonNodeType.OBJECT,JsonNodeType.OBJECT,JsonNodeType.STRING})).build()); expectedFlattenMap.put("data.channels.0.name", JsonParsingService.JsonPathData.builder() .value("channel_0") .types(Arrays.asList(new JsonNodeType[] {JsonNodeType.OBJECT,JsonNodeType.OBJECT,JsonNodeType.ARRAY,JsonNodeType.OBJECT,JsonNodeType.STRING})).build()); expectedFlattenMap.put("time", JsonParsingService.JsonPathData.builder() .value(123L) .types(Arrays.asList(new JsonNodeType[] {JsonNodeType.OBJECT,JsonNodeType.NUMBER})).build()); }
@Override public ServiceResponse<List<String>> findKnownIncomingMetricsBy(Tenant tenant, Application application, String deviceGuid, String channel, JsonNodeType nodeType) { ServiceResponse<EventSchema> metricsResponse = findIncomingBy(tenant, application, deviceGuid, channel); if (metricsResponse.isOk()) { EventSchema schema = metricsResponse.getResult(); List<String> listMetrics = filterMetricsByJsonType(schema, nodeType); return ServiceResponseBuilder.<List<String>>ok().withResult(listMetrics).build(); } else { return ServiceResponseBuilder.<List<String>>error().withMessages(metricsResponse.getResponseMessages()) .build(); } }
@Override public ServiceResponse<List<String>> findKnownIncomingMetricsBy(Tenant tenant, Application application, String deviceGuid, JsonNodeType nodeType) { ServiceResponse<List<EventSchema>> metricsResponse = findIncomingBy(tenant, application, deviceGuid); if (metricsResponse.isOk()) { List<String> listMetrics = new ArrayList<>(); for (EventSchema schema : metricsResponse.getResult()) { List<String> result = filterMetricsByJsonType(schema, nodeType); listMetrics.addAll(result); } return ServiceResponseBuilder.<List<String>>ok().withResult(listMetrics).build(); } else { return ServiceResponseBuilder.<List<String>>error().withMessages(metricsResponse.getResponseMessages()) .build(); } }
/** * List of all not-empty rooms * @param user the id of the person requesting the list, or null if unauthenticated * @param map * @return List of all sites, possibly filtered by owner and/or name. Will not return null. */ public List<JsonNode> listSites(ResourceAccessPolicy accessPolicy, String owner, String name) { Log.log(Level.FINER, this, "List all rooms"); List<JsonNode> result = sites.listSites(nullEmpty(owner), nullEmpty(name)); //we have to step through any results to remove the connectionDetails blocks. for(JsonNode j : result){ JsonNode ownerNode = j.get("owner"); if(ownerNode!=null && ownerNode.getNodeType().equals(JsonNodeType.STRING)){ String ownerNodeString = ownerNode.textValue(); //remove connectionDetailsBlocks unless requested by owner or the system id if( stripSensitiveData(accessPolicy, ownerNodeString)){ JsonNode info = j.get("info"); if(info.getNodeType() == JsonNodeType.OBJECT){ ObjectNode infoObj = (ObjectNode)info; if(infoObj.has("connectionDetails")){ infoObj.remove("connectionDetails"); } } } } } return result; }
private Observable<ArrayNode> observeGetWrappedArray(String endpoint, String wrappingField) { return observeGetObject(endpoint) .map((ObjectNode jsonObject) -> { JsonNode wrappedValue = jsonObject.get(wrappingField); if (wrappedValue == null) { throw new RuntimeException(String.format("Wrapping field '%s' is null", wrappingField)); } else if (wrappedValue.getNodeType() == JsonNodeType.ARRAY) { return (ArrayNode) wrappedValue; } else { throw new RuntimeException(String.format( "Wrappeed value '%s' is not an array, but %s", wrappingField, wrappedValue.getNodeType())); } }); }
private Observable<ObjectNode> observeGetWrappedObject(String endpoint, String wrappingField) { return observeGetObject(endpoint) .map((ObjectNode jsonObject) -> { JsonNode wrappedValue = jsonObject.get(wrappingField); if (wrappedValue == null) { throw new RuntimeException(String.format("Wrapping field '%s' is null", wrappingField)); } else if (wrappedValue.getNodeType() == JsonNodeType.OBJECT) { return (ObjectNode) wrappedValue; } else { throw new RuntimeException(String.format( "Wrappeed value '%s' is not an object, but %s", wrappingField, wrappedValue.getNodeType())); } }); }
private Map<String, String> decodeAttributes(JsonNode tree, String name) { final JsonNode n = tree.get(name); if (n == null) { return EMPTY_ATTRIBUTES; } if (n.getNodeType() != JsonNodeType.OBJECT) { return EMPTY_ATTRIBUTES; } final Map<String, String> attributes = Maps.newHashMap(); final Iterator<Map.Entry<String, JsonNode>> iter = n.fields(); while (iter.hasNext()) { final Map.Entry<String, JsonNode> e = iter.next(); attributes.put(e.getKey(), e.getValue().asText()); } return attributes; }
private Set<String> decodeTags(JsonNode tree, String name) { final JsonNode n = tree.get(name); if (n == null) { return EMPTY_TAGS; } if (n.getNodeType() != JsonNodeType.ARRAY) { return EMPTY_TAGS; } final List<String> tags = Lists.newArrayList(); final Iterator<JsonNode> iter = n.elements(); while (iter.hasNext()) { tags.add(iter.next().asText()); } return Sets.newHashSet(tags); }
private List<FieldValues> parseResponse(final JsonNode response) { if (response == null || response.get("fields") == null) { throw new RuntimeException("Failed to parse JSON"); } final JsonNode fieldsNode = response.get("fields"); if (fieldsNode.getNodeType() == JsonNodeType.OBJECT || fieldsNode.getNodeType() == JsonNodeType.ARRAY) { final List<FieldValues> output = new ArrayList<>(); for (final JsonNode node : fieldsNode) { try { final FieldValues fieldValues = objectMapper.treeToValue(node, FieldValues.class); output.add(fieldValues); } catch (final JsonProcessingException e) { throw new RuntimeException("Failed to parse JSON", e); } } return output; } else { throw new RuntimeException("Failed to parse JSON"); } }
public void setText(JsonNode jn) { if (isComposed) { if(jn.getNodeType() == JsonNodeType.OBJECT) { com.fasterxml.jackson.databind.node.ObjectNode on = (ObjectNode) jn; for(JComponent jc : children) { if(jc instanceof JTextComponent) { JsonNode jn2 = on.get(jc.getName()); // TODO nested components ((JTextComponent) jc).setText(jn2.asText()); } } } else { JOptionPane.showMessageDialog(null, "Unsupported Type", "Composed type value: " + jn, JOptionPane.ERROR_MESSAGE); } } else { ((JTextComponent) component).setText(jn.asText()); } }
public URI getUri(int index) { JsonNode uris = getMetadata().get("uris"); if (uris != null) { try { if (uris.getNodeType() == JsonNodeType.STRING) { return new URI(uris.asText()); } else if (uris.getNodeType() == JsonNodeType.ARRAY) { ArrayNode an = (ArrayNode)uris; return new URI(an.get(index).asText()); } } catch (URISyntaxException e) { throw new RuntimeException("TD with malformed base uris"); } } else { throw new RuntimeException("TD without base uris field"); } // should never be reached throw new RuntimeException("Unexpected error while retrieving uri at index " + index); }
public List<ClauseNode> getConditions() { List<ClauseNode> conditions = new ArrayList<ClauseNode>(); String comparator = root.get("condition").asText(); MatchCondition matchCondition = getMatchCondition(comparator); boolean not = false; if (root.get("not") != null) { not = root.get("not").asBoolean(false); } JsonNode valNode = getValue(); if (valNode.getNodeType() == JsonNodeType.ARRAY) { List<Token> tokens = new ArrayList<Token>(); for (JsonNode node : valNode) { tokens.add(getToken(node, matchCondition)); } conditions.add(new Condition(fieldName, new Token<List<Token>>(tokens, MatchCondition.IN), not)); } else { conditions.add(new Condition(fieldName, getToken(valNode, matchCondition), not)); } return conditions; }
/** * IntegerIndex backed fields are handled here * * @param fieldName name of the field * @param node JsonNode representing the field content. This can be an array or a number * @return Field instance */ private Field handleIntegerField(String fieldName, JsonNode node) { List<Token> tokens = new ArrayList<Token>(); if (node.getNodeType() == JsonNodeType.ARRAY) { Iterator<JsonNode> iterator = ((ArrayNode) node).elements(); while (iterator.hasNext()) { JsonNode subNode = iterator.next(); if (subNode.getNodeType() == JsonNodeType.NUMBER) { tokens.add(new Token<Integer>(subNode.asInt())); } } } else if (node.getNodeType() == JsonNodeType.NUMBER) { tokens.add(new Token<Integer>(node.asInt())); } return new Field(fieldName, tokens); }
private void parseJSON() throws SchemaConfigurationError { try { ObjectNode fields = (ObjectNode) root.get("fields"); Iterator<Map.Entry<String, JsonNode>> iterator = fields.fields(); while (iterator.hasNext()) { Map.Entry<String, JsonNode> entry = iterator.next(); FieldIndex index = buildField(entry.getKey(), entry.getValue()); schema.addFieldIndex(index.getName(), index); } JsonNode persistence = root.get("persistence"); //as a default set DummyQueryStorage. Only if persistence options are provided overwrite it schema.setQueryStorage(new DummyQueryStorage()); if (persistence != null && persistence.getNodeType() == JsonNodeType.OBJECT) { //if persistence key doesn't exist there is no persistence JsonNode file = persistence.get("file"); if (file != null && file.getNodeType() == JsonNodeType.STRING) { schema.setQueryStorage(new MapDBStore(new File(schemaDirectory, file.asText()))); } else { LOGGER.error("unable to get file name for query storage. Continuing with no persistence!"); } } } catch (Exception e) { throw new SchemaConfigurationError("Could not parse JSON tree", e); } schema.init(); }
@Test public void verifiedWithJacksonParser() throws Exception { ODataServerError error = new ODataServerError().setCode("Code").setMessage("Message").setTarget("Target") .setDetails(Collections.singletonList( new ODataErrorDetail().setCode("detailCode").setMessage("detailMessage").setTarget("detailTarget"))); InputStream stream = ser.error(error).getContent(); JsonNode tree = new ObjectMapper().readTree(stream); assertNotNull(tree); tree = tree.get("error"); assertNotNull(tree); assertEquals("Code", tree.get("code").textValue()); assertEquals("Message", tree.get("message").textValue()); assertEquals("Target", tree.get("target").textValue()); tree = tree.get("details"); assertNotNull(tree); assertEquals(JsonNodeType.ARRAY, tree.getNodeType()); tree = tree.get(0); assertNotNull(tree); assertEquals("detailCode", tree.get("code").textValue()); assertEquals("detailMessage", tree.get("message").textValue()); assertEquals("detailTarget", tree.get("target").textValue()); }
public static Object toObject(JsonNode node) throws IOException { JsonNodeType type = node.getNodeType(); switch (type) { case ARRAY: List<Object> list = new ArrayList<>(); for (JsonNode child : node) { list.add(toObject(child)); } return list; case BINARY: return node.binaryValue(); case BOOLEAN: return node.booleanValue(); case NULL: return null; case NUMBER: return node.numberValue(); case OBJECT: case POJO: return toMap(node); default: return node.textValue(); } }
@Test public void arrayProcessing() { final JsonNode root = TestUtil.readSampleJson("arraysample.json"); final JsonNode copy = FilteredTreeCopier.copyTree(root, Arrays.asList(new Node("b", new Node("c", new Node("doesNotExist")), new Node("d"), new Node("e")))); assertFalse(copy.has("a")); assertTrue(copy.has("b")); JsonNode b = copy.get("b"); assertEquals(b.size(), 2); JsonNode firstArrayElement = b.get(0); assertTrue(firstArrayElement.has("d")); JsonNode d = firstArrayElement.get("d"); assertEquals(d.getNodeType(), JsonNodeType.ARRAY); assertEquals(d.size(), 0); assertTrue(firstArrayElement.has("e")); JsonNode c = firstArrayElement.get("c"); assertEquals(c.getNodeType(), JsonNodeType.ARRAY); assertEquals(c.size(), 0); }
public T deserialize(String message, Websocket socket) throws MessageParseException, InvalidMessageCodeException { JsonNode rootNode; try { rootNode = this.objectMapper.readTree(message); } catch (IOException parseException) { // TODO: check when this actually can happen, build a test-case for this throw new MessageParseException(parseException.getMessage()); } if (JsonNodeType.ARRAY != rootNode.getNodeType()) { throw new MessageParseException("Message is no JSON-Array"); } return this.deserialize(rootNode, socket); }
private List<String> readStringArray(JsonNode rootNode, int position) throws MessageParseException { JsonNode arrayNode = rootNode.get(position); if (null == arrayNode || JsonNodeType.ARRAY != arrayNode.getNodeType()) { throw new MessageParseException("Expected array at position " + position); } List<String> stringList = new ArrayList<String>(); Iterator<JsonNode> elements = arrayNode.elements(); int iteratorPosition = 0; while(elements.hasNext()) { JsonNode element = elements.next(); if (JsonNodeType.STRING != element.getNodeType()) { throw new MessageParseException("Array-Item at position " + iteratorPosition + " is no string"); } String stringifiedElement = element.asText(); if (0 == stringifiedElement.length()) { throw new MessageParseException("Array-Item as position " + iteratorPosition + " may not be empty"); } stringList.add(stringifiedElement); iteratorPosition++; } return stringList; }
public static Object toRS(JsonNode value) { if (value.getNodeType() == JsonNodeType.STRING) { return value.asText(); } else if (value.getNodeType() == JsonNodeType.NUMBER) { if (value.numberType() == JsonParser.NumberType.INT) { return value.asInt(); } else if (value.numberType() == JsonParser.NumberType.LONG) { return value.asLong(); } else if (value.numberType() == JsonParser.NumberType.DOUBLE) { return value.asDouble(); } } else if (value.getNodeType() == JsonNodeType.BOOLEAN) { return value.asBoolean(); } else if ( value instanceof ArrayNode ) { List<Object> array = new ArrayList<Object>(); value.elements().forEachRemaining( (e)->{ array.add( toRS( e ) ); }); return array; } else if (value instanceof ObjectNode) { return convert( (ObjectNode) value ); } return null; }
@Test public void processTemplate() throws MalformedURLException, IOException { String json = template.get(); assertTrue(!StringUtils.isEmpty(json)); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(json); assertTrue(node.getNodeType() == JsonNodeType.OBJECT); }
private static void generateDiffs(final DiffProcessor processor, final JsonPointer pointer, final JsonNode source, final JsonNode target) { if (EQUIVALENCE.equivalent(source, target)) { return; } final JsonNodeType sourceType = source.getNodeType(); final JsonNodeType targetType = target.getNodeType(); /* * Node types differ: generate a replacement operation. */ if (sourceType != targetType) { processor.valueReplaced(pointer, source, target); return; } /* * If we reach this point, it means that both nodes are the same type, * but are not equivalent. * * If this is not a container, generate a replace operation. */ if (!source.isContainerNode()) { processor.valueReplaced(pointer, source, target); return; } /* * If we reach this point, both nodes are either objects or arrays; * delegate. */ if (sourceType == JsonNodeType.OBJECT) { generateObjectDiffs(processor, pointer, (ObjectNode) source, (ObjectNode) target); } else { // array generateArrayDiffs(processor, pointer, (ArrayNode) source, (ArrayNode) target); } }
private static void computeUnchanged(final Map<JsonPointer, JsonNode> ret, final JsonPointer pointer, final JsonNode source, final JsonNode target) { if (EQUIVALENCE.equivalent(source, target)) { ret.put(pointer, target); return; } final JsonNodeType sourceType = source.getNodeType(); final JsonNodeType targetType = target.getNodeType(); if (sourceType != targetType) { return; // nothing in common } // We know they are both the same type, so... switch (sourceType) { case OBJECT: computeUnchangedObject(ret, pointer, source, target); break; case ARRAY: computeUnchangedArray(ret, pointer, source, target); break; default: /* nothing */ } }
@Override protected boolean doEquivalent(final JsonNode a, final JsonNode b) { /* * If both are numbers, delegate to the helper method */ if (a.isNumber() && b.isNumber()) { return numEquals(a, b); } final JsonNodeType typeA = a.getNodeType(); final JsonNodeType typeB = b.getNodeType(); /* * If they are of different types, no dice */ if (typeA != typeB) { return false; } /* * For all other primitive types than numbers, trust JsonNode */ if (!a.isContainerNode()) { return a.equals(b); } /* * OK, so they are containers (either both arrays or objects due to the * test on types above). They are obviously not equal if they do not * have the same number of elements/members. */ if (a.size() != b.size()) { return false; } /* * Delegate to the appropriate method according to their type. */ return typeA == JsonNodeType.ARRAY ? arrayEquals(a, b) : objectEquals(a, b); }
private String parseDtmfFromUserInfo(JsonNode userInfo) { if (userInfo.get("dtmf").getNodeType() == JsonNodeType.STRING) { String dtmf = userInfo.get("dtmf").asText(); int indexOfPound = dtmf.indexOf("#"); if (indexOfPound != -1) { dtmf = dtmf.substring(0, indexOfPound); } return dtmf; } return null; }
private String parseStringParamFromUserInfo(JsonNode userInfo, String paramName) { if (null == userInfo || null == paramName) { return null; } if (userInfo.get(paramName).getNodeType() == JsonNodeType.STRING) { String value = userInfo.get(paramName).asText(); return value; } return null; }
private Boolean parseBooleanParamFromUserInfo(JsonNode userInfo, String paramName) { if (null == userInfo || null == paramName) { return null; } if (userInfo.get(paramName).getNodeType() == JsonNodeType.BOOLEAN) { Boolean value = userInfo.get(paramName).asBoolean() ? Boolean.TRUE : Boolean.FALSE; return value; } return null; }
private String parseDtmfFromUserInfo(JsonNode userInfo) { if (userInfo.get("dtmf").getNodeType() == JsonNodeType.STRING) { String dtmf = userInfo.get("dtmf").asText(); int indexOfPound = dtmf.indexOf("#"); if ( indexOfPound != -1) { dtmf = dtmf.substring(0, indexOfPound); } return dtmf; } return null; }