Search in sources :

Example 1 with JsonValidationService

use of org.leadpony.justify.api.JsonValidationService in project mosaic by eclipse.

the class ObjectInstantiation method validateFile.

private void validateFile(InputStream input, InputStream schemaInput) throws InstantiationException {
    final JsonValidationService service = JsonValidationService.newInstance();
    final JsonSchema schema = service.readSchema(schemaInput);
    final List<String> problems = new ArrayList<>();
    final ProblemHandler handler = service.createProblemPrinter(problems::add);
    try (JsonParser parser = service.createParser(input, schema, handler)) {
        while (parser.hasNext()) {
            parser.next();
        // ignore, we let GSON do the parsing later.
        }
    }
    if (!problems.isEmpty()) {
        StringBuilder errorMessage = new StringBuilder();
        problems.forEach((p) -> {
            errorMessage.append(p);
            errorMessage.append(NEWLINE);
        });
        throw new InstantiationException("The " + clazz.getSimpleName() + " config is not valid: " + errorMessage);
    }
}
Also used : ProblemHandler(org.leadpony.justify.api.ProblemHandler) JsonValidationService(org.leadpony.justify.api.JsonValidationService) JsonSchema(org.leadpony.justify.api.JsonSchema) ArrayList(java.util.ArrayList) JsonParser(javax.json.stream.JsonParser)

Example 2 with JsonValidationService

use of org.leadpony.justify.api.JsonValidationService in project zilla by aklivity.

the class ConfigureTask method call.

