Coder Social home page Coder Social logo

java-json-tools / json-schema-validator Goto Github PK

View Code? Open in Web Editor NEW
1.6K 93.0 396.0 19.11 MB

A JSON Schema validation implementation in pure Java, which aims for correctness and performance, in that order

Home Page: http://json-schema-validator.herokuapp.com/

License: Other

Shell 0.12% Java 99.88%

json-schema-validator's Introduction

License LGPLv3 License ASL 2.0 Build Status Maven Central

Read me first

The current version of this project is licensed under both LGPLv3 (or later) and ASL 2.0. The old version (2.0.x) was licensed under LGPL 3.0 (or later) only.

Version 2.2 is out. See here for the list of changes compared to 2.0. And of course, it still has all the features of older versions.

What this is

This is an implementation with complete validation support for the latest JSON Schema draft (v4, including hyperschema syntax support) and the previous draft (v3 -- no hyperschema support though). Its list of features would be too long to enumerate here; please refer to the links above!

Should you wonder about it, this library is reported to work on Android. Starting with version 2.2.x, all APK conflicts have been resolved, so you can use this in this context as well.

Google Group

This project has a dedicated Google group. For any questions you have about this software package, feel free to post! The author (me) will try and respond in a timely manner.

Testing online

You can test this library online; this web site is in a project of its own, which you can fork and run by yourself.

Versions

Available downloads

Gradle/maven

This package is available on Maven central; the artifact is as follows:

Gradle:

dependencies {
    compile(group: "com.github.java-json-tools", name: "json-schema-validator", version: "2.2.14");
}

Maven:

<dependency>
    <groupId>com.github.java-json-tools</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>2.2.14</version>
</dependency>

"Full" jar; command line

OUTDATED: Let me know if you need this in the issues section.

This jar contains the library plus all its dependencies. Download the lib jar (a little more than 6 MiB) from Bintray.

Versioning scheme policy

The versioning scheme is defined by the middle digit of the version number:

  • if this number is even, then this is the stable version; no new features will be added to such versions, and the user API will not change (save for some additions if requested).
  • if this number is odd, then this is the development version; new features will be added to those versions only, and the user API may change.

Relevant documents

This implementation is based on the following drafts:

More...

For a detailed discussion of the implementation, see here.

Please see the wiki for more details.

json-schema-validator's People

Contributors

agebhar1 avatar ajorg-aws avatar capstan avatar csciuto avatar dorzey avatar fge avatar gitgrimbo avatar huggsboson avatar kelvinpho avatar loki-afro avatar sslavic avatar sullis avatar tvdinh avatar vikasbodke avatar vjkoskela avatar zhangzheflying avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

json-schema-validator's Issues

Provide access to json source object from the JsonSchema object

This sounds trivial, but I just migrated my project etlunit (https://bitbucket.org/bradleysmithllc/etl-unit) away from using my own schema validator to yours (which is WAY better, by the way - I was happy to find it), and one annoying shortcoming is not being able to ask the schema object for the source that it was created from. E.G.:

JsonSchema featureOperationsJsonSchema;

JsonSchemaFactory fact = JsonSchemaFactory.byDefault();

try {
  JsonNode node = JsonLoader.fromURL(ResourceFeatureMetaInfo.class.getClassLoader().getResource("org/bitbucket/bradleysmithllc/etlunit/featureOperations.jsonSchema"));

  //  Utility class I wrote to validate the schema itself against the V4 draft
  // included in your project so I could get better feedback on problems with schemas
  JsonSchemaValidator.validateV4Schema(node);

  featureOperationsJsonSchema = fact.getJsonSchema(node);
} catch (IOException e) {
  throw new RuntimeException("Could not load operation schema", e);
} catch (ProcessingException e) {
  throw new RuntimeException("Could not process operation schema: " +     JsonProcessingUtil.getProcessingReport(e), e);
}

Once processed, I pass the schema around for validation. For logging and providing feedback on instance objects, I would like to be able to do:

JsonNode sourceNode = featureOperationsJsonSchema.getSourceNode();

Or something like it. It's a small thing, and I can track it internally, but it would be more convenient to extract it directly from the schema object.

This may already exist, but I couldn't figure out how to do it.

license of the project

hi, the license of the project is not visible, in the maven file it says it's LGPL v3 if it's that then could you add it in a section to the README and as a file at the root of the repo called LICENSE?

thanks

Generate Java classes from JSON Schema

Hi,

can the library fge/json-schema-validator generate Java classes from a JSON Schema?
otherwise, is it planned to add this feature some time soon?

if not, can you suggest a solution?
I've read about "jsonschema2pojo". is that a good solution?

best regards,
David

$ref loop detection after second call of 'validate' method

Hi!

I found that if I try to validate json-instance against a schema by specified path (validator.validate("#/schema/in", json)), validation pass for first time, but second third and so on calls will report an "$ref loop" error. It seems strange since I try to revalidate same json-instance.

JSON schema validation using java - $ref failed

I have an object called (Location) which has list of objects (BaseObject). i created a schema for location like shown below (location.json) with a ref to Base object(baseobject.json). But my validation fails with the error message - ["": domain: validation; keyword: properties; message: required property(ies) not found; missing: ["id","refName"]; required: ["id","refName"]]

Is there a mistake in the way i used the refs or is this a bug ?

Location.json - schema

{
"type":"object",
"properties":{
"locationType":{
"type":"string"
},
"mapsRefs":{
"$ref": "file://localhost/c:/baseobject.json"
}
}
}
}
baseobject.json - schema

