Java Code Examples for com.fasterxml.jackson.databind.JsonNode#isIntegralNumber()

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#isIntegralNumber() . 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: BuiltinFunctions.java    From jslt with Apache License 2.0 6 votes vote down vote up
public JsonNode call(JsonNode input, JsonNode[] arguments) {
  JsonNode array = arguments[0];
  if (array.isNull())
    return NullNode.instance;
  else if (!array.isArray())
    throw new JsltException("sum(): argument must be array, was " + array);

  double sum = 0.0;
  boolean integral = true;
  for (int ix = 0; ix < array.size(); ix++) {
    JsonNode value = array.get(ix);
    if (!value.isNumber())
      throw new JsltException("sum(): array must contain numbers, found " + value);
    integral &= value.isIntegralNumber();

    sum += value.doubleValue();
  }
  if (integral)
    return new LongNode((long) sum);
  else
    return new DoubleNode(sum);
}
 
Example 2
Source File: EqualsComparison.java    From jslt with Apache License 2.0 6 votes vote down vote up
static boolean equals(JsonNode v1, JsonNode v2) {
  boolean result;
  if (v1.isNumber() && v2.isNumber()) {
    // unfortunately, comparison of numeric nodes in Jackson is
    // deliberately less helpful than what we need here. so we have
    // to develop our own support for it.
    // https://github.com/FasterXML/jackson-databind/issues/1758

    if (v1.isIntegralNumber() && v2.isIntegralNumber())
      // if both are integers, then compare them as such
      return v1.longValue() == v2.longValue();
    else
      return v1.doubleValue() == v2.doubleValue();
  } else
    return v1.equals(v2);
}
 
Example 3
Source File: DivideOperator.java    From jslt with Apache License 2.0 6 votes vote down vote up
public JsonNode perform(JsonNode v1, JsonNode v2) {
  if (v1.isNull() || v2.isNull())
    return NullNode.instance;

  // we only support the numeric operation and nothing else
  v1 = NodeUtils.number(v1, true, location);
  v2 = NodeUtils.number(v2, true, location);

  if (v1.isIntegralNumber() && v2.isIntegralNumber()) {
    long l1 = v1.longValue();
    long l2 = v2.longValue();
    if (l1 % l2 == 0)
      return new LongNode(l1 / l2);
    else
      return new DoubleNode((double) l1 / (double) l2);
  } else
    return new DoubleNode(perform(v1.doubleValue(), v2.doubleValue()));
}
 
Example 4
Source File: Community.java    From batfish with Apache License 2.0 6 votes vote down vote up
@JsonCreator
private static Community create(@Nullable JsonNode node) {
  checkArgument(node != null && !node.isNull(), "Invalid value for BGP community");
  if (node.isIntegralNumber()) {
    // Backwards compatible with previous long representation
    return StandardCommunity.of(node.longValue());
  }
  if (!node.isTextual()) {
    throw new IllegalArgumentException(
        String.format("Invalid value for BGP community: %s", node));
  }
  String str = node.textValue();
  // Try each possible type
  switch (str.split(":").length) {
    case 2:
      return StandardCommunity.parse(str);
    case 3:
      return ExtendedCommunity.parse(str);
    case 4:
      return LargeCommunity.parse(str);
    default:
      throw new IllegalArgumentException(
          String.format("Invalid value for BGP community: %s", str));
  }
}
 
Example 5
Source File: TimestampParam.java    From digdag with Apache License 2.0 6 votes vote down vote up
@JsonCreator
public static TimestampParam parse(JsonNode expr)
{
    LocalTimeOrInstant timestamp;
    if (expr.isTextual()) {
        if (expr.asText().chars().allMatch(Character::isDigit)) {
            timestamp = LocalTimeOrInstant.of(Instant.ofEpochSecond(Long.parseLong(expr.asText())));
        }
        else {
            timestamp = LocalTimeOrInstant.fromString(expr.asText());
        }
    }
    else if (expr.isIntegralNumber()) {
        timestamp = LocalTimeOrInstant.of(Instant.ofEpochSecond(expr.asLong()));
    }
    else {
        throw new IllegalArgumentException("Not a valid timestamp: '" + expr + "'");
    }
    return new TimestampParam(timestamp);
}
 
Example 6
Source File: PutHBaseJSON.java    From nifi with Apache License 2.0 6 votes vote down vote up
private byte[] extractJNodeValue(final JsonNode n){
    if (n.isBoolean()){
        //boolean
        return clientService.toBytes(n.asBoolean());
    }else if(n.isNumber()){
        if(n.isIntegralNumber()){
            //interpret as Long
            return clientService.toBytes(n.asLong());
        }else{
            //interpret as Double
            return clientService.toBytes(n.asDouble());
        }
    }else{
        //if all else fails, interpret as String
        return clientService.toBytes(n.asText());
    }
}
 
