diff --git a/doc/compatibility.md b/doc/compatibility.md index 60b0fbb3e..556038247 100644 --- a/doc/compatibility.md +++ b/doc/compatibility.md @@ -150,7 +150,12 @@ This behavior can be overridden to generate assertions by setting the `setFormat | uri-template | 🚫 | 🟢 | 🟢 | 🟢 | 🟢 | | uuid | 🚫 | 🚫 | 🟢 | 🟢 | 🟢 | +##### Unknown Formats + +When the format assertion vocabularies are used in a meta schema, in accordance to the specification, unknown formats will result in assertions. If the format assertion vocabularies are not used, unknown formats will only result in assertions if the assertions are enabled and if `setStrict("format", true)`. + ##### Footnotes 1. Note that the validation are only optional for some of the keywords/formats. 2. Refer to the corresponding JSON schema for more information on whether the keyword/format is optional or not. + diff --git a/src/main/java/com/networknt/schema/Format.java b/src/main/java/com/networknt/schema/Format.java index 18f80b813..6f79b1021 100644 --- a/src/main/java/com/networknt/schema/Format.java +++ b/src/main/java/com/networknt/schema/Format.java @@ -16,23 +16,143 @@ package com.networknt.schema; +import java.util.Collections; +import java.util.Set; +import java.util.function.Supplier; + +import com.fasterxml.jackson.databind.JsonNode; + /** * Used to implement the various formats for the format keyword. + *

+ * Simple implementations need only override {@link #matches(ExecutionContext, String)}. */ public interface Format { /** + * Gets the format name. + * * @return the format name as referred to in a json schema format node. */ String getName(); + + /** + * Gets the message key to use for the message. + *

+ * See jsv-messages.properties. + *

+ * The following are the arguments.
+ * {0} The instance location
+ * {1} The format name
+ * {2} The error message description
+ * {3} The input value + * + * @return the message key + */ + default String getMessageKey() { + return "format"; + } + + /** + * Gets the error message description. + *

+ * Deprecated. Override getMessageKey() and set the localized message in the + * resource bundle or message source. + * + * @return the error message description. + */ + @Deprecated + default String getErrorMessageDescription() { + return ""; + } + /** * Determines if the value matches the format. - * + *

+ * This should be implemented for string node types. + * * @param executionContext the execution context * @param value to match * @return true if matches */ - boolean matches(ExecutionContext executionContext, String value); + default boolean matches(ExecutionContext executionContext, String value) { + return true; + } + + /** + * Determines if the value matches the format. + * + * @param executionContext the execution context + * @param validationContext the validation context + * @param value to match + * @return true if matches + */ + default boolean matches(ExecutionContext executionContext, ValidationContext validationContext, String value) { + return matches(executionContext, value); + } + + /** + * Determines if the value matches the format. + * + * @param executionContext the execution context + * @param validationContext the validation context + * @param value to match + * @return true if matches + */ + default boolean matches(ExecutionContext executionContext, ValidationContext validationContext, JsonNode value) { + JsonType nodeType = TypeFactory.getValueNodeType(value, validationContext.getConfig()); + if (nodeType != JsonType.STRING) { + return true; + } + return matches(executionContext, validationContext, value.textValue()); + } + + /** + * Determines if the value matches the format. + *

+ * This can be implemented for non-string node types. + * + * @param executionContext the execution context + * @param validationContext the validation context + * @param node the node + * @param rootNode the root node + * @param instanceLocation the instance location + * @param assertionsEnabled if assertions are enabled + * @param formatValidator the format validator + * @return true if matches + */ + default boolean matches(ExecutionContext executionContext, ValidationContext validationContext, JsonNode node, + JsonNode rootNode, JsonNodePath instanceLocation, boolean assertionsEnabled, FormatValidator formatValidator) { + return matches(executionContext, validationContext, node); + } - String getErrorMessageDescription(); + /** + * Validates the format. + *

+ * This is the most flexible method to implement. + * + * @param executionContext the execution context + * @param validationContext the validation context + * @param node the node + * @param rootNode the root node + * @param instanceLocation the instance locaiton + * @param assertionsEnabled if assertions are enabled + * @param message the message builder + * @param formatValidator the format validator + * @return the messages + */ + default Set validate(ExecutionContext executionContext, ValidationContext validationContext, + JsonNode node, JsonNode rootNode, JsonNodePath instanceLocation, boolean assertionsEnabled, + Supplier message, + FormatValidator formatValidator) { + if (assertionsEnabled) { + if (!matches(executionContext, validationContext, node, rootNode, instanceLocation, assertionsEnabled, + formatValidator)) { + return Collections + .singleton(message.get() + .arguments(this.getName(), this.getErrorMessageDescription(), node.asText()).build()); + } + } + return Collections.emptySet(); + } } diff --git a/src/main/java/com/networknt/schema/FormatKeyword.java b/src/main/java/com/networknt/schema/FormatKeyword.java index 214a4f00a..cb2031ffb 100644 --- a/src/main/java/com/networknt/schema/FormatKeyword.java +++ b/src/main/java/com/networknt/schema/FormatKeyword.java @@ -17,23 +17,31 @@ package com.networknt.schema; import com.fasterxml.jackson.databind.JsonNode; -import com.networknt.schema.format.DateTimeValidator; -import com.networknt.schema.format.DurationFormat; import java.util.Collection; import java.util.Collections; import java.util.Map; +/** + * Format Keyword. + */ public class FormatKeyword implements Keyword { - private static final String DATE_TIME = "date-time"; - private static final String DURATION = "duration"; - - private final ValidatorTypeCode type; + private final String value; + private final ErrorMessageType errorMessageType; private final Map formats; + + public FormatKeyword(Map formats) { + this(ValidatorTypeCode.FORMAT, formats); + } public FormatKeyword(ValidatorTypeCode type, Map formats) { - this.type = type; + this(type.getValue(), type, formats); + } + + public FormatKeyword(String value, ErrorMessageType errorMessageType, Map formats) { + this.value = value; this.formats = formats; + this.errorMessageType = errorMessageType; } Collection getFormats() { @@ -46,27 +54,13 @@ public JsonValidator newValidator(SchemaLocation schemaLocation, JsonNodePath ev if (schemaNode != null && schemaNode.isTextual()) { String formatName = schemaNode.textValue(); format = this.formats.get(formatName); - if (format != null) { - return new FormatValidator(schemaLocation, evaluationPath, schemaNode, parentSchema, validationContext, format, type); - } - - switch (formatName) { - case DURATION: - format = new DurationFormat(validationContext.getConfig().isStrict(DURATION)); - break; - - case DATE_TIME: { - ValidatorTypeCode typeCode = ValidatorTypeCode.DATETIME; - return new DateTimeValidator(schemaLocation, evaluationPath, schemaNode, parentSchema, validationContext, typeCode); - } - } } - - return new FormatValidator(schemaLocation, evaluationPath, schemaNode, parentSchema, validationContext, format, this.type); + return new FormatValidator(schemaLocation, evaluationPath, schemaNode, parentSchema, validationContext, format, + errorMessageType, this); } @Override public String getValue() { - return this.type.getValue(); + return this.value; } } diff --git a/src/main/java/com/networknt/schema/FormatValidator.java b/src/main/java/com/networknt/schema/FormatValidator.java index 7e588d447..966576246 100644 --- a/src/main/java/com/networknt/schema/FormatValidator.java +++ b/src/main/java/com/networknt/schema/FormatValidator.java @@ -23,71 +23,124 @@ import org.slf4j.LoggerFactory; import java.util.Collections; -import java.util.LinkedHashSet; import java.util.Set; import java.util.regex.PatternSyntaxException; +/** + * Validator for Format. + */ public class FormatValidator extends BaseFormatJsonValidator implements JsonValidator { private static final Logger logger = LoggerFactory.getLogger(FormatValidator.class); private final Format format; - - public FormatValidator(SchemaLocation schemaLocation, JsonNodePath evaluationPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext, Format format, ValidatorTypeCode type) { - super(schemaLocation, evaluationPath, schemaNode, parentSchema, type, validationContext); + + public FormatValidator(SchemaLocation schemaLocation, JsonNodePath evaluationPath, JsonNode schemaNode, + JsonSchema parentSchema, ValidationContext validationContext, Format format, + ErrorMessageType errorMessageType, Keyword keyword) { + super(schemaLocation, evaluationPath, schemaNode, parentSchema, errorMessageType, keyword, validationContext); this.format = format; } + public FormatValidator(SchemaLocation schemaLocation, JsonNodePath evaluationPath, JsonNode schemaNode, + JsonSchema parentSchema, ValidationContext validationContext, Format format, ValidatorTypeCode type) { + this(schemaLocation, evaluationPath, schemaNode, parentSchema, validationContext, format, type, type); + } + + /** + * Gets the annotation value. + * + * @return the annotation value + */ + protected Object getAnnotationValue() { + if (this.format != null) { + return this.format.getName(); + } + return this.schemaNode.isTextual() ? schemaNode.textValue() : null; + } + public Set validate(ExecutionContext executionContext, JsonNode node, JsonNode rootNode, JsonNodePath instanceLocation) { debug(logger, node, rootNode, instanceLocation); - - if (format != null) { - if (collectAnnotations(executionContext)) { + /* + * Annotations must be collected even if the format is unknown according to the specification. + */ + if (collectAnnotations(executionContext)) { + Object annotationValue = getAnnotationValue(); + if (annotationValue != null) { putAnnotation(executionContext, - annotation -> annotation.instanceLocation(instanceLocation).value(this.format.getName())); + annotation -> annotation.instanceLocation(instanceLocation).value(annotationValue)); } } - JsonType nodeType = TypeFactory.getValueNodeType(node, this.validationContext.getConfig()); - if (nodeType != JsonType.STRING) { - return Collections.emptySet(); - } - boolean assertionsEnabled = isAssertionsEnabled(executionContext); - Set errors = new LinkedHashSet<>(); - if (format != null) { - if(format.getName().equals("ipv6")) { - if(!node.textValue().trim().equals(node.textValue())) { - if (assertionsEnabled) { - // leading and trailing spaces - errors.add(message().instanceNode(node).instanceLocation(instanceLocation) - .locale(executionContext.getExecutionConfig().getLocale()) - .failFast(executionContext.isFailFast()) - .arguments(format.getName(), format.getErrorMessageDescription()).build()); - } - } else if(node.textValue().contains("%")) { - if (assertionsEnabled) { - // zone id is not part of the ipv6 - errors.add(message().instanceNode(node).instanceLocation(instanceLocation) - .locale(executionContext.getExecutionConfig().getLocale()) - .arguments(format.getName(), format.getErrorMessageDescription()).build()); - } - } - } + if (this.format != null) { try { - if (!format.matches(executionContext, node.textValue())) { - if (assertionsEnabled) { - errors.add(message().instanceNode(node).instanceLocation(instanceLocation) - .locale(executionContext.getExecutionConfig().getLocale()) - .arguments(format.getName(), format.getErrorMessageDescription()).build()); - } - } + return format.validate(executionContext, validationContext, node, rootNode, instanceLocation, + assertionsEnabled, + () -> this.message().instanceNode(node).instanceLocation(instanceLocation) + .messageKey(format.getMessageKey()) + .locale(executionContext.getExecutionConfig().getLocale()) + .failFast(executionContext.isFailFast()), + this); } catch (PatternSyntaxException pse) { // String is considered valid if pattern is invalid - logger.error("Failed to apply pattern on {}: Invalid RE syntax [{}]", instanceLocation, format.getName(), pse); + logger.error("Failed to apply pattern on {}: Invalid RE syntax [{}]", instanceLocation, + format.getName(), pse); + return Collections.emptySet(); } + } else { + return validateUnknownFormat(executionContext, node, rootNode, instanceLocation); } + } - return Collections.unmodifiableSet(errors); + /** + * When the Format-Assertion vocabulary is specified, implementations MUST fail upon encountering unknown formats. + * + * @param executionContext the execution context + * @param node the node + * @param rootNode the root node + * @param instanceLocation the instance location + * @return the messages + */ + protected Set validateUnknownFormat(ExecutionContext executionContext, + JsonNode node, JsonNode rootNode, JsonNodePath instanceLocation) { + /* + * Unknown formats should create an assertion if the vocab is specified + * according to the specification. + */ + if (createUnknownFormatAssertions(executionContext) && this.schemaNode.isTextual()) { + return Collections.singleton(message().instanceLocation(instanceLocation).instanceNode(node) + .messageKey("format.unknown").arguments(schemaNode.textValue()).build()); + } + return Collections.emptySet(); + } + + /** + * When the Format-Assertion vocabulary is specified, implementations MUST fail + * upon encountering unknown formats. + *

+ * Note that this is different from setting the setFormatAssertionsEnabled + * configuration option. + *

+ * The following logic will return true if the format assertions option is + * turned on and strict is enabled (default false) or the format assertion + * vocabulary is enabled. + * + * @param executionContext the execution context + * @return true if format assertions should be generated + */ + protected boolean createUnknownFormatAssertions(ExecutionContext executionContext) { + return (isAssertionsEnabled(executionContext) && isStrict(executionContext)) || (isFormatAssertionVocabularyEnabled()); } + /** + * Determines if strict handling. + *

+ * Note that this defaults to false. + * + * @param executionContext the execution context + * @return whether to perform strict handling + */ + protected boolean isStrict(ExecutionContext executionContext) { + return this.validationContext.getConfig().isStrict(getKeyword(), Boolean.FALSE); + } } diff --git a/src/main/java/com/networknt/schema/JsonMetaSchema.java b/src/main/java/com/networknt/schema/JsonMetaSchema.java index 6ecb6255e..5fd0464ff 100644 --- a/src/main/java/com/networknt/schema/JsonMetaSchema.java +++ b/src/main/java/com/networknt/schema/JsonMetaSchema.java @@ -19,7 +19,10 @@ import com.fasterxml.jackson.databind.JsonNode; import com.networknt.schema.SpecVersion.VersionFlag; import com.networknt.schema.format.DateFormat; +import com.networknt.schema.format.DateTimeFormat; +import com.networknt.schema.format.DurationFormat; import com.networknt.schema.format.EmailFormat; +import com.networknt.schema.format.IPv6Format; import com.networknt.schema.format.IdnEmailFormat; import com.networknt.schema.format.IdnHostnameFormat; import com.networknt.schema.format.IriFormat; @@ -36,13 +39,14 @@ import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; public class JsonMetaSchema { private static final Logger logger = LoggerFactory.getLogger(JsonMetaSchema.class); private static Map UNKNOWN_KEYWORDS = new ConcurrentHashMap<>(); - static PatternFormat pattern(String name, String regex, String description) { - return new PatternFormat(name, regex, description); + static PatternFormat pattern(String name, String regex, String messageKey) { + return PatternFormat.of(name, regex, messageKey); } static PatternFormat pattern(String name, String regex) { @@ -51,18 +55,17 @@ static PatternFormat pattern(String name, String regex) { public static final List COMMON_BUILTIN_FORMATS = new ArrayList<>(); - public static final String IPV6_PATTERN = "^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$"; - // this section contains formats common to all dialects. static { - COMMON_BUILTIN_FORMATS.add(pattern("hostname", "^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*$", "must be a valid RFC 1123 host name")); - COMMON_BUILTIN_FORMATS.add(pattern("ipv4", "^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$", "must be a valid RFC 2673 IP address")); - COMMON_BUILTIN_FORMATS.add(pattern("ipv6", IPV6_PATTERN, "must be a valid RFC 4291 IP address")); - COMMON_BUILTIN_FORMATS.add(pattern("json-pointer", "^(/([^/#~]|[~](?=[01]))*)*$", "must be a valid RFC 6901 JSON Pointer")); - COMMON_BUILTIN_FORMATS.add(pattern("relative-json-pointer", "^(0|([1-9]\\d*))(#|(/([^/#~]|[~](?=[01]))*)*)$", "must be a valid IETF Relative JSON Pointer")); - COMMON_BUILTIN_FORMATS.add(pattern("uri-template", "^([^\\p{Cntrl}\"'%<>\\^`\\{|\\}]|%\\p{XDigit}{2}|\\{[+#./;?&=,!@|]?((\\w|%\\p{XDigit}{2})(\\.?(\\w|%\\p{XDigit}{2}))*(:[1-9]\\d{0,3}|\\*)?)(,((\\w|%\\p{XDigit}{2})(\\.?(\\w|%\\p{XDigit}{2}))*(:[1-9]\\d{0,3}|\\*)?))*\\})*$", "must be a valid RFC 6570 URI Template")); - COMMON_BUILTIN_FORMATS.add(pattern("uuid", "^\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12}$", "must be a valid RFC 4122 UUID")); + COMMON_BUILTIN_FORMATS.add(pattern("hostname", "^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*$", "format.hostname")); + COMMON_BUILTIN_FORMATS.add(pattern("ipv4", "^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$", "format.ipv4")); + COMMON_BUILTIN_FORMATS.add(new IPv6Format()); + COMMON_BUILTIN_FORMATS.add(pattern("json-pointer", "^(/([^/#~]|[~](?=[01]))*)*$", "format.json-pointer")); + COMMON_BUILTIN_FORMATS.add(pattern("relative-json-pointer", "^(0|([1-9]\\d*))(#|(/([^/#~]|[~](?=[01]))*)*)$", "format.relative-json-pointer")); + COMMON_BUILTIN_FORMATS.add(pattern("uri-template", "^([^\\p{Cntrl}\"'%<>\\^`\\{|\\}]|%\\p{XDigit}{2}|\\{[+#./;?&=,!@|]?((\\w|%\\p{XDigit}{2})(\\.?(\\w|%\\p{XDigit}{2}))*(:[1-9]\\d{0,3}|\\*)?)(,((\\w|%\\p{XDigit}{2})(\\.?(\\w|%\\p{XDigit}{2}))*(:[1-9]\\d{0,3}|\\*)?))*\\})*$", "format.uri-template")); + COMMON_BUILTIN_FORMATS.add(pattern("uuid", "^\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12}$", "format.uuid")); COMMON_BUILTIN_FORMATS.add(new DateFormat()); + COMMON_BUILTIN_FORMATS.add(new DateTimeFormat()); COMMON_BUILTIN_FORMATS.add(new EmailFormat()); COMMON_BUILTIN_FORMATS.add(new IdnEmailFormat()); COMMON_BUILTIN_FORMATS.add(new IdnHostnameFormat()); @@ -72,7 +75,8 @@ static PatternFormat pattern(String name, String regex) { COMMON_BUILTIN_FORMATS.add(new TimeFormat()); COMMON_BUILTIN_FORMATS.add(new UriFormat()); COMMON_BUILTIN_FORMATS.add(new UriReferenceFormat()); - + COMMON_BUILTIN_FORMATS.add(new DurationFormat()); + // The following formats do not appear in any draft COMMON_BUILTIN_FORMATS.add(pattern("alpha", "^[a-zA-Z]+$")); COMMON_BUILTIN_FORMATS.add(pattern("alphanumeric", "^[a-zA-Z0-9]+$")); @@ -82,6 +86,10 @@ static PatternFormat pattern(String name, String regex) { COMMON_BUILTIN_FORMATS.add(pattern("style", "\\s*(.+?):\\s*([^;]+);?")); COMMON_BUILTIN_FORMATS.add(pattern("utc-millisec", "^[0-9]+(\\.?[0-9]+)?$")); } + + public interface FormatKeywordFactory { + FormatKeyword newInstance(Map formats); + } public static class Builder { private VersionFlag specification = null; @@ -90,30 +98,48 @@ public static class Builder { private Map vocabularies = new HashMap<>(); private String uri; private String idKeyword = "id"; + private FormatKeywordFactory formatKeywordFactory = null; public Builder(String uri) { this.uri = uri; } - private static Map createKeywordsMap(Map kwords, Map formats) { + private Map createKeywordsMap(Map kwords, Map formats) { Map map = new HashMap<>(); for (Map.Entry type : kwords.entrySet()) { String keywordName = type.getKey(); Keyword keyword = type.getValue(); if (ValidatorTypeCode.FORMAT.getValue().equals(keywordName)) { if (!(keyword instanceof FormatKeyword)) { - throw new IllegalArgumentException("Overriding the keyword 'format' is not supported"); + throw new IllegalArgumentException("Overriding the keyword 'format' is not supported. Use the formatKeywordFactory and extend the FormatKeyword."); } // ignore - format keyword will be created again below. } else { map.put(keyword.getValue(), keyword); } } - final FormatKeyword formatKeyword = new FormatKeyword(ValidatorTypeCode.FORMAT, formats); + final FormatKeyword formatKeyword = formatKeywordFactory != null ? formatKeywordFactory.newInstance(formats) + : new FormatKeyword(formats); map.put(formatKeyword.getValue(), formatKeyword); return map; } + public Builder formatKeywordFactory(FormatKeywordFactory formatKeywordFactory) { + this.formatKeywordFactory = formatKeywordFactory; + return this; + } + + public Builder formats(Consumer> customizer) { + customizer.accept(this.formats); + return this; + } + + public Builder keywords(Consumer> customizer) { + customizer.accept(this.keywords); + return this; + } + + public Builder addKeyword(Keyword keyword) { this.keywords.put(keyword.getValue(), keyword); return this; diff --git a/src/main/java/com/networknt/schema/SchemaValidatorsConfig.java b/src/main/java/com/networknt/schema/SchemaValidatorsConfig.java index a85f75b60..538aa8001 100644 --- a/src/main/java/com/networknt/schema/SchemaValidatorsConfig.java +++ b/src/main/java/com/networknt/schema/SchemaValidatorsConfig.java @@ -487,7 +487,18 @@ public PathType getPathType() { * @return Whether to perform a strict validation. */ public boolean isStrict(String keyword) { - return this.strictness.getOrDefault(Objects.requireNonNull(keyword, "keyword cannot be null"), Boolean.TRUE); + return isStrict(keyword, Boolean.TRUE); + } + + /** + * Determines if the validator should perform strict checking. + * + * @param keyword the keyword + * @param defaultValue the default value + * @return whether to perform a strict validation + */ + public boolean isStrict(String keyword, Boolean defaultValue) { + return this.strictness.getOrDefault(Objects.requireNonNull(keyword, "keyword cannot be null"), defaultValue); } /** diff --git a/src/main/java/com/networknt/schema/ValidatorTypeCode.java b/src/main/java/com/networknt/schema/ValidatorTypeCode.java index 44663c1f7..6ea177a0d 100644 --- a/src/main/java/com/networknt/schema/ValidatorTypeCode.java +++ b/src/main/java/com/networknt/schema/ValidatorTypeCode.java @@ -64,7 +64,6 @@ public enum ValidatorTypeCode implements Keyword, ErrorMessageType { CONTENT_ENCODING("contentEncoding", "1052", ContentEncodingValidator::new, VersionCode.V7), CONTENT_MEDIA_TYPE("contentMediaType", "1053", ContentMediaTypeValidator::new, VersionCode.V7), CROSS_EDITS("crossEdits", "1004", null, VersionCode.AllVersions), - DATETIME("dateTime", "1034", null, VersionCode.AllVersions), DEPENDENCIES("dependencies", "1007", DependenciesValidator::new, VersionCode.AllVersions), DEPENDENT_REQUIRED("dependentRequired", "1045", DependentRequired::new, VersionCode.MinV201909), DEPENDENT_SCHEMAS("dependentSchemas", "1046", DependentSchemas::new, VersionCode.MinV201909), diff --git a/src/main/java/com/networknt/schema/format/AbstractFormat.java b/src/main/java/com/networknt/schema/format/AbstractFormat.java index 52f7fff37..73d85e909 100644 --- a/src/main/java/com/networknt/schema/format/AbstractFormat.java +++ b/src/main/java/com/networknt/schema/format/AbstractFormat.java @@ -21,6 +21,7 @@ /** * Used for Formats that do not need to use the {@link ExecutionContext}. */ +@Deprecated public abstract class AbstractFormat extends BaseFormat { /** * Constructor. diff --git a/src/main/java/com/networknt/schema/format/AbstractRFC3986Format.java b/src/main/java/com/networknt/schema/format/AbstractRFC3986Format.java index 9b68b9962..0b0748b55 100644 --- a/src/main/java/com/networknt/schema/format/AbstractRFC3986Format.java +++ b/src/main/java/com/networknt/schema/format/AbstractRFC3986Format.java @@ -3,23 +3,15 @@ import java.net.URI; import java.net.URISyntaxException; +import com.networknt.schema.ExecutionContext; +import com.networknt.schema.Format; + /** * {@link AbstractFormat} for RFC 3986. */ -public abstract class AbstractRFC3986Format extends AbstractFormat { - - /** - * Constructor. - * - * @param name the format name - * @param errorMessageDescription the error message description - */ - public AbstractRFC3986Format(String name, String errorMessageDescription) { - super(name, errorMessageDescription); - } - +public abstract class AbstractRFC3986Format implements Format { @Override - public final boolean matches(String value) { + public final boolean matches(ExecutionContext executionContext, String value) { try { URI uri = new URI(value); return validate(uri); diff --git a/src/main/java/com/networknt/schema/format/BaseFormat.java b/src/main/java/com/networknt/schema/format/BaseFormat.java index da720fff4..d8310bb4c 100644 --- a/src/main/java/com/networknt/schema/format/BaseFormat.java +++ b/src/main/java/com/networknt/schema/format/BaseFormat.java @@ -21,6 +21,7 @@ /** * Base implementation of {@link Format}. */ +@Deprecated public abstract class BaseFormat implements Format { private final String name; private final String errorMessageDescription; diff --git a/src/main/java/com/networknt/schema/format/BaseFormatJsonValidator.java b/src/main/java/com/networknt/schema/format/BaseFormatJsonValidator.java index 80d985246..003fb493f 100644 --- a/src/main/java/com/networknt/schema/format/BaseFormatJsonValidator.java +++ b/src/main/java/com/networknt/schema/format/BaseFormatJsonValidator.java @@ -4,20 +4,22 @@ import com.fasterxml.jackson.databind.JsonNode; import com.networknt.schema.BaseJsonValidator; +import com.networknt.schema.ErrorMessageType; import com.networknt.schema.ExecutionContext; import com.networknt.schema.JsonNodePath; import com.networknt.schema.JsonSchema; +import com.networknt.schema.Keyword; import com.networknt.schema.SchemaLocation; import com.networknt.schema.ValidationContext; -import com.networknt.schema.ValidatorTypeCode; import com.networknt.schema.SpecVersion.VersionFlag; public abstract class BaseFormatJsonValidator extends BaseJsonValidator { protected final boolean assertionsEnabled; public BaseFormatJsonValidator(SchemaLocation schemaLocation, JsonNodePath evaluationPath, JsonNode schemaNode, - JsonSchema parentSchema, ValidatorTypeCode validatorType, ValidationContext validationContext) { - super(schemaLocation, evaluationPath, schemaNode, parentSchema, validatorType, validationContext); + JsonSchema parentSchema, ErrorMessageType errorMessageType, Keyword keyword, + ValidationContext validationContext) { + super(schemaLocation, evaluationPath, schemaNode, parentSchema, errorMessageType, keyword, validationContext, false); VersionFlag specification = this.validationContext.getMetaSchema().getSpecification(); if (specification == null || specification.getVersionFlagValue() < VersionFlag.V201909.getVersionFlagValue()) { assertionsEnabled = true; @@ -28,6 +30,11 @@ public BaseFormatJsonValidator(SchemaLocation schemaLocation, JsonNodePath evalu } } + protected boolean isFormatAssertionVocabularyEnabled() { + return isFormatAssertionVocabularyEnabled(this.validationContext.getMetaSchema().getSpecification(), + this.validationContext.getMetaSchema().getVocabularies()); + } + protected boolean isFormatAssertionVocabularyEnabled(VersionFlag specification, Map vocabularies) { if (VersionFlag.V202012.equals(specification)) { String vocabulary = "https://json-schema.org/draft/2020-12/vocab/format-assertion"; diff --git a/src/main/java/com/networknt/schema/format/DateFormat.java b/src/main/java/com/networknt/schema/format/DateFormat.java index 829f23a29..c5d921c9e 100644 --- a/src/main/java/com/networknt/schema/format/DateFormat.java +++ b/src/main/java/com/networknt/schema/format/DateFormat.java @@ -3,14 +3,15 @@ import java.time.LocalDate; import java.time.format.DateTimeParseException; -public class DateFormat extends AbstractFormat { - - public DateFormat() { - super("date", "must be a valid RFC 3339 full-date"); - } +import com.networknt.schema.ExecutionContext; +import com.networknt.schema.Format; +/** + * Format for date. + */ +public class DateFormat implements Format { @Override - public boolean matches(String value) { + public boolean matches(ExecutionContext executionContext, String value) { try { LocalDate date = LocalDate.parse(value); int year = date.getYear(); @@ -20,4 +21,13 @@ public boolean matches(String value) { } } + @Override + public String getName() { + return "date"; + } + + @Override + public String getMessageKey() { + return "format.date"; + } } diff --git a/src/main/java/com/networknt/schema/format/DateTimeFormat.java b/src/main/java/com/networknt/schema/format/DateTimeFormat.java new file mode 100644 index 000000000..9bc633f3c --- /dev/null +++ b/src/main/java/com/networknt/schema/format/DateTimeFormat.java @@ -0,0 +1,48 @@ +package com.networknt.schema.format; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.ethlo.time.ITU; +import com.ethlo.time.LeapSecondException; +import com.networknt.schema.ExecutionContext; +import com.networknt.schema.Format; + +/** + * Format for date-time. + */ +public class DateTimeFormat implements Format { + private static final Logger logger = LoggerFactory.getLogger(DateTimeFormat.class); + + @Override + public String getName() { + return "date-time"; + } + + @Override + public String getMessageKey() { + return "format.date-time"; + } + + @Override + public boolean matches(ExecutionContext executionContext, String value) { + return isLegalDateTime(value); + } + + private static boolean isLegalDateTime(String string) { + try { + try { + ITU.parseDateTime(string); + } catch (LeapSecondException ex) { + if (!ex.isVerifiedValidLeapYearMonth()) { + return false; + } + } + + return true; + } catch (Exception ex) { + logger.debug("Invalid {}: {}", "date-time", ex.getMessage()); + return false; + } + } +} diff --git a/src/main/java/com/networknt/schema/format/DateTimeValidator.java b/src/main/java/com/networknt/schema/format/DateTimeValidator.java deleted file mode 100644 index 54900fca0..000000000 --- a/src/main/java/com/networknt/schema/format/DateTimeValidator.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2016 Network New Technologies Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.networknt.schema.format; - -import com.ethlo.time.ITU; -import com.ethlo.time.LeapSecondException; -import com.fasterxml.jackson.databind.JsonNode; -import com.networknt.schema.ExecutionContext; -import com.networknt.schema.JsonNodePath; -import com.networknt.schema.JsonSchema; -import com.networknt.schema.JsonType; -import com.networknt.schema.SchemaLocation; -import com.networknt.schema.TypeFactory; -import com.networknt.schema.ValidationContext; -import com.networknt.schema.ValidationMessage; -import com.networknt.schema.ValidatorTypeCode; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Collections; -import java.util.Set; - -/** - * {@link BaseFormatJsonValidator} for format for date-time. - */ -public class DateTimeValidator extends BaseFormatJsonValidator { - private static final Logger logger = LoggerFactory.getLogger(DateTimeValidator.class); - private static final String DATETIME = "date-time"; - - public DateTimeValidator(SchemaLocation schemaLocation, JsonNodePath evaluationPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext, ValidatorTypeCode type) { - super(schemaLocation, evaluationPath, schemaNode, parentSchema, type, validationContext); - } - - @Override - public Set validate(ExecutionContext executionContext, JsonNode node, JsonNode rootNode, JsonNodePath instanceLocation) { - debug(logger, node, rootNode, instanceLocation); - - if (collectAnnotations(executionContext, "format")) { - putAnnotation(executionContext, - annotation -> annotation.instanceLocation(instanceLocation).keyword("format").value(DATETIME)); - } - - JsonType nodeType = TypeFactory.getValueNodeType(node, this.validationContext.getConfig()); - if (nodeType != JsonType.STRING) { - return Collections.emptySet(); - } - - boolean assertionsEnabled = isAssertionsEnabled(executionContext); - - if (!isLegalDateTime(node.textValue())) { - if (assertionsEnabled) { - return Collections.singleton(message().instanceNode(node).instanceLocation(instanceLocation) - .type("format") - .locale(executionContext.getExecutionConfig().getLocale()) - .failFast(executionContext.isFailFast()) - .arguments(node.textValue(), DATETIME).build()); - } - } - return Collections.emptySet(); - } - - private static boolean isLegalDateTime(String string) { - try { - try { - ITU.parseDateTime(string); - } catch (LeapSecondException ex) { - if (!ex.isVerifiedValidLeapYearMonth()) { - return false; - } - } - - return true; - } catch (Exception ex) { - logger.debug("Invalid {}: {}", DATETIME, ex.getMessage()); - return false; - } - } -} diff --git a/src/main/java/com/networknt/schema/format/DurationFormat.java b/src/main/java/com/networknt/schema/format/DurationFormat.java index 6bc0f4c19..ca8d0e1fb 100644 --- a/src/main/java/com/networknt/schema/format/DurationFormat.java +++ b/src/main/java/com/networknt/schema/format/DurationFormat.java @@ -3,19 +3,21 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -public class DurationFormat extends AbstractFormat { - private static final Pattern STRICT = Pattern.compile("^(?:P\\d+W)|(?:P(?:\\d+Y)?(?:\\d+M)?(?:\\d+D)?(?:T(?:\\d+H)?(?:\\d+M)?(?:\\d+S)?)?)$", Pattern.CASE_INSENSITIVE); - private static final Pattern LAX = Pattern.compile("^(?:[-+]?)P(?:[-+]?[0-9]+Y)?(?:[-+]?[0-9]+M)?(?:[-+]?[0-9]+W)?(?:[-+]?[0-9]+D)?(?:T(?:[-+]?[0-9]+H)?(?:[-+]?[0-9]+M)?(?:[-+]?[0-9]+(?:[.,][0-9]{0,9})?S)?)?$", Pattern.CASE_INSENSITIVE); +import com.networknt.schema.ExecutionContext; +import com.networknt.schema.Format; +import com.networknt.schema.ValidationContext; - private final boolean isStrictValidation; +/** + * Format for duration. + */ +public class DurationFormat implements Format { + private static final String DURATION = "duration"; - public DurationFormat(boolean isStrictValidation) { - super("duration", "must be a valid ISO 8601 duration"); - this.isStrictValidation = isStrictValidation; - } + private static final Pattern STRICT = Pattern.compile("^(?:P\\d+W)|(?:P(?:\\d+Y)?(?:\\d+M)?(?:\\d+D)?(?:T(?:\\d+H)?(?:\\d+M)?(?:\\d+S)?)?)$", Pattern.CASE_INSENSITIVE); + private static final Pattern LAX = Pattern.compile("^(?:[-+]?)P(?:[-+]?[0-9]+Y)?(?:[-+]?[0-9]+M)?(?:[-+]?[0-9]+W)?(?:[-+]?[0-9]+D)?(?:T(?:[-+]?[0-9]+H)?(?:[-+]?[0-9]+M)?(?:[-+]?[0-9]+(?:[.,][0-9]{0,9})?S)?)?$", Pattern.CASE_INSENSITIVE); @Override - public boolean matches(String duration) { + public boolean matches(ExecutionContext executionContext, ValidationContext validationContext, String duration) { if (null == duration) { return true; } @@ -24,9 +26,22 @@ public boolean matches(String duration) { return false; } - Pattern pattern = isStrictValidation ? STRICT : LAX; + Pattern pattern = isStrictValidation(validationContext) ? STRICT : LAX; Matcher matcher = pattern.matcher(duration); return matcher.matches(); } + protected boolean isStrictValidation(ValidationContext validationContext) { + return validationContext.getConfig().isStrict(DURATION); + } + + @Override + public String getName() { + return "duration"; + } + + @Override + public String getMessageKey() { + return "format.duration"; + } } diff --git a/src/main/java/com/networknt/schema/format/EmailFormat.java b/src/main/java/com/networknt/schema/format/EmailFormat.java index d58ee368b..3a329e4d0 100644 --- a/src/main/java/com/networknt/schema/format/EmailFormat.java +++ b/src/main/java/com/networknt/schema/format/EmailFormat.java @@ -17,18 +17,35 @@ package com.networknt.schema.format; import com.networknt.org.apache.commons.validator.routines.EmailValidator; +import com.networknt.schema.ExecutionContext; +import com.networknt.schema.Format; -public class EmailFormat extends AbstractFormat { - +/** + * Format for email. + */ +public class EmailFormat implements Format { private final EmailValidator emailValidator; public EmailFormat() { - super("email", "must be a valid RFC 5321 Mailbox"); - this.emailValidator = new IPv6AwareEmailValidator(true, true); + this(new IPv6AwareEmailValidator(true, true)); + } + + public EmailFormat(EmailValidator emailValidator) { + this.emailValidator = emailValidator; } @Override - public boolean matches(String value) { + public boolean matches(ExecutionContext executionContext, String value) { return this.emailValidator.isValid(value); } + + @Override + public String getName() { + return "email"; + } + + @Override + public String getMessageKey() { + return "format.email"; + } } diff --git a/src/main/java/com/networknt/schema/format/IPv6Format.java b/src/main/java/com/networknt/schema/format/IPv6Format.java new file mode 100644 index 000000000..ddcd2ce55 --- /dev/null +++ b/src/main/java/com/networknt/schema/format/IPv6Format.java @@ -0,0 +1,37 @@ +package com.networknt.schema.format; + +import java.util.regex.Pattern; + +import com.networknt.schema.ExecutionContext; +import com.networknt.schema.Format; + +/** + * Format for ipv6. + */ +public class IPv6Format implements Format { + public static final String PATTERN_VALUE = "^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$"; + + public static final Pattern PATTERN = Pattern.compile(PATTERN_VALUE); + + @Override + public boolean matches(ExecutionContext executionContext, String value) { + if (!value.trim().equals(value)) { + // leading and trailing spaces + return false; + } else if (value.contains("%")) { + // zone id is not part of the ipv6 + return false; + } + return PATTERN.matcher(value).matches(); + } + + @Override + public String getName() { + return "ipv6"; + } + + @Override + public String getMessageKey() { + return "format.ipv6"; + } +} diff --git a/src/main/java/com/networknt/schema/format/IdnEmailFormat.java b/src/main/java/com/networknt/schema/format/IdnEmailFormat.java index 36daf7927..855ba2180 100644 --- a/src/main/java/com/networknt/schema/format/IdnEmailFormat.java +++ b/src/main/java/com/networknt/schema/format/IdnEmailFormat.java @@ -1,19 +1,35 @@ package com.networknt.schema.format; import com.networknt.org.apache.commons.validator.routines.EmailValidator; +import com.networknt.schema.ExecutionContext; +import com.networknt.schema.Format; -public class IdnEmailFormat extends AbstractFormat { - +/** + * Format for idn-email. + */ +public class IdnEmailFormat implements Format { private final EmailValidator emailValidator; public IdnEmailFormat() { - super("idn-email", "must be a valid RFC 6531 Mailbox"); - this.emailValidator = new IPv6AwareEmailValidator(true, true); + this(new IPv6AwareEmailValidator(true, true)); + } + + public IdnEmailFormat(EmailValidator emailValidator) { + this.emailValidator = emailValidator; } @Override - public boolean matches(String value) { + public boolean matches(ExecutionContext executionContext, String value) { return this.emailValidator.isValid(value); } + @Override + public String getName() { + return "idn-email"; + } + + @Override + public String getMessageKey() { + return "format.idn-email"; + } } diff --git a/src/main/java/com/networknt/schema/format/IdnHostnameFormat.java b/src/main/java/com/networknt/schema/format/IdnHostnameFormat.java index 723d9e46c..5d1ec7ee0 100644 --- a/src/main/java/com/networknt/schema/format/IdnHostnameFormat.java +++ b/src/main/java/com/networknt/schema/format/IdnHostnameFormat.java @@ -1,16 +1,26 @@ package com.networknt.schema.format; +import com.networknt.schema.ExecutionContext; +import com.networknt.schema.Format; import com.networknt.schema.utils.RFC5892; -public class IdnHostnameFormat extends AbstractFormat { +/** + * Format for idn-hostname. + */ +public class IdnHostnameFormat implements Format { + @Override + public boolean matches(ExecutionContext executionContext, String value) { + if (null == value || value.isEmpty()) return true; + return RFC5892.isValid(value); + } - public IdnHostnameFormat() { - super("idn-hostname", "must be a valid RFC 5890 internationalized hostname"); + @Override + public String getName() { + return "idn-hostname"; } @Override - public boolean matches(String value) { - if (null == value || value.isEmpty()) return true; - return RFC5892.isValid(value); + public String getMessageKey() { + return "format.idn-hostname"; } } diff --git a/src/main/java/com/networknt/schema/format/IriFormat.java b/src/main/java/com/networknt/schema/format/IriFormat.java index 02475a530..ff2477989 100644 --- a/src/main/java/com/networknt/schema/format/IriFormat.java +++ b/src/main/java/com/networknt/schema/format/IriFormat.java @@ -1,24 +1,18 @@ package com.networknt.schema.format; import java.net.URI; -import java.util.regex.Pattern; - -import com.networknt.schema.JsonMetaSchema; +/** + * Format for iri. + */ public class IriFormat extends AbstractRFC3986Format { - private static final Pattern IPV6_PATTERN = Pattern.compile(JsonMetaSchema.IPV6_PATTERN); - - public IriFormat() { - super("iri", "must be a valid RFC 3987 IRI"); - } - @Override protected boolean validate(URI uri) { boolean result = uri.isAbsolute(); if (result) { String authority = uri.getAuthority(); if (authority != null) { - if (IPV6_PATTERN.matcher(authority).matches() ) { + if (IPv6Format.PATTERN.matcher(authority).matches() ) { return false; } } @@ -26,4 +20,13 @@ protected boolean validate(URI uri) { return result; } + @Override + public String getName() { + return "iri"; + } + + @Override + public String getMessageKey() { + return "format.iri"; + } } diff --git a/src/main/java/com/networknt/schema/format/IriReferenceFormat.java b/src/main/java/com/networknt/schema/format/IriReferenceFormat.java index adaaf312e..4a0cf0eb1 100644 --- a/src/main/java/com/networknt/schema/format/IriReferenceFormat.java +++ b/src/main/java/com/networknt/schema/format/IriReferenceFormat.java @@ -2,15 +2,23 @@ import java.net.URI; +/** + * Format for iri-reference. + */ public class IriReferenceFormat extends AbstractRFC3986Format { - - public IriReferenceFormat() { - super("iri-reference", "must be a valid RFC 3987 IRI-reference"); - } - @Override protected boolean validate(URI uri) { return true; } + @Override + public String getName() { + return "iri-reference"; + } + + @Override + public String getMessageKey() { + return "format.iri-reference"; + } + } diff --git a/src/main/java/com/networknt/schema/format/PatternFormat.java b/src/main/java/com/networknt/schema/format/PatternFormat.java index 8f57267e1..79fa91753 100644 --- a/src/main/java/com/networknt/schema/format/PatternFormat.java +++ b/src/main/java/com/networknt/schema/format/PatternFormat.java @@ -18,17 +18,71 @@ import java.util.regex.Pattern; -public class PatternFormat extends AbstractFormat { +import com.networknt.schema.ExecutionContext; +import com.networknt.schema.Format; + +/** + * Format using a regex pattern. + */ +public class PatternFormat implements Format { + private final String name; private final Pattern pattern; + private final String messageKey; + private final String errorMessageDescription; + /** + * Constructor. + *

+ * Use {@link #of(String, String, String)} instead. + * + * @param name the name + * @param regex the regex + * @param errorMessageDescription the error message description + */ + @Deprecated public PatternFormat(String name, String regex, String errorMessageDescription) { - super(name, null != errorMessageDescription ? errorMessageDescription : regex); + this.name = name; + this.errorMessageDescription = errorMessageDescription != null ? errorMessageDescription : regex; + this.messageKey = "format"; + this.pattern = Pattern.compile(regex); + } + + private PatternFormat(String name, String regex, String errorMessageDescription, String messageKey) { + this.name = name; + this.errorMessageDescription = errorMessageDescription != null ? errorMessageDescription : regex; + this.messageKey = messageKey; this.pattern = Pattern.compile(regex); } + /** + * Creates a pattern format. + * + * @param name the name + * @param regex the regex pattern + * @param messageKey the message key + * @return the pattern format + */ + public static PatternFormat of(String name, String regex, String messageKey) { + return new PatternFormat(name, regex, null, messageKey != null ? messageKey : "format"); + } + @Override - public boolean matches(String value) { + public boolean matches(ExecutionContext executionContext, String value) { return this.pattern.matcher(value).matches(); } + @Override + public String getName() { + return this.name; + } + + @Override + public String getMessageKey() { + return this.messageKey; + } + + @Override + public String getErrorMessageDescription() { + return this.errorMessageDescription; + } } diff --git a/src/main/java/com/networknt/schema/format/RegexFormat.java b/src/main/java/com/networknt/schema/format/RegexFormat.java index 34376a16f..c6f778b9b 100644 --- a/src/main/java/com/networknt/schema/format/RegexFormat.java +++ b/src/main/java/com/networknt/schema/format/RegexFormat.java @@ -16,17 +16,15 @@ import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; +import com.networknt.schema.ExecutionContext; +import com.networknt.schema.Format; + /** - * Validates that a value is a valid regex. + * Format for regex. */ -public class RegexFormat extends AbstractFormat { - - public RegexFormat() { - super("regex", "must be a valid ECMA-262 regular expression"); - } - +public class RegexFormat implements Format { @Override - public boolean matches(String value) { + public boolean matches(ExecutionContext executionContext, String value) { if (null == value) return true; try { Pattern.compile(value); @@ -37,4 +35,13 @@ public boolean matches(String value) { } } + @Override + public String getName() { + return "regex"; + } + + @Override + public String getMessageKey() { + return "format.regex"; + } } diff --git a/src/main/java/com/networknt/schema/format/TimeFormat.java b/src/main/java/com/networknt/schema/format/TimeFormat.java index 77abf0590..7ded636e7 100644 --- a/src/main/java/com/networknt/schema/format/TimeFormat.java +++ b/src/main/java/com/networknt/schema/format/TimeFormat.java @@ -19,13 +19,18 @@ import java.time.format.DateTimeFormatterBuilder; import java.time.temporal.TemporalAccessor; +import com.networknt.schema.ExecutionContext; +import com.networknt.schema.Format; + import static java.time.format.DateTimeFormatter.ISO_LOCAL_TIME; import static java.time.temporal.ChronoField.*; /** + * Format for time. + *

* Validates that a value conforms to the time specification in RFC 3339. */ -public class TimeFormat extends AbstractFormat { +public class TimeFormat implements Format { // In 2023, time-zone offsets around the world extend from -12:00 to +14:00. // However, RFC 3339 accepts -23:59 to +23:59. private static final long MAX_OFFSET_MIN = 24 * 60 - 1; @@ -38,12 +43,8 @@ public class TimeFormat extends AbstractFormat { .parseLenient() .toFormatter(); - public TimeFormat() { - super("time", "must be a valid RFC 3339 time"); - } - @Override - public boolean matches(String value) { + public boolean matches(ExecutionContext executionContext, String value) { try { if (null == value) return true; @@ -79,4 +80,13 @@ public boolean matches(String value) { } } + @Override + public String getName() { + return "time"; + } + + @Override + public String getMessageKey() { + return "format.time"; + } } diff --git a/src/main/java/com/networknt/schema/format/UriFormat.java b/src/main/java/com/networknt/schema/format/UriFormat.java index 805499119..50fc91106 100644 --- a/src/main/java/com/networknt/schema/format/UriFormat.java +++ b/src/main/java/com/networknt/schema/format/UriFormat.java @@ -2,15 +2,22 @@ import java.net.URI; +/** + * Format for uri. + */ public class UriFormat extends AbstractRFC3986Format { - - public UriFormat() { - super("uri", "must be a valid RFC 3986 URI"); - } - @Override protected boolean validate(URI uri) { return uri.isAbsolute(); } + @Override + public String getName() { + return "uri"; + } + + @Override + public String getMessageKey() { + return "format.uri"; + } } diff --git a/src/main/java/com/networknt/schema/format/UriReferenceFormat.java b/src/main/java/com/networknt/schema/format/UriReferenceFormat.java index 8c23e5212..943afafd4 100644 --- a/src/main/java/com/networknt/schema/format/UriReferenceFormat.java +++ b/src/main/java/com/networknt/schema/format/UriReferenceFormat.java @@ -2,15 +2,22 @@ import java.net.URI; +/** + * Format for uri-reference. + */ public class UriReferenceFormat extends AbstractRFC3986Format { - - public UriReferenceFormat() { - super("uri-reference", "must be a valid RFC 3986 URI-reference"); - } - @Override protected boolean validate(URI uri) { return true; } + @Override + public String getName() { + return "uri-reference"; + } + + @Override + public String getMessageKey() { + return "format.uri-reference"; + } } diff --git a/src/main/resources/jsv-messages.properties b/src/main/resources/jsv-messages.properties index ac55585c7..cc145ce5e 100644 --- a/src/main/resources/jsv-messages.properties +++ b/src/main/resources/jsv-messages.properties @@ -8,7 +8,6 @@ contains = {0}: does not contain an element that passes these validations: {2} contains.max = {0}: must contain fewer than {1} element(s) that passes these validations: {2} contains.min = {0}: must contain at least {1} element(s) that passes these validations: {2} crossEdits = {0}: has an error with ''cross edits'' -dateTime = {0}: {1} is an invalid {2} dependencies = {0}: has an error with dependencies {1} dependentRequired = {0}: has a missing property "{1}" which is dependent required because "{2}" is present dependentSchemas = {0}: has an error with dependentSchemas {1} @@ -18,6 +17,26 @@ exclusiveMaximum = {0}: must have an exclusive maximum value of {1} exclusiveMinimum = {0}: must have an exclusive minimum value of {1} false = {0}: schema for ''{1}'' is false format = {0}: does not match the {1} pattern {2} +format.date = {0}: does not match the {1} pattern must be a valid RFC 3339 full-date +format.date-time = {0}: does not match the {1} pattern must be a valid RFC 3339 date-time +format.duration = {0}: does not match the {1} pattern must be a valid ISO 8601 duration +format.email = {0}: does not match the {1} pattern must be a valid RFC 5321 Mailbox +format.ipv4 = {0}: does not match the {1} pattern must be a valid RFC 2673 IP address +format.ipv6 = {0}: does not match the {1} pattern must be a valid RFC 4291 IP address +format.idn-email = {0}: does not match the {1} pattern must be a valid RFC 6531 Mailbox +format.idn-hostname = {0}: does not match the {1} pattern must be a valid RFC 5890 internationalized hostname +format.iri = {0}: does not match the {1} pattern must be a valid RFC 3987 IRI +format.iri-reference = {0}: does not match the {1} pattern must be a valid RFC 3987 IRI-reference +format.uri = {0}: does not match the {1} pattern must be a valid RFC 3986 URI +format.uri-reference = {0}: does not match the {1} pattern must be a valid RFC 3986 URI-reference +format.uri-template = {0}: does not match the {1} pattern must be a valid RFC 6570 URI Template +format.uuid = {0}: does not match the {1} pattern must be a valid RFC 4122 UUID +format.regex = {0}: does not match the {1} pattern must be a valid ECMA-262 regular expression +format.time = {0}: does not match the {1} pattern must be a valid RFC 3339 time +format.hostname = {0}: does not match the {1} pattern must be a valid RFC 1123 host name +format.json-pointer = {0}: does not match the {1} pattern must be a valid RFC 6901 JSON Pointer +format.relative-json-pointer = {0}: does not match the {1} pattern must be a valid IETF Relative JSON Pointer +format.unknown = {0}: has an unknown format ''{1}'' id = {0}: {1} is an invalid segment for URI {2} items = {0}: index ''{1}'' is not defined in the schema and the schema does not allow additional items maxContains = {0}: must be a non-negative integer in {1} diff --git a/src/test/java/com/networknt/schema/CollectorContextTest.java b/src/test/java/com/networknt/schema/CollectorContextTest.java index a7956b9b8..69d59a843 100644 --- a/src/test/java/com/networknt/schema/CollectorContextTest.java +++ b/src/test/java/com/networknt/schema/CollectorContextTest.java @@ -99,7 +99,9 @@ public void testCollectorContextWithMultipleThreads() throws Exception { @Test public void testCollectorGetAll() throws JsonMappingException, JsonProcessingException, IOException { ObjectMapper objectMapper = new ObjectMapper(); - ValidationResult validationResult = jsonSchemaForCombine.validateAndCollect(objectMapper + ExecutionContext executionContext = jsonSchemaForCombine.createExecutionContext(); + executionContext.getExecutionConfig().setFormatAssertionsEnabled(true); + ValidationResult validationResult = jsonSchemaForCombine.validateAndCollect(executionContext, objectMapper .readTree("{\"property1\":\"sample1\",\"property2\":\"sample2\",\"property3\":\"sample3\" }")); CollectorContext collectorContext = validationResult.getCollectorContext(); Assertions.assertEquals(((List) collectorContext.get(SAMPLE_COLLECTOR)).size(), 1); diff --git a/src/test/java/com/networknt/schema/FormatValidatorTest.java b/src/test/java/com/networknt/schema/FormatValidatorTest.java new file mode 100644 index 000000000..fb6f40faf --- /dev/null +++ b/src/test/java/com/networknt/schema/FormatValidatorTest.java @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.networknt.schema; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.math.BigDecimal; +import java.util.Collections; +import java.util.Set; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +import com.fasterxml.jackson.databind.JsonNode; +import com.networknt.schema.SpecVersion.VersionFlag; +import com.networknt.schema.format.PatternFormat; +import com.networknt.schema.output.OutputUnit; + +/** + * Test for format validator. + */ +public class FormatValidatorTest { + @Test + void unknownFormatNoVocab() { + String schemaData = "{\r\n" + + " \"format\":\"unknown\"\r\n" + + "}"; + JsonSchema schema = JsonSchemaFactory.getInstance(VersionFlag.V202012).getSchema(schemaData); + Set messages = schema.validate("\"hello\"", InputFormat.JSON, executionContext -> { + executionContext.getExecutionConfig().setFormatAssertionsEnabled(true); + }); + assertEquals(0, messages.size()); + } + + @Test + void unknownFormatNoVocabStrictTrue() { + String schemaData = "{\r\n" + + " \"format\":\"unknown\"\r\n" + + "}"; + SchemaValidatorsConfig config = new SchemaValidatorsConfig(); + config.setStrict("format", true); + JsonSchema schema = JsonSchemaFactory.getInstance(VersionFlag.V202012).getSchema(schemaData, config); + Set messages = schema.validate("\"hello\"", InputFormat.JSON, executionContext -> { + executionContext.getExecutionConfig().setFormatAssertionsEnabled(true); + }); + assertEquals(1, messages.size()); + assertEquals("format.unknown", messages.iterator().next().getMessageKey()); + } + + @Test + void unknownFormatAssertionsVocab() { + String metaSchemaData = "{\r\n" + + " \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\r\n" + + " \"$id\": \"https://www.example.com/format-assertion/schema\",\r\n" + + " \"$vocabulary\": {\r\n" + + " \"https://json-schema.org/draft/2020-12/vocab/format-assertion\": true,\r\n" + + " \"https://json-schema.org/draft/2020-12/vocab/applicator\": true,\r\n" + + " \"https://json-schema.org/draft/2020-12/vocab/core\": true\r\n" + + " },\r\n" + + " \"allOf\": [\r\n" + + " { \"$ref\": \"https://json-schema.org/draft/2020-12/meta/applicator\" },\r\n" + + " { \"$ref\": \"https://json-schema.org/draft/2020-12/meta/core\" }\r\n" + + " ]\r\n" + + "}"; + + String schemaData = "{\r\n" + + " \"$schema\": \"https://www.example.com/format-assertion/schema\",\r\n" + + " \"format\":\"unknown\"\r\n" + + "}"; + SchemaValidatorsConfig config = new SchemaValidatorsConfig(); + JsonSchema schema = JsonSchemaFactory + .getInstance(VersionFlag.V202012, + builder -> builder + .schemaLoaders(schemaLoaders -> schemaLoaders.schemas(Collections.singletonMap("https://www.example.com/format-assertion/schema", metaSchemaData)))) + .getSchema(schemaData, config); + Set messages = schema.validate("\"hello\"", InputFormat.JSON); + assertEquals(1, messages.size()); + assertEquals("format.unknown", messages.iterator().next().getMessageKey()); + } + + @Test + void unknownFormatShouldCollectAnnotations() { + String schemaData = "{\r\n" + + " \"format\":\"unknown\"\r\n" + + "}"; + JsonSchema schema = JsonSchemaFactory.getInstance(VersionFlag.V202012).getSchema(schemaData); + OutputUnit outputUnit = schema.validate("\"hello\"", InputFormat.JSON, OutputFormat.HIERARCHICAL, executionContext -> { + executionContext.getExecutionConfig().setAnnotationCollectionEnabled(true); + executionContext.getExecutionConfig().setAnnotationCollectionFilter(keyword -> true); + }); + assertEquals("unknown", outputUnit.getAnnotations().get("format")); + assertTrue(outputUnit.isValid()); // as no assertion vocab and assertions not enabled + } + + enum FormatInput { + DATE_TIME("date-time"), + DATE("date"), + TIME("time"), + DURATION("duration"), + EMAIL("email"), + IDN_EMAIL("idn-email"), + HOSTNAME("hostname"), + IDN_HOSTNAME("idn-hostname"), + IPV4("ipv4"), + IPV6("ipv6"), + URI("uri"), + URI_REFERENCE("uri-reference"), + IRI("iri"), + IRI_REFERENCE("iri-reference"), + UUID("uuid"), + JSON_POINTER("json-pointer"), + RELATIVE_JSON_POINTER("relative-json-pointer"), + REGEX("regex"); + + String format; + + FormatInput(String format) { + this.format = format; + } + } + + @ParameterizedTest + @EnumSource(FormatInput.class) + void formatAssertions(FormatInput formatInput) { + String formatSchema = "{\r\n" + + " \"type\": \"string\",\r\n" + + " \"format\": \""+formatInput.format+"\"\r\n" + + "}"; + JsonSchemaFactory factory = JsonSchemaFactory.getInstance(VersionFlag.V202012); + SchemaValidatorsConfig config = new SchemaValidatorsConfig(); + config.setPathType(PathType.JSON_POINTER); + JsonSchema schema = factory.getSchema(formatSchema, config); + Set messages = schema.validate("\"inval!i:d^(abc]\"", InputFormat.JSON, executionConfiguration -> { + executionConfiguration.getExecutionConfig().setFormatAssertionsEnabled(true); + }); + assertFalse(messages.isEmpty()); + } + + /** + * This tests that the changes to use message key doesn't cause a regression to + * the existing message. + */ + @SuppressWarnings("deprecation") + @Test + void patternFormatDeprecated() { + JsonMetaSchema customMetaSchema = JsonMetaSchema + .builder("https://www.example.com/schema", JsonMetaSchema.getV7()) + .formats(formats -> { + PatternFormat format = new PatternFormat("custom", "test", "must be test"); + formats.put(format.getName(), format); + }) + .build(); + + JsonSchemaFactory factory = new JsonSchemaFactory.Builder().defaultMetaSchemaURI(customMetaSchema.getUri()) + .addMetaSchema(customMetaSchema).build(); + String formatSchema = "{\r\n" + + " \"type\": \"string\",\r\n" + + " \"format\": \"custom\"\r\n" + + "}"; + SchemaValidatorsConfig config = new SchemaValidatorsConfig(); + config.setPathType(PathType.JSON_POINTER); + JsonSchema schema = factory.getSchema(formatSchema, config); + Set messages = schema.validate("\"inval!i:d^(abc]\"", InputFormat.JSON, executionConfiguration -> { + executionConfiguration.getExecutionConfig().setFormatAssertionsEnabled(true); + }); + assertFalse(messages.isEmpty()); + assertEquals(": does not match the custom pattern must be test", messages.iterator().next().getMessage()); + } + + public static class CustomNumberFormat implements Format { + private final BigDecimal compare; + + public CustomNumberFormat(BigDecimal compare) { + this.compare = compare; + } + + @Override + public boolean matches(ExecutionContext executionContext, ValidationContext validationContext, JsonNode value) { + JsonType nodeType = TypeFactory.getValueNodeType(value, validationContext.getConfig()); + if (nodeType != JsonType.NUMBER && nodeType != JsonType.INTEGER) { + return true; + } + BigDecimal number = value.isBigDecimal() ? value.decimalValue() : BigDecimal.valueOf(value.doubleValue()); + number = new BigDecimal(number.toPlainString()); + return number.compareTo(compare) == 0; + } + + @Override + public String getName() { + return "custom-number"; + } + } + + @Test + void shouldAllowNumberFormat() { + JsonMetaSchema customMetaSchema = JsonMetaSchema + .builder("https://www.example.com/schema", JsonMetaSchema.getV7()) + .formats(formats -> { + CustomNumberFormat format = new CustomNumberFormat(new BigDecimal("12345")); + formats.put(format.getName(), format); + }) + .build(); + + JsonSchemaFactory factory = new JsonSchemaFactory.Builder().defaultMetaSchemaURI(customMetaSchema.getUri()) + .addMetaSchema(customMetaSchema).build(); + String formatSchema = "{\r\n" + + " \"type\": \"number\",\r\n" + + " \"format\": \"custom-number\"\r\n" + + "}"; + SchemaValidatorsConfig config = new SchemaValidatorsConfig(); + config.setPathType(PathType.JSON_POINTER); + JsonSchema schema = factory.getSchema(formatSchema, config); + Set messages = schema.validate("123451", InputFormat.JSON, executionConfiguration -> { + executionConfiguration.getExecutionConfig().setFormatAssertionsEnabled(true); + }); + assertFalse(messages.isEmpty()); + assertEquals(": does not match the custom-number pattern ", messages.iterator().next().getMessage()); + messages = schema.validate("12345", InputFormat.JSON, executionConfiguration -> { + executionConfiguration.getExecutionConfig().setFormatAssertionsEnabled(true); + }); + assertTrue(messages.isEmpty()); + + } +} diff --git a/src/test/java/com/networknt/schema/Issue784Test.java b/src/test/java/com/networknt/schema/Issue784Test.java index eea913c99..39715eb59 100644 --- a/src/test/java/com/networknt/schema/Issue784Test.java +++ b/src/test/java/com/networknt/schema/Issue784Test.java @@ -2,10 +2,10 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; + import org.junit.jupiter.api.Test; import java.io.IOException; -import java.util.Collections; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -61,11 +61,14 @@ private Set validate(JsonSchema jsonSchema, String myDateTime } private JsonSchema createSchema(boolean useCustomDateFormat) { - JsonMetaSchema overrideDateTimeValidator = new JsonMetaSchema - .Builder(JsonMetaSchema.getV7().getUri()) - .idKeyword("$id") - .addKeywords(ValidatorTypeCode.getNonFormatKeywords(SpecVersion.VersionFlag.V7)) - .addFormats(useCustomDateFormat ? Collections.singletonList(new CustomDateTimeFormat()) : Collections.emptyList()) + JsonMetaSchema overrideDateTimeValidator =JsonMetaSchema + .builder(JsonMetaSchema.getV7().getUri(), JsonMetaSchema.getV7()) + .formats(formats -> { + if (useCustomDateFormat) { + CustomDateTimeFormat format = new CustomDateTimeFormat(); + formats.put(format.getName(), format); + } + }) .build(); return new JsonSchemaFactory diff --git a/src/test/java/com/networknt/schema/Issue832Test.java b/src/test/java/com/networknt/schema/Issue832Test.java index 1235ddffe..0fba9674c 100644 --- a/src/test/java/com/networknt/schema/Issue832Test.java +++ b/src/test/java/com/networknt/schema/Issue832Test.java @@ -2,7 +2,6 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.networknt.schema.format.AbstractFormat; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -13,14 +12,20 @@ import java.util.Set; public class Issue832Test { - private class NoMatchFormat extends AbstractFormat { - public NoMatchFormat() { - super("no_match", "always fail match"); + private class NoMatchFormat implements Format { + @Override + public boolean matches(ExecutionContext executionContext, String value) { + return false; } @Override - public boolean matches(String value) { - return false; + public String getName() { + return "no_match"; + } + + @Override + public String getErrorMessageDescription() { + return "always fail match"; } } diff --git a/src/test/java/com/networknt/schema/OverrideValidatorTest.java b/src/test/java/com/networknt/schema/OverrideValidatorTest.java index ccedb0ab9..afac2de89 100644 --- a/src/test/java/com/networknt/schema/OverrideValidatorTest.java +++ b/src/test/java/com/networknt/schema/OverrideValidatorTest.java @@ -56,7 +56,7 @@ public void overrideDefaultValidator() throws JsonProcessingException, IOExcepti // Override EmailValidator final JsonMetaSchema overrideValidatorMetaSchema = JsonMetaSchema .builder(URI, JsonMetaSchema.getV201909()) - .addFormat(new PatternFormat("email", "^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$", null)) + .addFormat(PatternFormat.of("email", "^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$", "format.email")) .build(); final JsonSchemaFactory overrideValidatorFactory = JsonSchemaFactory.builder(JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V201909)).addMetaSchema(overrideValidatorMetaSchema).build();