/** * Map path segments to tree nodes, each segment to a set of nodes of a same level from the root * * @param pathSegments * @param treeRoot * @return * @throws PathException */ public static Map<String, List<JsonNode>> mapPath2Tree( List<String> pathSegments, JsonNode treeRoot) throws PathException { if (treeRoot == null || !treeRoot.has(pathSegments.get(0))) { // Failed from root return null; } Map<String, List<JsonNode>> queryMap = new HashMap<String, List<JsonNode>>(); for (String s : pathSegments) { queryMap.put(s, new ArrayList<JsonNode>()); } for (int i = 0; i < pathSegments.size(); i++) { String nodeName = pathSegments.get(i); List<JsonNode> ret = new ArrayList<JsonNode>(); if (i == 0) { JsonNode childs = treeRoot.get(nodeName); if (childs != null) { if (childs.isArray()) { Iterator<JsonNode> iter = childs.iterator(); while (iter.hasNext()) { ret.add(iter.next()); } } else { ret.add(childs); } } } else { // parent node List<JsonNode> parents = queryMap.get(pathSegments.get(i - 1)); for (JsonNode parent : parents) { JsonNode childs = parent.get(nodeName); if (childs != null) { if (childs.isArray()) { Iterator<JsonNode> iter = childs.iterator(); while (iter.hasNext()) { ret.add(iter.next()); } } else { ret.add(childs); } } } } if (ret.size() > 0) { queryMap.get(nodeName).addAll(ret); } else if (i < pathSegments.size() - 1) { // not found in the middle of the path return null; } } return queryMap; }
private static void mergeJsonObject(ObjectNode src, ObjectNode other) { Iterator<Map.Entry<String, JsonNode>> ite = other.fields(); while (ite.hasNext()) { Map.Entry<String, JsonNode> pair = ite.next(); JsonNode s = src.get(pair.getKey()); JsonNode v = pair.getValue(); if (v.isObject() && s != null && s.isObject()) { mergeJsonObject((ObjectNode) s, (ObjectNode) v); } else if (v.isArray() && s != null && s.isArray()) { mergeJsonArray((ArrayNode) s, (ArrayNode) v); } else { src.replace(pair.getKey(), v); } } }
@Test public void testCommandGetFilteredCollection() { running( fakeApplication(), () -> { try { DbHelper.open("1234567890", TEST_USER, TEST_USER); ObjectNode cmd = MAPPER.createObjectNode(); ObjectNode p = MAPPER.createObjectNode(); ObjectNode q = MAPPER.createObjectNode(); q.put("where", "idx < ?"); ArrayNode params = MAPPER.createArrayNode(); params.add("5"); q.put("params", params); p.put("collection", TEST_COLLECTION); p.put("query", q); cmd.put(ScriptCommand.RESOURCE, "documents"); cmd.put(ScriptCommand.NAME, "list"); cmd.put(ScriptCommand.PARAMS, p); JsonNode node = CommandRegistry.execute(cmd, null); assertNotNull(node); assertTrue(node.isArray()); assertEquals(5, node.size()); } catch (Throwable t) { fail(ExceptionUtils.getFullStackTrace(t)); } finally { DbHelper.close(DbHelper.getConnection()); } }); }
@Override public Tuple convert(String source) { TupleBuilder builder = TupleBuilder.tuple(); try { JsonNode root = mapper.readTree(source); for (Iterator<Entry<String, JsonNode>> it = root.fields(); it.hasNext(); ) { Entry<String, JsonNode> entry = it.next(); String name = entry.getKey(); JsonNode node = entry.getValue(); if (node.isObject()) { // tuple builder.addEntry(name, convert(node.toString())); } else if (node.isArray()) { builder.addEntry(name, nodeToList(node)); } else { if (name.equals("id")) { // TODO how should this be handled? } else if (name.equals("timestamp")) { // TODO how should this be handled? } else { builder.addEntry(name, node.asText()); } } } } catch (Exception e) { throw new RuntimeException(e); } return builder.build(); }
private static void mergeJsonArray(ArrayNode src, ArrayNode other) { for (int i = 0; i < other.size(); i++) { JsonNode s = src.get(i); JsonNode v = other.get(i); if (s == null) { src.add(v); } else if (v.isObject() && s.isObject()) { mergeJsonObject((ObjectNode) s, (ObjectNode) v); } else if (v.isArray() && s.isArray()) { mergeJsonArray((ArrayNode) s, (ArrayNode) v); } else { src.remove(i); src.insert(i, v); } } }
@Override public Tuple convert(String source) { TupleBuilder builder = TupleBuilder.tuple(); try { JsonNode root = mapper.readTree(source); for (Iterator<Entry<String, JsonNode>> it = root.fields(); it.hasNext(); ) { Entry<String, JsonNode> entry = it.next(); String name = entry.getKey(); JsonNode node = entry.getValue(); if (node.isObject()) { // tuple builder.addEntry(name, convert(node.toString())); } else if (node.isArray()) { builder.addEntry(name, nodeToList(node)); } else if (node.isNull()) { builder.addEntry(name, null); } else if (node.isBoolean()) { builder.addEntry(name, node.booleanValue()); } else if (node.isNumber()) { builder.addEntry(name, node.numberValue()); } else { builder.addEntry(name, mapper.treeToValue(node, Object.class)); } } } catch (Exception e) { throw new RuntimeException(e); } return builder.build(); }
protected Coordinate[] decodeCoordinates(JsonNode node) throws GeoJSONException { if (!node.isArray()) { throw new GeoJSONException("expected array"); } Coordinate[] coordinates = new Coordinate[node.size()]; for (int i = 0; i < node.size(); ++i) { coordinates[i] = decodeCoordinate(node.get(i)); } return coordinates; }
@Test public void unclosedArray_AutoClosesOnClose() throws IOException { jsonGenerator.writeStartArray(); jsonGenerator.writeValue("valOne"); jsonGenerator.writeValue("valTwo"); jsonGenerator.writeValue("valThree"); JsonNode node = toJsonNode(); assertTrue(node.isArray()); assertEquals(3, node.size()); }
@Test public void canWriteSimpleResults() throws IOException { libratoWriter.beforeBatch(out); libratoWriter.write(out, counterResult1); libratoWriter.write(out, counterResult2); libratoWriter.write(out, gaugeResult1); libratoWriter.write(out, gaugeResult2); libratoWriter.afterBatch(out); JsonNode tree = objectMapper.readTree(out.toByteArray()); JsonNode counters = tree.findPath("counters"); assertThat(counters.isArray()).isTrue(); assertThat(counters.size()).isEqualTo(2); JsonNode counter1 = counters.get(0); assertThat(counter1.get("name").textValue()).isEqualTo("counter1"); assertThat(counter1.get("source").textValue()).isEqualTo("myHost.test.net"); assertThat(counter1.get("measure_time").intValue()).isEqualTo(1); assertThat(counter1.get("value").intValue()).isEqualTo(1); JsonNode counter2 = counters.get(1); assertThat(counter2.get("name").textValue()).isEqualTo("counter2"); assertThat(counter2.get("source").textValue()).isEqualTo("myHost.test.net"); assertThat(counter2.get("measure_time").intValue()).isEqualTo(2); assertThat(counter2.get("value").longValue()).isEqualTo(2L); JsonNode gauges = tree.findPath("gauges"); assertThat(gauges.isArray()).isTrue(); JsonNode gauge1 = gauges.get(0); assertThat(gauge1.get("name").textValue()).isEqualTo("gauge1"); assertThat(gauge1.get("source").textValue()).isEqualTo("myHost.test.net"); assertThat(gauge1.get("measure_time").intValue()).isEqualTo(3); assertThat(gauge1.get("value").doubleValue()).isEqualTo(3.3); JsonNode gauge2 = gauges.get(1); assertThat(gauge2.get("name").textValue()).isEqualTo("gauge2"); assertThat(gauge2.get("source").textValue()).isEqualTo("myHost.test.net"); assertThat(gauge2.get("measure_time").intValue()).isEqualTo(4); assertThat(gauge2.get("value").floatValue()).isEqualTo(4.4f); }
/** * Determines whether or not the given {@link JsonNode} matches the given type. This method is * limitted to a few java types only and shouldn't be used to determine with great accuracy * whether or not the types match. * * @param node the {@link JsonNode} * @param type the {@link Class} * @return true if the types match, false otherwise */ protected boolean isMatchingType(JsonNode node, Class<?> type) { if (node.isNull()) { return true; } else if (node.isTextual()) { return String.class.isAssignableFrom(type); } else if (node.isNumber()) { return Number.class.isAssignableFrom(type) || short.class.isAssignableFrom(type) || int.class.isAssignableFrom(type) || long.class.isAssignableFrom(type) || float.class.isAssignableFrom(type) || double.class.isAssignableFrom(type); } else if (node.isArray() && type.isArray()) { return (node.size() > 0) ? isMatchingType(node.get(0), type.getComponentType()) : false; } else if (node.isArray()) { return type.isArray() || Collection.class.isAssignableFrom(type); } else if (node.isBinary()) { return byte[].class.isAssignableFrom(type) || Byte[].class.isAssignableFrom(type) || char[].class.isAssignableFrom(type) || Character[].class.isAssignableFrom(type); } else if (node.isBoolean()) { return boolean.class.isAssignableFrom(type) || Boolean.class.isAssignableFrom(type); } else if (node.isObject() || node.isPojo()) { return !type.isPrimitive() && !String.class.isAssignableFrom(type) && !Number.class.isAssignableFrom(type) && !Boolean.class.isAssignableFrom(type); } // not sure if it's a matching type return false; }
@Override public Object valueFromJson(JsonNode node) { if (node.isArray()) { if (node.size() == 2) { if (node.get(0).isTextual() && "map".equals(node.get(0).asText())) { OvsdbMap<Object, Object> map = new OvsdbMap<Object, Object>(); for (JsonNode pairNode : node.get(1)) { if (pairNode.isArray() && node.size() == 2) { Object key = getKeyType().toValue(pairNode.get(0)); Object value = getBaseType().toValue(pairNode.get(1)); map.put(key, value); } } return map; } else if (node.size() == 0) { return null; } } } return null; }
protected GeometryCollection decodeGeometryCollection(JsonNode node, GeometryFactory fac) throws GeoJSONException { final JsonNode geometries = node.path(GEOMETRIES); if (!geometries.isArray()) { throw new GeoJSONException("expected 'geometries' array"); } Geometry[] geoms = new Geometry[geometries.size()]; for (int i = 0; i < geometries.size(); ++i) { geoms[i] = decodeGeometry(geometries.get(i), fac); } return fac.createGeometryCollection(geoms); }
private AutoPromotionProperty loadAutoPromotionProperty(JsonNode node) { // Backward compatibility (before 2.14) if (node.isArray()) { return new AutoPromotionProperty(readValidationStamps(node), "", ""); } else { JsonNode validationStamps = node.get("validationStamps"); List<ValidationStamp> validationStampList = readValidationStamps(validationStamps); return new AutoPromotionProperty( validationStampList, JsonUtils.get(node, "include", false, ""), JsonUtils.get(node, "exclude", false, "")); } }
public void testEmbeddedObjectInArray() throws Exception { TokenBuffer buf = new TokenBuffer(MAPPER); buf.writeStartArray(); buf.writeObject(MARKER); buf.writeEndArray(); JsonNode node = MAPPER.readTree(buf.asParser()); buf.close(); assertTrue(node.isArray()); assertEquals(1, node.size()); JsonNode n = node.get(0); assertTrue(n.isPojo()); assertSame(MARKER, ((POJONode) n).getPojo()); }
@Test public void stringArray() throws IOException { jsonGenerator.writeStartArray(); jsonGenerator.writeValue("valOne"); jsonGenerator.writeValue("valTwo"); jsonGenerator.writeValue("valThree"); jsonGenerator.writeEndArray(); JsonNode node = toJsonNode(); assertTrue(node.isArray()); assertEquals("valOne", node.get(0).textValue()); assertEquals("valTwo", node.get(1).textValue()); assertEquals("valThree", node.get(2).textValue()); }
@Override public void validate(final ValidationReport report, final JsonNode instance) { final JsonNode oldParent = report.getSchema(); report.setSchema(parent); for (final KeywordValidator validator : validators) validator.validateInstance(report, instance); if (!(instance.isContainerNode() || report.isSuccess())) { report.setSchema(oldParent); return; } final JsonPointer ptr = report.getPath(); JsonPointer current; if (instance.isArray()) { JsonNode subSchema; int i = 0; for (final JsonNode element : instance) { current = ptr.append(i); report.setPath(current); subSchema = arrayPath(i); JsonSchema.fromNode(parent, subSchema).validate(report, element); i++; } report.setSchema(oldParent); report.setPath(ptr); return; } // Can only be an object now final Map<String, JsonNode> map = CollectionUtils.toMap(instance.fields()); String key; JsonNode value; for (final Map.Entry<String, JsonNode> entry : map.entrySet()) { key = entry.getKey(); value = entry.getValue(); current = ptr.append(key); report.setPath(current); for (final JsonNode subSchema : objectPath(key)) JsonSchema.fromNode(parent, subSchema).validate(report, value); } report.setSchema(oldParent); report.setPath(ptr); }
private List<Object> nodeToList(JsonNode node) { List<Object> list = new ArrayList<Object>(node.size()); for (int i = 0; i < node.size(); i++) { JsonNode item = node.get(i); if (item.isObject()) { list.add(convert(item.toString())); } else if (item.isArray()) { list.add(nodeToList(item)); } else { list.add(item.asText()); } } return list; }
/** More complicated test */ public static void test2() { ObjectMapper mapper = new ObjectMapper(); // create once, reuse try { String fullPath = System.getProperty("user.dir") + File.separator + "etc/RES-15-46.json"; // Target JsonNode root = mapper.readTree(new File(fullPath)); System.out.println("URI: " + root.get("uri")); // JsonNode targets = root.get("targets"); // if (targets.isArray()) { // Iterator<JsonNode> iter = targets.elements(); // while (iter.hasNext()) { // JsonNode node = iter.next(); // System.out.println(node.get("name").asText()); // } // } // try null // JsonNode cannotBeFound = root.get("aaa"); // System.out.println(cannotBeFound); // cannotBeFound = root.path("aaa"); // System.out.println(cannotBeFound.isMissingNode()); // // cannotBeFound = root.with("aaa"); // System.out.println(cannotBeFound); // Try to query JsonNode result = root.path("targets"); System.out.println(result.isArray()); // List<JsonNode> list = root.findValues("system"); // for (JsonNode n : list) { // System.out.println(n.get("uri").asText()); // ((ObjectNode) n).put("uri", "new uri"); // } // ObjectWriter w = mapper.writer().with( // SerializationFeature.INDENT_OUTPUT); // w.writeValue(new File(System.getProperty("user.dir") // + File.separator + "user-modified.json"), root); } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private JsonNode createProduct(JsonNode node, String userName) throws Exception { ObjectMapper om = new ObjectMapper(); ArrayNode anode = om.createArrayNode(); if (node.isArray()) { Iterator<JsonNode> nodeiterator = node.iterator(); while (nodeiterator.hasNext()) { ProductBack cbase = om.convertValue(nodeiterator.next(), ProductBack.class); anode.add(createProductToDb(om, cbase, userName)); } } else { ProductBack cbase = JSON.parseObject(node.asText(), ProductBack.class); anode.add(createProductToDb(om, cbase, userName)); } return anode; }
@Test public void nonNumericValuesAreSentEmpty() throws IOException { libratoWriter.beforeBatch(out); libratoWriter.write(out, new QueryResult("nonNumeric", COUNTER, "stringValue", 1000)); libratoWriter.afterBatch(out); JsonNode tree = objectMapper.readTree(out.toByteArray()); JsonNode counters = tree.findPath("counters"); assertThat(counters.isArray()).isTrue(); assertThat(counters.size()).isEqualTo(1); JsonNode counter1 = counters.get(0); assertThat(counter1.get("name").textValue()).isEqualTo("nonNumeric"); assertThat(counter1.get("value")).isNull(); }
protected Polygon decodePolygonCoordinates(JsonNode coordinates, GeometryFactory fac) throws GeoJSONException { if (!coordinates.isArray()) { throw new GeoJSONException("expected array"); } if (coordinates.size() < 1) { throw new GeoJSONException("missing polygon shell"); } LinearRing shell = fac.createLinearRing(decodeCoordinates(coordinates.get(0))); LinearRing[] holes = new LinearRing[coordinates.size() - 1]; for (int i = 1; i < coordinates.size(); ++i) { holes[i - 1] = fac.createLinearRing(decodeCoordinates(coordinates.get(i))); } return fac.createPolygon(shell, holes); }
@Test public void atomicLongAreSentAsNumbers() throws IOException { libratoWriter.beforeBatch(out); libratoWriter.write(out, new QueryResult("atomicLong", COUNTER, new AtomicLong(2), 1000)); libratoWriter.afterBatch(out); JsonNode tree = objectMapper.readTree(out.toByteArray()); JsonNode counters = tree.findPath("counters"); assertThat(counters.isArray()).isTrue(); assertThat(counters.size()).isEqualTo(1); JsonNode counter1 = counters.get(0); assertThat(counter1.get("name").textValue()).isEqualTo("atomicLong"); assertThat(counter1.get("value").longValue()).isEqualTo(2); }
/** * Handles the given {@link JsonNode} and writes the responses to the given {@link OutputStream}. * * @param node the {@link JsonNode} * @param ops the {@link OutputStream} * @throws IOException on error */ protected void handleNode(JsonNode node, OutputStreamWrapper opsw) throws IOException { // handle objects if (node.isObject()) { handleObject(ObjectNode.class.cast(node), opsw); // handle arrays } else if (node.isArray()) { handleArray(ArrayNode.class.cast(node), opsw); // bail on bad data } else { throw new IllegalArgumentException("Invalid JsonNode type: " + node.getClass().getName()); } }
private List<ValidationStamp> readValidationStamps(JsonNode validationStampIds) { List<ValidationStamp> validationStampList; if (validationStampIds.isArray()) { List<Integer> ids = new ArrayList<>(); validationStampIds.forEach(id -> ids.add(id.asInt())); // Reading the validation stamps and then the names validationStampList = ids.stream() .map(id -> structureService.getValidationStamp(ID.of(id))) .collect(Collectors.toList()); } else { throw new AutoPromotionPropertyCannotParseException( "Cannot get the list of validation stamps"); } return validationStampList; }
@Override public void receiveLoop() { log.debug("receiveLoop starts"); ObjectReader reader = this.mapper.reader(); while (true) { try { JsonNode root = reader.readTree(this.istream); String type = root.path(TYPE).asText(); JsonNode data = root.path(DATA); log.debug("Processing {} with {}", type, data); if (type.equals(GOODBYE)) { log.info("Connection closing from server."); break; } else if (type.equals(HELLO)) { this.receiveHello(data); } else if (type.equals(LOCALE)) { this.receiveHello(data); } else if (type.equals(PONG)) { // silently ignore } else if (!data.isMissingNode() || (root.isArray() && ((ArrayNode) root).size() > 0)) { // process replies with a data node or non-empty arrays JsonClientReply reply = new JsonClientReply(root); Runnable r = new RcvNotifier(reply, mLastSender, this); try { SwingUtilities.invokeAndWait(r); } catch (InterruptedException e) { log.error("Exception notifying listeners of reply: {}", e.getMessage(), e); } catch (InvocationTargetException e) { log.error("Exception notifying listeners of reply: {}", e.getMessage(), e); } } } catch (IOException e) { this.rcvException = true; reportReceiveLoopException(e); break; } catch (NoSuchElementException nse) { // we get an NSE when we are finished with this client // so break out of the loop break; } } ConnectionStatus.instance() .setConnectionState(this.controller.getCurrentPortName(), ConnectionStatus.CONNECTION_DOWN); log.error("Exit from rcv loop"); this.recovery(); }
/** * Return true if value is not present or if underlying JSON is empty object, array or null. * WARNING this method can throw same exceptions as {@link JsonNodeValue#get()} in a case if * source is invalid JSON string. */ public boolean isEmpty() { if (!isPresent()) { return true; } JsonNode n = get(); if ((n.isObject() || n.isArray()) && n.size() == 0) { return true; } if (n.isNull()) { return true; } return false; }
private static void testJson() { String json1 = "[\"hello\"]"; JsonNode jsonNode = Json.parse(json1); Json.stringify(jsonNode); System.out.println(jsonNode.toString()); System.out.println(Json.stringify(jsonNode)); ObjectNode jsonObject = Json.newObject(); jsonObject.put("hello", jsonNode); jsonObject.put("hello", 56); System.out.println(jsonObject.toString()); List<Object> strings = new ArrayList<Object>(); strings.add("hello"); strings.add("world"); jsonObject.put("test", Json.toJson(strings)); System.out.println(jsonObject.toString()); jsonObject.put("test2", Json.toJson("string")); jsonObject.put("test2", Json.toJson("sshshhs")); List<String> list = new ArrayList<String>(); list.add("hello me"); // ObjectNode objectNode = Json.newObject(); jsonObject.put("me", Json.toJson(list)); System.out.println(jsonObject.toString()); System.out.println(jsonObject.size()); System.out.println(jsonObject.get("test").isArray()); JsonNode jsonNode1 = jsonObject.get("test"); Iterator iterator = jsonNode1.iterator(); while ((iterator.hasNext())) { System.out.println(iterator.next()); } Iterator<JsonNode> iterator1 = jsonObject.iterator(); while (iterator1.hasNext()) { System.out.println("----------------------"); JsonNode jsonNode2 = iterator1.next(); if (jsonNode2.isArray()) { Iterator iterator2 = jsonNode2.iterator(); while ((iterator2.hasNext())) { System.out.println(iterator2.next()); } } else { if (jsonNode2.isTextual()) { System.out.println("String:" + jsonNode2); } } } }
private BasicDBList processGeneList(String genes) { BasicDBList list = new BasicDBList(); Client wsRestClient = Client.create(); WebResource webResource = wsRestClient.resource("http://ws.bioinfo.cipf.es/cellbase/rest/latest/hsa/feature/gene/"); ObjectMapper mapper = new ObjectMapper(); String response = webResource.path(genes).path("info").queryParam("of", "json").get(String.class); try { JsonNode actualObj = mapper.readTree(response); Iterator<JsonNode> it = actualObj.iterator(); Iterator<JsonNode> aux; while (it.hasNext()) { JsonNode node = it.next(); if (node.isArray()) { aux = node.iterator(); while (aux.hasNext()) { JsonNode auxNode = aux.next(); DBObject regionClause = new BasicDBObject("chr", auxNode.get("chromosome").asText()); regionClause.put( "pos", new BasicDBObject("$gte", auxNode.get("start").asInt()) .append("$lte", auxNode.get("end").asInt())); list.add(regionClause); } } } } catch (IOException e) { e.printStackTrace(); } return list; }
private void setupArrayNodes(final JsonNode schema) { JsonNode node = schema.path("items"); /** * We don't bother at this point: if items is a schema, then it will be used for each and every * element of the instance to validate -- it's just as if additionalItems were never defined. * So, as items is defined as a list above, we just leave it empty and assign the contents of * the keyword to additionalItems. */ if (node.isObject()) { additionalItems = node; return; } if (node.isArray()) for (final JsonNode item : node) items.add(item); node = schema.path("additionalItems"); if (node.isObject()) additionalItems = node; }
private List<Object> nodeToList(JsonNode node) throws JsonProcessingException { List<Object> list = new ArrayList<Object>(node.size()); for (int i = 0; i < node.size(); i++) { JsonNode item = node.get(i); if (item.isObject()) { list.add(convert(item.toString())); } else if (item.isArray()) { list.add(nodeToList(item)); } else if (item.isNull()) { list.add(null); } else if (item.isBoolean()) { list.add(item.booleanValue()); } else if (item.isNumber()) { list.add(item.numberValue()); } else { list.add(mapper.treeToValue(item, Object.class)); } } return list; }