Repository: networknt/json-schema-validator
Pull request #593 (2022-07-31 11:59:48)

add validator for duration format
Add  validatior for duration format introduced on the Draft 2019-09 : https://json-schema.org/draft/2019-09/release-notes.html




Patch:
diff --git a/pom.xml b/pom.xml
index 0f680ac..26449d1 100644
--- a/pom.xml
+++ b/pom.xml
@@ -84,10 +84,18 @@
             <artifactId>slf4j-api</artifactId>
             <version>${version.slf4j}</version>
         </dependency>
+        <!-- 
+        Commons lang slated for removal but kept for projects that accidentally depend on it
+        through accidental transitive runtime dependencies.
+        
+        For projects that depend on it for compile they will get an immediate failure as the
+        scope is now runtime instead of compile.
+        -->
         <dependency>
             <groupId>org.apache.commons</groupId>
             <artifactId>commons-lang3</artifactId>
             <version>${version.common-lang3}</version>
+            <scope>runtime</scope>
         </dependency>
         <dependency>
             <groupId>org.jruby.joni</groupId>
diff --git a/src/main/java/com/networknt/schema/BaseJsonValidator.java b/src/main/java/com/networknt/schema/BaseJsonValidator.java
index 7ffa4ba..5100931 100644
--- a/src/main/java/com/networknt/schema/BaseJsonValidator.java
+++ b/src/main/java/com/networknt/schema/BaseJsonValidator.java
@@ -26,7 +26,7 @@ import java.util.Set;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.node.ObjectNode;
 import com.networknt.schema.ValidationContext.DiscriminatorContext;