{
"type":"object",
"properties":{
"refName":{
"type":"string",
"required":true
},
"id":{
"type":"integer",
"required":true
},
"refs":{
"type":"array",
"required":false,
"items":{
"type":"string"
}
}
}

}

Sample Json
{
"locationType":"HOME",
"mapsRefs":[
{
"refName":"name",
"id":1,
"refs":[

     ]
  },
  {
     "refName":"name3",
     "id":2,
     "refs":[

     ]
  }

]
}

Invalid JSON is accepted by validator.

I had the following JSON schema defined:
{
"description" : "Example Address JSON Schema",
"type" : "object",
"properties" : {
"address" : {
"title": "Street name and number",
"type" : "string"
},
"city" : {
"title" : "City name",
"type" : "string"
},
"postalCode" : {
"title" : "Zip Code: 2 letters dash five digits",
"type" : "string",
"pattern" : "^[A-Z]{2}-[0-9]{5}"
},
"region" : {
"title" : "Optional Region name",
"type" : "string",
"optional" : true
}
},
"additionalProperties" : false
}

Then I attempted to validate the following JSON, which is invalid since non-optional property "city" is missing:

{
"address" : "happy fake address"
}

But it accepted as valid.

Relative URLs over http and file don't seem to work.

Issue

I have been working to make our Schema project more robust and allow it to be used offline and online. Your validator is the best, but I can't seem to get it tor validate a linked relative uri schema.

I have looked at your "Example 5" and have also written two tests against our schema as a test. The issue it that I would like set the namespace depending on how I want to use the schema files. It would be really nice to be able to checkout the whole schema repository and set the namespace to a specific file, or if I wanted to set the namespace to be on the public website, I could do that too.

Tests

Here is the test I wrote: https://github.com/spidasoftware/schema/blob/cee/utils/test/groovy/com/spidasoftware/schema/validation/ConceptualSchemaTest.groovy

Here is the base schema file: https://github.com/spidasoftware/schema/blob/cee/v1/spidacalc/calc/point.schema
that references two other files.

Am I doing something totally wrong, or is this a bug?

Offline validation

Hi,

Firstly, thanks for creating this library.

I'm trying to validate some JSON data against a schema I have. I am getting the "a parent schema's id must be absolute" error.

If I make the schema id absolute, such as using a "http://" URI, my problem then becomes that I am using offline tests.

I now want to be able to get hold of the the URIManager and override the "http" downloader, in order to resolve the URIs myself to local files, but all the fields I seem to need to access are private and final.

Can you offer any advice please?

Thanks.

Question about JSON schema validation

Hi.
I have a question regarding json schema validation on version 1.6.2.
Imagine that the following schema is defined (the schema has an error, the field2 as the incorrect type strung):

{
    "$schema":"http://json-schema.org/draft-03/schema#",
    "description":"test",
    "id":"http://example.com/test_v1",
    "properties":{
    "field1":{"required":true,"type":"string","format":"date"},
    "field2":{"type":"strung"}
    },
    "type":"object"
}

To check the schema validity:

JsonSchemaFactory.Builder builder = new JsonSchemaFactory.Builder();
for (BuiltinSchemas schema: BuiltinSchemas.values())
    builder.addSchema(schema.getURI(), schema.getRawSchema());

JsonNode schemaNode = JsonLoader.fromFile(<schema-above>));
ValidationReport report;

