Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ This project does not adhere to [Semantic Versioning](https://semver.org/) and m
- Opt-in `ExecutionConfig.maxEvaluationSteps` and `maxEvaluationDepth` limits for validation and schema walking, including walking without assertions. Exhaustion throws `ValidationLimitExceededException` instead of returning a partial validity result. Both limits default to unlimited; they bound admitted evaluation steps and schema frames, not work inside a keyword. (#1276)

### Changed
- `MultipleOfValidator.getDivisor` and `getDividend` now preserve exact integral and BigDecimal values. Custom validators, including overrides calling `super`, receive these exact values; validation uses hook results without further rounding. Integral dividend scales can change (for example, `2.0` becomes `2`), which affects scale-sensitive comparisons in overrides. Mixed integral/Double or Float inputs above 2^53 can produce different results. Precision already lost when parsing floating-point values is tracked separately in #1293. (#1286)
- Extend document-root unknown-keyword suppression to external `$ref` JSON Pointer targets. Keep container and direct-schema caches separate so direct registry loads retain normal diagnostics regardless of registry load order, including rejection by `DisallowUnknownKeywordFactory`. Within one schema, a whole-document reference following a JSON Pointer reference can still reuse the container and suppress root diagnostics, including strict-factory rejection. Apply the container annotation fallback after nullable/discriminator special handling and make the container marker volatile. (#1325)
- Treat unknown document-root fields as annotations when loading a schema by JSON Pointer fragment, while preserving known keyword processing and diagnostics in subschemas. With `DisallowUnknownKeywordFactory`, such fragment loads now succeed instead of throwing on unknown root fields; direct document loads still throw. If the selected schema references the root with `$ref: "#"`, unknown root fields also remain annotations and do not reach the unknown-keyword factory. (#1205)
- Unlimited validation/walking bypasses execution counters and keeps the original recursion frame structure. During an active limited execution, reentrant convenience calls share the budget and the caller's evaluation path; unlimited calls retain their legacy root-path initialization.
Expand Down
119 changes: 105 additions & 14 deletions src/main/java/com/networknt/schema/keyword/MultipleOfValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,55 +25,143 @@
import com.networknt.schema.utils.JsonNodeTypes;

import java.math.BigDecimal;
import java.math.BigInteger;

/**
* {@link KeywordValidator} for multipleOf.
*/
public class MultipleOfValidator extends BaseKeywordValidator implements KeywordValidator {
private final BigDecimal divisor;
private final BigInteger denominator;
private final long longDivisor;
private final String divisorMessage;

public MultipleOfValidator(SchemaLocation schemaLocation, JsonNode schemaNode,
Schema parentSchema, SchemaContext schemaContext) {
super(KeywordType.MULTIPLE_OF, schemaNode, schemaLocation, parentSchema, schemaContext);
this.divisor = getDivisor(schemaNode);
this.denominator = this.divisor == null ? null : this.divisor.unscaledValue().abs();
this.longDivisor = integralDivisor(this.divisor);
this.divisorMessage = this.divisor == null ? null : this.divisor.toString();
}

public void validate(ExecutionContext executionContext, JsonNode node, JsonNode rootNode,
NodePath instanceLocation) {

if (this.divisor != null) {
BigDecimal dividend = getDividend(node);
if (dividend != null) {
if (dividend.divideAndRemainder(this.divisor)[1].abs().compareTo(BigDecimal.ZERO) > 0) {
executionContext.addError(error().instanceNode(node).instanceLocation(instanceLocation)
.evaluationPath(executionContext.getEvaluationPath()).locale(executionContext.getExecutionConfig().getLocale())
.arguments(this.divisor.toString()) // String is used as the MessageFormat NumberFormat considers 3 fractional digits by default
.build());
}
if (this.divisor == null) {
return;
}
BigDecimal dividend = getDividend(node);
if (dividend == null) {
return;
}
boolean invalid;
if (this.longDivisor != 0 && dividend.scale() >= 0 && dividend.precision() <= 19) {
// Check the hook result itself, including scaled integers, before using long arithmetic.
long value = dividend.longValue();
invalid = dividend.compareTo(BigDecimal.valueOf(value)) == 0
? value % this.longDivisor != 0
: !isMultipleOf(dividend, this.divisor, this.denominator);
} else {
invalid = !isMultipleOf(dividend, this.divisor, this.denominator);
}
if (invalid) {
executionContext.addError(error().instanceNode(node).instanceLocation(instanceLocation)
.evaluationPath(executionContext.getEvaluationPath()).locale(executionContext.getExecutionConfig().getLocale())
.arguments(this.divisorMessage) // Avoid MessageFormat NumberFormat rounding
.build());
}
}

private static long integralDivisor(BigDecimal value) {
if (value == null) {
return 0;
}
try {
return value.longValueExact();
} catch (ArithmeticException exception) {
return 0;
}
}

private static BigDecimal normalizeDivisor(BigDecimal value) {
try {
return value.stripTrailingZeros();
} catch (ArithmeticException exception) {
// Removing zeros at the minimum scale can overflow the scale range.
return value;
}
}

/**
* Checks divisibility without constructing exponent-sized powers or quotients.
*/
private static boolean isMultipleOf(BigDecimal dividend, BigDecimal divisor, BigInteger denominator) {
BigInteger numerator = dividend.unscaledValue();
if (numerator.signum() == 0) {
return true;
}
long scaleDifference = (long) divisor.scale() - dividend.scale();
if (scaleDifference < 0) {
long zeros = -scaleDifference;
// Bound constructed powers by the input coefficient size.
// 30103/100000 is an upper bound for log10(2).
BigInteger absoluteNumerator = numerator.abs();
long digitUpperBound = (absoluteNumerator.bitLength() * 30103L) / 100000 + 1;
if (zeros >= digitUpperBound || absoluteNumerator.getLowestSetBit() < zeros) {
return false;
}
BigInteger[] division = numerator.divideAndRemainder(BigInteger.TEN.pow((int) zeros));
return division[1].signum() == 0 && division[0].remainder(denominator).signum() == 0;
}
BigInteger remainder = numerator.remainder(denominator);
if (remainder.signum() == 0) {
return true;
}
if (scaleDifference == 0) {
return false;
}
// Small powers fit in a long; reserve modular exponentiation for larger scales.
BigInteger powerOfTen = scaleDifference <= 18 ? BigInteger.TEN.pow((int) scaleDifference)
: BigInteger.TEN.modPow(BigInteger.valueOf(scaleDifference), denominator);
return remainder.multiply(powerOfTen).remainder(denominator).signum() == 0;
}

/**
* Gets the divisor to use.
* Gets the divisor to use. The default implementation preserves exact values
* for integral and BigDecimal nodes. Double and Float nodes are converted with
* {@link BigDecimal#valueOf(double)} using their {@code doubleValue()}.
* Validation uses the returned value without further rounding, including when
* this method is overridden.
* The default conversion removes trailing zeros unless doing so would overflow the scale.
* Error messages preserve the string representation of the returned value.
*
* @param schemaNode the schema node
* @return the divisor or null if the input is not correct
*/
protected BigDecimal getDivisor(JsonNode schemaNode) {
if (schemaNode.isNumber()) {
if (schemaNode.isIntegralNumber() || schemaNode.isBigDecimal()) {
BigDecimal value = schemaNode.decimalValue();
return value.signum() == 0 ? null : normalizeDivisor(value);
}
double divisor = schemaNode.doubleValue();
if (divisor != 0 && Double.isFinite(divisor)) {
// convert to BigDecimal since double type is not accurate enough to do the
// division and multiple
return schemaNode.isBigDecimal() ? schemaNode.decimalValue().stripTrailingZeros() : BigDecimal.valueOf(divisor).stripTrailingZeros();
return BigDecimal.valueOf(divisor).stripTrailingZeros();
}
}
return null;
}

/**
* Gets the dividend to use.
* Gets the dividend to use. The default implementation preserves exact values
* for integral and BigDecimal nodes. Double and Float nodes are converted with
* {@link BigDecimal#valueOf(double)} using their {@code doubleValue()}.
* Validation uses the returned value without further rounding, including when
* this method is overridden.
* Integral inputs can have a different scale than with the former
* double-based conversion, for example {@code 2} instead of {@code 2.0}.
*
* @param node the node
* @return the dividend or null if the type is incorrect
Expand All @@ -87,7 +175,10 @@ protected BigDecimal getDividend(JsonNode node) {
}
// convert to BigDecimal since double type is not accurate enough to do the
// division and multiple
return node.isBigDecimal() ? node.decimalValue() : BigDecimal.valueOf(node.doubleValue());
if (node.isIntegralNumber() || node.isBigDecimal()) {
return node.decimalValue();
}
return BigDecimal.valueOf(node.doubleValue());
} else if (this.schemaContext.getSchemaRegistryConfig().isTypeLoose()
&& JsonNodeTypes.isNumber(node, this.schemaContext.getSchemaRegistryConfig())) {
// handling for type loose
Expand Down
Loading
Loading