From 7c4944b79195720bb5c809be99cef79c475ab441 Mon Sep 17 00:00:00 2001 From: "J. Koster" Date: Mon, 18 Nov 2024 23:06:55 +0100 Subject: [PATCH] Clean up code (#1130) * Simplify code, add final keyword, use diamond operator, correct English, use lambdas, remove .toString, use .isEmpty(), use .addAll, and more * Thanks to IntelliJ code analyses feature --- .../validator/routines/DomainValidator.java | 1 - .../validator/routines/EmailValidator.java | 6 +--- .../routines/InetAddressValidator.java | 5 +-- .../networknt/schema/AnnotationKeyword.java | 4 +-- .../networknt/schema/BaseJsonValidator.java | 2 +- .../java/com/networknt/schema/Collector.java | 4 +-- .../schema/DefaultJsonMetaSchemaFactory.java | 5 +-- .../schema/DependenciesValidator.java | 4 +-- .../networknt/schema/DependentRequired.java | 4 +-- .../DisallowUnknownJsonMetaSchemaFactory.java | 2 +- .../schema/DisallowUnknownKeywordFactory.java | 2 +- .../com/networknt/schema/EnumValidator.java | 4 +-- .../com/networknt/schema/ItemsValidator.java | 2 +- .../schema/ItemsValidator202012.java | 2 +- .../com/networknt/schema/JsonMetaSchema.java | 6 ++-- .../com/networknt/schema/JsonNodePath.java | 2 +- .../java/com/networknt/schema/JsonSchema.java | 23 ++++-------- .../networknt/schema/JsonSchemaFactory.java | 10 +++--- .../schema/JsonSchemaIdValidator.java | 6 ++-- .../java/com/networknt/schema/JsonType.java | 2 +- .../com/networknt/schema/JsonValidator.java | 6 ++-- .../schema/NonValidationKeyword.java | 2 +- .../com/networknt/schema/OutputFormat.java | 24 ++++++------- .../java/com/networknt/schema/PathType.java | 10 +++--- .../networknt/schema/PatternValidator.java | 4 +-- .../schema/PrefixItemsValidator.java | 2 +- .../schema/RecursiveRefValidator.java | 4 +-- .../com/networknt/schema/SchemaLocation.java | 6 ++-- .../schema/SchemaValidatorsConfig.java | 8 ++--- .../networknt/schema/SpecVersionDetector.java | 2 +- .../schema/UnevaluatedItemsValidator.java | 6 ++-- .../UnevaluatedPropertiesValidator.java | 4 +-- .../schema/UniqueItemsValidator.java | 2 +- .../schema/UnknownKeywordFactory.java | 2 +- .../networknt/schema/ValidationMessage.java | 7 ++-- .../schema/ValidationMessageHandler.java | 4 +-- .../networknt/schema/ValidatorTypeCode.java | 7 ++-- .../com/networknt/schema/Version201909.java | 6 ++-- .../com/networknt/schema/Version202012.java | 6 ++-- .../java/com/networknt/schema/Vocabulary.java | 5 ++- .../schema/format/AbstractRFC3986Format.java | 5 +-- .../schema/format/IriReferenceFormat.java | 4 +-- .../i18n/ResourceBundleMessageSource.java | 22 ++++-------- .../com/networknt/schema/oas/OpenApi31.java | 6 ++-- .../schema/regex/JoniRegularExpression.java | 6 ++-- .../schema/resource/DisallowSchemaLoader.java | 2 +- .../schema/resource/SchemaLoaders.java | 2 +- .../schema/resource/SchemaMappers.java | 2 +- .../schema/serialization/JsonNodeReader.java | 2 +- .../networknt/schema/utils/JsonNodeUtil.java | 18 +++------- .../com/networknt/schema/utils/RFC5892.java | 36 +++++++++---------- .../com/networknt/schema/utils/SetView.java | 2 +- .../networknt/schema/utils/StringChecker.java | 4 +-- .../com/networknt/schema/utils/UCDLoader.java | 2 +- .../schema/walk/JsonSchemaWalkListener.java | 4 +-- .../schema/walk/JsonSchemaWalker.java | 6 ++-- .../com/networknt/schema/walk/WalkEvent.java | 2 +- .../schema/walk/WalkListenerRunner.java | 8 ++--- 58 files changed, 146 insertions(+), 200 deletions(-) diff --git a/src/main/java/com/networknt/org/apache/commons/validator/routines/DomainValidator.java b/src/main/java/com/networknt/org/apache/commons/validator/routines/DomainValidator.java index c621e2877..4c9550ba0 100644 --- a/src/main/java/com/networknt/org/apache/commons/validator/routines/DomainValidator.java +++ b/src/main/java/com/networknt/org/apache/commons/validator/routines/DomainValidator.java @@ -96,7 +96,6 @@ public enum ArrayType { * @since 1.7 */ LOCAL_MINUS - ; } private static class IDNBUGHOLDER { diff --git a/src/main/java/com/networknt/org/apache/commons/validator/routines/EmailValidator.java b/src/main/java/com/networknt/org/apache/commons/validator/routines/EmailValidator.java index 6876d7959..5c86af0f4 100644 --- a/src/main/java/com/networknt/org/apache/commons/validator/routines/EmailValidator.java +++ b/src/main/java/com/networknt/org/apache/commons/validator/routines/EmailValidator.java @@ -186,11 +186,7 @@ public boolean isValid(final String email) { return false; } - if (!isValidDomain(emailMatcher.group(2))) { - return false; - } - - return true; + return isValidDomain(emailMatcher.group(2)); } /** diff --git a/src/main/java/com/networknt/org/apache/commons/validator/routines/InetAddressValidator.java b/src/main/java/com/networknt/org/apache/commons/validator/routines/InetAddressValidator.java index f3ed5aeba..8a27409c3 100644 --- a/src/main/java/com/networknt/org/apache/commons/validator/routines/InetAddressValidator.java +++ b/src/main/java/com/networknt/org/apache/commons/validator/routines/InetAddressValidator.java @@ -213,9 +213,6 @@ public boolean isValidInet6Address(String inet6Address) { } validOctets++; } - if (validOctets > IPV6_MAX_HEX_GROUPS || validOctets < IPV6_MAX_HEX_GROUPS && !containsCompressedZeroes) { - return false; - } - return true; + return validOctets <= IPV6_MAX_HEX_GROUPS && (validOctets >= IPV6_MAX_HEX_GROUPS || containsCompressedZeroes); } } \ No newline at end of file diff --git a/src/main/java/com/networknt/schema/AnnotationKeyword.java b/src/main/java/com/networknt/schema/AnnotationKeyword.java index e0d7d5c82..484d1eb1a 100644 --- a/src/main/java/com/networknt/schema/AnnotationKeyword.java +++ b/src/main/java/com/networknt/schema/AnnotationKeyword.java @@ -44,7 +44,7 @@ public Set validate(ExecutionContext executionContext, JsonNo return Collections.emptySet(); } - protected Object getAnnotationValue(JsonNode schemaNode) { + private Object getAnnotationValue(JsonNode schemaNode) { if (schemaNode.isTextual()) { return schemaNode.textValue(); } else if (schemaNode.isNumber()) { @@ -62,7 +62,7 @@ public AnnotationKeyword(String keyword) { @Override public JsonValidator newValidator(SchemaLocation schemaLocation, JsonNodePath evaluationPath, JsonNode schemaNode, - JsonSchema parentSchema, ValidationContext validationContext) throws JsonSchemaException, Exception { + JsonSchema parentSchema, ValidationContext validationContext) { return new Validator(schemaLocation, evaluationPath, schemaNode, parentSchema, validationContext, this); } } diff --git a/src/main/java/com/networknt/schema/BaseJsonValidator.java b/src/main/java/com/networknt/schema/BaseJsonValidator.java index be816be36..ca1c33867 100644 --- a/src/main/java/com/networknt/schema/BaseJsonValidator.java +++ b/src/main/java/com/networknt/schema/BaseJsonValidator.java @@ -147,7 +147,7 @@ public static void debug(Logger logger, ExecutionContext executionContext, JsonN /** * Checks based on the current {@link DiscriminatorContext} whether the provided {@link JsonSchema} a match against - * against the current discriminator. + * the current discriminator. * * @param currentDiscriminatorContext the currently active {@link DiscriminatorContext} * @param discriminator the discriminator to use for the check diff --git a/src/main/java/com/networknt/schema/Collector.java b/src/main/java/com/networknt/schema/Collector.java index c8404e063..f3e84f00b 100644 --- a/src/main/java/com/networknt/schema/Collector.java +++ b/src/main/java/com/networknt/schema/Collector.java @@ -32,7 +32,7 @@ public interface Collector { * at multiple touch points or accumulating data at same touch point. * @param object Object */ - public void combine(Object object); + void combine(Object object); /** * Final method called by the framework that returns the actual collected data. @@ -40,7 +40,7 @@ public interface Collector { * multiple touch points, only this method can be implemented. * @return E element */ - public E collect(); + E collect(); } diff --git a/src/main/java/com/networknt/schema/DefaultJsonMetaSchemaFactory.java b/src/main/java/com/networknt/schema/DefaultJsonMetaSchemaFactory.java index 342e86f6c..69a41b631 100644 --- a/src/main/java/com/networknt/schema/DefaultJsonMetaSchemaFactory.java +++ b/src/main/java/com/networknt/schema/DefaultJsonMetaSchemaFactory.java @@ -15,6 +15,7 @@ */ package com.networknt.schema; +import java.util.Map; import java.util.Map.Entry; import com.fasterxml.jackson.databind.JsonNode; @@ -60,7 +61,7 @@ protected JsonMetaSchema.Builder loadMetaSchemaBuilder(String iri, JsonSchemaFac // Process vocabularies JsonNode vocabulary = schema.getSchemaNode().get("$vocabulary"); if (vocabulary != null) { - builder.vocabularies(vocabularies -> vocabularies.clear()); + builder.vocabularies(Map::clear); for (Entry vocabs : vocabulary.properties()) { builder.vocabulary(vocabs.getKey(), vocabs.getValue().booleanValue()); } @@ -71,7 +72,7 @@ protected JsonMetaSchema.Builder loadMetaSchemaBuilder(String iri, JsonSchemaFac } private static class Holder { - private static DefaultJsonMetaSchemaFactory INSTANCE = new DefaultJsonMetaSchemaFactory(); + private static final DefaultJsonMetaSchemaFactory INSTANCE = new DefaultJsonMetaSchemaFactory(); } public static DefaultJsonMetaSchemaFactory getInstance() { diff --git a/src/main/java/com/networknt/schema/DependenciesValidator.java b/src/main/java/com/networknt/schema/DependenciesValidator.java index 72b6c7889..882d66592 100644 --- a/src/main/java/com/networknt/schema/DependenciesValidator.java +++ b/src/main/java/com/networknt/schema/DependenciesValidator.java @@ -27,8 +27,8 @@ */ public class DependenciesValidator extends BaseJsonValidator implements JsonValidator { private static final Logger logger = LoggerFactory.getLogger(DependenciesValidator.class); - private final Map> propertyDeps = new HashMap>(); - private final Map schemaDeps = new HashMap(); + private final Map> propertyDeps = new HashMap<>(); + private final Map schemaDeps = new HashMap<>(); /** * Constructor. diff --git a/src/main/java/com/networknt/schema/DependentRequired.java b/src/main/java/com/networknt/schema/DependentRequired.java index 8c7110f41..14a7bc21b 100644 --- a/src/main/java/com/networknt/schema/DependentRequired.java +++ b/src/main/java/com/networknt/schema/DependentRequired.java @@ -27,7 +27,7 @@ */ public class DependentRequired extends BaseJsonValidator implements JsonValidator { private static final Logger logger = LoggerFactory.getLogger(DependentRequired.class); - private final Map> propertyDependencies = new HashMap>(); + private final Map> propertyDependencies = new HashMap<>(); public DependentRequired(SchemaLocation schemaLocation, JsonNodePath evaluationPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) { @@ -49,7 +49,7 @@ public DependentRequired(SchemaLocation schemaLocation, JsonNodePath evaluationP public Set validate(ExecutionContext executionContext, JsonNode node, JsonNode rootNode, JsonNodePath instanceLocation) { debug(logger, executionContext, node, rootNode, instanceLocation); - Set errors = new LinkedHashSet(); + Set errors = new LinkedHashSet<>(); for (Iterator it = node.fieldNames(); it.hasNext(); ) { String pname = it.next(); diff --git a/src/main/java/com/networknt/schema/DisallowUnknownJsonMetaSchemaFactory.java b/src/main/java/com/networknt/schema/DisallowUnknownJsonMetaSchemaFactory.java index 6ca259bef..6ef036c61 100644 --- a/src/main/java/com/networknt/schema/DisallowUnknownJsonMetaSchemaFactory.java +++ b/src/main/java/com/networknt/schema/DisallowUnknownJsonMetaSchemaFactory.java @@ -28,7 +28,7 @@ public JsonMetaSchema getMetaSchema(String iri, JsonSchemaFactory schemaFactory, } private static class Holder { - private static DisallowUnknownJsonMetaSchemaFactory INSTANCE = new DisallowUnknownJsonMetaSchemaFactory(); + private static final DisallowUnknownJsonMetaSchemaFactory INSTANCE = new DisallowUnknownJsonMetaSchemaFactory(); } /** diff --git a/src/main/java/com/networknt/schema/DisallowUnknownKeywordFactory.java b/src/main/java/com/networknt/schema/DisallowUnknownKeywordFactory.java index e0f3f7e30..f3397b957 100644 --- a/src/main/java/com/networknt/schema/DisallowUnknownKeywordFactory.java +++ b/src/main/java/com/networknt/schema/DisallowUnknownKeywordFactory.java @@ -33,7 +33,7 @@ public Keyword getKeyword(String value, ValidationContext validationContext) { } private static class Holder { - private static DisallowUnknownKeywordFactory INSTANCE = new DisallowUnknownKeywordFactory(); + private static final DisallowUnknownKeywordFactory INSTANCE = new DisallowUnknownKeywordFactory(); } /** diff --git a/src/main/java/com/networknt/schema/EnumValidator.java b/src/main/java/com/networknt/schema/EnumValidator.java index db87130c6..44983f26c 100644 --- a/src/main/java/com/networknt/schema/EnumValidator.java +++ b/src/main/java/com/networknt/schema/EnumValidator.java @@ -48,7 +48,7 @@ static String asText(JsonNode node) { public EnumValidator(SchemaLocation schemaLocation, JsonNodePath evaluationPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) { super(schemaLocation, evaluationPath, schemaNode, parentSchema, ValidatorTypeCode.ENUM, validationContext); if (schemaNode != null && schemaNode.isArray()) { - nodes = new HashSet(); + nodes = new HashSet<>(); StringBuilder sb = new StringBuilder(); sb.append('['); @@ -144,7 +144,7 @@ protected ArrayNode processArrayNode(ArrayNode node) { if (!hasNumber(node)) { return node; } - ArrayNode a = (ArrayNode) node.deepCopy(); + ArrayNode a = node.deepCopy(); for (int x = 0; x < a.size(); x++) { JsonNode v = a.get(x); if (v.isNumber()) { diff --git a/src/main/java/com/networknt/schema/ItemsValidator.java b/src/main/java/com/networknt/schema/ItemsValidator.java index 5a6932f58..26f2813f6 100644 --- a/src/main/java/com/networknt/schema/ItemsValidator.java +++ b/src/main/java/com/networknt/schema/ItemsValidator.java @@ -125,7 +125,7 @@ public Set validate(ExecutionContext executionContext, JsonNo } boolean hasAdditionalItem = false; - SetView errors = new SetView(); + SetView errors = new SetView<>(); if (node.isArray()) { int i = 0; for (JsonNode n : node) { diff --git a/src/main/java/com/networknt/schema/ItemsValidator202012.java b/src/main/java/com/networknt/schema/ItemsValidator202012.java index d8efd1a33..b37971141 100644 --- a/src/main/java/com/networknt/schema/ItemsValidator202012.java +++ b/src/main/java/com/networknt/schema/ItemsValidator202012.java @@ -146,7 +146,7 @@ public Set walk(ExecutionContext executionContext, JsonNode n } } } else { - // If the node is not an ArrayNode, eg. ObjectNode or null then the instance is null. + // If the node is not an ArrayNode, e.g. ObjectNode or null then the instance is null. // The instance location starts at the end of the prefix count. walkSchema(executionContext, this.schema, null, rootNode, instanceLocation.append(this.prefixCount), shouldValidateSchema, validationMessages); diff --git a/src/main/java/com/networknt/schema/JsonMetaSchema.java b/src/main/java/com/networknt/schema/JsonMetaSchema.java index 38e561687..e2a90056e 100644 --- a/src/main/java/com/networknt/schema/JsonMetaSchema.java +++ b/src/main/java/com/networknt/schema/JsonMetaSchema.java @@ -56,9 +56,9 @@ public static class Builder { private String iri; private String idKeyword = "$id"; private VersionFlag specification = null; - private Map keywords = new HashMap<>(); - private Map formats = new HashMap<>(); - private Map vocabularies = new HashMap<>(); + private final Map keywords = new HashMap<>(); + private final Map formats = new HashMap<>(); + private final Map vocabularies = new HashMap<>(); private FormatKeywordFactory formatKeywordFactory = null; private VocabularyFactory vocabularyFactory = null; private KeywordFactory unknownKeywordFactory = null; diff --git a/src/main/java/com/networknt/schema/JsonNodePath.java b/src/main/java/com/networknt/schema/JsonNodePath.java index 19a0bca81..a0ca579da 100644 --- a/src/main/java/com/networknt/schema/JsonNodePath.java +++ b/src/main/java/com/networknt/schema/JsonNodePath.java @@ -120,7 +120,7 @@ public String getName(int index) { public Object getElement(int index) { if (index == -1) { if (this.pathSegmentIndex != -1) { - return Integer.valueOf(this.pathSegmentIndex); + return this.pathSegmentIndex; } else { return this.pathSegment; } diff --git a/src/main/java/com/networknt/schema/JsonSchema.java b/src/main/java/com/networknt/schema/JsonSchema.java index 9cd2071cf..65d67b284 100644 --- a/src/main/java/com/networknt/schema/JsonSchema.java +++ b/src/main/java/com/networknt/schema/JsonSchema.java @@ -332,7 +332,7 @@ public JsonSchema getRefSchema(JsonNodePath fragment) { } else { // Anchor String base = this.getSchemaLocation().getAbsoluteIri() != null ? this.schemaLocation.getAbsoluteIri().toString() : ""; - String anchor = base + "#" + fragment.toString(); + String anchor = base + "#" + fragment; JsonSchema result = this.validationContext.getSchemaResources().get(anchor); if (result == null) { result = this.validationContext.getDynamicAnchors().get(anchor); @@ -468,11 +468,8 @@ public boolean isSchemaResourceRoot() { return true; } // The schema should not cross - if (!Objects.equals(getSchemaLocation().getAbsoluteIri(), - getParentSchema().getSchemaLocation().getAbsoluteIri())) { - return true; - } - return false; + return !Objects.equals(getSchemaLocation().getAbsoluteIri(), + getParentSchema().getSchemaLocation().getAbsoluteIri()); } public String getId() { @@ -581,7 +578,7 @@ private long activeDialect() { * A comparator that sorts validators, such that 'properties' comes before 'required', * so that we can apply default values before validating required. */ - private static Comparator VALIDATOR_SORT = (lhs, rhs) -> { + private static final Comparator VALIDATOR_SORT = (lhs, rhs) -> { String lhsName = lhs.getEvaluationPath().getName(-1); String rhsName = rhs.getEvaluationPath().getName(-1); @@ -771,9 +768,7 @@ public T validate(JsonNode rootNode, OutputFormat format, ExecutionContex * @return the result */ public T validate(JsonNode rootNode, OutputFormat format, Consumer executionCustomizer) { - return validate(createExecutionContext(), rootNode, format, (executionContext, validationContext) -> { - executionCustomizer.accept(executionContext); - }); + return validate(createExecutionContext(), rootNode, format, (executionContext, validationContext) -> executionCustomizer.accept(executionContext)); } /** @@ -892,9 +887,7 @@ public T validate(String input, InputFormat inputFormat, OutputFormat for * @return the result */ public T validate(String input, InputFormat inputFormat, OutputFormat format, Consumer executionCustomizer) { - return validate(createExecutionContext(), deserialize(input, inputFormat), format, (executionContext, validationContext) -> { - executionCustomizer.accept(executionContext); - }); + return validate(createExecutionContext(), deserialize(input, inputFormat), format, (executionContext, validationContext) -> executionCustomizer.accept(executionContext)); } /** @@ -1241,9 +1234,7 @@ public ValidationResult walkAtNode(ExecutionContext executionContext, JsonNode n private T walkAtNodeInternal(ExecutionContext executionContext, JsonNode node, JsonNode rootNode, JsonNodePath instanceLocation, boolean validate, OutputFormat format, Consumer executionCustomizer) { return walkAtNodeInternal(executionContext, node, rootNode, instanceLocation, validate, format, - (executeContext, validationContext) -> { - executionCustomizer.accept(executeContext); - }); + (executeContext, validationContext) -> executionCustomizer.accept(executeContext)); } private T walkAtNodeInternal(ExecutionContext executionContext, JsonNode node, JsonNode rootNode, diff --git a/src/main/java/com/networknt/schema/JsonSchemaFactory.java b/src/main/java/com/networknt/schema/JsonSchemaFactory.java index 4055ded9b..6e4d56787 100644 --- a/src/main/java/com/networknt/schema/JsonSchemaFactory.java +++ b/src/main/java/com/networknt/schema/JsonSchemaFactory.java @@ -57,7 +57,7 @@ public static class Builder { private ObjectMapper yamlMapper = null; private JsonNodeReader jsonNodeReader = null; private String defaultMetaSchemaIri; - private final ConcurrentMap metaSchemas = new ConcurrentHashMap(); + private final ConcurrentMap metaSchemas = new ConcurrentHashMap<>(); private SchemaLoaders.Builder schemaLoadersBuilder = null; private SchemaMappers.Builder schemaMappersBuilder = null; private boolean enableSchemaCache = true; @@ -83,7 +83,7 @@ public Builder jsonNodeReader(JsonNodeReader jsonNodeReader) { *

* If the object reader is set this will not be used. *

- * This is deprecated use a object reader instead. + * This is deprecated use an object reader instead. * * @param jsonMapper the json mapper * @return the builder @@ -99,7 +99,7 @@ public Builder jsonMapper(final ObjectMapper jsonMapper) { *

* If the object reader is set this will not be used. *

- * This is deprecated use a object reader instead. + * This is deprecated use an object reader instead. * * @param yamlMapper the yaml mapper * @return the builder @@ -439,7 +439,7 @@ private JsonMetaSchema getMetaSchema(final JsonNode schemaNode, SchemaValidators private JsonMetaSchema getMetaSchemaOrDefault(final JsonNode schemaNode, SchemaValidatorsConfig config) { final JsonNode iriNode = schemaNode.get("$schema"); if (iriNode != null && !iriNode.isNull() && !iriNode.isTextual()) { - throw new JsonSchemaException("Unknown MetaSchema: " + iriNode.toString()); + throw new JsonSchemaException("Unknown MetaSchema: " + iriNode); } final String iri = iriNode == null || iriNode.isNull() ? defaultMetaSchemaIri : iriNode.textValue(); return getMetaSchema(iri, config); @@ -669,7 +669,7 @@ protected SchemaValidatorsConfig createSchemaValidatorsConfig() { protected JsonSchema getMappedSchema(final SchemaLocation schemaUri, SchemaValidatorsConfig config) { try (InputStream inputStream = this.schemaLoader.getSchema(schemaUri.getAbsoluteIri()).getInputStream()) { if (inputStream == null) { - throw new IOException("Cannot load schema at " + schemaUri.toString()); + throw new IOException("Cannot load schema at " + schemaUri); } final JsonNode schemaNode; if (isYaml(schemaUri)) { diff --git a/src/main/java/com/networknt/schema/JsonSchemaIdValidator.java b/src/main/java/com/networknt/schema/JsonSchemaIdValidator.java index 0629e43f4..3a2ee98f7 100644 --- a/src/main/java/com/networknt/schema/JsonSchemaIdValidator.java +++ b/src/main/java/com/networknt/schema/JsonSchemaIdValidator.java @@ -36,19 +36,19 @@ public interface JsonSchemaIdValidator { boolean validate(String id, boolean rootSchema, SchemaLocation schemaLocation, SchemaLocation resolvedSchemaLocation, ValidationContext validationContext); - public static final JsonSchemaIdValidator DEFAULT = new DefaultJsonSchemaIdValidator(); + JsonSchemaIdValidator DEFAULT = new DefaultJsonSchemaIdValidator(); /** * Implementation of {@link JsonSchemaIdValidator}. *

* Note that this does not strictly follow the specification. *

- * This allows an $id that isn't an absolute-IRI on the root schema but it must + * This allows an $id that isn't an absolute-IRI on the root schema, but it must * resolve to an absolute-IRI given a base-IRI. *

* This also allows non-empty fragments. */ - public static class DefaultJsonSchemaIdValidator implements JsonSchemaIdValidator { + class DefaultJsonSchemaIdValidator implements JsonSchemaIdValidator { @Override public boolean validate(String id, boolean rootSchema, SchemaLocation schemaLocation, SchemaLocation resolvedSchemaLocation, ValidationContext validationContext) { diff --git a/src/main/java/com/networknt/schema/JsonType.java b/src/main/java/com/networknt/schema/JsonType.java index 440a4ec16..ddf933670 100644 --- a/src/main/java/com/networknt/schema/JsonType.java +++ b/src/main/java/com/networknt/schema/JsonType.java @@ -39,7 +39,7 @@ public enum JsonType { * * @param typeStr the type value */ - private JsonType(String typeStr) { + JsonType(String typeStr) { this.type = typeStr; } diff --git a/src/main/java/com/networknt/schema/JsonValidator.java b/src/main/java/com/networknt/schema/JsonValidator.java index 158a09556..43b180bca 100644 --- a/src/main/java/com/networknt/schema/JsonValidator.java +++ b/src/main/java/com/networknt/schema/JsonValidator.java @@ -75,7 +75,7 @@ default Set walk(ExecutionContext executionContext, JsonNode * * @return the schema location */ - public SchemaLocation getSchemaLocation(); + SchemaLocation getSchemaLocation(); /** * The evaluation path is the set of keys, starting from the schema root, @@ -84,12 +84,12 @@ default Set walk(ExecutionContext executionContext, JsonNode * * @return the evaluation path */ - public JsonNodePath getEvaluationPath(); + JsonNodePath getEvaluationPath(); /** * The keyword of the validator. * * @return the keyword */ - public String getKeyword(); + String getKeyword(); } diff --git a/src/main/java/com/networknt/schema/NonValidationKeyword.java b/src/main/java/com/networknt/schema/NonValidationKeyword.java index 573ebea01..a5f2c15fb 100644 --- a/src/main/java/com/networknt/schema/NonValidationKeyword.java +++ b/src/main/java/com/networknt/schema/NonValidationKeyword.java @@ -62,7 +62,7 @@ public NonValidationKeyword(String keyword) { @Override public JsonValidator newValidator(SchemaLocation schemaLocation, JsonNodePath evaluationPath, JsonNode schemaNode, - JsonSchema parentSchema, ValidationContext validationContext) throws JsonSchemaException, Exception { + JsonSchema parentSchema, ValidationContext validationContext) { return new Validator(schemaLocation, evaluationPath, schemaNode, parentSchema, validationContext, this); } } diff --git a/src/main/java/com/networknt/schema/OutputFormat.java b/src/main/java/com/networknt/schema/OutputFormat.java index 751f4702a..61e0c904d 100644 --- a/src/main/java/com/networknt/schema/OutputFormat.java +++ b/src/main/java/com/networknt/schema/OutputFormat.java @@ -57,40 +57,40 @@ T format(JsonSchema jsonSchema, Set validationMessages, /** * The Default output format. */ - public static final Default DEFAULT = new Default(); + Default DEFAULT = new Default(); /** * The Boolean output format. */ - public static final Boolean BOOLEAN = new Boolean(); + Boolean BOOLEAN = new Boolean(); /** * The Flag output format. */ - public static final Flag FLAG = new Flag(); + Flag FLAG = new Flag(); /** * The List output format. */ - public static final List LIST = new List(); + List LIST = new List(); /** * The Hierarchical output format. */ - public static final Hierarchical HIERARCHICAL = new Hierarchical(); + Hierarchical HIERARCHICAL = new Hierarchical(); /** * The Result output format. *

* This is currently not exposed to consumers. */ - static final Result RESULT = new Result(); + Result RESULT = new Result(); /** * The Default output format. */ - public static class Default implements OutputFormat> { + class Default implements OutputFormat> { @Override public void customize(ExecutionContext executionContext, ValidationContext validationContext) { executionContext.getExecutionConfig().setAnnotationCollectionEnabled(false); @@ -106,7 +106,7 @@ public Set format(JsonSchema jsonSchema, /** * The Flag output format. */ - public static class Flag implements OutputFormat { + class Flag implements OutputFormat { @Override public void customize(ExecutionContext executionContext, ValidationContext validationContext) { executionContext.getExecutionConfig().setAnnotationCollectionEnabled(false); @@ -123,7 +123,7 @@ public OutputFlag format(JsonSchema jsonSchema, Set validatio /** * The Boolean output format. */ - public static class Boolean implements OutputFormat { + class Boolean implements OutputFormat { @Override public void customize(ExecutionContext executionContext, ValidationContext validationContext) { executionContext.getExecutionConfig().setAnnotationCollectionEnabled(false); @@ -140,7 +140,7 @@ public java.lang.Boolean format(JsonSchema jsonSchema, Set va /** * The List output format. */ - public static class List implements OutputFormat { + class List implements OutputFormat { private final Function assertionMapper; public List() { @@ -171,7 +171,7 @@ public OutputUnit format(JsonSchema jsonSchema, Set validatio /** * The Hierarchical output format. */ - public static class Hierarchical implements OutputFormat { + class Hierarchical implements OutputFormat { private final Function assertionMapper; public Hierarchical() { @@ -204,7 +204,7 @@ public OutputUnit format(JsonSchema jsonSchema, Set validatio *

* This is currently not exposed to consumers. */ - static class Result implements OutputFormat { + class Result implements OutputFormat { @Override public void customize(ExecutionContext executionContext, ValidationContext validationContext) { } diff --git a/src/main/java/com/networknt/schema/PathType.java b/src/main/java/com/networknt/schema/PathType.java index 4104c77d3..869ee4f21 100644 --- a/src/main/java/com/networknt/schema/PathType.java +++ b/src/main/java/com/networknt/schema/PathType.java @@ -35,7 +35,7 @@ public enum PathType { return currentPath + "." + token; } - // Replace single quote (used to wrap property names when not shorthand form. + // Replace single quote (used to wrap property names when not shorthand form). if (token.indexOf('\'') != -1) token = token.replace("'", "\\'"); // Replace other special characters. token = replaceCommonSpecialCharactersIfPresent(token); @@ -60,9 +60,7 @@ public enum PathType { /** * Paths as a URI reference. */ - URI_REFERENCE("", (currentPath, token) -> { - return !currentPath.isEmpty() ? currentPath + "/" + token : token; - }, (currentPath, index) -> currentPath + "/" + index); + URI_REFERENCE("", (currentPath, token) -> !currentPath.isEmpty() ? currentPath + "/" + token : token, (currentPath, index) -> currentPath + "/" + index); /** * The default path generation approach to use. @@ -211,7 +209,7 @@ static int parseSelector(StringBuilder sb, String s, int pos) { if ('\'' == s.charAt(pos)) { parseQuote(sb, s, pos + 1); } else { - sb.append(s.substring(pos, close)); + sb.append(s, pos, close); } return close + 1; @@ -232,7 +230,7 @@ static int parseQuote(StringBuilder sb, String s, int pos) { throw new IllegalArgumentException("JSONPath contains an unterminated quoted string"); } } while ('\\' == s.charAt(close - 1)) ; - sb.append(s.substring(pos, close)); + sb.append(s, pos, close); return close + 1; } diff --git a/src/main/java/com/networknt/schema/PatternValidator.java b/src/main/java/com/networknt/schema/PatternValidator.java index 9163ab741..166c553a4 100644 --- a/src/main/java/com/networknt/schema/PatternValidator.java +++ b/src/main/java/com/networknt/schema/PatternValidator.java @@ -27,8 +27,8 @@ public class PatternValidator extends BaseJsonValidator { private static final Logger logger = LoggerFactory.getLogger(PatternValidator.class); - private String pattern; - private RegularExpression compiledPattern; + private final String pattern; + private final RegularExpression compiledPattern; public PatternValidator(SchemaLocation schemaLocation, JsonNodePath evaluationPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) { super(schemaLocation, evaluationPath, schemaNode, parentSchema, ValidatorTypeCode.PATTERN, validationContext); diff --git a/src/main/java/com/networknt/schema/PrefixItemsValidator.java b/src/main/java/com/networknt/schema/PrefixItemsValidator.java index f79bf8345..c390a5af9 100644 --- a/src/main/java/com/networknt/schema/PrefixItemsValidator.java +++ b/src/main/java/com/networknt/schema/PrefixItemsValidator.java @@ -44,7 +44,7 @@ public class PrefixItemsValidator extends BaseJsonValidator { public PrefixItemsValidator(SchemaLocation schemaLocation, JsonNodePath evaluationPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) { super(schemaLocation, evaluationPath, schemaNode, parentSchema, ValidatorTypeCode.PREFIX_ITEMS, validationContext); - if (schemaNode instanceof ArrayNode && 0 < schemaNode.size()) { + if (schemaNode instanceof ArrayNode && !schemaNode.isEmpty()) { int i = 0; this.tupleSchema = new ArrayList<>(schemaNode.size()); for (JsonNode s : schemaNode) { diff --git a/src/main/java/com/networknt/schema/RecursiveRefValidator.java b/src/main/java/com/networknt/schema/RecursiveRefValidator.java index ad8f009c3..711fe932d 100644 --- a/src/main/java/com/networknt/schema/RecursiveRefValidator.java +++ b/src/main/java/com/networknt/schema/RecursiveRefValidator.java @@ -49,9 +49,7 @@ public RecursiveRefValidator(SchemaLocation schemaLocation, JsonNodePath evaluat static JsonSchemaRef getRefSchema(JsonSchema parentSchema, ValidationContext validationContext, String refValue, JsonNodePath evaluationPath) { - return new JsonSchemaRef(getSupplier(() -> { - return getSchema(parentSchema, validationContext, refValue, evaluationPath); - }, validationContext.getConfig().isCacheRefs())); + return new JsonSchemaRef(getSupplier(() -> getSchema(parentSchema, validationContext, refValue, evaluationPath), validationContext.getConfig().isCacheRefs())); } static Supplier getSupplier(Supplier supplier, boolean cache) { diff --git a/src/main/java/com/networknt/schema/SchemaLocation.java b/src/main/java/com/networknt/schema/SchemaLocation.java index 2257e36e8..18d44448d 100644 --- a/src/main/java/com/networknt/schema/SchemaLocation.java +++ b/src/main/java/com/networknt/schema/SchemaLocation.java @@ -250,7 +250,7 @@ public static JsonNodePath of(String fragmentString) { if (index != -1) { fragment = fragment.append(index); } else { - String fragmentPartString = fragmentPart.toString(); + String fragmentPartString = fragmentPart; if (PathType.JSON_POINTER.equals(fragment.getPathType())) { if (fragmentPartString.contains("~")) { fragmentPartString = fragmentPartString.replace("~1", "/"); @@ -399,11 +399,11 @@ public String toString() { } else { StringBuilder result = new StringBuilder(); if (this.absoluteIri != null) { - result.append(this.absoluteIri.toString()); + result.append(this.absoluteIri); } result.append("#"); if (this.fragment != null) { - result.append(this.fragment.toString()); + result.append(this.fragment); } this.value = result.toString(); } diff --git a/src/main/java/com/networknt/schema/SchemaValidatorsConfig.java b/src/main/java/com/networknt/schema/SchemaValidatorsConfig.java index 2c4f56fe2..c9d9b7a47 100644 --- a/src/main/java/com/networknt/schema/SchemaValidatorsConfig.java +++ b/src/main/java/com/networknt/schema/SchemaValidatorsConfig.java @@ -173,7 +173,7 @@ public class SchemaValidatorsConfig { private boolean typeLoose; /** - * When set to true assumes that schema is used to to validate outgoing data from an API. + * When set to true assumes that schema is used to validate outgoing data from an API. */ private Boolean writeOnly = null; @@ -693,8 +693,8 @@ public void setMessageSource(MessageSource messageSource) { * discriminator property matches * * - * @param openAPI3StyleDiscriminators whether or not discriminators should be - * used. Defaults to false + * @param openAPI3StyleDiscriminators whether discriminators should be used. + * Defaults to false * @since 1.0.51 */ public void setOpenAPI3StyleDiscriminators(boolean openAPI3StyleDiscriminators) { @@ -902,7 +902,7 @@ public Builder failFast(boolean failFast) { /** * Sets if format assertions are enabled. If format assertions are not enabled - * the format keyword will behave like a annotation and not attempt to validate + * the format keyword will behave like an annotation and not attempt to validate * if the inputs are valid. *

* Defaults to not enabling format assertions for Draft 2019-09 and above and diff --git a/src/main/java/com/networknt/schema/SpecVersionDetector.java b/src/main/java/com/networknt/schema/SpecVersionDetector.java index ce7fd9b5f..219a2866b 100644 --- a/src/main/java/com/networknt/schema/SpecVersionDetector.java +++ b/src/main/java/com/networknt/schema/SpecVersionDetector.java @@ -35,7 +35,7 @@ */ public final class SpecVersionDetector { - protected static final Map supportedVersions = new HashMap<>(); + private static final Map supportedVersions = new HashMap<>(); private static final String SCHEMA_TAG = "$schema"; static { diff --git a/src/main/java/com/networknt/schema/UnevaluatedItemsValidator.java b/src/main/java/com/networknt/schema/UnevaluatedItemsValidator.java index 1794ce6bb..43ceb3eb7 100644 --- a/src/main/java/com/networknt/schema/UnevaluatedItemsValidator.java +++ b/src/main/java/com/networknt/schema/UnevaluatedItemsValidator.java @@ -75,9 +75,7 @@ public Set validate(ExecutionContext executionContext, JsonNo boolean evaluated = false; // Get all the valid adjacent annotations - Predicate validEvaluationPathFilter = a -> { - return executionContext.getResults().isValid(instanceLocation, a.getEvaluationPath()); - }; + Predicate validEvaluationPathFilter = a -> executionContext.getResults().isValid(instanceLocation, a.getEvaluationPath()); Predicate adjacentEvaluationPathFilter = a -> a.getEvaluationPath() .startsWith(this.evaluationPath.getParent()); @@ -90,7 +88,7 @@ public Set validate(ExecutionContext executionContext, JsonNo valid = true; // No need to actually evaluate since the schema is true but if there are any // items the annotation needs to be set - if (node.size() > 0) { + if (!node.isEmpty()) { evaluated = true; } } else { diff --git a/src/main/java/com/networknt/schema/UnevaluatedPropertiesValidator.java b/src/main/java/com/networknt/schema/UnevaluatedPropertiesValidator.java index e40b242e5..c35115b46 100644 --- a/src/main/java/com/networknt/schema/UnevaluatedPropertiesValidator.java +++ b/src/main/java/com/networknt/schema/UnevaluatedPropertiesValidator.java @@ -52,9 +52,7 @@ public Set validate(ExecutionContext executionContext, JsonNo debug(logger, executionContext, node, rootNode, instanceLocation); // Get all the valid adjacent annotations - Predicate validEvaluationPathFilter = a -> { - return executionContext.getResults().isValid(instanceLocation, a.getEvaluationPath()); - }; + Predicate validEvaluationPathFilter = a -> executionContext.getResults().isValid(instanceLocation, a.getEvaluationPath()); Predicate adjacentEvaluationPathFilter = a -> a.getEvaluationPath() .startsWith(this.evaluationPath.getParent()); diff --git a/src/main/java/com/networknt/schema/UniqueItemsValidator.java b/src/main/java/com/networknt/schema/UniqueItemsValidator.java index 2740d4082..9ee15e959 100644 --- a/src/main/java/com/networknt/schema/UniqueItemsValidator.java +++ b/src/main/java/com/networknt/schema/UniqueItemsValidator.java @@ -45,7 +45,7 @@ public Set validate(ExecutionContext executionContext, JsonNo debug(logger, executionContext, node, rootNode, instanceLocation); if (unique) { - Set set = new HashSet(); + Set set = new HashSet<>(); for (JsonNode n : node) { if (!set.add(n)) { return Collections.singleton(message().instanceNode(node).instanceLocation(instanceLocation) diff --git a/src/main/java/com/networknt/schema/UnknownKeywordFactory.java b/src/main/java/com/networknt/schema/UnknownKeywordFactory.java index 2d0d486b3..688330d18 100644 --- a/src/main/java/com/networknt/schema/UnknownKeywordFactory.java +++ b/src/main/java/com/networknt/schema/UnknownKeywordFactory.java @@ -42,7 +42,7 @@ public Keyword getKeyword(String value, ValidationContext validationContext) { } private static class Holder { - private static UnknownKeywordFactory INSTANCE = new UnknownKeywordFactory(); + private static final UnknownKeywordFactory INSTANCE = new UnknownKeywordFactory(); } public static UnknownKeywordFactory getInstance() { diff --git a/src/main/java/com/networknt/schema/ValidationMessage.java b/src/main/java/com/networknt/schema/ValidationMessage.java index 2f5576637..013d8e257 100644 --- a/src/main/java/com/networknt/schema/ValidationMessage.java +++ b/src/main/java/com/networknt/schema/ValidationMessage.java @@ -215,8 +215,7 @@ public boolean equals(Object o) { if (evaluationPath != null ? !evaluationPath.equals(that.evaluationPath) : that.evaluationPath != null) return false; if (details != null ? !details.equals(that.details) : that.details != null) return false; if (messageKey != null ? !messageKey.equals(that.messageKey) : that.messageKey != null) return false; - if (!Arrays.equals(arguments, that.arguments)) return false; - return true; + return Arrays.equals(arguments, that.arguments); } @Override @@ -405,9 +404,7 @@ protected Object[] getMessageArguments() { Object[] objs = new Object[(arguments == null ? 0 : arguments.length) + 1]; objs[0] = instanceLocation; if (arguments != null) { - for (int i = 1; i < objs.length; i++) { - objs[i] = arguments[i - 1]; - } + System.arraycopy(arguments, 0, objs, 1, objs.length - 1); } return objs; } diff --git a/src/main/java/com/networknt/schema/ValidationMessageHandler.java b/src/main/java/com/networknt/schema/ValidationMessageHandler.java index 7fd2688b5..819153bfe 100644 --- a/src/main/java/com/networknt/schema/ValidationMessageHandler.java +++ b/src/main/java/com/networknt/schema/ValidationMessageHandler.java @@ -102,9 +102,7 @@ protected Map getErrorMessage(String errorMessageKeyword, JsonNo return Collections.singletonMap("", messageNode.asText()); } else if (messageNode.isObject()) { Map result = new LinkedHashMap<>(); - messageNode.fields().forEachRemaining(entry -> { - result.put(entry.getKey(), entry.getValue().textValue()); - }); + messageNode.fields().forEachRemaining(entry -> result.put(entry.getKey(), entry.getValue().textValue())); if (!result.isEmpty()) { return result; } diff --git a/src/main/java/com/networknt/schema/ValidatorTypeCode.java b/src/main/java/com/networknt/schema/ValidatorTypeCode.java index dda56d163..458efc762 100644 --- a/src/main/java/com/networknt/schema/ValidatorTypeCode.java +++ b/src/main/java/com/networknt/schema/ValidatorTypeCode.java @@ -20,6 +20,7 @@ import com.networknt.schema.SpecVersion.VersionFlag; import java.util.ArrayList; +import java.util.Arrays; import java.util.EnumSet; import java.util.HashMap; import java.util.List; @@ -48,9 +49,7 @@ enum VersionCode { VersionCode(SpecVersion.VersionFlag[] versionFlags) { this.versions = EnumSet.noneOf(VersionFlag.class); - for (VersionFlag flag: versionFlags) { - this.versions.add(flag); - } + this.versions.addAll(Arrays.asList(versionFlags)); } EnumSet getVersions() { @@ -129,7 +128,7 @@ public enum ValidatorTypeCode implements Keyword, ErrorMessageType { private final ValidatorFactory validatorFactory; private final VersionCode versionCode; - private ValidatorTypeCode(String value, String errorCode, ValidatorFactory validatorFactory, VersionCode versionCode) { + ValidatorTypeCode(String value, String errorCode, ValidatorFactory validatorFactory, VersionCode versionCode) { this.value = value; this.errorCode = errorCode; this.validatorFactory = validatorFactory; diff --git a/src/main/java/com/networknt/schema/Version201909.java b/src/main/java/com/networknt/schema/Version201909.java index 9a9efed0b..69763f2bc 100644 --- a/src/main/java/com/networknt/schema/Version201909.java +++ b/src/main/java/com/networknt/schema/Version201909.java @@ -1,6 +1,6 @@ package com.networknt.schema; -import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -32,8 +32,8 @@ private static class Holder { .formats(Formats.DEFAULT) .keywords(ValidatorTypeCode.getKeywords(SpecVersion.VersionFlag.V201909)) // keywords that may validly exist, but have no validation aspect to them - .keywords(Arrays.asList( - new NonValidationKeyword("definitions") + .keywords(Collections.singletonList( + new NonValidationKeyword("definitions") )) .vocabularies(VOCABULARY) .build(); diff --git a/src/main/java/com/networknt/schema/Version202012.java b/src/main/java/com/networknt/schema/Version202012.java index 6e75cc642..32fabc35a 100644 --- a/src/main/java/com/networknt/schema/Version202012.java +++ b/src/main/java/com/networknt/schema/Version202012.java @@ -1,6 +1,6 @@ package com.networknt.schema; -import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -33,8 +33,8 @@ private static class Holder { .formats(Formats.DEFAULT) .keywords(ValidatorTypeCode.getKeywords(SpecVersion.VersionFlag.V202012)) // keywords that may validly exist, but have no validation aspect to them - .keywords(Arrays.asList( - new NonValidationKeyword("definitions") + .keywords(Collections.singletonList( + new NonValidationKeyword("definitions") )) .vocabularies(VOCABULARY) .build(); diff --git a/src/main/java/com/networknt/schema/Vocabulary.java b/src/main/java/com/networknt/schema/Vocabulary.java index 473c2915e..aa2c360de 100644 --- a/src/main/java/com/networknt/schema/Vocabulary.java +++ b/src/main/java/com/networknt/schema/Vocabulary.java @@ -15,6 +15,7 @@ */ package com.networknt.schema; +import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; @@ -112,9 +113,7 @@ ValidatorTypeCode.PROPERTYNAMES, ValidatorTypeCode.IF_THEN_ELSE, new NonValidati public Vocabulary(String iri, Keyword... keywords) { this.iri = iri; this.keywords = new LinkedHashSet<>(); - for (Keyword keyword : keywords) { - this.keywords.add(keyword); - } + this.keywords.addAll(Arrays.asList(keywords)); } /** diff --git a/src/main/java/com/networknt/schema/format/AbstractRFC3986Format.java b/src/main/java/com/networknt/schema/format/AbstractRFC3986Format.java index 2500d88e5..b08dd9ba0 100644 --- a/src/main/java/com/networknt/schema/format/AbstractRFC3986Format.java +++ b/src/main/java/com/networknt/schema/format/AbstractRFC3986Format.java @@ -38,9 +38,6 @@ public final boolean matches(ExecutionContext executionContext, String value) { * @return false if it does not match */ protected boolean handleException(URISyntaxException e) { - if (VALID.matcher(e.getInput()).matches()) { - return true; - } - return false; + return VALID.matcher(e.getInput()).matches(); } } diff --git a/src/main/java/com/networknt/schema/format/IriReferenceFormat.java b/src/main/java/com/networknt/schema/format/IriReferenceFormat.java index aa0a0d0c9..b0be2bb0a 100644 --- a/src/main/java/com/networknt/schema/format/IriReferenceFormat.java +++ b/src/main/java/com/networknt/schema/format/IriReferenceFormat.java @@ -17,9 +17,7 @@ protected boolean validate(URI uri) { String query = uri.getRawQuery(); if (query != null) { // [ and ] must be percent encoded - if (query.indexOf('[') != -1 || query.indexOf(']') != -1) { - return false; - } + return query.indexOf('[') == -1 && query.indexOf(']') == -1; } return true; } diff --git a/src/main/java/com/networknt/schema/i18n/ResourceBundleMessageSource.java b/src/main/java/com/networknt/schema/i18n/ResourceBundleMessageSource.java index 761bc927e..df2879395 100644 --- a/src/main/java/com/networknt/schema/i18n/ResourceBundleMessageSource.java +++ b/src/main/java/com/networknt/schema/i18n/ResourceBundleMessageSource.java @@ -34,19 +34,19 @@ public class ResourceBundleMessageSource implements MessageSource { /** * Resource Bundle Cache. baseName -> locale -> resourceBundle. */ - private Map> resourceBundleMap = new ConcurrentHashMap<>(); + private final Map> resourceBundleMap = new ConcurrentHashMap<>(); /** * Message Cache. locale -> key -> message. */ - private Map> messageMap = new ConcurrentHashMap<>(); + private final Map> messageMap = new ConcurrentHashMap<>(); /** * Message Format Cache. locale -> message -> messageFormat. *

* Note that Message Format is not threadsafe. */ - private Map> messageFormatMap = new ConcurrentHashMap<>(); + private final Map> messageFormatMap = new ConcurrentHashMap<>(); private final List baseNames; @@ -76,12 +76,8 @@ public String getMessage(String key, Supplier defaultMessage, Locale loc } protected MessageFormat getMessageFormat(Locale locale, String message) { - Map map = messageFormatMap.computeIfAbsent(locale, l -> { - return new ConcurrentHashMap<>(); - }); - return map.computeIfAbsent(message, m -> { - return new MessageFormat(m, locale); - }); + Map map = messageFormatMap.computeIfAbsent(locale, l -> new ConcurrentHashMap<>()); + return map.computeIfAbsent(message, m -> new MessageFormat(m, locale)); } /** @@ -94,9 +90,7 @@ protected MessageFormat getMessageFormat(Locale locale, String message) { */ protected String getMessageFromCache(Locale locale, String key) { Map map = messageMap.computeIfAbsent(locale, l -> new ConcurrentHashMap<>()); - return map.computeIfAbsent(key, k -> { - return resolveMessage(locale, k); - }); + return map.computeIfAbsent(key, k -> resolveMessage(locale, k)); } /** @@ -120,9 +114,7 @@ protected String resolveMessage(Locale locale, String key) { } protected Map getResourceBundle(String baseName) { - return resourceBundleMap.computeIfAbsent(baseName, key -> { - return new ConcurrentHashMap<>(); - }); + return resourceBundleMap.computeIfAbsent(baseName, key -> new ConcurrentHashMap<>()); } protected ResourceBundle getResourceBundle(String baseName, Locale locale) { diff --git a/src/main/java/com/networknt/schema/oas/OpenApi31.java b/src/main/java/com/networknt/schema/oas/OpenApi31.java index a5bf94964..69f1a50a1 100644 --- a/src/main/java/com/networknt/schema/oas/OpenApi31.java +++ b/src/main/java/com/networknt/schema/oas/OpenApi31.java @@ -1,6 +1,6 @@ package com.networknt.schema.oas; -import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -41,8 +41,8 @@ private static class Holder { .formats(Formats.DEFAULT) .keywords(ValidatorTypeCode.getKeywords(SpecVersion.VersionFlag.V202012)) // keywords that may validly exist, but have no validation aspect to them - .keywords(Arrays.asList( - new NonValidationKeyword("definitions") + .keywords(Collections.singletonList( + new NonValidationKeyword("definitions") )) .vocabularies(VOCABULARY) .build(); diff --git a/src/main/java/com/networknt/schema/regex/JoniRegularExpression.java b/src/main/java/com/networknt/schema/regex/JoniRegularExpression.java index 21cbdd1e6..703b6117d 100644 --- a/src/main/java/com/networknt/schema/regex/JoniRegularExpression.java +++ b/src/main/java/com/networknt/schema/regex/JoniRegularExpression.java @@ -34,9 +34,9 @@ class JoniRegularExpression implements RegularExpression { Syntax.ECMAScript.op2 | SyntaxProperties.OP2_QMARK_LT_NAMED_GROUP | SyntaxProperties.OP2_ESC_K_NAMED_BACKREF, Syntax.ECMAScript.op3, Syntax.ECMAScript.behavior, Syntax.ECMAScript.options, - Syntax.ECMAScript.metaCharTable);; + Syntax.ECMAScript.metaCharTable); - JoniRegularExpression(String regex) { + JoniRegularExpression(String regex) { this(regex, SYNTAX); } @@ -60,7 +60,7 @@ protected void validate(String regex) { if (INVALID_ESCAPE_PATTERN.matcher(regex).matches()) { /* * One option considered was a custom Encoding implementation that rejects - * certain code points but it is unable to distinguish \a vs \cG for instance as + * certain code points, but it is unable to distinguish \a vs \cG for instance as * both translate to BEL */ throw new SyntaxException("Invalid escape"); diff --git a/src/main/java/com/networknt/schema/resource/DisallowSchemaLoader.java b/src/main/java/com/networknt/schema/resource/DisallowSchemaLoader.java index e2d81d18e..a63375dfa 100644 --- a/src/main/java/com/networknt/schema/resource/DisallowSchemaLoader.java +++ b/src/main/java/com/networknt/schema/resource/DisallowSchemaLoader.java @@ -23,7 +23,7 @@ * {@link SchemaLoader} that disallows loading external resources. */ public class DisallowSchemaLoader implements SchemaLoader { - private static DisallowSchemaLoader INSTANCE = new DisallowSchemaLoader(); + private static final DisallowSchemaLoader INSTANCE = new DisallowSchemaLoader(); /** * Disallows loading schemas from external resources. diff --git a/src/main/java/com/networknt/schema/resource/SchemaLoaders.java b/src/main/java/com/networknt/schema/resource/SchemaLoaders.java index dbe847c6d..8a18a8871 100644 --- a/src/main/java/com/networknt/schema/resource/SchemaLoaders.java +++ b/src/main/java/com/networknt/schema/resource/SchemaLoaders.java @@ -45,7 +45,7 @@ public static Builder builder() { } public static class Builder { - private SchemaLoaders values = new SchemaLoaders(); + private final SchemaLoaders values = new SchemaLoaders(); public Builder() { } diff --git a/src/main/java/com/networknt/schema/resource/SchemaMappers.java b/src/main/java/com/networknt/schema/resource/SchemaMappers.java index 1bdc79e2d..9757c6837 100644 --- a/src/main/java/com/networknt/schema/resource/SchemaMappers.java +++ b/src/main/java/com/networknt/schema/resource/SchemaMappers.java @@ -47,7 +47,7 @@ public static Builder builder() { } public static class Builder { - private SchemaMappers values = new SchemaMappers(); + private final SchemaMappers values = new SchemaMappers(); public Builder() { } diff --git a/src/main/java/com/networknt/schema/serialization/JsonNodeReader.java b/src/main/java/com/networknt/schema/serialization/JsonNodeReader.java index 46db1bc3a..cb4b53f36 100644 --- a/src/main/java/com/networknt/schema/serialization/JsonNodeReader.java +++ b/src/main/java/com/networknt/schema/serialization/JsonNodeReader.java @@ -51,7 +51,7 @@ public interface JsonNodeReader { * * @return the builder */ - public static DefaultJsonNodeReader.Builder builder() { + static DefaultJsonNodeReader.Builder builder() { return DefaultJsonNodeReader.builder(); } } diff --git a/src/main/java/com/networknt/schema/utils/JsonNodeUtil.java b/src/main/java/com/networknt/schema/utils/JsonNodeUtil.java index d480ee7c4..083efc061 100644 --- a/src/main/java/com/networknt/schema/utils/JsonNodeUtil.java +++ b/src/main/java/com/networknt/schema/utils/JsonNodeUtil.java @@ -9,7 +9,6 @@ import com.networknt.schema.PathType; import com.networknt.schema.SchemaValidatorsConfig; import com.networknt.schema.SpecVersion.VersionFlag; -import com.networknt.schema.SpecVersionDetector; import com.networknt.schema.TypeFactory; import com.networknt.schema.ValidationContext; @@ -54,10 +53,7 @@ private static void visitObject(PathType pathType, String root, JsonNode node, C public static boolean isNodeNullable(JsonNode schema){ JsonNode nullable = schema.get(NULLABLE); - if (nullable != null && nullable.asBoolean()) { - return true; - } - return false; + return nullable != null && nullable.asBoolean(); } //Check to see if a JsonNode is nullable with checking the isHandleNullableField @@ -110,17 +106,11 @@ public static boolean equalsToSchemaType(JsonNode node, JsonType schemaType, Jso } if (nodeType == JsonType.STRING) { if (schemaType == JsonType.INTEGER) { - if (StringChecker.isInteger(node.textValue())) { - return true; - } + return StringChecker.isInteger(node.textValue()); } else if (schemaType == JsonType.BOOLEAN) { - if (StringChecker.isBoolean(node.textValue())) { - return true; - } + return StringChecker.isBoolean(node.textValue()); } else if (schemaType == JsonType.NUMBER) { - if (StringChecker.isNumeric(node.textValue())) { - return true; - } + return StringChecker.isNumeric(node.textValue()); } } } diff --git a/src/main/java/com/networknt/schema/utils/RFC5892.java b/src/main/java/com/networknt/schema/utils/RFC5892.java index 76d044436..35b30686e 100644 --- a/src/main/java/com/networknt/schema/utils/RFC5892.java +++ b/src/main/java/com/networknt/schema/utils/RFC5892.java @@ -36,21 +36,21 @@ public class RFC5892 { private static final BitSet DISALLOWED = new BitSet(0x110000); private static final BitSet UNASSIGNED = new BitSet(0x110000); - private static BiPredicate RULE_ARABIC_INDIC_DIGITS_RULE = RFC5892::testArabicIndicDigit; - private static BiPredicate RULE_EXTENDED_ARABIC_INDIC_DIGITS_RULE = RFC5892::testExtendedArabicIndicDigit; - private static BiPredicate RULE_GREEK_LOWER_NUMERAL_SIGN = RFC5892::testGreekLowerNumeralSign; - private static BiPredicate RULE_HEBREW_GERESH_GERSHAYIM = RFC5892::testHebrewPuncuation; - private static BiPredicate RULE_KATAKANA_MIDDLE_DOT = RFC5892::testKatakanaMiddleDot; - private static BiPredicate RULE_MIDDLE_DOT = RFC5892::testeMiddleDotRule; - private static BiPredicate RULE_ZERO_WIDTH_JOINER = RFC5892::testZeroWidthJoiner; - private static BiPredicate RULE_ZERO_WIDTH_NON_JOINER = RFC5892::testZeroWidthNonJoiner; + private static final BiPredicate RULE_ARABIC_INDIC_DIGITS_RULE = RFC5892::testArabicIndicDigit; + private static final BiPredicate RULE_EXTENDED_ARABIC_INDIC_DIGITS_RULE = RFC5892::testExtendedArabicIndicDigit; + private static final BiPredicate RULE_GREEK_LOWER_NUMERAL_SIGN = RFC5892::testGreekLowerNumeralSign; + private static final BiPredicate RULE_HEBREW_GERESH_GERSHAYIM = RFC5892::testHebrewPuncuation; + private static final BiPredicate RULE_KATAKANA_MIDDLE_DOT = RFC5892::testKatakanaMiddleDot; + private static final BiPredicate RULE_MIDDLE_DOT = RFC5892::testeMiddleDotRule; + private static final BiPredicate RULE_ZERO_WIDTH_JOINER = RFC5892::testZeroWidthJoiner; + private static final BiPredicate RULE_ZERO_WIDTH_NON_JOINER = RFC5892::testZeroWidthNonJoiner; - private static BiPredicate ALLOWED_CHARACTER = RFC5892::testAllowedCharacter; + private static final BiPredicate ALLOWED_CHARACTER = RFC5892::testAllowedCharacter; - private static BiPredicate LTR = RFC5892::testLTR; - private static BiPredicate RTL = RFC5892::testRTL; + private static final BiPredicate LTR = RFC5892::testLTR; + private static final BiPredicate RTL = RFC5892::testRTL; - private static BiPredicate IDNA_RULES = + private static final BiPredicate IDNA_RULES = ALLOWED_CHARACTER .and(RULE_ARABIC_INDIC_DIGITS_RULE) .and(RULE_EXTENDED_ARABIC_INDIC_DIGITS_RULE) @@ -235,7 +235,7 @@ private static boolean testGreekLowerNumeralSign(String s, int i) { // There must be a Greek character after this symbol if (s.length() == 1 + i) return false; int following = s.codePointAt(i + 1); - if (!isGreek(following)) return false; + return isGreek(following); } return true; } @@ -254,7 +254,7 @@ private static boolean testHebrewPuncuation(String s, int i) { // There must be a Hebrew character before this symbol if (0 == i) return false; int preceding = s.codePointAt(i - 1); - if (!isHebrew(preceding)) return false; + return isHebrew(preceding); } return true; } @@ -273,7 +273,7 @@ private static boolean testKatakanaMiddleDot(String s, int i) { // There must be a Katakana, Hiragana or Han character after this symbol if (s.length() == 1 + i) return false; int following = s.codePointAt(i + 1); - if (!isKatakana(following)) return false; + return isKatakana(following); } return true; } @@ -294,7 +294,7 @@ private static boolean testeMiddleDotRule(String s, int i) { if (s.length() == 1 + i) return false; int preceding = s.codePointAt(i - 1); int following = s.codePointAt(i + 1); - if ('l' != preceding || 'l' != following) return false; + return 'l' == preceding && 'l' == following; } return true; } @@ -313,7 +313,7 @@ private static boolean testZeroWidthJoiner(String s, int i) { // There must be a virama character before this symbol. if (0 == i) return false; int preceding = s.codePointAt(i - 1); - if (VIRAMA != preceding) return false; + return VIRAMA == preceding; } return true; } @@ -351,7 +351,7 @@ private static boolean testZeroWidthNonJoiner(String s, int i) { if (len == j) return false; int following = s.codePointAt(j); - if (!isJoinTypeRight(following) && !isJoinTypeDual(following)) return false; + return isJoinTypeRight(following) || isJoinTypeDual(following); } return true; } diff --git a/src/main/java/com/networknt/schema/utils/SetView.java b/src/main/java/com/networknt/schema/utils/SetView.java index 08749070e..a7385f02a 100644 --- a/src/main/java/com/networknt/schema/utils/SetView.java +++ b/src/main/java/com/networknt/schema/utils/SetView.java @@ -58,7 +58,7 @@ public boolean contains(Object o) { @Override public Iterator iterator() { - return new SetViewIterator(this); + return new SetViewIterator<>(this); } @Override diff --git a/src/main/java/com/networknt/schema/utils/StringChecker.java b/src/main/java/com/networknt/schema/utils/StringChecker.java index a4194d308..4ba6388bf 100644 --- a/src/main/java/com/networknt/schema/utils/StringChecker.java +++ b/src/main/java/com/networknt/schema/utils/StringChecker.java @@ -12,7 +12,7 @@ public class StringChecker { private static final char CHAR_e = 'e'; public static boolean isInteger(String str) { - if (str == null || str.equals("")) { + if (str == null || str.isEmpty()) { return false; } @@ -39,7 +39,7 @@ public static boolean isBoolean(String s) { } public static boolean isNumeric(String str) { - if (str == null || str.equals("")) { + if (str == null || str.isEmpty()) { return false; } diff --git a/src/main/java/com/networknt/schema/utils/UCDLoader.java b/src/main/java/com/networknt/schema/utils/UCDLoader.java index 46b577e09..c64afcb75 100644 --- a/src/main/java/com/networknt/schema/utils/UCDLoader.java +++ b/src/main/java/com/networknt/schema/utils/UCDLoader.java @@ -18,7 +18,7 @@ public class UCDLoader { static void loadMapping(String filename, Function selector) { try ( InputStream is = IdnHostnameFormat.class.getResourceAsStream(filename); - LineNumberReader rd = new LineNumberReader(new InputStreamReader(is)); + LineNumberReader rd = new LineNumberReader(new InputStreamReader(is)) ) { rd.lines().forEach(line -> { if (!line.isEmpty() && '#' != line.charAt(0)) { diff --git a/src/main/java/com/networknt/schema/walk/JsonSchemaWalkListener.java b/src/main/java/com/networknt/schema/walk/JsonSchemaWalkListener.java index 187387926..4c830c2ac 100644 --- a/src/main/java/com/networknt/schema/walk/JsonSchemaWalkListener.java +++ b/src/main/java/com/networknt/schema/walk/JsonSchemaWalkListener.java @@ -11,7 +11,7 @@ */ public interface JsonSchemaWalkListener { - public WalkFlow onWalkStart(WalkEvent walkEvent); + WalkFlow onWalkStart(WalkEvent walkEvent); - public void onWalkEnd(WalkEvent walkEvent, Set validationMessages); + void onWalkEnd(WalkEvent walkEvent, Set validationMessages); } diff --git a/src/main/java/com/networknt/schema/walk/JsonSchemaWalker.java b/src/main/java/com/networknt/schema/walk/JsonSchemaWalker.java index 1a2b4355f..c6bd6ac7c 100644 --- a/src/main/java/com/networknt/schema/walk/JsonSchemaWalker.java +++ b/src/main/java/com/networknt/schema/walk/JsonSchemaWalker.java @@ -12,12 +12,12 @@ public interface JsonSchemaWalker { /** * * This method gives the capability to walk through the given JsonNode, allowing - * functionality beyond validation like collecting information,handling cross - * cutting concerns like logging or instrumentation. This method also performs + * functionality beyond validation like collecting information,handling cross-cutting + * concerns like logging or instrumentation. This method also performs * the validation if {@code shouldValidateSchema} is set to true.
*
* {@link BaseJsonValidator#walk(ExecutionContext, JsonNode, JsonNode, JsonNodePath, boolean)} provides - * a default implementation of this method. However validators that parse + * a default implementation of this method. However, validators that parse * sub-schemas should override this method to call walk method on those * sub-schemas. * diff --git a/src/main/java/com/networknt/schema/walk/WalkEvent.java b/src/main/java/com/networknt/schema/walk/WalkEvent.java index a85e9554d..36f857c6f 100644 --- a/src/main/java/com/networknt/schema/walk/WalkEvent.java +++ b/src/main/java/com/networknt/schema/walk/WalkEvent.java @@ -99,7 +99,7 @@ public String toString() { static class WalkEventBuilder { - private WalkEvent walkEvent; + private final WalkEvent walkEvent; WalkEventBuilder() { walkEvent = new WalkEvent(); diff --git a/src/main/java/com/networknt/schema/walk/WalkListenerRunner.java b/src/main/java/com/networknt/schema/walk/WalkListenerRunner.java index 0476d8bc2..9001f753b 100644 --- a/src/main/java/com/networknt/schema/walk/WalkListenerRunner.java +++ b/src/main/java/com/networknt/schema/walk/WalkListenerRunner.java @@ -11,10 +11,10 @@ public interface WalkListenerRunner { - public boolean runPreWalkListeners(ExecutionContext executionContext, String keyword, JsonNode instanceNode, - JsonNode rootNode, JsonNodePath instanceLocation, JsonSchema schema, JsonValidator validator); + boolean runPreWalkListeners(ExecutionContext executionContext, String keyword, JsonNode instanceNode, + JsonNode rootNode, JsonNodePath instanceLocation, JsonSchema schema, JsonValidator validator); - public void runPostWalkListeners(ExecutionContext executionContext, String keyword, JsonNode instanceNode, - JsonNode rootNode, JsonNodePath instanceLocation, JsonSchema schema, JsonValidator validator, Set validationMessages); + void runPostWalkListeners(ExecutionContext executionContext, String keyword, JsonNode instanceNode, + JsonNode rootNode, JsonNodePath instanceLocation, JsonSchema schema, JsonValidator validator, Set validationMessages); }