Example 7
Source File: BeatsCodec.java    From graylog-plugin-beats with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
private Object valueNode(JsonNode jsonNode) {
    if (jsonNode.isInt()) {
        return jsonNode.asInt();
    } else if (jsonNode.isLong()) {
        return jsonNode.asLong();
    } else if (jsonNode.isIntegralNumber()) {
        return jsonNode.asLong();
    } else if (jsonNode.isFloatingPointNumber()) {
        return jsonNode.asDouble();
    } else if (jsonNode.isBoolean()) {
        return jsonNode.asBoolean();
    } else if (jsonNode.isNull()) {
        return null;
    } else {
        return jsonNode.asText();
    }
}
 
Example 8
Source File: TypeFactory.java    From json-schema-validator with Apache License 2.0 6 votes vote down vote up
public static JsonType getValueNodeType(JsonNode node) {
    if (node.isContainerNode()) {
        if (node.isObject())
            return JsonType.OBJECT;
        if (node.isArray())
            return JsonType.ARRAY;
        return JsonType.UNKNOWN;
    }

    if (node.isValueNode()) {
        if (node.isTextual())
            return JsonType.STRING;
        if (node.isIntegralNumber())
            return JsonType.INTEGER;
        if (node.isNumber())
            return JsonType.NUMBER;
        if (node.isBoolean())
            return JsonType.BOOLEAN;
        if (node.isNull())
            return JsonType.NULL;
        return JsonType.UNKNOWN;
    }

    return JsonType.UNKNOWN;
}
 
Example 9
Source File: MappingTest4.java    From jolt with Apache License 2.0 5 votes vote down vote up
/**
 * Demonstrates how to do recursive polymorphic JSON deserialization in Jackson 2.2.
 *
 * Aka specify a Deserializer and "catch" some input, determine what type of Class it
 *  should be parsed too, and then reuse the Jackson infrastructure to recursively do so.
 */
@Override
public QueryFilter4 deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException {

    ObjectNode root = jp.readValueAsTree();

    // pass in our objectCodec so that the subJsonParser knows about our configured Modules and Annotations
    JsonParser subJsonParser = root.traverse( jp.getCodec() );

    // Check if it is a "RealFilter"
    JsonNode valueParam = root.get("value");

    if ( valueParam == null ) {
         return subJsonParser.readValueAs( LogicalFilter4.class );
    }
    if ( valueParam.isBoolean() ) {
        return subJsonParser.readValueAs( BooleanRealFilter4.class );
    }
    else if ( valueParam.isTextual() ) {
        return subJsonParser.readValueAs( StringRealFilter4.class );
    }
    else if ( valueParam.isIntegralNumber() ) {
        return subJsonParser.readValueAs( IntegerRealFilter4.class );
    }
    else {
        throw new RuntimeException("Unknown type");
    }
}
 
Example 10
Source File: MaxItemsValidator.java    From json-schema-validator with Apache License 2.0 5 votes vote down vote up
public MaxItemsValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
    super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.MAX_ITEMS, validationContext);
    if (schemaNode.isIntegralNumber()) {
        max = schemaNode.intValue();
    }

    parseErrorCode(getValidatorType().getErrorCodeKey());
}
 
Example 11
Source File: MinLengthValidator.java    From json-schema-validator with Apache License 2.0 5 votes vote down vote up
public MinLengthValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
    super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.MIN_LENGTH, validationContext);
    minLength = Integer.MIN_VALUE;
    if (schemaNode != null && schemaNode.isIntegralNumber()) {
        minLength = schemaNode.intValue();
    }

    parseErrorCode(getValidatorType().getErrorCodeKey());
}
 
Example 12
Source File: MaxLengthValidator.java    From json-schema-validator with Apache License 2.0 5 votes vote down vote up
public MaxLengthValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
    super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.MAX_LENGTH, validationContext);
    maxLength = Integer.MAX_VALUE;
    if (schemaNode != null && schemaNode.isIntegralNumber()) {
        maxLength = schemaNode.intValue();
    }

    parseErrorCode(getValidatorType().getErrorCodeKey());
}
 
Example 13
Source File: MaxPropertiesValidator.java    From json-schema-validator with Apache License 2.0 5 votes vote down vote up
public MaxPropertiesValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema,
                              ValidationContext validationContext) {
    super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.MAX_PROPERTIES, validationContext);
    if (schemaNode.isIntegralNumber()) {
        max = schemaNode.intValue();
    }

    parseErrorCode(getValidatorType().getErrorCodeKey());
}
 
Example 14
Source File: FloatConverter.java    From agrest with Apache License 2.0 5 votes vote down vote up
@Override
protected Float valueNonNull(JsonNode node) {
	if (node.isTextual()) {
		String value = node.asText();
		if ("NaN".equalsIgnoreCase(value)) {
			return Float.NaN;
		} else if ("infinity".equalsIgnoreCase(value) || "+infinity".equalsIgnoreCase(value)) {
			return Float.POSITIVE_INFINITY;
		} else if ("-infinity".equalsIgnoreCase(value)) {
			return Float.NEGATIVE_INFINITY;
		}
	}

	if (!node.isIntegralNumber() && !node.isFloatingPointNumber()) {
		throw new AgException(Status.BAD_REQUEST, "Expected numeric value, got: " + node.asText());
	}

	Double doubleValue = node.asDouble();
	if (Double.valueOf(0).equals(doubleValue)) {
		return 0f;
	}

	Double absDoubleValue = Math.abs(doubleValue);
	if (absDoubleValue < Float.MIN_VALUE || absDoubleValue > Float.MAX_VALUE) {
		throw new AgException(Status.BAD_REQUEST,
				"Value is either too small or too large for the java.lang.Float datatype: " + node.asText());
	}
	return doubleValue.floatValue();
}
 
