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

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#isNumber() . 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: ModelLoader.java    From aws-sdk-java-resources with Apache License 2.0 6 votes vote down vote up
private static ServiceModel loadV1Model(JsonNode tree, JsonNode version)
        throws JsonProcessingException {

    JsonNode minor = version.get("Minor");
    if (minor == null || !minor.isNumber()) {
        throw new IllegalStateException("No Minor version found");
    }
    if (minor.asInt() < 0) {
        throw new IllegalStateException("Invalid minor version: "
                + minor.asInt());
    }

    if (minor.asInt() > LATEST_V1_MINOR_VERSION) {
        throw new IllegalStateException(
                "Unknown minor version " + minor.asInt() + ". Perhaps "
                + "you need a newer version of the resources runtime?");
    }

    JsonNode service = tree.get("Service");
    if (service == null) {
        throw new IllegalStateException("No Service found");
    }

    return MAPPER.treeToValue(service, ServiceModel.class);
}
 
Example 2
Source File: ServiceParameters.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link ServiceParameters} instance based on all properties in the given
 * object node. Only numbers, text and boolean values are added, nested object structures
 * are ignored.
 */
public static ServiceParameters fromObjectNode(ObjectNode node) {
	ServiceParameters parameters = new ServiceParameters();
	
	Iterator<String> ir = node.fieldNames();
	String name = null;
	JsonNode value = null; 
	while(ir.hasNext()) {
		name = ir.next();
		value = node.get(name);
		
		// Depending on the type, extract the raw value object
		if(value != null) {
			if(value.isNumber()) {
				parameters.addParameter(name, value.numberValue());
			} else if(value.isBoolean()) {
				parameters.addParameter(name, value.booleanValue());
			} else if(value.isTextual()) {
				parameters.addParameter(name, value.textValue());
			}
		}
	}
  return parameters;
 }
 
Example 3
Source File: ServiceParameters.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link ServiceParameters} instance based on all properties in the given object node. Only numbers, text and boolean values are added, nested object structures are ignored.
 */
public static ServiceParameters fromObjectNode(ObjectNode node) {
    ServiceParameters parameters = new ServiceParameters();

    Iterator<String> ir = node.fieldNames();
    String name = null;
    JsonNode value = null;
    while (ir.hasNext()) {
        name = ir.next();
        value = node.get(name);

        // Depending on the type, extract the raw value object
        if (value != null) {
            if (value.isNumber()) {
                parameters.addParameter(name, value.numberValue());
            } else if (value.isBoolean()) {
                parameters.addParameter(name, value.booleanValue());
            } else if (value.isTextual()) {
                parameters.addParameter(name, value.textValue());
            }
        }
    }
    return parameters;
}
 
Example 4
Source File: EditEntityDialog.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 6 votes vote down vote up
private Object readValue(JsonNode node) {
    if (node.isFloatingPointNumber()) {
        return node.asDouble();
    } else if (node.isNumber()) {
        return node.asLong();
    } else if (node.isBoolean()) {
        return node.asBoolean();
    } else if (node.isTextual()) {
        return node.asText();
    } else if (node.isArray()) {
        return StreamSupport.stream(node.spliterator(), false)
                .map(this::readValue)
                .collect(toList());
    }

    return node.toString();
}
 
Example 5
Source File: Int8TypeParser.java    From connect-utils with Apache License 2.0 6 votes vote down vote up
@Override
public Object parseJsonNode(JsonNode input, Schema schema) {
  Object result;
  if (input.isNumber()) {
    result = input.bigIntegerValue().byteValue();
  } else if (input.isTextual()) {
    result = parseString(input.textValue(), schema);
  } else {
    throw new UnsupportedOperationException(
        String.format(
            "Could not parse '%s' to %s",
            input,
            this.expectedClass().getSimpleName()
        )
    );
  }
  return result;
}
 