String schemaUri = schemaNode.get("$schema").textValue();
JsonSchema schema = factory.fromURI(schemaUri);
report = schema.validate(schemaNode);

Is it possible to check the schema validity with this code or I should use a SyntaxValidator?

Help getting latest version to work

Hello,

I upgraded to the latest version today and my code no longer works. I have tried looking through the code but so much has changed that I can't understand how to make it work.

This is what I used to do. How should I do it now?

/**
     * Returns <code>true</code> if the specified JSON conforms to the specified JSON schema.
     * 
     * @param json JSON to check.
     * @param jsonSchema JSON schema that the JSON must conform to.
     * @throws IOException If the JSON schema file cannot be opened.
     * @throws JsonValidationFailureException If the specified JSON is invalid.
     * @return <code>true</code> if the JSON is valid.
     */
    public boolean isValidJson(final String json, final File jsonSchema) throws IOException, JsonValidationFailureException {
        final JsonNode jsonSchemaNode = JsonLoader.fromFile(jsonSchema);
        final JsonValidator jsonValidator = new JsonValidator(jsonSchemaNode);
        final JsonNode jsonNode = JsonLoader.fromReader(new StringReader(json));
        final ValidationReport validationReport = jsonValidator.validate(jsonNode);
        return validationReport.isSuccess();
    }

Error in extended schemas

I was performing some tests of json-schema-validator and found the following behavior.
I defined the following schema

{
"extends":{"$ref" : "http://json-schema.org/draft-03/schema#"},
"properties":{
"indexed":{"type": "boolean", "default":false}
}
}

and after that I try the validate the next schema.

{
"type" : "object",
"properties" : {
"from" : { "type" : "string", "indexed":111 }
}
}

It should give an error, since Indexed is a boolean property and not a integer. And it don't.
The schema is validated and is considered correct.

Adding granularity to validation error messages

Hi,

A colleague and I have completed the work of adding more specific error messages to schema validation (adding boundary conditions into the message with MessageFormat) , and would like to contribute it back to the project. What's the best way to get the code to you ... I remember in the past you saying that you are not overly fond of pull requests.

I can create a one page summary document of the changes if that would be helpful.

Thanks
Mike

onWalk is called in alphabetical order

While testing more of the SchemaListener code, I noticed that onWalk is called on each property in a json schema in alphabetical order of the name. Is there a reason it is done in alphabetical order vs in the order it appears in the schema?

extends + additionalProperties doesn't seem supported

Mixing 'extends' with 'additionalProperties', doesn't seem to have the effects I would assume.
Given the 2 schemas A and B:
A

{
    "type":"object",
    "extends":{
        "$ref": "b.json"
    },
    "additionalProperties":false,
    "properties":{
        "foo":{
            "type":"string"
        }
    }
}

B

{
    "type":"object",
    "additionalProperties":false,
    "properties":{
        "bar":{
            "type":"string"
        }
    }
}

I would expect that the following data would be valid:

{
    "foo":"baz",
    "bar":"bat"
}

But instead I get the following errors:

: domain: validation; keyword: additionalProperties; message: additional properties not permitted; unwanted: ["foo"]
: domain: validation; keyword: additionalProperties; message: additional properties not permitted; unwanted: ["bar"]

Possible to customize messages?

As far as i can see, all error messages are stored as enumerations and cannot be modified via any configuration? Is this correct?

For example, changing the message from 'input is not a valid email address' to 'The value you have entered is not a valid email address'.

Thanks!

Failing tests in latest

Trying to build latest, 6 failing tests ....

