I'm attempting to add JSON schema validation to sanitize user inputs for a Java application. All of the schema are stored in the file system that's doing the validation. My schema is something like this:
{
"$id": "https://www.my-url.org/schemas/schemaName.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Train Approximation",
"type": "object",
"properties":{
"settings":{
"type":"object",
"oneOf":[
{"$ref":"https://www.my-url.org/anotherSchema.json"}
]
}
}
}
(There's additional items in the "oneOf", plus other properties and descriptions that aren't relevant.)
I'm using the Everit library for schema validation. My code for checking schema looks like this:
String[] schemaNames = {"schemaName.json","anotherSchema.json", "moreSchemasEtc.json"};
String schemaFile = schemaName + ".json";
File fSchemaFile = new File(dir.getAbsoluteFile() + File.separator + schemaFile);
if (fSchemaFile.exists()) {
try (InputStream inputStream = new FileInputStream(fSchemaFile)) {
JSONObject rawSchema = new JSONObject(new JSONTokener(inputStream));
SchemaLoaderBuilder slb = SchemaLoader.builder()
.schemaClient(SchemaClient.classPathAwareClient())
.schemaJson(rawSchema)
.resolutionScope("classpath://Schema");
for(String schemaFileName : schemaNames) {
File tSchemaFile = new File(dir.getAbsoluteFile() + File.separator + schemaFileName);
InputStream inStream = new FileInputStream(tSchemaFile);
JSONObject rawTSchema = new JSONObject(new JSONTokener(inStream));
slb.registerSchemaByURI(new URI("https://www.my-url.org/schemas/"+schemaFileName), rawTSchema);
}
SchemaLoader schemaLoader = slb.build();
Schema schema = schemaLoader.load().build();
schema.validate(new JSONObject(jsonString));
} catch (ValidationException e) {
//Do error handling
}
} else { /* Do other stuff */ }
This works for all of my schema that don't have external references. (E.g: "$ref":"https://www.my-url.org/anotherSchema.json") For schema like the one I have posted here, I get a java.io.FileNotFoundException with the path from the reference.
What am I doing wrong here? I also tried:
-Using the classpath aware client (still in the code above) and adding the parent directory above my /Schema/ directory to my Java classpath, then referencing everything as e.g "$ref":"anotherSchema.json" instead of having the whole path
-Using the my-url.org path in the resolution scope instead of classpath
With the classpath option, I get an error that has a path like classpath://Schema/anotherSchema.json in the FileNotFoundException, but an exception nonetheless.