com.fasterxml.jackson.databind.node.NumericNode Java Examples

The following examples show how to use com.fasterxml.jackson.databind.node.NumericNode. 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: TsdbResult.java    From splicer with Apache License 2.0 6 votes vote down vote up
@Override
public Points deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
	TreeNode n = jp.getCodec().readTree(jp);
	Map<String, Object> points = new HashMap<>();
	Iterator<String> namesIter = n.fieldNames();
	while(namesIter.hasNext()) {
		String field = namesIter.next();
		TreeNode child = n.get(field);

		Object o;
		if (child instanceof DoubleNode || child instanceof FloatNode) {
			o = ((NumericNode) child).doubleValue();
		} else if (child instanceof IntNode || child instanceof LongNode) {
			o = ((NumericNode) child).longValue();
		} else {
			throw new MergeException("Unsupported Type, " + child.getClass());
		}

		points.put(field, o);
	}
	return new Points(points);
}
 
Example #2
Source File: BsonObjectIdToStringDeserializer.java    From mongodb-aggregate-query-support with Apache License 2.0 6 votes vote down vote up
@Override
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
  LOGGER.trace(">>>> BsonObjectIdToStringDeserializer::deserialize");
  JsonNode bsonNode = p.getCodec().readTree(p);
  JsonNode nodeValue = bsonNode.get(NODE_KEY);
  if(nodeValue == null) {
    // parse this as a regular String
    if(bsonNode instanceof NumericNode) {
      return bsonNode.asText();
    }
    else if(bsonNode instanceof ObjectNode) {
      return (String) jsonNodeDeserializer.deserializeJsonNode(bsonNode);
    }
    return bsonNode.textValue();
  }
  LOGGER.trace("<<<< BsonObjectIdToStringDeserializer::deserialize");
  return nodeValue.textValue();
}
 
Example #3
Source File: IsJsonNumber.java    From java-hamcrest with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #4
Source File: IsJsonNumber.java    From java-hamcrest with Apache License 2.0 5 votes vote down vote up
@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;
  }
}
 
Example #5
Source File: GeneralUtils.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Convert an opaque JSON node to Decimal using the most correct
 * conversion method.
 */
public static Decimal nodeToDecimal(JsonNode node) {
  JsonNodeType type = node.getNodeType();
  if (type == JsonNodeType.NUMBER) {
    return numericToDecimal((NumericNode)node);

  } else {
    try {
      return new Decimal(node.asText());
    } catch (ArithmeticException | NumberFormatException e) {
      // Fall through..
    }
  }
  return null;
}
 
Example #6
Source File: IsJsonObject.java    From java-hamcrest with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example #7
Source File: JacksonStringMapper.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Override
public String toString(T input) {
	JsonNode jsonNode = mapper.valueToTree(input);

	if (jsonNode instanceof TextNode) {
		return jsonNode.textValue();
	}
	if (jsonNode instanceof NumericNode) {
		return jsonNode.asText();
	}

	// fallback to String for complex type
	return input.toString();
}
 
Example #8
Source File: GeneralUtils.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #9
Source File: GeneralUtils.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a numeric JSON node to Decimal using the most correct
 * conversion method.
 */
private static Decimal numericToDecimal(NumericNode node) {
  switch (node.numberType()) {
    case INT:
    case LONG:
      return new Decimal(node.asLong());
    case FLOAT:
    case DOUBLE:
      return new Decimal(node.asDouble());
    case BIG_DECIMAL:
    case BIG_INTEGER:
    default:
      return new Decimal(node.decimalValue().toString());
  }
}
 
Example #10
Source File: GeneralUtils.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
  }
}
 
Example #11
Source File: SanskritObjectImpl.java    From terracotta-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Long getLong(String key) {
  return Optional.ofNullable(mappings.get(key))
      .map(NumericNode.class::cast)
      .map(NumericNode::longValue)
      .orElse(null);
}
 
Example #12
Source File: InvocationMessage.java    From jlibs with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #13
Source File: CustomAttributeDeserializer.java    From intercom-java with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #14
Source File: JsonDataModelTree.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Gets integer on specific json pointer.
 *
 * @param ptr json pointer
 * @return integer on specific json pointer
 * @throws WorkflowException workflow exception
 */
public Integer intAt(JsonPointer ptr) throws WorkflowException {
    if (root == null || root instanceof MissingNode) {
        throw new WorkflowException("Invalid root node");
    }
    JsonNode node = root.at(ptr);
    if (node instanceof MissingNode) {
        return null;
    }
    if (!(node instanceof NumericNode)) {
        throw new WorkflowException("Invalid node(" + node + ") at " + ptr);
    }
    return ((NumericNode) node).asInt();
}
 
Example #15
Source File: RestAccessInfo.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Builds RestAccessInfo from json.
 * @param root json root node for RestAccessinfo
 * @return REST access information
 * @throws WorkflowException workflow exception
 */
