@Override public int compare(JsonNode o1, JsonNode o2) { if (o1.equals(o2)) { return 0; } if ((o1 instanceof NumericNode) && (o2 instanceof NumericNode)) { double d1 = ((NumericNode) o1).asDouble(); double d2 = ((NumericNode) o2).asDouble(); return Double.compare(d1, d2); } int comp = o1.asText().compareTo(o2.asText()); if (comp == 0) { return Integer.compare(o1.hashCode(), o2.hashCode()); } return comp; }
public static Matcher<JsonNode> jsonNumber(final NumericNode value) { final JsonParser.NumberType numberType = value.numberType(); switch (numberType) { case INT: return jsonInt(value.asInt()); case LONG: return jsonLong(value.asLong()); case BIG_INTEGER: return jsonBigInteger(value.bigIntegerValue()); case FLOAT: return jsonFloat(value.floatValue()); case DOUBLE: return jsonDouble(value.doubleValue()); case BIG_DECIMAL: return jsonBigDecimal(value.decimalValue()); default: throw new UnsupportedOperationException("Unsupported number type " + numberType); } }
/** * Returns a Java object for a json value node based on the node type. */ public static Object valueFromJson(ValueNode node) { if (node instanceof NullNode) { return null; } else { if(node instanceof TextNode) { return node.textValue(); } else if(node instanceof BooleanNode) { return node.booleanValue(); } else if(node instanceof NumericNode) { return node.numberValue(); } else { throw new RuntimeException("Unsupported node type:"+node.getClass().getName()); } } }
@Override public RTimeSeriesData deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { final TreeNode node = jp.getCodec().readTree(jp); final HashMap<RMeasure, Double> data = new HashMap<>(); node.fieldNames().forEachRemaining(field -> { if (!field.equals("date")) { final RMeasure key = RMeasure.fromId(field); final double value = ((NumericNode) node.get(field)).doubleValue(); data.put(key, value); } }); return new RTimeSeriesData(ctx.parseDate(((TextNode) node.get("date")).textValue()), data); }
@Override public TimeSeriesItem deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { final TreeNode node = jp.getCodec().readTree(jp); final Measure[] measure = new Measure[1]; final Double[] value = new Double[1]; node.fieldNames().forEachRemaining(field -> { if (!field.equals("date")) { measure[0] = Measure.fromId(field); value[0] = ((NumericNode) node.get(field)).doubleValue(); } }); return new TimeSeriesItem(ctx.parseDate(((TextNode) node.get("date")).textValue()), measure[0], value[0]); }
/** * Converts the passed object to a JSON numeric node * @param number A {@link Number} or a string representing one * @return A JSON Numeric Node */ public static NumericNode numerify(Object number) { if(number==null) throw new IllegalArgumentException("Passed number was null"); //if(!(number instanceof Number)) throw new IllegalArgumentException("The passed object [" + number + "] is not a number"); String s = number.toString(); if(s.indexOf('.')!=-1) { return jsonNodeFactory.numberNode(new BigDecimal(s)); } return jsonNodeFactory.numberNode(Long.parseLong(s)); }
@Override protected boolean matchesNode(NumericNode node, Description mismatchDescription) { final Object number = projection.apply(node); if (numberMatcher.matches(number)) { return true; } else { mismatchDescription.appendText("was a number node with value that "); numberMatcher.describeMismatch(number, mismatchDescription); return false; } }
private static Matcher<JsonNode> createNodeMatcher(final JsonNode value) { final JsonNodeType nodeType = value.getNodeType(); switch (nodeType) { case ARRAY: return IsJsonArray.jsonArray((ArrayNode) value); case BINARY: throw new UnsupportedOperationException( "Expected value contains a binary node, which is not implemented."); case BOOLEAN: return IsJsonBoolean.jsonBoolean((BooleanNode) value); case MISSING: return IsJsonMissing.jsonMissing((MissingNode) value); case NULL: return IsJsonNull.jsonNull((NullNode) value); case NUMBER: return IsJsonNumber.jsonNumber((NumericNode) value); case OBJECT: return IsJsonObject.jsonObject((ObjectNode) value); case POJO: throw new UnsupportedOperationException( "Expected value contains a POJO node, which is not implemented."); case STRING: return IsJsonText.jsonText((TextNode) value); default: throw new UnsupportedOperationException("Unsupported node type " + nodeType); } }
/** * Deserialize. * * @param node the node * @return the json element */ @SuppressWarnings("unchecked") private T deserialize(JsonNode node) { JsonElement result = JsonNull.INSTANCE; if (null != node && !node.isNull()) { if (node.isObject()) { ObjectNode onode = (ObjectNode) node; JsonObject jsonObject = new JsonObject(); Iterator<Entry<String, JsonNode>> fields = onode.fields(); while (fields.hasNext()) { Entry<String, JsonNode> next = fields.next(); jsonObject.add(next.getKey(), deserialize(next.getValue())); } result = jsonObject; } else if (node.isArray()) { ArrayNode anode = (ArrayNode) node; JsonArray jsonArray = new JsonArray(); Iterator<JsonNode> elements = anode.elements(); while (elements.hasNext()) { jsonArray.add(deserialize(elements.next())); } result = jsonArray; } else if (node.isBoolean()) { result = new JsonPrimitive(node.asBoolean()); } else if (node.isNumber()) { NumericNode nnode = (NumericNode) node; result = new JsonPrimitive(nnode.numberValue()); } else if (node.isTextual()) { TextNode tnode = (TextNode) node; result = new JsonPrimitive(tnode.textValue()); } } return (T) result; }
protected BigInteger getQuantity(JsonNode node) { if (node instanceof NumericNode) { return BigInteger.valueOf(node.longValue()); } String value = getHexString(node); if (value == null) return null; return HexEncoding.fromHex(value); }
/** * Convert an opaque JSON node to BigDecimal using the most correct * conversion method. */ public static BigDecimal nodeToBigDecimal(JsonNode node) { JsonNodeType type = node.getNodeType(); if (type == JsonNodeType.NUMBER) { return numericToBigDecimal((NumericNode)node); } else { try { return new BigDecimal(node.asText()); } catch (ArithmeticException | NumberFormatException e) { // Fall through.. } } return null; }
/** * Convert a numeric JSON node to BigDecimal using the most correct * conversion method. */ private static BigDecimal numericToBigDecimal(NumericNode node) { switch (node.numberType()) { case INT: case LONG: return BigDecimal.valueOf(node.asLong()); case FLOAT: case DOUBLE: return BigDecimal.valueOf(node.asDouble()); case BIG_DECIMAL: case BIG_INTEGER: default: return node.decimalValue(); } }
public InvocationMessage(long requestID, NumericNode registrationID, ObjectNode details, ArrayNode arguments, ObjectNode argumentsKw){ this.requestID = requestID; this.registrationID = registrationID; this.details = details; this.arguments = arguments; this.argumentsKw = argumentsKw; }
@Override public CustomAttribute deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { CustomAttribute cda = null; final String currentName = jp.getParsingContext().getCurrentName(); final ObjectMapper mapper = (ObjectMapper) jp.getCodec(); final ValueNode vNode = mapper.readTree(jp); if (vNode.asToken().isScalarValue()) { if (vNode.getNodeType() == JsonNodeType.BOOLEAN) { cda = new CustomAttribute<Boolean>(currentName, vNode.asBoolean(), Boolean.class); } else if (vNode.getNodeType() == JsonNodeType.STRING) { cda = new CustomAttribute<String>(currentName, vNode.asText(), String.class); } else if (vNode.getNodeType() == JsonNodeType.NUMBER) { final NumericNode nNode = (NumericNode) vNode; if (currentName.endsWith("_at")) { cda = new CustomAttribute<Long>(currentName, vNode.longValue(), Long.class); } else if (nNode.isInt()) { cda = new CustomAttribute<Integer>(currentName, vNode.intValue(), Integer.class); } else if (nNode.isFloat()) { cda = new CustomAttribute<Float>(currentName, vNode.floatValue(), Float.class); } else if (nNode.isDouble()) { cda = new CustomAttribute<Double>(currentName, vNode.doubleValue(), Double.class); } else if (nNode.isLong()) { cda = new CustomAttribute<Long>(currentName, vNode.longValue(), Long.class); } else { cda = new CustomAttribute<String>(currentName, vNode.asText(), String.class); } } else { cda = new CustomAttribute<String>(currentName, vNode.asText(), String.class); } } return cda; }
@Test public void nextSibling_ArrayNode() throws IOException { String jsonString = "{\"x\":[1,2,3,4]}"; JsonNode node = JsonUtils.json(jsonString); JsonNodeCursor c = new JsonNodeCursor(new Path(""), node); Assert.assertTrue(c.firstChild()); Assert.assertTrue(c.firstChild()); Assert.assertNotNull(c.getCurrentNode()); Assert.assertTrue(c.getCurrentNode() instanceof NumericNode); Assert.assertEquals("x.0", c.getCurrentPath().toString()); }
@Override public void validate(NumberOverlay overlay, ValidationResults results) { super.validate(overlay, results, NumericNode.class); }
private IsJsonNumber(final Matcher<?> numberMatcher, final Function<NumericNode, Object> projection) { super(JsonNodeType.NUMBER); this.numberMatcher = Objects.requireNonNull(numberMatcher); this.projection = Objects.requireNonNull(projection); }
public static Matcher<JsonNode> jsonInt(int number) { return new IsJsonNumber(is(number), NumericNode::asInt); }
public static Matcher<JsonNode> jsonInt(Matcher<? super Integer> numberMatcher) { return new IsJsonNumber(numberMatcher, NumericNode::asInt); }
public static Matcher<JsonNode> jsonLong(long number) { return new IsJsonNumber(is(number), NumericNode::asLong); }
public static Matcher<JsonNode> jsonLong(Matcher<? super Long> numberMatcher) { return new IsJsonNumber(numberMatcher, NumericNode::asLong); }
public static Matcher<JsonNode> jsonBigInteger(BigInteger number) { return new IsJsonNumber(is(number), NumericNode::bigIntegerValue); }
public static Matcher<JsonNode> jsonBigInteger(Matcher<? super BigInteger> numberMatcher) { return new IsJsonNumber(numberMatcher, NumericNode::bigIntegerValue); }
public static Matcher<JsonNode> jsonFloat(float number) { return new IsJsonNumber(is(number), NumericNode::floatValue); }
public static Matcher<JsonNode> jsonFloat(Matcher<? super Float> numberMatcher) { return new IsJsonNumber(numberMatcher, NumericNode::floatValue); }
public static Matcher<JsonNode> jsonDouble(double number) { return new IsJsonNumber(is(number), NumericNode::asDouble); }
public static Matcher<JsonNode> jsonDouble(Matcher<? super Double> numberMatcher) { return new IsJsonNumber(numberMatcher, NumericNode::asDouble); }
public static Matcher<JsonNode> jsonBigDecimal(BigDecimal number) { return new IsJsonNumber(is(number), NumericNode::decimalValue); }
public static Matcher<JsonNode> jsonBigDecimal(Matcher<? super BigDecimal> numberMatcher) { return new IsJsonNumber(numberMatcher, NumericNode::decimalValue); }
public static Matcher<JsonNode> jsonNumber(NumericNode value) { return IsJsonNumber.jsonNumber(value); }
private NumericNode processNumericNode(JsonNode numericNode) { int value = numericNode.asInt(); return JsonNodeFactory.instance.numberNode(value); }
public InvocationMessage(long requestID, NumericNode registrationID, ObjectNode details, ArrayNode arguments){ this(requestID, registrationID, details, arguments, null); }
public InvocationMessage(long requestID, NumericNode registrationID, ObjectNode details){ this(requestID, registrationID, details, null, null); }
static NumericNode numericNode(ArrayNode array, int index) throws InvalidMessageException{ JsonNode node = array.get(index); if(!node.isNumber()) throw new InvalidMessageException(); return (NumericNode)node; }
private static <T> T visit(JsonNode node, JsonTreeVisitor<T> visitor) { switch (node.getNodeType()) { case OBJECT: Preconditions.checkArgument(node instanceof ObjectNode, "Expected instance of ObjectNode: " + node); // use LinkedHashMap to preserve field order Map<String, T> fields = Maps.newLinkedHashMap(); Iterator<Map.Entry<String, JsonNode>> iter = node.fields(); while (iter.hasNext()) { Map.Entry<String, JsonNode> entry = iter.next(); visitor.recordLevels.push(entry.getKey()); fields.put(entry.getKey(), visit(entry.getValue(), visitor)); visitor.recordLevels.pop(); } return visitor.object((ObjectNode) node, fields); case ARRAY: Preconditions.checkArgument(node instanceof ArrayNode, "Expected instance of ArrayNode: " + node); List<T> elements = Lists.newArrayListWithExpectedSize(node.size()); for (JsonNode element : node) { elements.add(visit(element, visitor)); } return visitor.array((ArrayNode) node, elements); case BINARY: Preconditions.checkArgument(node instanceof BinaryNode, "Expected instance of BinaryNode: " + node); return visitor.binary((BinaryNode) node); case STRING: Preconditions.checkArgument(node instanceof TextNode, "Expected instance of TextNode: " + node); return visitor.text((TextNode) node); case NUMBER: Preconditions.checkArgument(node instanceof NumericNode, "Expected instance of NumericNode: " + node); return visitor.number((NumericNode) node); case BOOLEAN: Preconditions.checkArgument(node instanceof BooleanNode, "Expected instance of BooleanNode: " + node); return visitor.bool((BooleanNode) node); case MISSING: Preconditions.checkArgument(node instanceof MissingNode, "Expected instance of MissingNode: " + node); return visitor.missing((MissingNode) node); case NULL: Preconditions.checkArgument(node instanceof NullNode, "Expected instance of NullNode: " + node); return visitor.nullNode((NullNode) node); default: throw new IllegalArgumentException( "Unknown node type: " + node.getNodeType() + ": " + node); } }
@Override public OpaqueFieldValue createNilValue() { NumericNode jsonNode = JsonNodeFactory.instance.numberNode(0); return new JsonLiteralFieldValue(jsonNode); }
private Object extractValue(JsonNode node) { switch (node.getNodeType()) { case ARRAY: case POJO: case OBJECT: { throw new LmRuntimeException("Expected a value node"); } case MISSING: case NULL: { return null; } case BINARY: case STRING: { return node.asText(); } case BOOLEAN: { return node.asBoolean(); } case NUMBER: { NumericNode numericNode = (NumericNode) node; switch (numericNode.numberType()) { case INT: { return numericNode.intValue(); } case LONG: { return numericNode.longValue(); } case FLOAT: { return numericNode.floatValue(); } case DOUBLE: { return numericNode.doubleValue(); } case BIG_INTEGER: { return numericNode.bigIntegerValue(); } case BIG_DECIMAL: { return numericNode.decimalValue(); } // intentionally fall through } } default: { throw new LmRuntimeException("Unexpected JSON node type: " + node.getNodeType()); } } }
@Test public void next() throws IOException { String jsonString = "{\"text\":\"value\",\"parent\":{\"array\":[1,2,3,4],\"object\":{\"foo\":\"bar\"}}}"; MutablePath p = new MutablePath(); JsonNode node = JsonUtils.json(jsonString); JsonNodeCursor c = new JsonNodeCursor(new Path(""), node); // simply going to walk through the document with next() and verify after each call manually Assert.assertTrue(c.next()); Assert.assertNotNull(c.getCurrentNode()); Assert.assertEquals("text", c.getCurrentPath().toString()); Assert.assertEquals("value", c.getCurrentNode().asText()); p.push("parent"); Assert.assertTrue(c.next()); Assert.assertNotNull(c.getCurrentNode()); Assert.assertEquals(p.toString(), c.getCurrentPath().toString()); Assert.assertTrue(c.getCurrentNode() instanceof ObjectNode); p.push("array"); Assert.assertTrue(c.next()); Assert.assertNotNull(c.getCurrentNode()); Assert.assertEquals(p.toString(), c.getCurrentPath().toString()); Assert.assertTrue(c.getCurrentNode() instanceof ArrayNode); p.push("0"); Assert.assertTrue(c.next()); Assert.assertNotNull(c.getCurrentNode()); Assert.assertEquals(p.toString(), c.getCurrentPath().toString()); Assert.assertTrue(c.getCurrentNode() instanceof NumericNode); Assert.assertEquals(1, c.getCurrentNode().asInt()); p.setLast("1"); Assert.assertTrue(c.next()); Assert.assertNotNull(c.getCurrentNode()); Assert.assertEquals(p.toString(), c.getCurrentPath().toString()); Assert.assertTrue(c.getCurrentNode() instanceof NumericNode); Assert.assertEquals(2, c.getCurrentNode().asInt()); p.setLast("2"); Assert.assertTrue(c.next()); Assert.assertNotNull(c.getCurrentNode()); Assert.assertEquals(p.toString(), c.getCurrentPath().toString()); Assert.assertTrue(c.getCurrentNode() instanceof NumericNode); Assert.assertEquals(3, c.getCurrentNode().asInt()); p.setLast("3"); Assert.assertTrue(c.next()); Assert.assertNotNull(c.getCurrentNode()); Assert.assertEquals(p.toString(), c.getCurrentPath().toString()); Assert.assertTrue(c.getCurrentNode() instanceof NumericNode); Assert.assertEquals(4, c.getCurrentNode().asInt()); p.pop(); p.pop(); p.push("object"); Assert.assertTrue(c.next()); Assert.assertNotNull(c.getCurrentNode()); Assert.assertEquals(p.toString(), c.getCurrentPath().toString()); Assert.assertTrue(c.getCurrentNode() instanceof ObjectNode); p.push("foo"); Assert.assertTrue(c.next()); Assert.assertNotNull(c.getCurrentNode()); Assert.assertEquals(p.toString(), c.getCurrentPath().toString()); Assert.assertTrue(c.getCurrentNode() instanceof TextNode); Assert.assertEquals("bar", c.getCurrentNode().asText()); Assert.assertFalse(c.next()); }
public static NumericNode jsn(int val) { return factory.numberNode(val); }