Example 6
Source File: MultipleOfValidator.java    From json-schema-validator with Apache License 2.0 6 votes vote down vote up
public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
    debug(logger, node, rootNode, at);

    if (node.isNumber()) {
        double nodeValue = node.doubleValue();
        if (divisor != 0) {
            // convert to BigDecimal since double type is not accurate enough to do the division and multiple
            BigDecimal accurateDividend = new BigDecimal(String.valueOf(nodeValue));
            BigDecimal accurateDivisor = new BigDecimal(String.valueOf(divisor));
            if (accurateDividend.divideAndRemainder(accurateDivisor)[1].abs().compareTo(BigDecimal.ZERO) > 0) {
                return Collections.singleton(buildValidationMessage(at, "" + divisor));
            }
        }
    }

    return Collections.emptySet();
}
 
Example 7
Source File: RangeBoundValueDeserializer.java    From presto with Apache License 2.0 6 votes vote down vote up
private Object toValue(JsonNode node)
        throws IOException
{
    if (node.isTextual()) {
        return node.asText();
    }
    else if (node.isNumber()) {
        return node.numberValue();
    }
    else if (node.isBoolean()) {
        return node.asBoolean();
    }
    else if (node.isBinary()) {
        return node.binaryValue();
    }
    else {
        throw new IllegalStateException("Unexpected range bound value: " + node);
    }
}
 
Example 8
Source File: NodeUtils.java    From jslt with Apache License 2.0 5 votes vote down vote up
public static boolean isTrue(JsonNode value) {
  return value != BooleanNode.FALSE &&
    !(value.isObject() && value.size() == 0) &&
    !(value.isTextual() && value.asText().length() == 0) &&
    !(value.isArray() && value.size() == 0) &&
    !(value.isNumber() && value.doubleValue() == 0.0) &&
    !value.isNull();
}
 
Example 9
Source File: JsonHelpers.java    From samantha with MIT License 5 votes vote down vote up
/**
 * @return a double from the input JsonNode with the given name, or throw an BadRequestException
 */
public static double getRequiredDouble(JsonNode json, String name) throws BadRequestException {
    JsonNode node = json.get(name);
    if (node == null || !node.isNumber()) {
        throw new BadRequestException("json is missing required double: " + name);
    }
    return node.asDouble();
}
 
Example 10
Source File: Json.java    From immutables with Apache License 2.0 5 votes vote down vote up
private static SearchTotal parseSearchTotal(JsonNode node) {

      final Number value;
      if (node.isNumber()) {
        value = node.numberValue();
      } else {
        value = node.get("value").numberValue();
      }

      return new SearchTotal(value.longValue());
    }
 
Example 11
Source File: EnumValidator.java    From json-schema-validator with Apache License 2.0 5 votes vote down vote up
public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
    debug(logger, node, rootNode, at);

    Set<ValidationMessage> errors = new LinkedHashSet<ValidationMessage>();
    if (node.isNumber()) node = DecimalNode.valueOf(node.decimalValue());
    if (!nodes.contains(node) && !(config.isTypeLoose() && isTypeLooseContainsInEnum(node))) {
        errors.add(buildValidationMessage(at, error));
    }

    return Collections.unmodifiableSet(errors);
}
 
Example 12
Source File: JSONMatchers.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matchesSafely(JsonNode item, Description desc) {
    if (item.isNumber()) {
        return true;
    } else {
        return describeNodeType(item, desc);
    }
}
 
Example 13
Source File: SizeParser.java    From agrest with Apache License 2.0 5 votes vote down vote up
@Override
public Integer startFromJson(JsonNode json) {

    if (json != null) {
        if (!json.isNumber()) {
            throw new AgException(Response.Status.BAD_REQUEST, "Expected 'int' as 'start' value, got: " + json);
        }

        return json.asInt();
    }

    return null;
}
 
Example 14
Source File: Id.java    From digdag with Apache License 2.0 5 votes vote down vote up
@JsonCreator
@Deprecated
static Id fromJson(JsonNode node)
        throws JsonMappingException
{
    if (node.isTextual() || node.isNumber()) {
        return of(node.asText());
    }
    else {
        throw new JsonMappingException("Invalid ID. Expected string but got " + node);
    }
}
 