@Override
public Void call() throws Exception {
    String configText;
    if (configURL == null) {
        configText = "{\"name\":\"default\"}";
    } else if ("https".equals(configURL.getProtocol()) || "https".equals(configURL.getProtocol())) {
        HttpClient client = HttpClient.newBuilder().version(HTTP_2).followRedirects(NORMAL).build();
        HttpRequest request = HttpRequest.newBuilder().GET().uri(configURL.toURI()).build();
        HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
        String body = response.body();
        configText = body;
    } else {
        URLConnection connection = configURL.openConnection();
        try (InputStream input = connection.getInputStream()) {
            configText = new String(input.readAllBytes(), UTF_8);
        }
    }
    if (config.configSyntaxMustache()) {
        configText = Mustache.resolve(configText, System::getenv);
    }
    logger.accept(configText);
    List<String> errors = new LinkedList<>();
    parse: try {
        InputStream schemaInput = Engine.class.getResourceAsStream("internal/schema/engine.schema.json");
        JsonProvider schemaProvider = JsonProvider.provider();
        JsonReader schemaReader = schemaProvider.createReader(schemaInput);
        JsonObject schemaObject = schemaReader.readObject();
        for (URL schemaType : schemaTypes) {
            InputStream schemaPatchInput = schemaType.openStream();
            JsonReader schemaPatchReader = schemaProvider.createReader(schemaPatchInput);
            JsonArray schemaPatchArray = schemaPatchReader.readArray();
            JsonPatch schemaPatch = schemaProvider.createPatch(schemaPatchArray);
            schemaObject = schemaPatch.apply(schemaObject);
        }
        JsonParser schemaParser = schemaProvider.createParserFactory(null).createParser(new StringReader(schemaObject.toString()));
        JsonValidationService service = JsonValidationService.newInstance();
        ProblemHandler handler = service.createProblemPrinter(errors::add);
        JsonSchemaReader reader = service.createSchemaReader(schemaParser);
        JsonSchema schema = new UniquePropertyKeysSchema(reader.read());
        JsonProvider provider = service.createJsonProvider(schema, parser -> handler);
        provider.createReader(new StringReader(configText)).read();
        if (!errors.isEmpty()) {
            break parse;
        }
        JsonbConfig config = new JsonbConfig().withAdapters(new NamespaceAdapter());
        Jsonb jsonb = JsonbBuilder.newBuilder().withProvider(provider).withConfig(config).build();
        NamespaceConfig namespace = jsonb.fromJson(configText, NamespaceConfig.class);
        if (!errors.isEmpty()) {
            break parse;
        }
        namespace.id = supplyId.applyAsInt(namespace.name);
        for (BindingConfig binding : namespace.bindings) {
            binding.id = NamespacedId.id(namespace.id, supplyId.applyAsInt(binding.entry));
            if (binding.vault != null) {
                binding.vault.id = NamespacedId.id(supplyId.applyAsInt(ofNullable(binding.vault.namespace).orElse(namespace.name)), supplyId.applyAsInt(binding.vault.name));
            }
            // TODO: consider route exit namespace
            for (RouteConfig route : binding.routes) {
                route.id = NamespacedId.id(namespace.id, supplyId.applyAsInt(route.exit));
            }
            // TODO: consider binding exit namespace
            if (binding.exit != null) {
                binding.exit.id = NamespacedId.id(namespace.id, supplyId.applyAsInt(binding.exit.exit));
            }
            tuning.affinity(binding.id, tuning.affinity(binding.id));
        }
        for (VaultConfig vault : namespace.vaults) {
            vault.id = NamespacedId.id(namespace.id, supplyId.applyAsInt(vault.name));
        }
        CompletableFuture<Void> future = CompletableFuture.completedFuture(null);
        for (DispatchAgent dispatcher : dispatchers) {
            future = CompletableFuture.allOf(future, dispatcher.attach(namespace));
        }
        future.join();
        extensions.forEach(e -> e.onConfigured(context));
    } catch (Throwable ex) {
        errorHandler.onError(ex);
    }
    if (!errors.isEmpty()) {
        errors.forEach(msg -> errorHandler.onError(new JsonException(msg)));
    }
    return null;
}
Also used : JsonSchemaReader(org.leadpony.justify.api.JsonSchemaReader) ErrorHandler(org.agrona.ErrorHandler) BodyHandlers(java.net.http.HttpResponse.BodyHandlers) EngineExtContext(io.aklivity.zilla.runtime.engine.ext.EngineExtContext) URL(java.net.URL) Engine(io.aklivity.zilla.runtime.engine.Engine) NamespaceConfig(io.aklivity.zilla.runtime.engine.config.NamespaceConfig) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) EngineConfiguration(io.aklivity.zilla.runtime.engine.EngineConfiguration) HttpRequest(java.net.http.HttpRequest) Jsonb(jakarta.json.bind.Jsonb) UniquePropertyKeysSchema(io.aklivity.zilla.runtime.engine.internal.registry.json.UniquePropertyKeysSchema) URLConnection(java.net.URLConnection) RouteConfig(io.aklivity.zilla.runtime.engine.config.RouteConfig) JsonObject(jakarta.json.JsonObject) Mustache(io.aklivity.zilla.runtime.engine.internal.util.Mustache) HttpClient(java.net.http.HttpClient) JsonException(jakarta.json.JsonException) JsonReader(jakarta.json.JsonReader) LinkedList(java.util.LinkedList) JsonSchema(org.leadpony.justify.api.JsonSchema) ProblemHandler(org.leadpony.justify.api.ProblemHandler) HttpResponse(java.net.http.HttpResponse) JsonbBuilder(jakarta.json.bind.JsonbBuilder) JsonbConfig(jakarta.json.bind.JsonbConfig) HTTP_2(java.net.http.HttpClient.Version.HTTP_2) JsonProvider(jakarta.json.spi.JsonProvider) JsonParser(jakarta.json.stream.JsonParser) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Optional.ofNullable(java.util.Optional.ofNullable) Tuning(io.aklivity.zilla.runtime.engine.internal.Tuning) Collection(java.util.Collection) ToIntFunction(java.util.function.ToIntFunction) NORMAL(java.net.http.HttpClient.Redirect.NORMAL) EngineExtSpi(io.aklivity.zilla.runtime.engine.ext.EngineExtSpi) BindingConfig(io.aklivity.zilla.runtime.engine.config.BindingConfig) Consumer(java.util.function.Consumer) List(java.util.List) JsonPatch(jakarta.json.JsonPatch) VaultConfig(io.aklivity.zilla.runtime.engine.config.VaultConfig) StringReader(java.io.StringReader) JsonValidationService(org.leadpony.justify.api.JsonValidationService) NamespaceAdapter(io.aklivity.zilla.runtime.engine.internal.config.NamespaceAdapter) NamespacedId(io.aklivity.zilla.runtime.engine.internal.stream.NamespacedId) JsonArray(jakarta.json.JsonArray) InputStream(java.io.InputStream) NamespaceConfig(io.aklivity.zilla.runtime.engine.config.NamespaceConfig) JsonException(jakarta.json.JsonException) NamespaceAdapter(io.aklivity.zilla.runtime.engine.internal.config.NamespaceAdapter) JsonSchema(org.leadpony.justify.api.JsonSchema) JsonObject(jakarta.json.JsonObject) UniquePropertyKeysSchema(io.aklivity.zilla.runtime.engine.internal.registry.json.UniquePropertyKeysSchema) JsonProvider(jakarta.json.spi.JsonProvider) URL(java.net.URL) VaultConfig(io.aklivity.zilla.runtime.engine.config.VaultConfig) ProblemHandler(org.leadpony.justify.api.ProblemHandler) Jsonb(jakarta.json.bind.Jsonb) CompletableFuture(java.util.concurrent.CompletableFuture) JsonValidationService(org.leadpony.justify.api.JsonValidationService) StringReader(java.io.StringReader) JsonReader(jakarta.json.JsonReader) Engine(io.aklivity.zilla.runtime.engine.Engine) JsonParser(jakarta.json.stream.JsonParser) HttpRequest(java.net.http.HttpRequest) InputStream(java.io.InputStream) HttpResponse(java.net.http.HttpResponse) RouteConfig(io.aklivity.zilla.runtime.engine.config.RouteConfig) JsonPatch(jakarta.json.JsonPatch) URLConnection(java.net.URLConnection) LinkedList(java.util.LinkedList) JsonArray(jakarta.json.JsonArray) JsonbConfig(jakarta.json.bind.JsonbConfig) JsonSchemaReader(org.leadpony.justify.api.JsonSchemaReader) BindingConfig(io.aklivity.zilla.runtime.engine.config.BindingConfig) HttpClient(java.net.http.HttpClient)

