Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

segregated getDefaultNode in utils #1005

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 4 additions & 16 deletions src/main/java/com/networknt/schema/ItemsValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.networknt.schema.annotation.JsonNodeAnnotation;
import com.networknt.schema.utils.JsonSchemaRefs;
import com.networknt.schema.utils.SetView;

import com.networknt.schema.utils.Defaults;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -241,7 +240,7 @@ public Set<ValidationMessage> walk(ExecutionContext executionContext, JsonNode n
ArrayNode arrayNode = (ArrayNode) node;
JsonNode defaultNode = null;
if (this.validationContext.getConfig().getApplyDefaultsStrategy().shouldApplyArrayDefaults()) {
defaultNode = getDefaultNode(this.schema);
defaultNode = Defaults.getDefaultNode(this.schema);
}
for (int i = 0; i < count; i++) {
JsonNode n = arrayNode.get(i);
Expand All @@ -266,7 +265,7 @@ else if (this.tupleSchema != null) {
JsonNode defaultNode = null;
JsonNode n = arrayNode.get(i);
if (this.validationContext.getConfig().getApplyDefaultsStrategy().shouldApplyArrayDefaults()) {
defaultNode = getDefaultNode(this.tupleSchema.get(i));
defaultNode = Defaults.getDefaultNode(this.tupleSchema.get(i));
}
if (n != null) {
if (n.isNull() && defaultNode != null) {
Expand All @@ -293,7 +292,7 @@ else if (this.tupleSchema != null) {
JsonNode defaultNode = null;
JsonNode n = arrayNode.get(i);
if (this.validationContext.getConfig().getApplyDefaultsStrategy().shouldApplyArrayDefaults()) {
defaultNode = getDefaultNode(this.additionalSchema);
defaultNode = Defaults.getDefaultNode(this.additionalSchema);
}
if (n != null) {
if (n.isNull() && defaultNode != null) {
Expand Down Expand Up @@ -326,17 +325,6 @@ else if (this.tupleSchema != null) {
return validationMessages;
}

private static JsonNode getDefaultNode(JsonSchema schema) {
JsonNode result = schema.getSchemaNode().get("default");
if (result == null) {
JsonSchemaRef schemaRef = JsonSchemaRefs.from(schema);
if (schemaRef != null) {
result = getDefaultNode(schemaRef.getSchema());
}
}
return result;
}

private void walkSchema(ExecutionContext executionContext, JsonSchema walkSchema, JsonNode node, JsonNode rootNode,
JsonNodePath instanceLocation, boolean shouldValidateSchema, Set<ValidationMessage> validationMessages, String keyword) {
boolean executeWalk = this.validationContext.getConfig().getItemWalkListenerRunner().runPreWalkListeners(executionContext, keyword,
Expand Down
16 changes: 3 additions & 13 deletions src/main/java/com/networknt/schema/ItemsValidator202012.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.networknt.schema.annotation.JsonNodeAnnotation;
import com.networknt.schema.utils.JsonSchemaRefs;
import com.networknt.schema.utils.Defaults;
import com.networknt.schema.utils.SetView;

import org.slf4j.Logger;
Expand Down Expand Up @@ -120,7 +120,7 @@ public Set<ValidationMessage> walk(ExecutionContext executionContext, JsonNode n
JsonNode defaultNode = null;
if (this.validationContext.getConfig().getApplyDefaultsStrategy().shouldApplyArrayDefaults()
&& this.schema != null) {
defaultNode = getDefaultNode(this.schema);
defaultNode = Defaults.getDefaultNode(this.schema);
}
boolean evaluated = false;
for (int i = this.prefixCount; i < node.size(); ++i) {
Expand Down Expand Up @@ -155,17 +155,7 @@ public Set<ValidationMessage> walk(ExecutionContext executionContext, JsonNode n
return validationMessages;
}

private static JsonNode getDefaultNode(JsonSchema schema) {
JsonNode result = schema.getSchemaNode().get("default");
if (result == null) {
JsonSchemaRef schemaRef = JsonSchemaRefs.from(schema);
if (schemaRef != null) {
result = getDefaultNode(schemaRef.getSchema());
}
}
return result;
}


private void walkSchema(ExecutionContext executionContext, JsonSchema walkSchema, JsonNode node, JsonNode rootNode,
JsonNodePath instanceLocation, boolean shouldValidateSchema, Set<ValidationMessage> validationMessages) {
//@formatter:off
Expand Down
14 changes: 2 additions & 12 deletions src/main/java/com/networknt/schema/PrefixItemsValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.networknt.schema.annotation.JsonNodeAnnotation;
import com.networknt.schema.utils.JsonSchemaRefs;
import com.networknt.schema.utils.Defaults;
import com.networknt.schema.utils.SetView;

import org.slf4j.Logger;
Expand Down Expand Up @@ -110,7 +110,7 @@ public Set<ValidationMessage> walk(ExecutionContext executionContext, JsonNode n
for (int i = 0; i < count; ++i) {
JsonNode n = node.get(i);
if (this.validationContext.getConfig().getApplyDefaultsStrategy().shouldApplyArrayDefaults()) {
JsonNode defaultNode = getDefaultNode(this.tupleSchema.get(i));
JsonNode defaultNode = Defaults.getDefaultNode(this.tupleSchema.get(i));
if (n != null) {
// Defaults only set if array index is explicitly null
if (n.isNull() && defaultNode != null) {
Expand Down Expand Up @@ -150,16 +150,6 @@ public Set<ValidationMessage> walk(ExecutionContext executionContext, JsonNode n
return validationMessages;
}

private static JsonNode getDefaultNode(JsonSchema schema) {
JsonNode result = schema.getSchemaNode().get("default");
if (result == null) {
JsonSchemaRef schemaRef = JsonSchemaRefs.from(schema);
if (schemaRef != null) {
result = getDefaultNode(schemaRef.getSchema());
}
}
return result;
}

private void doWalk(ExecutionContext executionContext, Set<ValidationMessage> validationMessages, int i,
JsonNode node, JsonNode rootNode, JsonNodePath instanceLocation, boolean shouldValidateSchema) {
Expand Down
15 changes: 2 additions & 13 deletions src/main/java/com/networknt/schema/PropertiesValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import com.fasterxml.jackson.databind.node.MissingNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.networknt.schema.annotation.JsonNodeAnnotation;
import com.networknt.schema.utils.JsonSchemaRefs;
import com.networknt.schema.utils.Defaults;
import com.networknt.schema.utils.SetView;
import com.networknt.schema.walk.WalkListenerRunner;
import org.slf4j.Logger;
Expand Down Expand Up @@ -192,7 +192,7 @@ private void applyPropertyDefaults(ObjectNode node) {
for (Map.Entry<String, JsonSchema> entry : this.schemas.entrySet()) {
JsonNode propertyNode = node.get(entry.getKey());

JsonNode defaultNode = getDefaultNode(entry.getValue());
JsonNode defaultNode = Defaults.getDefaultNode(entry.getValue());
if (defaultNode == null) {
continue;
}
Expand All @@ -204,17 +204,6 @@ private void applyPropertyDefaults(ObjectNode node) {
}
}

private static JsonNode getDefaultNode(JsonSchema schema) {
JsonNode result = schema.getSchemaNode().get("default");
if (result == null) {
JsonSchemaRef schemaRef = JsonSchemaRefs.from(schema);
if (schemaRef != null) {
result = getDefaultNode(schemaRef.getSchema());
}
}
return result;
}

private void walkSchema(ExecutionContext executionContext, Map.Entry<String, JsonSchema> entry, JsonNode node,
JsonNode rootNode, JsonNodePath instanceLocation, boolean shouldValidateSchema,
SetView<ValidationMessage> validationMessages, WalkListenerRunner propertyWalkListenerRunner) {
Expand Down
66 changes: 66 additions & 0 deletions src/main/java/com/networknt/schema/utils/Defaults.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* Copyright (c) 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.networknt.schema.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.networknt.schema.JsonSchema;
import com.networknt.schema.JsonSchemaRef;

/**
* The 'Defaults' class provides utility methods for retrieving default values
* from a JSON schema.
*
* This class contains a single static method, 'getDefaultNode', which takes a
* 'JsonSchema' object as input
* and returns the default value specified in the schema. If the schema does not
* have a default value,
* it checks if the schema has a reference to another schema and recursively
* calls itself with the referenced schema.
*
* Usage:
* JsonSchema schema = ...; // create or obtain a JSON schema
* JsonNode defaultNode = Defaults.getDefaultNode(schema); // retrieve the
* default value from the schema
*
* Note: This class requires the 'com.networknt.schema.JsonSchema' and
* 'com.networknt.schema.JsonSchemaRef' classes
* from the 'networknt/json-schema-validator' library.
*/
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just change this to The 'Defaults' class provides utility methods for retrieving default values from a JSON schema.

public class Defaults {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add the javadoc for the class.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

/**
* Retrieves the default value specified in the JSON schema.
*
* This method takes a 'JsonSchema' object as input and returns the default
* value specified in the schema.
* If the schema does not have a default value, it checks if the schema has a
* reference to another schema
* and recursively calls itself with the referenced schema.
*
* @param schema the JSON schema from which to retrieve the default value
* @return the default value specified in the schema, or null if no default
* value is found
*/
public static JsonNode getDefaultNode(JsonSchema schema) {
JsonNode result = schema.getSchemaNode().get("default");
if (result == null) {
JsonSchemaRef schemaRef = JsonSchemaRefs.from(schema);
if (schemaRef != null) {
result = getDefaultNode(schemaRef.getSchema());
}
}
return result;
}
}
53 changes: 53 additions & 0 deletions src/test/java/com/networknt/schema/utils/DefaultsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package com.networknt.schema.utils;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;

import java.io.InputStream;

import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.networknt.schema.JsonSchema;
import com.networknt.schema.JsonSchemaFactory;
import com.networknt.schema.SpecVersion.VersionFlag;
public class DefaultsTest {

@Test
void testGetDefaultNodeNotNull() throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree("{\"default\": \"defaultValue\"}");
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(VersionFlag.V7);
JsonSchema schema = factory.getSchema(node);
JsonNode result = Defaults.getDefaultNode(schema);
assertNotNull(result, "Default node should not be null");
}

@Test
void testGetDefaultNodeWhenDefaultNotFound() throws Exception {
ObjectMapper mapper = new ObjectMapper();
// Create a JsonNode without a "default" field
JsonNode node = mapper.readTree("{\"notDefault\": \"value\"}");
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(VersionFlag.V7);
JsonSchema schema = factory.getSchema(node);
JsonNode result = Defaults.getDefaultNode(schema);
// Assert that the result is null, as there's no "default" node in the schema
assertNull(result, "Default node should be null when 'default' node is not found in the schema");
}

@Test
void testGetDefaultNodeWhenDefaultInRef() throws Exception {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't create external resources for the test. Just use strings inline as it makes the test hard to read and verify. This test isn't even valid. You have a unused variable JsonNode mainSchemaNode.

InputStream mainSchemaInputStream = DefaultsTest.class.getResourceAsStream("/mainSchema.json");
InputStream referredSchemaInputStream = DefaultsTest.class.getResourceAsStream("/referredSchema.json");
ObjectMapper mapper = new ObjectMapper();
JsonNode mainSchemaNode = mapper.readTree(mainSchemaInputStream);
JsonNode referredSchemaNode = mapper.readTree(referredSchemaInputStream);
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(VersionFlag.V7);
JsonSchema mainSchema = factory.getSchema(referredSchemaNode); // Use referred schema here
JsonNode result = Defaults.getDefaultNode(mainSchema);
assertNotNull(result, "Default node should not be null when 'default' node is in the referred schema");
assertEquals("defaultValue", result.asText(), "Default node should have the default value in the referred schema");
}

}
3 changes: 3 additions & 0 deletions src/test/resources/mainSchema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"$ref": "referredSchema.json"
}
4 changes: 4 additions & 0 deletions src/test/resources/referredSchema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"type": "string",
"default": "defaultValue"
}