Example 15
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 number = arguments[0];
  if (number.isNull())
    return NullNode.instance;
  else if (!number.isNumber())
    throw new JsltException("round() cannot round a non-number: " + number);

  return new LongNode(Math.round(number.doubleValue()));
}
 
Example 16
Source File: FunctionWrapper.java    From jslt with Apache License 2.0 4 votes vote down vote up
public Object convert(JsonNode node) {
  if (!node.isNumber())
    throw new JsltException("Cannot convert " + node + " to int");
  else
    return node.asInt();
}
 
Example 17
Source File: MinimumValidator.java    From json-schema-validator with Apache License 2.0 4 votes vote down vote up
public MinimumValidator(String schemaPath, final JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
    super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.MINIMUM, validationContext);

    if (!schemaNode.isNumber()) {
        throw new JsonSchemaException("minimum value is not a number");
    }

    JsonNode exclusiveMinimumNode = getParentSchema().getSchemaNode().get(PROPERTY_EXCLUSIVE_MINIMUM);
    if (exclusiveMinimumNode != null && exclusiveMinimumNode.isBoolean()) {
        excludeEqual = exclusiveMinimumNode.booleanValue();
    }

    parseErrorCode(getValidatorType().getErrorCodeKey());

    final String minimumText = schemaNode.asText();
    if ((schemaNode.isLong() || schemaNode.isInt()) && JsonType.INTEGER.toString().equals(getNodeFieldType())) {
        // "integer", and within long range
        final long lmin = schemaNode.asLong();
        typedMinimum = new ThresholdMixin() {
            @Override
            public boolean crossesThreshold(JsonNode node) {
                if (node.isBigInteger()) {
                    //node.isBigInteger is not trustable, the type BigInteger doesn't mean it is a big number.
                    int compare = node.bigIntegerValue().compareTo(new BigInteger(minimumText));
                    return compare < 0 || (excludeEqual && compare == 0);

                } else if (node.isTextual()) {
                    BigDecimal min = new BigDecimal(minimumText);
                    BigDecimal value = new BigDecimal(node.asText());
                    int compare = value.compareTo(min);
                    return compare < 0 || (excludeEqual && compare == 0);

                }
                long val = node.asLong();
                return lmin > val || (excludeEqual && lmin == val);
            }

            @Override
            public String thresholdValue() {
                return String.valueOf(lmin);
            }
        };

    } else {
        typedMinimum = new ThresholdMixin() {
            @Override
            public boolean crossesThreshold(JsonNode node) {
                // jackson's BIG_DECIMAL parsing is limited. see https://github.com/FasterXML/jackson-databind/issues/1770
                if (schemaNode.isDouble() && schemaNode.doubleValue() == Double.NEGATIVE_INFINITY) {
                    return false;
                }
                if (schemaNode.isDouble() && schemaNode.doubleValue() == Double.POSITIVE_INFINITY) {
                    return true;
                }
                if (node.isDouble() && node.doubleValue() == Double.NEGATIVE_INFINITY) {
                    return true;
                }
                if (node.isDouble() && node.doubleValue() == Double.POSITIVE_INFINITY) {
                    return false;
                }
                final BigDecimal min = new BigDecimal(minimumText);
                BigDecimal value = new BigDecimal(node.asText());
                int compare = value.compareTo(min);
                return compare < 0 || (excludeEqual && compare == 0);
            }

            @Override
            public String thresholdValue() {
                return minimumText;
            }
        };
    }
}
 