Example 3 with JsonValidationService

use of org.leadpony.justify.api.JsonValidationService in project zilla by aklivity.

the class ConfigSchemaRule method apply.

@Override
public Statement apply(Statement base, Description description) {
    Objects.requireNonNull(schemaName, "schema");
    schemaPatchNames.forEach(n -> Objects.requireNonNull(n, "schemaPatch"));
    Function<String, InputStream> findResource = description.getTestClass().getClassLoader()::getResourceAsStream;
    InputStream schemaInput = findResource.apply(schemaName);
    JsonProvider schemaProvider = JsonProvider.provider();
    JsonReader schemaReader = schemaProvider.createReader(schemaInput);
    JsonObject schemaObject = schemaReader.readObject();
    for (String schemaPatchName : schemaPatchNames) {
        InputStream schemaPatchInput = findResource.apply(schemaPatchName);
        Objects.requireNonNull(schemaPatchInput, "schemaPatch");
        JsonReader schemaPatchReader = schemaProvider.createReader(schemaPatchInput);
        JsonArray schemaPatchArray = schemaPatchReader.readArray();
        JsonPatch schemaPatch = schemaProvider.createPatch(schemaPatchArray);
        schemaObject = schemaPatch.apply(schemaObject);
    }
    JsonParser schemaParser = schemaProvider.createParserFactory(null).createParser(new StringReader(schemaObject.toString()));
    JsonValidationService service = JsonValidationService.newInstance();
    ProblemHandler handler = service.createProblemPrinter(msg -> rethrowUnchecked(new JsonException(msg)));
    JsonSchemaReader reader = service.createSchemaReader(schemaParser);
    JsonSchema schema = reader.read();
    provider = service.createJsonProvider(schema, parser -> handler);
    if (configurationRoot != null) {
        String configFormat = String.format("%s/%%s", configurationRoot);
        findConfig = configName -> findResource.apply(String.format(configFormat, configName));
    } else {
        Class<?> testClass = description.getTestClass();
        String configFormat = String.format("%s-%%s", testClass.getSimpleName());
        findConfig = configName -> testClass.getResourceAsStream(String.format(configFormat, configName));
    }
    return base;
}
Also used : JsonException(jakarta.json.JsonException) Statement(org.junit.runners.model.Statement) JsonSchemaReader(org.leadpony.justify.api.JsonSchemaReader) JsonProvider(jakarta.json.spi.JsonProvider) JsonParser(jakarta.json.stream.JsonParser) LangUtil.rethrowUnchecked(org.agrona.LangUtil.rethrowUnchecked) TestRule(org.junit.rules.TestRule) Description(org.junit.runner.Description) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Objects(java.util.Objects) List(java.util.List) JsonPatch(jakarta.json.JsonPatch) StringReader(java.io.StringReader) JsonObject(jakarta.json.JsonObject) JsonValidationService(org.leadpony.justify.api.JsonValidationService) JsonException(jakarta.json.JsonException) JsonReader(jakarta.json.JsonReader) JsonArray(jakarta.json.JsonArray) JsonSchema(org.leadpony.justify.api.JsonSchema) ProblemHandler(org.leadpony.justify.api.ProblemHandler) InputStream(java.io.InputStream) InputStream(java.io.InputStream) JsonSchema(org.leadpony.justify.api.JsonSchema) JsonObject(jakarta.json.JsonObject) JsonProvider(jakarta.json.spi.JsonProvider) JsonPatch(jakarta.json.JsonPatch) JsonArray(jakarta.json.JsonArray) ProblemHandler(org.leadpony.justify.api.ProblemHandler) JsonValidationService(org.leadpony.justify.api.JsonValidationService) JsonSchemaReader(org.leadpony.justify.api.JsonSchemaReader) StringReader(java.io.StringReader) JsonReader(jakarta.json.JsonReader) JsonParser(jakarta.json.stream.JsonParser)