public static RestAccessInfo valueOf(JsonNode root) throws WorkflowException {

    JsonNode node = root.at(ptr(REMOTE_IP));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid remoteIp for " + root);
    }
    IpAddress remoteIp = IpAddress.valueOf(node.asText());

    node = root.at(ptr(PORT));
    if (node == null || !(node instanceof NumericNode)) {
        throw new WorkflowException("invalid port for " + root);
    }
    TpPort tpPort = TpPort.tpPort(node.asInt());

    node = root.at(ptr(USER));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid user for " + root);
    }
    String strUser = node.asText();

    node = root.at(ptr(PASSWORD));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid password for " + root);
    }
    String strPassword = node.asText();

    return new RestAccessInfo(remoteIp, tpPort, strUser, strPassword);
}
 
Example #16
Source File: SshAccessInfo.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Builds SshAccessInfo from json.
 * @param root json root node for SshAccessinfo
 * @return SSH access information
 * @throws WorkflowException workflow exception
 */
public static SshAccessInfo valueOf(JsonNode root) throws WorkflowException {

    JsonNode node = root.at(ptr(REMOTE_IP));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid remoteIp for " + root);
    }
    IpAddress sshIp = IpAddress.valueOf(node.asText());

    node = root.at(ptr(PORT));
    if (node == null || !(node instanceof NumericNode)) {
        throw new WorkflowException("invalid port for " + root);
    }
    TpPort sshPort = TpPort.tpPort(node.asInt());

    node = root.at(ptr(USER));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid user for " + root);
    }
    String sshUser = node.asText();

    node = root.at(ptr(PASSWORD));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid password for " + root);
    }
    String sshPassword = node.asText();

    node = root.at(ptr(KEYFILE));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid keyfile for " + root);
    }
    String sshKeyfile = node.asText();

    return new SshAccessInfo(sshIp, sshPort, sshUser, sshPassword, sshKeyfile);
}
 
Example #17
Source File: NetconfAccessInfo.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Builds NetconfAccessInfo from json.
 * @param root json root node for NetconfAccessinfo
 * @return NETCONF access information
 * @throws WorkflowException workflow exception
 */
public static NetconfAccessInfo valueOf(JsonNode root) throws WorkflowException {

    JsonNode node = root.at(ptr(REMOTE_IP));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid remoteIp for " + root);
    }
    IpAddress remoteIp = IpAddress.valueOf(node.asText());

    node = root.at(ptr(PORT));
    if (node == null || !(node instanceof NumericNode)) {
        throw new WorkflowException("invalid port for " + root);
    }
    TpPort tpPort = TpPort.tpPort(node.asInt());

    node = root.at(ptr(USER));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid user for " + root);
    }
    String strUser = node.asText();

    node = root.at(ptr(PASSWORD));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid password for " + root);
    }
    String strPassword = node.asText();

    return new NetconfAccessInfo(remoteIp, tpPort, strUser, strPassword);
}
 
Example #18
Source File: JsonCompareUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@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();
        if (d1.compareTo(d2) == 0) {
            return 0;
        }
    }
    return 1;
}
 
Example #19
Source File: EtherJsonDeserializer.java    From etherjar with Apache License 2.0 5 votes vote down vote up
protected BigInteger getQuantity(JsonNode node) {
    if (node instanceof NumericNode) {
        return BigInteger.valueOf(node.longValue());
    }
    String value = getHexString(node);
    if (value == null) return null;
    if (!value.startsWith("0x")) {
        return new BigInteger(value, 10);
    }
    return HexEncoding.fromHex(value);
}
 
Example #20
Source File: JacksonScalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private static Map<Type, GraphQLScalarType> getScalarMapping() {
    Map<Type, GraphQLScalarType> scalarMapping = new HashMap<>();
    scalarMapping.put(TextNode.class, JsonTextNode);
    scalarMapping.put(BooleanNode.class, JsonBooleanNode);
    scalarMapping.put(BinaryNode.class, JsonBinaryNode);
    scalarMapping.put(BigIntegerNode.class, JsonBigIntegerNode);
    scalarMapping.put(IntNode.class, JsonIntegerNode);
    scalarMapping.put(ShortNode.class, JsonShortNode);
    scalarMapping.put(DecimalNode.class, JsonDecimalNode);
    scalarMapping.put(FloatNode.class, JsonFloatNode);
    scalarMapping.put(DoubleNode.class, JsonDoubleNode);
    scalarMapping.put(NumericNode.class, JsonDecimalNode);
    return Collections.unmodifiableMap(scalarMapping);
}
 
