Home > Back-end >  ERROR | Failed to load json schema! java.io.IOException: Stream closed
ERROR | Failed to load json schema! java.io.IOException: Stream closed

Time:02-03

I am trying to validate a json object against its schema and my schema file is very big (386 lines).

This is my lines of code in java:

public static void jsonSchemValidator() throws Exception {

        ObjectMapper objectMapper = new ObjectMapper();;


        InputStream jsonStream = inputStreamFromClasspath("/json/pickevent1.json");
        InputStream schemaStream = inputStreamFromClasspath("/json/schemaeg.json");

        JsonNode json = objectMapper.readTree(jsonStream);
        JsonNode jsonSchema = objectMapper.readTree(schemaStream);
        JsonSchemaFactory validatorFactory = JsonSchemaFactory.getInstance(SpecVersionDetector.detect(jsonSchema));
        JsonSchema schema = validatorFactory.getSchema(schemaStream);
        Set<ValidationMessage> validationResult = schema.validate(json);
        if (validationResult.isEmpty()) {
            System.out.println("no validation errors :-)");
        } else {
            validationResult.forEach(vm -> System.out.println(vm.getMessage()));
        }
        jsonStream.close();
        schemaStream.close();
    }
}

The code for IndputStream:

  public static InputStream inputStreamFromClasspath(String path) {
        return Utils.class.getResourceAsStream(path);
    }

The above works well for small schema. But it gives an error of:

ERROR | Failed to load json schema!
java.io.IOException: Stream closed

This is the stacktrace:

ERROR | Failed to load json schema!
java.io.IOException: Stream closed
    at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:170)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:336)
    at com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper.ensureLoaded(ByteSourceJsonBootstrapper.java:539)
    at com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper.detectEncoding(ByteSourceJsonBootstrapper.java:133)
    at com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper.constructParser(ByteSourceJsonBootstrapper.java:256)
    at com.fasterxml.jackson.core.JsonFactory._createParser(JsonFactory.java:1655)
    at com.fasterxml.jackson.core.JsonFactory.createParser(JsonFactory.java:1083)
    at com.fasterxml.jackson.databind.ObjectMapper.readTree(ObjectMapper.java:3056)
    at com.networknt.schema.JsonSchemaFactory.getSchema(JsonSchemaFactory.java:315)
    at com.networknt.schema.JsonSchemaFactory.getSchema(JsonSchemaFactory.java:324)
    at common.Utils.jsonSchemValidator(Utils.java:105)
    at picking.begin.TestAssertionForPickBegin.before(TestAssertionForPickBegin.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:458)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:142)
    at org.testng.TestRunner.beforeRun(TestRunner.java:529)
    at org.testng.TestRunner.run(TestRunner.java:497)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)
    at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:110)
com.networknt.schema.JsonSchemaException: java.io.IOException: Stream closed
    at com.networknt.schema.JsonSchemaFactory.getSchema(JsonSchemaFactory.java:319)
    at com.networknt.schema.JsonSchemaFactory.getSchema(JsonSchemaFactory.java:324)
    at common.Utils.jsonSchemValidator(Utils.java:105)
    at picking.begin.TestAssertionForPickBegin.before(TestAssertionForPickBegin.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:458)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:142)
    at org.testng.TestRunner.beforeRun(TestRunner.java:529)
    at org.testng.TestRunner.run(TestRunner.java:497)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)
    at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:110)
Caused by: java.io.IOException: Stream closed
    at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:170)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:336)
    at com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper.ensureLoaded(ByteSourceJsonBootstrapper.java:539)
    at com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper.detectEncoding(ByteSourceJsonBootstrapper.java:133)
    at com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper.constructParser(ByteSourceJsonBootstrapper.java:256)
    at com.fasterxml.jackson.core.JsonFactory._createParser(JsonFactory.java:1655)
    at com.fasterxml.jackson.core.JsonFactory.createParser(JsonFactory.java:1083)
    at com.fasterxml.jackson.databind.ObjectMapper.readTree(ObjectMapper.java:3056)
    at com.networknt.schema.JsonSchemaFactory.getSchema(JsonSchemaFactory.java:315)
    ... 26 more

I am quite new to java. Any suggestions will be helpful. Thank you.

CodePudding user response:

I think the problem is that you are reading from the InputStream schemaStream twice.

You pass it first to objectMapper.readTree(...), and later on, you pass the same InputStream to validatorFactory.getSchema(...).

In general, doing this is a bad thing, because the first use of the stream may leave it exhausted (i.e. it has no more data to return) or closed, as it seems happens in your case. If I'm honest, I'm surprised that you don't get similar behaviour with small schemas: I guess this is a quirk of the InputStream that gets returned from a call to .getResourceAsStream(...).

Try opening a new InputStream from the resource rather than attempting to read from one for the second time. I've also adjusted your code to use try-with-resources, so that the InputStreams get closed even in the event of an exception being thrown:

public static void jsonSchemValidator() throws Exception {

    ObjectMapper objectMapper = new ObjectMapper();

    try (InputStream jsonStream = inputStreamFromClasspath("/json/pickevent1.json")) {
        JsonNode json = objectMapper.readTree(jsonStream);
        JsonSchemaFactory validatorFactory;
        try (InputStream schemaStream = inputStreamFromClasspath("/json/schemaeg.json")) {
            JsonNode jsonSchema = objectMapper.readTree(schemaStream);
            validatorFactory = JsonSchemaFactory.getInstance(SpecVersionDetector.detect(jsonSchema));
        }

        try (InputStream schemaStream = inputStreamFromClasspath("/json/schemaeg.json")) {
            JsonSchema schema = validatorFactory.getSchema(schemaStream);
            Set<ValidationMessage> validationResult = schema.validate(json);
            if (validationResult.isEmpty()) {
                System.out.println("no validation errors :-)");
            } else {
                validationResult.forEach(vm -> System.out.println(vm.getMessage()));
            }
        }
    }
}

  •  Tags:  
  • Related