Failed tests:
resolveWorksAsExpected(org.eel.kitchen.jsonschema.ref.JsonResolverAbsoluteURITest): URI and id of downloaded schema disagree (URI: schema://schema4#, id: #)
resolveWorksAsExpected(org.eel.kitchen.jsonschema.ref.JsonResolverAbsoluteURITest): URI and id of downloaded schema disagree (URI: schema://schema1#, id: #)
loopsAreDetected(org.eel.kitchen.jsonschema.ref.JsonResolverAbsoluteURITest): expected: but was:<URI and id of downloaded schema disagree (URI: a://b.c#, id: #)>
loopsAreDetected(org.eel.kitchen.jsonschema.ref.JsonResolverAbsoluteURITest): expected: but was:<URI and id of downloaded schema disagree (URI: schema://schema2#, id: #)>
sameLocatorIsOnlyLookedUpOnce(org.eel.kitchen.jsonschema.ref.JsonResolverAbsoluteURITest): URI and id of downloaded schema disagree (URI: schema://schema4#, id: #)
testIssue7(org.eel.kitchen.Issue7Test): expected: but was:

Tests run: 366, Failures: 6, Errors: 0, Skipped: 0

allOf in the use of "items" can't be overridden.

I have a schema file that I would like to "extend" all the properties of another schema, but then override a specific value. This worked as expected when it was an object value, but seems to revert back to the original schema when it is used in an "items" of an array.

Here is the example of the overridden values. There is an object and an array override in this file.

https://github.com/spidasoftware/schema/blob/cee/v1/spidacalc/analysis/structure.schema

Here is the test that tests that the "clientItem" is overridden:

https://github.com/spidasoftware/schema/blob/cee/utils/test/groovy/com/spidasoftware/schema/validation/AnalysisSchemaTest.groovy

Here is the fixture used in that test against that schema:

https://github.com/spidasoftware/schema/blob/cee/fixtures/spidacalc/analysis/pole_with_anchor.json

As you can see if you run "mvn test" you get a failure that clientItem should be a string, but it should be an object. If I make it a string it actually tells me it should be an object. :-)

ISO-8601 DateTime formats

My project currently supports two different ISO-8601 date formats (please see http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html):

yyyy-MM-dd'T'HH:mm:ss.SSS
yyyy-MM-dd'T'HH:mm:ss

JSON-Schema-Validator currently only supports the latter - it considers the former to not be valid.

As the former format is more precise (as it uses miliseconds), it isn't an option for me to change my project to use the millisecondless version to make the DateTime formatter happy. It clearly isn't an option to change JSON-Schema-Validator to use the format with milliseconds, because that'd break every existing consumer project.

Ultimately, the correct course of action is probably to have JSON-Schema-Validator able to load in acceptable date/time formats at startup from some sort of configuration file, with the default being "yyyy-MM-dd'T'HH:mm:ss"

In the meantime, I have a code change that I don't love but does the trick I'd like to propose:

csciuto@f112688

Thoughts?

Thanks,

Corey

maven repository for >= 1.5.3

this artifact is on the standard maven repository:

org.kitchen-eel
json-schema-validator
your-version-here

but starting from 1.5.3 you are using the other groupip:

com.github.fge
json-schema-validator
your-version-here

and this artifact is not on the standard maven repository.
why is that?
what is the maven repository that we need to use for this artifact?

Give schema-specific view of the json tree behind a schema

Once I load a schema, I can ask the json node questions about the schema attributes like so:

JsonNode node = JsonLoader.fromString("{}");   // some inspired schema

JsonSchema schema = factory.getJsonSchema(node);

if (node.get("properties") != null)
{
  // schema has properties
}

But I would rather ask the schema itself if it has properties:

if (schema.hasProperties())
{
  Map<String, JsonNode> properties = schema.getProperties();
}

. . . likewise for other schema attributes.

ref not resolved while walking a list

using draft-04, I have the following schema.

{
  "$schema" : "http://json-schema.org/draft-04/schema#",
  "id" : "testSchema",
  "description" : "some schema",
  "type" : "object",
  "properties" : {
    "arrayOne" : {
      "id" : "arrayOne",
      "type" : "array",
      "minItems" : 0,
      "items" : {
        "itemOne" : {
          "id" : "itemOne",
          "description" : "an item in the array",
          "$ref" : "reference.json"
        }
      }
    }
  }
}

For every call of onWalk, I am printing the node associated with the tree (to verify the behavior of ResolvingSchemaWalker). I see the following output.

onWalk called for {
  "$schema" : "http://json-schema.org/draft-04/schema#",
  "id" : "testSchema",
  "description" : "some schema",
  "type" : "object",
  "properties" : {
    "arrayOne" : {
      "id" : "arrayOne",
      "type" : "array",
      "minItems" : 0,
      "items" : {
        "itemOne" : {
          "id" : "itemOne",
          "description" : "an item in the array",
          "$ref" : "reference.json"
        }
      }
    }
  }
}
onWalk called for {
  "id" : "arrayOne",
  "type" : "array",
  "minItems" : 0,
  "items" : {
    "itemsOne" : {
      "id" : "itemsOne",
      "description" : "an item in the array",
      "$ref" : "reference.json"
    }
  }
}
onWalk called for {
  "itemsOne" : {
    "id" : "itemsOne",
    "description" : "an item in the array",
    "$ref" : "reference.json"
  }
}

I don't see any onWalk calls for the resolution of reference.json. Am I doing something wrong in my schema?

Helpful if URIManager.getContent showed the URI in the error message(s)

Hi,

Maybe add uri here:

https://github.com/fge/json-schema-validator/blob/482f01f6048ec53adfbcecd40f1732087bbd750d/src/main/java/org/eel/kitchen/jsonschema/uri/URIManager.java#L69

Preconditions.checkArgument(uri.isAbsolute(), "URI \"" + uri + "\" is not absolute");

And also here:

https://github.com/fge/json-schema-validator/blob/482f01f6048ec53adfbcecd40f1732087bbd750d/src/main/java/org/eel/kitchen/jsonschema/uri/URIManager.java#L75

    if (downloader == null)
        throw new JsonSchemaException("cannot handle scheme \"" + scheme
            + "\" for URI \"" + uri + "\"");

Using JSON schema with an array of mixed object types

as far as I understand - this should be a valid schema:

{
"type" : "array",
"items" : {
"type" : [
{ "type" : "object", "properties" : { "name" : { "type" : "string" }}},
{ "type" : "object", "properties" : { "price" : { "type" : "number" } } }
]
}
}

but it comes out as invalid in the schema validator
is this a bug? or it's actually invalid?
thanks!

Invalid extended schema is validated as correct

Lastest version: 1.4.1
Error explanation:

  • Define a schema1 that is an extension from draftv3 and that add a new property, 'indexed', that is declared as boolean.
  • Define an new schema using schema1, schema2. The value for property 'indexed' is 111.
  • The validator should give an error, since for property 'indexed' only a boolean value should be allowed.

Code:

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.databind.JsonNode;
import org.eel.kitchen.jsonschema.main.JsonSchema;
import org.eel.kitchen.jsonschema.main.JsonSchemaFactory;
import org.eel.kitchen.jsonschema.report.ValidationReport;
import org.eel.kitchen.jsonschema.util.JsonLoader;

public class JsonSchemaTest {

  public static void main(String[] args) {
    try {
        JsonNode draftv3 = JsonLoader.fromResource("/draftv3/schema");
        JsonNode schema1 = JsonLoader.fromFile(new File("schema1.json"));
        JsonNode schema2 = JsonLoader.fromFile(new File("schema2.json"));

        ValidationReport report;

        JsonSchemaFactory factory = JsonSchemaFactory.defaultFactory();
        JsonSchema draftv3Schema = factory.fromSchema(draftv3);
        report = draftv3Schema.validate(schema1);
        if (!report.isSuccess())
            System.out.println("Schema1: " + report.asJsonObject());

        JsonSchema schema1Schema = factory.fromSchema(schema1);
        report = schema1Schema.validate(schema2);
        if (!report.isSuccess())
            System.out.println("Schema2: " + report.asJsonObject());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
  }
}

The schema1.json file is

{
 "extends" : {
    "$ref" : "http://json-schema.org/draft-03/schema#"
   },
  "properties" : {
  "indexed" : {
     "type" :  "boolean",
     "default" : false
   }
 }
}

The schema2.json is

{
 "type" : "object",
 "properties" : {
   "from" :  {
      "type" : "string",
      "required" : true,
      "indexed" : 111
   }
  }
}

Infinity vs. +Infinity

Using ALLOW_NON_NUMERIC_NUMBERS, "+Infinity" is accepted as a number, but "Infinity" is not (and the documentation suggests otherwise). This is with version 0.4.1.

Union Types (section 5.1 of draft 3) of schemas are not implemented: report as such

A schema for a heterogeneous/polymorphic array fails to validate. Here is an example, which is the schema for an array of objects that match one of two schema versions:

[EDIT: ignore this schema, it is written incorrectly. Please see corrected example below]

{ "type" : "array",
"items" :
[
{ "type" : "object",
"properties" :
{ "a" : { "type" : "string", "required" : true },
"b" : { "type" : "string", "required" : true } }
},
{ "type" : "object",
"properties" :
{ "c" : { "type" : "string", "required" : true },
"d" : { "type" : "string", "required" : true } }
}
]
}

Here is a conformant object:

[ {"a" : "1", "b" : "2"}, {"c":"3", "d":"4"}]

validation fails with messages like "property c is required but was not found". The suspected reason is that separate schema versions are somehow collapsed internally and validation of required properties is not done separately for each schema that can match. As a result, any non-homogeneous arrays cannot contain objects with required properties.

Objects in a "array" dont seem to get validated

With 0.4.1, type validation seems to not happen for objects that are within an 'array' type.
Example:

JSON Schema:

{
"properties": {
"age":{
"type":"integer"
"required":true
}

}
}

validates the JSON instance for numeric types
wheras if the same 'age "object was enclosed in an "array" no numeric type validation occurs.
It allows "abc" against "age"

Design questions

What's the purpose of those deques present at the JsonNodeTree ?

What's the start point for building a JsonSchema ?

ClassLoader Issues with ObjectNode

I see that you have overriden com.fasterxml.jackson.databind.node.ObjectNode in your jar. This is causing class loading issues for when trying to invoke your code. When I have both json-schema-validator and jackson-databind on my classpath in eclipse, it is loading the jackson-databind's version of ObjectNode instead of yours. This is causing the following error:

java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.node.ObjectNode.asMap()Ljava/util/Map; at org.eel.kitchen.jsonschema.validator.ObjectValidator.<init>(ObjectValidator.java:68) at org.eel.kitchen.jsonschema.validator.InstanceValidator.validate(InstanceValidator.java:89) at org.eel.kitchen.jsonschema.main.JsonSchema.validate(JsonSchema.java:71) at com.dibs.json_validator.AppTest.testJSON(AppTest.java:58) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

Is there some standard workaround or solution for this? I would prefer not to mess with my classloader. I am using the latest version of the 1.4 branch.

Does the validator apply default values

In JSON schema draft 03 spec 5.20, it defines the default attribute (keyword) where a default value for the instance can be specified if the instance is undefined.

As of the latest stable builds, 1.2.2 (or 1.2.3-SNAPSHOT) it doesn't appear as though the default values are being applied by the json-schema-validator. I searched the code and didn't find a reference to "default" (that would be used to test for the presence of that attribute) or a keyword definition for default.

Just the like example below, I defined default values when the instance itself is not required. When I tested making the instance required, instead of applying the default value the validator returned an error about the missing instance.

Please advise.

Example

  {   "type": "object",
       "properties": {
            "a": {
                "type": "string",
                "required": false,
                "default": "z"
             }
       }
  }

Method to access json tree with the refs resolved.

This may be a question more than a feature request (unless it isn't possible), but I would like to have access to the json tree after the refs are resolved. I can load a json node which contains refs and the factory will resolve refs, etc, but I have some code which needs to perform meta-operations on the schema tree, but I have to implement the ref resolution myself. Since this already happens in the schema validator, I thought this might not be difficult to expose as a service (perhaps in conjunction with my other request to provide access to the schema tree behind the schema itself this might work).

EmailFormatSpecifier not validating in 0.5.0beta4

in version 0.5.0beta4 the EmailFormatSpecifier is not properly checking if the email address is valid. According to the javadoc for InternetAddress: http://javamail.kenai.com/nonav/javadocs/javax/mail/internet/InternetAddress.html#InternetAddress(java.lang.String)

the constructor being used defaults strict mode to false. In order for to enforce RFC822 syntax, the second parameter in the constructor needs to be set to true. ie:

new InternetAddress(instance.textValue(), true);

Crash while invoked from Intellij Idea as a part of JUnit test

I've adopted the validator for testing of my REST interface responses. When I run my tests from maven everything is ok, but if I run tests from Intellij Idea validator crashes. The Idea runs both static initialisation of RhinoHelper and invocation of regexIsValid() method from the same thread and validator crashes while entering Context from regexIsValid() method because Context is the one created during static init and it is sealed. Here's the stacktrace I have:

com.google.common.util.concurrent.UncheckedExecutionException: java.lang.IllegalStateException
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2256)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3980)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3984)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4868)
    at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4874)
    at com.github.fge.jsonschema.validator.JsonValidatorCache.getValidator(JsonValidatorCache.java:97)
    at com.github.fge.jsonschema.main.JsonSchema.validate(JsonSchema.java:69)
~~
    My code
~~
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:76)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:195)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:63)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.lang.IllegalStateException
    at org.mozilla.javascript.Context.onSealedMutation(Context.java:712)
    at org.mozilla.javascript.Context.enter(Context.java:417)
    at org.mozilla.javascript.Context.enter(Context.java:398)
    at org.mozilla.javascript.Context.enter(Context.java:378)
    at com.github.fge.jsonschema.util.RhinoHelper.regexIsValid(RhinoHelper.java:107)
    at com.github.fge.jsonschema.syntax.common.PatternSyntaxChecker.checkValue(PatternSyntaxChecker.java:55)
    at com.github.fge.jsonschema.syntax.AbstractSyntaxChecker.checkSyntax(AbstractSyntaxChecker.java:63)
    at com.github.fge.jsonschema.syntax.SyntaxValidator.validate(SyntaxValidator.java:75)
    at com.github.fge.jsonschema.syntax.draftv3.DraftV3PropertiesSyntaxChecker.checkValue(DraftV3PropertiesSyntaxChecker.java:93)
    at com.github.fge.jsonschema.syntax.AbstractSyntaxChecker.checkSyntax(AbstractSyntaxChecker.java:63)
    at com.github.fge.jsonschema.syntax.SyntaxValidator.validate(SyntaxValidator.java:75)
    at com.github.fge.jsonschema.validator.JsonValidatorCache$2.load(JsonValidatorCache.java:132)
    at com.github.fge.jsonschema.validator.JsonValidatorCache$2.load(JsonValidatorCache.java:115)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3579)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2372)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2335)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2250)
    ... 34 more