-import org.apache.commons.lang3.StringUtils;
+import com.networknt.schema.utils.StringUtils;
 import org.slf4j.Logger;
 
 public abstract class BaseJsonValidator implements JsonValidator {
diff --git a/src/main/java/com/networknt/schema/FormatKeyword.java b/src/main/java/com/networknt/schema/FormatKeyword.java
index 5c77935..0154e73 100644
--- a/src/main/java/com/networknt/schema/FormatKeyword.java
+++ b/src/main/java/com/networknt/schema/FormatKeyword.java
@@ -17,6 +17,7 @@
 package com.networknt.schema;
 
 import com.fasterxml.jackson.databind.JsonNode;
+import com.networknt.schema.format.DurationValidator;
 import com.networknt.schema.format.EmailValidator;
 
 import java.util.Collection;
@@ -31,6 +32,7 @@ public class FormatKeyword implements Keyword {
     private final String DATE_TIME = "date-time";
     private final String UUID = "uuid";
     private final String EMAIL = "email";
+    private final String DURATION = "duration";
 
     public FormatKeyword(ValidatorTypeCode type, Map<String, Format> formats) {
         this.type = type;
@@ -60,6 +62,9 @@ public class FormatKeyword implements Keyword {
             } else if (formatName.equals(EMAIL)) {
                 return new EmailValidator(schemaPath, schemaNode, parentSchema, validationContext, formatName);
             }
+            else if (formatName.equals(DURATION)) {
+                return new DurationValidator(schemaPath, schemaNode, parentSchema, validationContext, formatName);
+            }
         }
         return new FormatValidator(schemaPath, schemaNode, parentSchema, validationContext, format);
     }
diff --git a/src/main/java/com/networknt/schema/JsonMetaSchema.java b/src/main/java/com/networknt/schema/JsonMetaSchema.java
index 1e543f3..61699bf 100644
--- a/src/main/java/com/networknt/schema/JsonMetaSchema.java
+++ b/src/main/java/com/networknt/schema/JsonMetaSchema.java
@@ -17,7 +17,7 @@
 package com.networknt.schema;
 
 import com.fasterxml.jackson.databind.JsonNode;
-import org.apache.commons.lang3.StringUtils;
+import com.networknt.schema.utils.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
diff --git a/src/main/java/com/networknt/schema/ValidationMessage.java b/src/main/java/com/networknt/schema/ValidationMessage.java
index 843e4fe..db14cab 100644
--- a/src/main/java/com/networknt/schema/ValidationMessage.java
+++ b/src/main/java/com/networknt/schema/ValidationMessage.java
@@ -16,7 +16,7 @@
 
 package com.networknt.schema;
 
-import org.apache.commons.lang3.StringUtils;
+import com.networknt.schema.utils.StringUtils;
 
 import java.text.MessageFormat;
 import java.util.Arrays;
diff --git a/src/main/java/com/networknt/schema/format/DurationValidator.java b/src/main/java/com/networknt/schema/format/DurationValidator.java
new file mode 100644
index 0000000..a4aceb4
--- /dev/null
+++ b/src/main/java/com/networknt/schema/format/DurationValidator.java
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.fasterxml.jackson.databind.JsonNode;
+import com.networknt.schema.*;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ *
+ * <p>This class provides methods to validate a duration format .
+ *
+ * @version $Revision$
+ * @since Validator 1.4
+ */
+public class DurationValidator extends BaseJsonValidator implements JsonValidator {
+    private static final Logger logger = LoggerFactory.getLogger(DurationValidator.class);
+
+    private static final String DURATION_REGEX = "^(-?)P(?=\\d|T\\d)(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)([DW]))?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+(?:\\.\\d+)?)S)?)?$";
+    private static final Pattern DURATION_PATTERN = Pattern.compile(DURATION_REGEX);
+    private final String formatName;
+
+
+
+    /**
+     * <p>Checks if a field has a valid duration.</p>
+     *
+     * @param duration The value validation is being performed on.  A <code>null</code>
+     *              value is considered invalid.
+     * @return true if the duration valid.
+     */
+    public boolean isValid(String duration) {
+        if (duration == null) {
+            return false;
+        }
+
+        Matcher durationMatcher = DURATION_PATTERN.matcher(duration);
+        if (!durationMatcher.matches()) {
+            return false;
+        }
+
+        return true;
+    }
+
+    public DurationValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext, String formatName) {
+        super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.FORMAT, validationContext);
+        this.formatName = formatName;
+        this.validationContext = validationContext;
+        parseErrorCode(getValidatorType().getErrorCodeKey());
+    }
+
+    @Override
+    public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
+        debug(logger, node, rootNode, at);
+
+        Set<ValidationMessage> errors = new LinkedHashSet<ValidationMessage>();
+
+        JsonType nodeType = TypeFactory.getValueNodeType(node, this.validationContext.getConfig());
+        if (nodeType != JsonType.STRING) {
+            return errors;
+        }
+        if (!isValid(node.textValue())) {
+            errors.add(buildValidationMessage(at, node.textValue(), formatName));
+        }
+        return Collections.unmodifiableSet(errors);
+
+    }
+}
\ No newline at end of file
diff --git a/src/main/java/com/networknt/schema/utils/StringUtils.java b/src/main/java/com/networknt/schema/utils/StringUtils.java
new file mode 100644
index 0000000..2e06651
--- /dev/null
+++ b/src/main/java/com/networknt/schema/utils/StringUtils.java
@@ -0,0 +1,53 @@
+package com.networknt.schema.utils;
+
+public final class StringUtils {
+
+    private StringUtils() {
+    }
+
+    public static boolean isBlank(final CharSequence cs) {
+        int strLen = length(cs);
+        if (strLen == 0) {
+            return true;
+        }
+        for (int i = 0; i < strLen; i++) {
+            if (!Character.isWhitespace(cs.charAt(i))) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    public static boolean isNotBlank(final CharSequence cs) {
+        return !isBlank(cs);
+    }
+
+    private static int length(final CharSequence cs) {
+        return cs == null ? 0 : cs.length();
+    }
+
+    // The following was borrowed from Apache Commons Lang 3
+    public static boolean equals(final CharSequence cs1, final CharSequence cs2) {
+        if (cs1 == cs2) {
+            return true;
+        }
+        if (cs1 == null || cs2 == null) {
+            return false;
+        }
+        if (cs1.length() != cs2.length()) {
+            return false;
+        }
+        if (cs1 instanceof String && cs2 instanceof String) {
+            return cs1.equals(cs2);
+        }
+        // Step-wise comparison
+        final int length = cs1.length();
+        for (int i = 0; i < length; i++) {
+            if (cs1.charAt(i) != cs2.charAt(i)) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+}


Test patch:
diff --git a/src/test/java/com/networknt/schema/BaseSuiteJsonSchemaTest.java b/src/test/java/com/networknt/schema/BaseSuiteJsonSchemaTest.java
index 2a316a4..7711cdd 100644
--- a/src/test/java/com/networknt/schema/BaseSuiteJsonSchemaTest.java
+++ b/src/test/java/com/networknt/schema/BaseSuiteJsonSchemaTest.java
@@ -21,7 +21,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.node.ArrayNode;
 import io.undertow.Undertow;
 import io.undertow.server.handlers.resource.FileResourceManager;
-import org.apache.commons.lang3.StringUtils;
+import com.networknt.schema.utils.StringUtils;
 import org.junit.jupiter.api.AfterAll;
 import org.junit.jupiter.api.BeforeAll;
 
diff --git a/src/test/java/com/networknt/schema/DurationFormatValidatorTest.java b/src/test/java/com/networknt/schema/DurationFormatValidatorTest.java
new file mode 100644
index 0000000..df85b34
--- /dev/null
+++ b/src/test/java/com/networknt/schema/DurationFormatValidatorTest.java
@@ -0,0 +1,48 @@
+/*
+ * 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;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class DurationFormatValidatorTest {
+
+    @Test
+    public void durationFormatValidatorTest() throws JsonProcessingException, IOException {
+        ObjectMapper objectMapper = new ObjectMapper();
+        final String schema = "{\"type\": \"string\", \"format\": \"duration\"}\n";
+        final JsonNode validTargetNode = objectMapper.readTree("\"P1D\"");
+        final JsonNode invalidTargetNode = objectMapper.readTree("\"INVALID_DURATION\"");
+
+        final JsonSchemaFactory validatorFactory = JsonSchemaFactory.builder(JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V201909)).build();
+        final JsonSchema validatorSchema = validatorFactory.getSchema(schema);
+
+        Set<ValidationMessage> messages = validatorSchema.validate(validTargetNode);
+        assertEquals(0, messages.size());
+
+        messages = validatorSchema.validate(invalidTargetNode);
+        assertEquals(1, messages.size());
+
+    }
+}