leadpony / justify

Justify is a JSON validator based on JSON Schema Specification and Jakarta JSON Processing API (JSON-P).
Apache License 2.0
96 stars 18 forks source link

List<Problem> in ProblemHandler only seems to contain one Probleme at a time #22

Closed peter-ponzel closed 5 years ago

peter-ponzel commented 5 years ago

Hello,

first of all, nice project, thanks a bunch for all your effort.

I created a JSON with 5 errors (related to my schema) and wanted to propagate them altogether in the handleProblems(List<Problem> problems) with an exception. But it seems that although a list is passed, there is only one Problem at the time in it.

To demonstrate that issue, I've simplified my example to

@Test
    public void reader() {

        final JsonValidationService service = JsonValidationService.newInstance();

        final StringReader schema = new StringReader("{\"properties\":{\"keywords\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"pattern\":\"^[\\\\w]+$\"}}}}");
        final StringReader json = new StringReader("{\"keywords\":[null,\"wh#o\",\"would\",\"have\",\" \",\"thought\",42,false]}");

        final JsonSchema jsonSchema = service.readSchema(schema);

        final ProblemHandler handler = new SomeProblemHandler();

        try (final JsonReader reader = service.createReader(json, jsonSchema, handler)) {
            System.out.println(reader.readValue());
        }
    }

    public class SomeProblemHandler implements ProblemHandler {

        @Override
        public void handleProblems(final List<Problem> problems) {
            System.err.println("number of problems: " + problems.size());
        }
    }

Am I doing something wrong or is this intentionally?

leadpony commented 5 years ago

Hello @peter-ponzel, thank you for trying this library. Yes, this is intended behaviour. The JSON validator calls ProblemHandler.handleProblems() once it detects any problem. Note that multiple problems caused by the same parser event, in other words the same JsonLocation, are collected into the parameter of handleProblems() and dispatched altogether. Applications can stop the validation by throwing an unchecked exception in the method, or just continue the validation.

The following example shows how to create a ProblemHandler which will accumulates all problems detected by the validator.

List<Problem> problems = new ArrayList<>();
ProblemHandler handler = ProblemHandler.collectingTo(problems);

After parsing completed, you can check the problems accumulated in the problems variable.

peter-ponzel commented 5 years ago

ah I see, thank you very much