For now I have a hack:

Runnable staticInitHack = new Runnable() {
    @Override public void run() {
        try {
            RhinoHelper.regexIsValid( "^ $" );
        } catch ( Exception ignored ) { }
    }
};
Thread thread = new Thread( staticInitHack );
thread.start();
try {
    thread.join();
} catch ( InterruptedException e ) {
    Assert.fail();
}

It simply does static initialisation of RhinoHelper from another thread and after that everything goes fine.

Opaque namespaces (at least "jar" URIs) do not work properly

Test file: https://github.com/fge/json-schema-validator/blob/master/src/test/java/org/eel/kitchen/jsonschema/other/JarNamespaceValidationTest.java

Failing test: callingSchemaViaJarURINamespaceWorks() (except, it doesn't)

The test which breaks is due to a difference in behavior between:

factory = JsonSchemaFactory.defaultFactory();
schema = factory.fromURI("jar:/foo.jar!/a/b.json");

and:

factory = new JsonSchemaFactory.Builder()
    .setNamespace("jar:/foo.jar!/a/").build();
schema = factory.fromURI("b.json");

While the first solution will use the base URIDownloader and succeed, the second
one will fail since SchemaRegistry does not use JsonRef, which has a hack for
jar relative resolution, but URI resolution -- and resolving any URI against an
opaque URI, which "jar" URIs are, leads to the URI given as an argument.

First highlighted in issue #19.

Array with possible enum values doesn't get validated correctly

having the following schema:

{
"title": "myType",
"type": "object",
"properties": {
"id": {
"type": "string",
"required": false
},
"arrayProperty": {

                "type": "array",
                "enum": [
                    "val1",
                    "val2",
                    "val3",
                    "val4"
                ]
    }
}

}

validating the following json won't pass validation:
{
"id":"an_id",
"arrayProperty":["val1","val2","val3"]
}

Don't know exactly how the library should work but I think that the EnumKeywordValidator.validate method needs to be improved to accept list values also.

allOf and additionalProperties

I have run into an issue when trying to use additionalProperties and allOf. I have a data model where I would like to externalize some objects to their own file so that I may reuse them across schemas. Additionally, in some instances, I would like the extend these objects and add additional properties. For example:

dresser.json

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "dresser",
    "description": "JSON representation of a dresser",
    "type": "object",
    "properties": {
        "designer": {
            "type": "string"   
        },
        "drawers": {
            "type": "array",
            "items": {
                "allOf": [
                    {
                        "$ref": "file:////Users/matthewmason/Development/workspaces/json-validator/json-validator/src/main/resources/schema/drawer.json"        
                    }
                ], 
                "properties": {
                    "handle": {
                        "type": "string"
                    }
                }, 
                "additionalProperties": false
            }
        }
    },
    "additionalProperties": false
}