Example 18
Source File: SearchQuery.java    From conciliator with GNU General Public License v3.0 4 votes vote down vote up
public SearchQuery(JsonNode queryStruct) {
    int limit = queryStruct.path("limit").asInt();
    if(limit == 0) {
        limit = 3;
    }

    String typeFromJson = queryStruct.path("type").asText();
    NameType nameType = null;
    if(typeFromJson != null && typeFromJson.length() > 0) {
        nameType = new NameType(typeFromJson, null);
    }

    String typeStrict = null;
    if(!queryStruct.path("type_strict").isMissingNode()) {
        typeStrict = queryStruct.path("type_strict").asText();
    }

    Map<String, PropertyValue> properties = new HashMap<>();
    if(!queryStruct.path("properties").isMissingNode()) {
        Iterator<JsonNode> propObjects = queryStruct.path("properties").elements();
        while(propObjects.hasNext()) {
            JsonNode prop = propObjects.next();
            String key = null;
            if(!prop.path("p").isMissingNode()) {
                key = prop.path("p").asText();
            } else if(!prop.path("pid").isMissingNode()) {
                key = prop.path("pid").asText();
            }

            JsonNode valNode = prop.path("v");
            PropertyValue val = null;
            if(!valNode.isMissingNode()) {
                if(valNode.isTextual()) {
                    val = new PropertyValueString(valNode.asText());
                } else if(valNode.isNumber()) {
                    val = new PropertyValueNumber(valNode.asLong());
                } else if(!valNode.path("id").isMissingNode()) {
                    val = new PropertyValueId(valNode.path("id").asText());
                }
            }

            properties.put(key, val);
        }
    }

    this.query = queryStruct.path("query").asText().trim();
    this.limit = limit;
    this.nameType = nameType;
    this.typeStrict = typeStrict;
    this.properties = properties;
}
 
Example 19
Source File: JsonNumEquals.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
@Override
protected int doHash(final JsonNode t) {
    /*
     * If this is a numeric node, we want the same hashcode for the same
     * mathematical values. Go with double, its range is good enough for
     * 99+% of use cases.
     */
    if (t.isNumber()) {
        return Double.valueOf(t.doubleValue()).hashCode();
    }

    /*
     * If this is a primitive type (other than numbers, handled above),
     * delegate to JsonNode.
     */
    if (!t.isContainerNode()) {
        return t.hashCode();
    }

    /*
     * The following hash calculations work, yes, but they are poor at best.
     * And probably slow, too.
     *
     * TODO: try and figure out those hash classes from Guava
     */
    int ret = 0;

    /*
     * If the container is empty, just return
     */
    if (t.size() == 0) {
        return ret;
    }

    /*
     * Array
     */
    if (t.isArray()) {
        for (final JsonNode element : t) {
            ret = 31 * ret + doHash(element);
        }
        return ret;
    }

    /*
     * Not an array? An object.
     */
    final Iterator<Map.Entry<String, JsonNode>> iterator = t.fields();

    Map.Entry<String, JsonNode> entry;

    while (iterator.hasNext()) {
        entry = iterator.next();
        ret = 31 * ret + (entry.getKey().hashCode() ^ doHash(entry.getValue()));
    }

    return ret;
}
 
Example 20
Source File: RevisionJsonDeserializer.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
@Override
public Revision deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
    final JsonNode node = p.readValueAsTree();
    if (node.isNumber()) {
        validateRevisionNumber(ctx, node, "major", false);
        return new Revision(node.intValue());
    }

    if (node.isTextual()) {
        try {
            return new Revision(node.textValue());
        } catch (IllegalArgumentException e) {
            ctx.reportInputMismatch(Revision.class, e.getMessage());
            // Should never reach here.
            throw new Error();
        }
    }

    if (!node.isObject()) {
        ctx.reportInputMismatch(Revision.class,
                                "A revision must be a non-zero integer or " +
                                "an object that contains \"major\" and \"minor\" properties.");
        // Should never reach here.
        throw new Error();
    }

    final JsonNode majorNode = node.get("major");
    final JsonNode minorNode = node.get("minor");
    final int major;

    validateRevisionNumber(ctx, majorNode, "major", false);
    major = majorNode.intValue();
    if (minorNode != null) {
        validateRevisionNumber(ctx, minorNode, "minor", true);
        if (minorNode.intValue() != 0) {
            ctx.reportInputMismatch(Revision.class,
                                    "A revision must not have a non-zero \"minor\" property.");
        }
    }

    return new Revision(major);
}