Skip to content

Commit dc25d09

Browse files
committed
Add Schema-based validation operations
1 parent 491a0cd commit dc25d09

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package com.relogiclabs.json.schema;
2+
3+
import com.relogiclabs.json.schema.message.MessageFormatter;
4+
import com.relogiclabs.json.schema.tree.JsonTree;
5+
import com.relogiclabs.json.schema.tree.RuntimeContext;
6+
import com.relogiclabs.json.schema.tree.SchemaTree;
7+
import com.relogiclabs.json.schema.util.DebugUtils;
8+
import lombok.Getter;
9+
10+
import java.util.Queue;
11+
12+
/**
13+
* {@code JsonSchema} provides Schema validation functionalities for JSON document.
14+
*/
15+
@Getter
16+
public class JsonSchema {
17+
private final RuntimeContext runtime;
18+
private final SchemaTree schemaTree;
19+
private final Queue<Exception> exceptions;
20+
21+
/**
22+
* Initializes a new instance of the {@link JsonSchema} class for the
23+
* specified Schema string.
24+
* @param schema A Schema string for validation
25+
*/
26+
public JsonSchema(String schema) {
27+
runtime = new RuntimeContext(MessageFormatter.SCHEMA_VALIDATION, false);
28+
exceptions = runtime.getExceptions();
29+
schemaTree = new SchemaTree(runtime, schema);
30+
}
31+
32+
/**
33+
* Indicates whether the input JSON string conforms to the Schema specified
34+
* in the {@link JsonSchema} constructor.
35+
* @param json The JSON to validate with Schema
36+
* @return Returns {@code true} if the JSON string conforms to the Schema and {@code false} otherwise.
37+
*/
38+
public boolean isValid(String json) {
39+
exceptions.clear();
40+
var jsonTree = new JsonTree(runtime, json);
41+
DebugUtils.print(schemaTree, jsonTree);
42+
return schemaTree.getRoot().match(jsonTree.getRoot());
43+
}
44+
45+
/**
46+
* Writes error messages that occur during Schema validation process, to the
47+
* standard error output stream.
48+
*/
49+
public void writeError() {
50+
for(var exception : exceptions)
51+
System.err.println(exception.getMessage());
52+
}
53+
54+
/**
55+
* Indicates whether the input JSON string conforms to the given Schema string.
56+
* @param schema The Schema string to conform or validate
57+
* @param json The JSON string to conform or validate
58+
* @return Returns {@code true} if the JSON string conforms to the Schema and {@code false} otherwise.
59+
*/
60+
public static boolean isValid(String schema, String json) {
61+
var jsonSchema = new JsonSchema(schema);
62+
var result = jsonSchema.isValid(json);
63+
if(!result) jsonSchema.writeError();
64+
return result;
65+
}
66+
}

0 commit comments

Comments
 (0)