drawer.json

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "drawer",
    "description": "JSON representation of a drawer",
    "type": "object",
    "properties": {
        "contents": "string"
    }
}

Here, the standard behavior of a drawer is to have contents while it sometimes may be extended to have a handle. However, when I specify additionalProperties: false, I get an error saying that contents are unwanted. I cannot move `additionalProperties: false' because I would like to sometimes add additional properties to a drawer.

I would expect that specifying additionalProperties: false in the drawers field of dresser would respect the fields brought in from allOf as well as the fields explicitly declared as a property of drawers.

Test Case:

package com.dibs.json_validator;

import java.io.IOException;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.eel.kitchen.jsonschema.main.JsonSchema;
import org.eel.kitchen.jsonschema.main.JsonSchemaFactory;
import org.eel.kitchen.jsonschema.report.ValidationReport;
import org.eel.kitchen.jsonschema.util.JsonLoader;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;

/**
 * Unit test for simple App.
 */
public class BugTest extends TestCase {

    protected ObjectWriter WRITER = new ObjectMapper().writerWithDefaultPrettyPrinter();


    /**
     * Create the test case
     * 
     * @param testName
     *            name of the test case
     */
    public BugTest(String testName) {
        super(testName);
    }

    /**
     * @return the suite of tests being tested
     */
    public static Test suite() {
        return new TestSuite(BugTest.class);
    }

    /**
     * @throws IOException 
     */
    public void testJSON() throws IOException {
        final JsonNode valid = JsonLoader.fromResource("/samples/dresser-valid.json");

        final JsonSchemaFactory factory = JsonSchemaFactory.defaultFactory();
        JsonNode schemaNode = JsonLoader.fromResource("/schema/dresser.json");

        final JsonSchema schema = factory.fromSchema(schemaNode);

        ValidationReport report;

        report = schema.validate(valid);
        printReport(report);
        assertTrue(report.isSuccess());
    }

    protected void printReport(final ValidationReport report)
            throws IOException
        {
            final boolean success = report.isSuccess();
            System.out.println("Validation " + (success ? "succeeded" : "failed"));

            if (!success) {
                System.out.println("---- BEGIN REPORT ----");
                System.out.println(WRITER.writeValueAsString(report.asJsonObject()));
                System.out.println("---- END REPORT ----");
            }
        }
}
{
    "designer": "Charles Eames",
    "drawers": [
        {
            "contents": "shirts",
            "handle": "wooden knob"
        },
        {
            "contents": "socks"
        }
    ]
}

Ability to use an opaque namespace?

First I must say that after experimenting with other JSON libraries I am thoroughly impressed with this project, and thank you for it. It's simple to use and works great.

Is there a way that I'm missing, or do you have any thoughts on having an opaque namespace for schemas? I hate to talk to generics, so here's the specific use case -
Our schemas $ref each other with relative links - in this case all sit inside a folder. That folder is packaged inside the jar. I then create the factory and set the namespace similar to:

new JsonSchemaFactory.Builder().setNamespace(getClass().getResource("/schemas/").toURI().toASCIIString()).build();

Unfortunately, during validation this fails, because of the line in SchemaRegistry.get():

realURI = namespace.resolve(uri).normalize();

Because namespace is an opaque URI in this case (jar:file:/<path>!/schemas/), the Java URI API simply returns the value of the uri parameter.

A simple hack I've done to get around it is to change SchemaRegistry and basically concat namespace + uri, but I wanted to see if there was a more elegant way to do this, or a reason why not.

Thanks for the feedback.

Over-zealous caching leads to false validation results

The problem is with SchemaContext: its equality is only based on the locator.

But this is wrong given the way validators are cached: SchemaNode checks that its context equals to another one, along with its node; and this leads to this unfortunate bug.

Must backport to 1.4.x, since it prevents real validator caching when using anonymous schemas.

The problem has been triggered on the web site, but it basically prevents uses of anonymous schemas containing refs.

Polymorphic types

A XML Schema has the xsi:type attribute, which allows an instance to assert its type.

Is there an equivalent in JsonSchema?

Does fge/json-schema-validator implement such feature?

ps: Jackson supports such a feature, see http://programmerbruce.blogspot.de/2011/05/deserialize-json-with-jackson-into.html
+++++++++++++++++
@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@type(value = Cat.class, name = "cat"),
@type(value = Dog.class, name = "dog") })
abstract class Animal
{
public String name;
}
+++++++++++++++++

Specify schema as the type for a given property

Was wondering if it was at all possible to specify the schema for a given property.

for e.g. could I have the following schema?

{
    "title": "myType",
    "type": "object",
    "properties": {
        "id": { 
            "type": "string"
        },
        "complexProp": {                        
            "type": "array",
            "items": {
                "type": "myType",
                "required": true
            }
        }
    }
}

where the type of items in complexProp is also myType ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.