Example #21
Source File: JacksonModule.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp(SetupContext context) {
    if (!getTypeMappers().isEmpty()) {
        context.getSchemaGenerator().withTypeMappersPrepended(getTypeMappers().toArray(new TypeMapper[0]));
    }
    if (!getOutputConverters().isEmpty()) {
        context.getSchemaGenerator().withOutputConvertersPrepended(getOutputConverters().toArray(new OutputConverter[0]));
    }
    if (!getInputConverters().isEmpty()) {
        context.getSchemaGenerator().withInputConvertersPrepended(getInputConverters().toArray(new InputConverter[0]));
    }
    context.getSchemaGenerator().withTypeComparators(new SynonymBaseTypeComparator(ObjectNode.class, POJONode.class));
    context.getSchemaGenerator().withTypeComparators(new SynonymBaseTypeComparator(DecimalNode.class, NumericNode.class));
}
 
Example #22
Source File: IsJsonNumber.java    From java-hamcrest with Apache License 2.0 4 votes vote down vote up
public static Matcher<JsonNode> jsonInt(Matcher<? super Integer> numberMatcher) {
  return new IsJsonNumber(numberMatcher, NumericNode::asInt);
}
 
Example #23
Source File: JsonUtil.java    From kite with Apache License 2.0 4 votes vote down vote up
@edu.umd.cs.findbugs.annotations.SuppressWarnings(
    value="BC_UNCONFIRMED_CAST",
    justification="Uses precondition to validate casts")
public 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);
  }
}
 
Example #24
Source File: JsonBuilder.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
public static NumericNode jsn(long val) {
  return factory.numberNode(val);
}
 
Example #25
Source File: JsonBuilder.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
public static NumericNode jsn(int val) {
  return factory.numberNode(val);
}
 
Example #26
Source File: JsonBuilder.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
public static NumericNode jsn(long val) {
  return factory.numberNode(val);
}
 
Example #27
Source File: JsonBuilder.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
public static NumericNode jsn(int val) {
  return factory.numberNode(val);
}
 
Example #28
Source File: JsonWrittenEventProvider.java    From tasmo with Apache License 2.0 4 votes vote down vote up
@Override
public OpaqueFieldValue createNilValue() {
    NumericNode jsonNode = JsonNodeFactory.instance.numberNode(0);
    return new JsonLiteralFieldValue(jsonNode);
}
 
Example #29
Source File: DistributedWorkplaceStore.java    From onos with Apache License 2.0 4 votes vote down vote up
@Activate
public void activate() {

    appId = coreService.registerApplication("org.onosproject.workplacestore");
    log.info("appId=" + appId);

    KryoNamespace workplaceNamespace = KryoNamespace.newBuilder()
            .register(KryoNamespaces.API)
            .register(WorkflowData.class)
            .register(Workplace.class)
            .register(DefaultWorkplace.class)
            .register(WorkflowContext.class)
            .register(DefaultWorkflowContext.class)
            .register(SystemWorkflowContext.class)
            .register(WorkflowState.class)
            .register(ProgramCounter.class)
            .register(DataModelTree.class)
            .register(JsonDataModelTree.class)
            .register(List.class)
            .register(ArrayList.class)
            .register(JsonNode.class)
            .register(ObjectNode.class)
            .register(TextNode.class)
            .register(LinkedHashMap.class)
            .register(ArrayNode.class)
            .register(BaseJsonNode.class)
            .register(BigIntegerNode.class)
            .register(BinaryNode.class)
            .register(BooleanNode.class)
            .register(ContainerNode.class)
            .register(DecimalNode.class)
            .register(DoubleNode.class)
            .register(FloatNode.class)
            .register(IntNode.class)
            .register(JsonNodeType.class)
            .register(LongNode.class)
            .register(MissingNode.class)
            .register(NullNode.class)
            .register(NumericNode.class)
            .register(POJONode.class)
            .register(ShortNode.class)
            .register(ValueNode.class)
            .register(JsonNodeCreator.class)
            .register(JsonNodeFactory.class)
            .build();

    localWorkplaceMap.clear();
    workplaceMap = storageService.<String, WorkflowData>consistentMapBuilder()
            .withSerializer(Serializer.using(workplaceNamespace))
            .withName("workplace-map")
            .withApplicationId(appId)
            .build();
    workplaceMap.addListener(workplaceMapEventListener);

    localContextMap.clear();
    contextMap = storageService.<String, WorkflowData>consistentMapBuilder()
            .withSerializer(Serializer.using(workplaceNamespace))
            .withName("workflow-context-map")
            .withApplicationId(appId)
            .build();
    contextMap.addListener(contextMapEventListener);

    workplaceMapEventListener.syncLocal();
    contextMapEventListener.syncLocal();
    log.info("Started");
}
 
Example #30
Source File: IsJsonNumber.java    From java-hamcrest with Apache License 2.0 4 votes vote down vote up
private IsJsonNumber(final Matcher<?> numberMatcher,
                     final Function<NumericNode, Object> projection) {
  super(JsonNodeType.NUMBER);
  this.numberMatcher = Objects.requireNonNull(numberMatcher);
  this.projection = Objects.requireNonNull(projection);
}