Skip to content

Commit

Permalink
Clean up code (#1130)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
jkosternl authored Nov 18, 2024
1 parent d4d0bb3 commit 7c4944b
Show file tree
Hide file tree
Showing 58 changed files with 146 additions and 200 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,6 @@ public enum ArrayType {
* @since 1.7
*/
LOCAL_MINUS
;
}

private static class IDNBUGHOLDER {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
4 changes: 2 additions & 2 deletions src/main/java/com/networknt/schema/AnnotationKeyword.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public Set<ValidationMessage> 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()) {
Expand All @@ -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);
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/networknt/schema/BaseJsonValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/networknt/schema/Collector.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,15 @@ public interface Collector<E> {
* 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.
* If the collector is not accumulating data or being used to collect data at
* multiple touch points, only this method can be implemented.
* @return E element
*/
public E collect();
E collect();


}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package com.networknt.schema;

import java.util.Map;
import java.util.Map.Entry;

import com.fasterxml.jackson.databind.JsonNode;
Expand Down Expand Up @@ -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<String, JsonNode> vocabs : vocabulary.properties()) {
builder.vocabulary(vocabs.getKey(), vocabs.getValue().booleanValue());
}
Expand All @@ -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() {
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/networknt/schema/DependenciesValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@
*/
public class DependenciesValidator extends BaseJsonValidator implements JsonValidator {
private static final Logger logger = LoggerFactory.getLogger(DependenciesValidator.class);
private final Map<String, List<String>> propertyDeps = new HashMap<String, List<String>>();
private final Map<String, JsonSchema> schemaDeps = new HashMap<String, JsonSchema>();
private final Map<String, List<String>> propertyDeps = new HashMap<>();
private final Map<String, JsonSchema> schemaDeps = new HashMap<>();

/**
* Constructor.
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/networknt/schema/DependentRequired.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
*/
public class DependentRequired extends BaseJsonValidator implements JsonValidator {
private static final Logger logger = LoggerFactory.getLogger(DependentRequired.class);
private final Map<String, List<String>> propertyDependencies = new HashMap<String, List<String>>();
private final Map<String, List<String>> propertyDependencies = new HashMap<>();

public DependentRequired(SchemaLocation schemaLocation, JsonNodePath evaluationPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {

Expand All @@ -49,7 +49,7 @@ public DependentRequired(SchemaLocation schemaLocation, JsonNodePath evaluationP
public Set<ValidationMessage> validate(ExecutionContext executionContext, JsonNode node, JsonNode rootNode, JsonNodePath instanceLocation) {
debug(logger, executionContext, node, rootNode, instanceLocation);

Set<ValidationMessage> errors = new LinkedHashSet<ValidationMessage>();
Set<ValidationMessage> errors = new LinkedHashSet<>();

for (Iterator<String> it = node.fieldNames(); it.hasNext(); ) {
String pname = it.next();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/networknt/schema/EnumValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<JsonNode>();
nodes = new HashSet<>();
StringBuilder sb = new StringBuilder();

sb.append('[');
Expand Down Expand Up @@ -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()) {
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/networknt/schema/ItemsValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public Set<ValidationMessage> validate(ExecutionContext executionContext, JsonNo
}

boolean hasAdditionalItem = false;
SetView<ValidationMessage> errors = new SetView<ValidationMessage>();
SetView<ValidationMessage> errors = new SetView<>();
if (node.isArray()) {
int i = 0;
for (JsonNode n : node) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ public Set<ValidationMessage> 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);
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/com/networknt/schema/JsonMetaSchema.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ public static class Builder {
private String iri;
private String idKeyword = "$id";
private VersionFlag specification = null;
private Map<String, Keyword> keywords = new HashMap<>();
private Map<String, Format> formats = new HashMap<>();
private Map<String, Boolean> vocabularies = new HashMap<>();
private final Map<String, Keyword> keywords = new HashMap<>();
private final Map<String, Format> formats = new HashMap<>();
private final Map<String, Boolean> vocabularies = new HashMap<>();
private FormatKeywordFactory formatKeywordFactory = null;
private VocabularyFactory vocabularyFactory = null;
private KeywordFactory unknownKeywordFactory = null;
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/networknt/schema/JsonNodePath.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
23 changes: 7 additions & 16 deletions src/main/java/com/networknt/schema/JsonSchema.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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<JsonValidator> VALIDATOR_SORT = (lhs, rhs) -> {
private static final Comparator<JsonValidator> VALIDATOR_SORT = (lhs, rhs) -> {
String lhsName = lhs.getEvaluationPath().getName(-1);
String rhsName = rhs.getEvaluationPath().getName(-1);

Expand Down Expand Up @@ -771,9 +768,7 @@ public <T> T validate(JsonNode rootNode, OutputFormat<T> format, ExecutionContex
* @return the result
*/
public <T> T validate(JsonNode rootNode, OutputFormat<T> format, Consumer<ExecutionContext> executionCustomizer) {
return validate(createExecutionContext(), rootNode, format, (executionContext, validationContext) -> {
executionCustomizer.accept(executionContext);
});
return validate(createExecutionContext(), rootNode, format, (executionContext, validationContext) -> executionCustomizer.accept(executionContext));
}

/**
Expand Down Expand Up @@ -892,9 +887,7 @@ public <T> T validate(String input, InputFormat inputFormat, OutputFormat<T> for
* @return the result
*/
public <T> T validate(String input, InputFormat inputFormat, OutputFormat<T> format, Consumer<ExecutionContext> 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));
}

/**
Expand Down Expand Up @@ -1241,9 +1234,7 @@ public ValidationResult walkAtNode(ExecutionContext executionContext, JsonNode n
private <T> T walkAtNodeInternal(ExecutionContext executionContext, JsonNode node, JsonNode rootNode,
JsonNodePath instanceLocation, boolean validate, OutputFormat<T> format, Consumer<ExecutionContext> executionCustomizer) {
return walkAtNodeInternal(executionContext, node, rootNode, instanceLocation, validate, format,
(executeContext, validationContext) -> {
executionCustomizer.accept(executeContext);
});
(executeContext, validationContext) -> executionCustomizer.accept(executeContext));
}

private <T> T walkAtNodeInternal(ExecutionContext executionContext, JsonNode node, JsonNode rootNode,
Expand Down
10 changes: 5 additions & 5 deletions src/main/java/com/networknt/schema/JsonSchemaFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public static class Builder {
private ObjectMapper yamlMapper = null;
private JsonNodeReader jsonNodeReader = null;
private String defaultMetaSchemaIri;
private final ConcurrentMap<String, JsonMetaSchema> metaSchemas = new ConcurrentHashMap<String, JsonMetaSchema>();
private final ConcurrentMap<String, JsonMetaSchema> metaSchemas = new ConcurrentHashMap<>();
private SchemaLoaders.Builder schemaLoadersBuilder = null;
private SchemaMappers.Builder schemaMappersBuilder = null;
private boolean enableSchemaCache = true;
Expand All @@ -83,7 +83,7 @@ public Builder jsonNodeReader(JsonNodeReader jsonNodeReader) {
* <p>
* If the object reader is set this will not be used.
* <p>
* This is deprecated use a object reader instead.
* This is deprecated use an object reader instead.
*
* @param jsonMapper the json mapper
* @return the builder
Expand All @@ -99,7 +99,7 @@ public Builder jsonMapper(final ObjectMapper jsonMapper) {
* <p>
* If the object reader is set this will not be used.
* <p>
* This is deprecated use a object reader instead.
* This is deprecated use an object reader instead.
*
* @param yamlMapper the yaml mapper
* @return the builder
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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)) {
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/com/networknt/schema/JsonSchemaIdValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -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}.
* <p>
* Note that this does not strictly follow the specification.
* <p>
* 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.
* <p>
* 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) {
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/networknt/schema/JsonType.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public enum JsonType {
*
* @param typeStr the type value
*/
private JsonType(String typeStr) {
JsonType(String typeStr) {
this.type = typeStr;
}

Expand Down
6 changes: 3 additions & 3 deletions src/main/java/com/networknt/schema/JsonValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ default Set<ValidationMessage> 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,
Expand All @@ -84,12 +84,12 @@ default Set<ValidationMessage> 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();
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Loading

0 comments on commit 7c4944b

Please sign in to comment.