Example 4 with JsonValidationService

use of org.leadpony.justify.api.JsonValidationService in project graphql-maven-plugin-project by graphql-java-generator.

the class GenerateCodeJsonSchemaPersonalization method loadGraphQLSchemaPersonalization.

/**
 * Let's load the schema personalization from the configuration json file.
 *
 * @return
 *
 * @throws IOException
 * @throws ProcessingException
 *             When the JSON file is not valid
 * @throws URISyntaxException
 *             If we can't process the JSON URIs. It would be an internal error.
 */
public SchemaPersonalization loadGraphQLSchemaPersonalization() throws IOException, URISyntaxException {
    if (((GenerateServerCodeConfiguration) configuration).getSchemaPersonalizationFile() == null) {
        return null;
    } else {
        // Let's check that the JSON is valid
        JsonValidationService service = JsonValidationService.newInstance();
        // Reads the JSON schema
        // 
        // There is an issue in reading the json schema, when the project is built with Gradle 7
        // It seems to be linked to https://issues.apache.org/jira/browse/JOHNZON-147 (solved in Johnzon 1.1.6, in
        // february 2018)
        // A workaround is to first read the schema in a string, then call the readSchema
        BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/" + JSON_SCHEMA_FILENAME), Charset.forName("UTF-8")));
        String text = br.lines().collect(Collectors.joining("\n"));
        // readSchema should directly read the InputStream
        JsonSchema schema = service.readSchema(new StringReader(text));
        // Problem handler which will print problems found
        ProblemHandler handler = service.createProblemPrinter(this::logParsingError);
        // Reads the JSON instance by javax.json.JsonReader
        nbErrors = 0;
        try (JsonReader reader = service.createReader(new FileInputStream(((GenerateServerCodeConfiguration) configuration).getSchemaPersonalizationFile()), schema, handler)) {
            // JsonValue value =
            reader.readValue();
        // Do something useful here
        }
        if (nbErrors > 0) {
            throw new RuntimeException("The json file '" + ((GenerateServerCodeConfiguration) configuration).getSchemaPersonalizationFile().getAbsolutePath() + "' is invalid. See the logs for details");
        }
        // Let's read the flow definition
        logger.info("Loading file " + ((GenerateServerCodeConfiguration) configuration).getSchemaPersonalizationFile().getAbsolutePath());
        ObjectMapper objectMapper = new ObjectMapper();
        SchemaPersonalization ret;
        try (InputStream isFlowJson = new FileInputStream(((GenerateServerCodeConfiguration) configuration).getSchemaPersonalizationFile())) {
            ret = objectMapper.readValue(isFlowJson, SchemaPersonalization.class);
        }
        return ret;
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JsonSchema(org.leadpony.justify.api.JsonSchema) FileInputStream(java.io.FileInputStream) ProblemHandler(org.leadpony.justify.api.ProblemHandler) JsonValidationService(org.leadpony.justify.api.JsonValidationService) GenerateServerCodeConfiguration(com.graphql_java_generator.plugin.conf.GenerateServerCodeConfiguration) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

JsonSchema (org.leadpony.justify.api.JsonSchema)4 JsonValidationService (org.leadpony.justify.api.JsonValidationService)4 ProblemHandler (org.leadpony.justify.api.ProblemHandler)4 InputStream (java.io.InputStream)3 StringReader (java.io.StringReader)3 JsonArray (jakarta.json.JsonArray)2 JsonException (jakarta.json.JsonException)2 JsonObject (jakarta.json.JsonObject)2 JsonPatch (jakarta.json.JsonPatch)2 JsonReader (jakarta.json.JsonReader)2 JsonProvider (jakarta.json.spi.JsonProvider)2 JsonParser (jakarta.json.stream.JsonParser)2 List (java.util.List)2 JsonSchemaReader (org.leadpony.justify.api.JsonSchemaReader)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 GenerateServerCodeConfiguration (com.graphql_java_generator.plugin.conf.GenerateServerCodeConfiguration)1 Engine (io.aklivity.zilla.runtime.engine.Engine)1 EngineConfiguration (io.aklivity.zilla.runtime.engine.EngineConfiguration)1 BindingConfig (io.aklivity.zilla.runtime.engine.config.BindingConfig)1 NamespaceConfig (io.aklivity.zilla.runtime.engine.config.NamespaceConfig)1