Example 15
Source File: MinPropertiesValidator.java    From json-schema-validator with Apache License 2.0 5 votes vote down vote up
public MinPropertiesValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema,
                              ValidationContext validationContext) {
    super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.MIN_PROPERTIES, validationContext);
    if (schemaNode.isIntegralNumber()) {
        min = schemaNode.intValue();
    }

    parseErrorCode(getValidatorType().getErrorCodeKey());
}
 
Example 16
Source File: MessageFormats.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
@Override
public String asString(Object arg) {
  if (arg instanceof JsonNode) {
    JsonNode node = (JsonNode) arg;
    JsonNode decimal = currency(node);
    if (!decimal.isMissingNode()) {
      return decimal.asText();
    }
    switch (node.getNodeType()) {
      case BOOLEAN:
        return node.asBoolean() ? "true" : "false";
      case NULL:
      case MISSING:
        return "";
      case NUMBER:
        if (node.isBigInteger() || node.isBigDecimal()) {
          return node.asText();
        }
        return node.isIntegralNumber() ? Long.toString(node.longValue()) : Double.toString(node.doubleValue());
      case ARRAY:
      case OBJECT:
      case STRING:
      default:
        return node.asText();
    }
  }
  try {
    return super.asString(arg);
  } catch (Exception e) {
    return "";
  }
}
 
Example 17
Source File: NumberValue.java    From zentity with Apache License 2.0 5 votes vote down vote up
/**
 * Serialize the attribute value from a JsonNode object to a String object.
 *
 * @return
 */
@Override
public String serialize(JsonNode value) {
    if (value.isNull())
        return "null";
    else if (value.isIntegralNumber())
        return value.bigIntegerValue().toString();
    else if (value.isFloatingPointNumber())
        return String.valueOf(value.doubleValue());
    else
        return value.numberValue().toString();
}
 
Example 18
Source File: Utils.java    From link-move with Apache License 2.0 5 votes vote down vote up
/**
 * @return For strings, number and booleans - returns value of java.lang.Comparable#compareTo
 * @throws RuntimeException for other types
 */
public static int compare(JsonNode node1, JsonNode node2) {

    if (hasComparableType(node1) && hasComparableType(node2) && ofEqualTypes(node1, node2)) {
        switch (node1.getNodeType()) {
            case STRING: {
                return node1.textValue().compareTo(node2.textValue());
            }
            case BOOLEAN: {
                Boolean left = node1.asBoolean(), right = node2.asBoolean();
                return left.compareTo(right);
            }
            case NUMBER: {
                if (node1.isIntegralNumber()) {
                    Integer left = node1.asInt(), right = node2.asInt();
                    return left.compareTo(right);
                } else if (node1.isFloatingPointNumber()) {
                    Double left = node1.asDouble(), right = node2.asDouble();
                    return left.compareTo(right);
                }
                // fall through
            }
            default: {
                // fall through
            }
        }
    }
    throw new RuntimeException("Unsupported comparable type: " + node1.getNodeType().name());
}
 
Example 19
Source File: NumericOperator.java    From jslt with Apache License 2.0 5 votes vote down vote up
public JsonNode perform(JsonNode v1, JsonNode v2) {
  if (v1.isNull() || v2.isNull())
    return NullNode.instance;

  v1 = NodeUtils.number(v1, true, location);
  v2 = NodeUtils.number(v2, true, location);

  if (v1.isIntegralNumber() && v2.isIntegralNumber())
    return new LongNode(perform(v1.longValue(), v2.longValue()));
  else
    return new DoubleNode(perform(v1.doubleValue(), v2.doubleValue()));
}
 
Example 20
Source File: BuiltinFunctions.java    From jslt with Apache License 2.0 5 votes vote down vote up
public JsonNode call(JsonNode input, JsonNode[] arguments) {
  JsonNode dividend = arguments[0];
  if (dividend.isNull())
    return NullNode.instance;
  else if (!dividend.isNumber())
    throw new JsltException("mod(): dividend cannot be a non-number: " + dividend);

  JsonNode divisor = arguments[1];
  if (divisor.isNull())
    return NullNode.instance;
  else if (!divisor.isNumber())
    throw new JsltException("mod(): divisor cannot be a non-number: " + divisor);

  if (!dividend.isIntegralNumber() || !divisor.isIntegralNumber()) {
    throw new JsltException("mod(): operands must be integral types");
  } else {
    long D = dividend.longValue();
    long d = divisor.longValue();
    if (d == 0)
      throw new JsltException("mod(): cannot divide by zero");

    long r = D % d;
    if (r < 0) {
      if (d > 0)
        r += d;
      else
        r -= d;
    }

    return new LongNode(r);
  }
}