Initial version of camel-everit-json-schema component
Project: http://git-wip-us.apache.org/repos/asf/camel/repo Commit: http://git-wip-us.apache.org/repos/asf/camel/commit/8ba38cf8 Tree: http://git-wip-us.apache.org/repos/asf/camel/tree/8ba38cf8 Diff: http://git-wip-us.apache.org/repos/asf/camel/diff/8ba38cf8 Branch: refs/heads/master Commit: 8ba38cf8d301ff552bf4780df207ad3bd6d42444 Parents: b584b3d Author: Pontus Ullgren <ullg...@gmail.com> Authored: Fri Sep 29 22:59:48 2017 +0200 Committer: Pontus Ullgren <pontus.ullg...@redpill-linpro.com> Committed: Fri Oct 6 22:37:42 2017 +0200 ---------------------------------------------------------------------- .../src/main/descriptors/common-bin.xml | 2 + components/camel-everit-json-schema/pom.xml | 89 ++++++++ .../src/main/docs/json-validator-component.adoc | 136 +++++++++++++ .../DefaultJsonValidationErrorHandler.java | 42 ++++ .../JsonSchemaValidationException.java | 41 ++++ .../JsonSchemaValidatorComponent.java | 46 +++++ .../jsonschema/JsonSchemaValidatorEndpoint.java | 176 ++++++++++++++++ .../jsonschema/JsonSchemaValidatorProducer.java | 56 +++++ .../jsonschema/JsonValidatingProcessor.java | 150 ++++++++++++++ .../jsonschema/JsonValidatorErrorHandler.java | 38 ++++ .../NoJsonBodyValidationException.java | 37 ++++ .../NoJsonHeaderValidationException.java | 38 ++++ .../component/everit/jsonschema/package.html | 25 +++ .../src/main/resources/META-INF/LICENSE.txt | 203 +++++++++++++++++++ .../src/main/resources/META-INF/NOTICE.txt | 11 + .../org/apache/camel/component/json-validator | 18 ++ .../jsonschema/FileValidatorRouteTest.java | 97 +++++++++ .../everit/jsonschema/ValidatorRouteTest.java | 174 ++++++++++++++++ .../src/test/resources/log4j2.properties | 31 +++ .../component/everit/jsonschema/schema.json | 34 ++++ components/pom.xml | 1 + parent/pom.xml | 8 + .../camel-everit-json-schema-starter/pom.xml | 69 +++++++ ...hemaValidatorComponentAutoConfiguration.java | 129 ++++++++++++ ...onSchemaValidatorComponentConfiguration.java | 49 +++++ .../src/main/resources/META-INF/LICENSE.txt | 203 +++++++++++++++++++ .../src/main/resources/META-INF/NOTICE.txt | 11 + .../main/resources/META-INF/spring.factories | 19 ++ .../src/main/resources/META-INF/spring.provides | 17 ++ .../spring-boot/components-starter/pom.xml | 1 + 30 files changed, 1951 insertions(+) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/apache-camel/src/main/descriptors/common-bin.xml ---------------------------------------------------------------------- diff --git a/apache-camel/src/main/descriptors/common-bin.xml b/apache-camel/src/main/descriptors/common-bin.xml index 59d5c5e..64c2c2a 100644 --- a/apache-camel/src/main/descriptors/common-bin.xml +++ b/apache-camel/src/main/descriptors/common-bin.xml @@ -88,6 +88,7 @@ <include>org.apache.camel:camel-elsql</include> <include>org.apache.camel:camel-etcd</include> <include>org.apache.camel:camel-eventadmin</include> + <include>org.apache.camel:camel-everit-json-schema</include> <include>org.apache.camel:camel-exec</include> <include>org.apache.camel:camel-facebook</include> <include>org.apache.camel:camel-fastjson</include> @@ -383,6 +384,7 @@ <include>org.apache.camel:camel-elasticsearch5-starter</include> <include>org.apache.camel:camel-elsql-starter</include> <include>org.apache.camel:camel-etcd-starter</include> + <include>org.apache.camel:camel-everit-json-schema-starter</include> <include>org.apache.camel:camel-exec-starter</include> <include>org.apache.camel:camel-facebook-starter</include> <include>org.apache.camel:camel-fastjson-starter</include> http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/pom.xml ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/pom.xml b/components/camel-everit-json-schema/pom.xml new file mode 100644 index 0000000..9d7938d --- /dev/null +++ b/components/camel-everit-json-schema/pom.xml @@ -0,0 +1,89 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version + 2.0 (the "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 Unless required by + applicable law or agreed to in writing, software distributed under the + License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. See the License for + the specific language governing permissions and limitations under the + License. +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.apache.camel</groupId> + <artifactId>components</artifactId> + <version>2.20.0-SNAPSHOT</version> + </parent> + + <artifactId>camel-everit-json-schema</artifactId> + <name>Camel :: Everit Kft. JSON Schema validator</name> + <description>Camel JSON Schema validation based on everit-org json-schema library</description> + <packaging>jar</packaging> + + <properties> + <camel.osgi.export.pkg>org.apache.camel.component.everit.jsonschema.*</camel.osgi.export.pkg> + <camel.osgi.export.service>org.apache.camel.spi.ComponentResolver;component=json-validator</camel.osgi.export.service> + </properties> + <repositories> + <repository> + <id>jitpack.io</id> + <url>https://jitpack.io</url> + </repository> + </repositories> + <dependencies> + + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-core</artifactId> + </dependency> + <dependency> + <groupId>com.github.everit-org.json-schema</groupId> + <artifactId>org.everit.json.schema</artifactId> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + </dependency> + + <!-- for testing --> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-test</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.apache.logging.log4j</groupId> + <artifactId>log4j-api</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.apache.logging.log4j</groupId> + <artifactId>log4j-core</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.apache.logging.log4j</groupId> + <artifactId>log4j-slf4j-impl</artifactId> + <scope>test</scope> + </dependency> + + </dependencies> +</project> http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/main/docs/json-validator-component.adoc ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/main/docs/json-validator-component.adoc b/components/camel-everit-json-schema/src/main/docs/json-validator-component.adoc new file mode 100644 index 0000000..2f10a7b --- /dev/null +++ b/components/camel-everit-json-schema/src/main/docs/json-validator-component.adoc @@ -0,0 +1,136 @@ +== JSON Schema Validator Component +=== Everit Json Schema Validator Component + +*Available as of Camel version 2.20* + +The Validator component performs bean validation of the message body +agains JSON Schemas using the Everit.org JSON Schema library +(https://github.com/everit-org/json-schema). + +Maven users will need to add the following dependency to their `pom.xml` +for this component: + +[source,xml] +------------------------------------------------------------ +<dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-everit-json-schema</artifactId> + <version>x.y.z</version> + <!-- use the same version as your Camel core version --> +</dependency> +------------------------------------------------------------ + + +=== URI format + +[source,java] +------------------------------ +json-validator:resourceUri[?options] +------------------------------ + + +Where *label* is an arbitrary text value describing the endpoint. + + You can append query options to the URI in the following format, +?option=value&option=value&... + +=== URI Options + + +// component options: START +The JSON Schema Validator component has no options. +// component options: END + + + +// endpoint options: START +The JSON Schema Validator endpoint is configured using URI syntax: + +---- +json-validator:resourceUri +---- + +with the following path and query parameters: + +==== Path Parameters (1 parameters): + +[width="100%",cols="2,5,^1,2",options="header"] +|=== +| Name | Description | Default | Type +| *resourceUri* | *Required* URL to a local resource on the classpath or a reference to lookup a bean in the Registry or a full URL to a remote resource or resource on the file system which contains the JSON Schema to validate against. | | String +|=== + +==== Query Parameters (5 parameters): + +[width="100%",cols="2,5,^1,2",options="header"] +|=== +| Name | Description | Default | Type +| *failOnNullBody* (producer) | Whether to fail if no body exists. | true | boolean +| *failOnNullHeader* (producer) | Whether to fail if no header exists when validating against a header. | true | boolean +| *headerName* (producer) | To validate against a header instead of the message body. | | String +| *errorHandler* (advanced) | To use a custom org.apache.camel.processor.validation.ValidatorErrorHandler. The default error handler captures the errors and throws an exception. | | JsonValidatorError Handler +| *synchronous* (advanced) | Sets whether synchronous processing should be strictly used or Camel is allowed to use asynchronous processing (if supported). | false | boolean +|=== +// endpoint options: END + + +=== Example + +Assumed we have the following JSON Schema + +*schema.json* + +[source,json] +----------------------------------------------------------- +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "definitions": {}, + "id": "http://example.com/example.json", + "properties": { + "id": { + "default": 1, + "description": "An explanation about the purpose of this instance.", + "id": "/properties/id", + "title": "The id schema", + "type": "integer" + }, + "name": { + "default": "A green door", + "description": "An explanation about the purpose of this instance.", + "id": "/properties/name", + "title": "The name schema", + "type": "string" + }, + "price": { + "default": 12.5, + "description": "An explanation about the purpose of this instance.", + "id": "/properties/price", + "title": "The price schema", + "type": "number" + } + }, + "required": [ + "name", + "id", + "price" + ], + "type": "object" +} +----------------------------------------------------------- + +we can validate incomming JSON with the following Camel route. + +[source,java] +------------------------- +from("direct:start") + .to("json-validator:schema.json") + .to("mock:end") +------------------------- + +-------------------------------------------------------------------------------------------------- + +=== See Also + +* link:configuring-camel.html[Configuring Camel] +* link:component.html[Component] +* link:endpoint.html[Endpoint] +* link:getting-started.html[Getting Started] http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/DefaultJsonValidationErrorHandler.java ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/DefaultJsonValidationErrorHandler.java b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/DefaultJsonValidationErrorHandler.java new file mode 100644 index 0000000..b6ef7c2 --- /dev/null +++ b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/DefaultJsonValidationErrorHandler.java @@ -0,0 +1,42 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.everit.jsonschema; + +import org.apache.camel.Exchange; +import org.apache.camel.ValidationException; + +public class DefaultJsonValidationErrorHandler implements + JsonValidatorErrorHandler { + + @Override + public void reset() { + // Do nothing since we do not keep state + } + + @Override + public void handleErrors(Exchange exchange, + org.everit.json.schema.Schema schema, + Exception e) + throws ValidationException { + if (e instanceof org.everit.json.schema.ValidationException) { + throw new JsonSchemaValidationException(exchange, schema, (org.everit.json.schema.ValidationException)e); + } else { + throw new JsonSchemaValidationException(exchange, schema, e); + } + } + +} http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidationException.java ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidationException.java b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidationException.java new file mode 100644 index 0000000..ade36d5 --- /dev/null +++ b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidationException.java @@ -0,0 +1,41 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.everit.jsonschema; + +import java.util.stream.Collectors; + +import org.apache.camel.Exchange; +import org.apache.camel.ValidationException; +import org.everit.json.schema.Schema; + +public class JsonSchemaValidationException extends ValidationException { + + private static final long serialVersionUID = 1L; + + public JsonSchemaValidationException(Exchange exchange, Schema schema, + org.everit.json.schema.ValidationException e) { + super(e.getAllMessages().stream().collect(Collectors.joining(", ")), + exchange, + e + ); + } + + public JsonSchemaValidationException(Exchange exchange, Schema schema, + Exception e) { + super(e.getMessage(), exchange, e); + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidatorComponent.java ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidatorComponent.java b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidatorComponent.java new file mode 100644 index 0000000..61cdd05 --- /dev/null +++ b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidatorComponent.java @@ -0,0 +1,46 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.everit.jsonschema; + +import java.util.Map; + +import org.apache.camel.Endpoint; +import org.apache.camel.impl.UriEndpointComponent; + +/** + * The JSON Schema Validator Component is for validating JSON against a schema. + * + * @version + */ +public class JsonSchemaValidatorComponent extends UriEndpointComponent { + + public JsonSchemaValidatorComponent() { + this(JsonSchemaValidatorEndpoint.class); + } + + public JsonSchemaValidatorComponent(Class<? extends Endpoint> endpointClass) { + super(endpointClass); + } + + + protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { + JsonSchemaValidatorEndpoint endpoint = new JsonSchemaValidatorEndpoint(uri, this, remaining); + setProperties(endpoint, parameters); + return endpoint; + } + +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidatorEndpoint.java ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidatorEndpoint.java b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidatorEndpoint.java new file mode 100644 index 0000000..ea0db62 --- /dev/null +++ b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidatorEndpoint.java @@ -0,0 +1,176 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.everit.jsonschema; + +import java.io.IOException; +import java.io.InputStream; + +import org.apache.camel.Component; +import org.apache.camel.Consumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.api.management.ManagedOperation; +import org.apache.camel.api.management.ManagedResource; +import org.apache.camel.impl.DefaultEndpoint; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.UriEndpoint; +import org.apache.camel.spi.UriParam; +import org.apache.camel.spi.UriPath; +import org.apache.camel.util.ObjectHelper; +import org.apache.camel.util.ResourceHelper; +import org.everit.json.schema.Schema; +import org.everit.json.schema.loader.SchemaLoader; +import org.json.JSONObject; +import org.json.JSONTokener; + + +/** + * Validates the payload of a message using XML Schema and JAXP Validation. + */ +@ManagedResource(description = "Managed JSON ValidatorEndpoint") +@UriEndpoint(scheme = "json-validator", title = "JSON Schema Validator", syntax = "json-validator:resourceUri", producerOnly = true, label = "core,validation") +public class JsonSchemaValidatorEndpoint extends DefaultEndpoint { + + @UriPath(description = "URL to a local resource on the classpath, or a reference to lookup a bean in the Registry," + + " or a full URL to a remote resource or resource on the file system which contains the JSON Schema to validate against.") + @Metadata(required = "true") + private String resourceUri; + @UriParam(label = "advanced", description = "To use a custom org.apache.camel.component.everit.jsonschema.JsonValidatorErrorHandler. " + + "The default error handler captures the errors and throws an exception.") + private JsonValidatorErrorHandler errorHandler = new DefaultJsonValidationErrorHandler(); + @UriParam(defaultValue = "true", description = "Whether to fail if no body exists.") + private boolean failOnNullBody = true; + @UriParam(defaultValue = "true", description = "Whether to fail if no header exists when validating against a header.") + private boolean failOnNullHeader = true; + @UriParam(description = "To validate against a header instead of the message body.") + private String headerName; + + /** + * We need a one-to-one relation between endpoint and a Schema + * to be able to clear the cached schema. See method + * {@link #clearCachedSchema}. + */ + private Schema schema; + + public JsonSchemaValidatorEndpoint(String endpointUri, Component component, String resourceUri) { + super(endpointUri, component); + this.resourceUri = resourceUri; + } + + private Schema loadSchema() throws IOException { + ObjectHelper.notNull(getCamelContext(), "camelContext"); + ObjectHelper.notNull(this.resourceUri, "resourceUri"); + try (InputStream inputStream = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), this.resourceUri)) { + JSONObject rawSchema = new JSONObject(new JSONTokener(inputStream)); + // LOG.debug("JSON schema: {}", rawSchema); + return SchemaLoader.load(rawSchema); + } + } + + @ManagedOperation(description = "Clears the cached schema, forcing to re-load the schema on next request") + public void clearCachedSchema() { + this.schema = null; // will cause to reload the schema + } + + @Override + public Producer createProducer() throws Exception { + if (this.schema == null) { + this.schema = loadSchema(); + } + JsonValidatingProcessor validator = new JsonValidatingProcessor(this.schema); + configureValidator(validator); + + return new JsonSchemaValidatorProducer(this, validator); + } + + private void configureValidator(JsonValidatingProcessor validator) { + validator.setErrorHandler(errorHandler); + validator.setFailOnNullBody(failOnNullBody); + validator.setFailOnNullHeader(failOnNullHeader); + validator.setHeaderName(headerName); + } + + @Override + public Consumer createConsumer(Processor processor) throws Exception { + throw new UnsupportedOperationException("Cannot consume from validator"); + } + + @Override + public boolean isSingleton() { + return true; + } + + + public String getResourceUri() { + return resourceUri; + } + + /** + * URL to a local resource on the classpath, or a reference to lookup a bean in the Registry, + * or a full URL to a remote resource or resource on the file system which contains the JSON Schema to validate against. + */ + public void setResourceUri(String resourceUri) { + this.resourceUri = resourceUri; + } + + + public JsonValidatorErrorHandler getErrorHandler() { + return errorHandler; + } + + /** + * To use a custom org.apache.camel.processor.validation.ValidatorErrorHandler. + * <p/> + * The default error handler captures the errors and throws an exception. + */ + public void setErrorHandler(JsonValidatorErrorHandler errorHandler) { + this.errorHandler = errorHandler; + } + + public boolean isFailOnNullBody() { + return failOnNullBody; + } + + /** + * Whether to fail if no body exists. + */ + public void setFailOnNullBody(boolean failOnNullBody) { + this.failOnNullBody = failOnNullBody; + } + + public boolean isFailOnNullHeader() { + return failOnNullHeader; + } + + /** + * Whether to fail if no header exists when validating against a header. + */ + public void setFailOnNullHeader(boolean failOnNullHeader) { + this.failOnNullHeader = failOnNullHeader; + } + + public String getHeaderName() { + return headerName; + } + + /** + * To validate against a header instead of the message body. + */ + public void setHeaderName(String headerName) { + this.headerName = headerName; + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidatorProducer.java ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidatorProducer.java b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidatorProducer.java new file mode 100644 index 0000000..b7efbee --- /dev/null +++ b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonSchemaValidatorProducer.java @@ -0,0 +1,56 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.everit.jsonschema; + +import org.apache.camel.AsyncCallback; +import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultAsyncProducer; +import org.apache.camel.util.ServiceHelper; + +public class JsonSchemaValidatorProducer extends DefaultAsyncProducer { + + private final JsonValidatingProcessor validatingProcessor; + + public JsonSchemaValidatorProducer(Endpoint endpoint, JsonValidatingProcessor validatingProcessor) { + super(endpoint); + this.validatingProcessor = validatingProcessor; + } + + @Override + public boolean process(Exchange exchange, AsyncCallback callback) { + return validatingProcessor.process(exchange, callback); + } + + @Override + protected void doStart() throws Exception { + super.doStart(); + ServiceHelper.startService(validatingProcessor); + } + + @Override + protected void doStop() throws Exception { + super.doStop(); + ServiceHelper.stopService(validatingProcessor); + } + + @Override + protected void doShutdown() throws Exception { + super.doStop(); + ServiceHelper.stopAndShutdownService(validatingProcessor); + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonValidatingProcessor.java ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonValidatingProcessor.java b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonValidatingProcessor.java new file mode 100644 index 0000000..7b5fb68 --- /dev/null +++ b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonValidatingProcessor.java @@ -0,0 +1,150 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.everit.jsonschema; + +import java.io.InputStream; + +import org.apache.camel.AsyncCallback; +import org.apache.camel.AsyncProcessor; +import org.apache.camel.Exchange; +import org.apache.camel.util.AsyncProcessorHelper; +import org.apache.camel.util.IOHelper; +import org.everit.json.schema.ObjectSchema; +import org.everit.json.schema.Schema; +import org.everit.json.schema.ValidationException; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A processor which validates the JSON of the inbound message body + * against some JSON schema + */ +public class JsonValidatingProcessor implements AsyncProcessor { + private static final Logger LOG = LoggerFactory.getLogger(JsonValidatingProcessor.class); + private Schema schema; + private JsonValidatorErrorHandler errorHandler = new DefaultJsonValidationErrorHandler(); + private boolean failOnNullBody = true; + private boolean failOnNullHeader = true; + private String headerName; + + public JsonValidatingProcessor() { + + } + + public JsonValidatingProcessor(Schema schema) { + this.schema = schema; + } + + public void process(Exchange exchange) throws Exception { + AsyncProcessorHelper.process(this, exchange); + } + + public boolean process(Exchange exchange, AsyncCallback callback) { + try { + doProcess(exchange); + } catch (Exception e) { + exchange.setException(e); + } + callback.done(true); + return true; + } + + protected void doProcess(Exchange exchange) throws Exception { + Object jsonPayload = null; + InputStream is = null; + try { + is = getContentToValidate(exchange, InputStream.class); + if (shouldUseHeader()) { + if (is == null && isFailOnNullHeader()) { + throw new NoJsonHeaderValidationException(exchange, headerName); + } + } else { + if (is == null && isFailOnNullBody()) { + throw new NoJsonBodyValidationException(exchange); + } + } + if (is != null) { + if (schema instanceof ObjectSchema) { + jsonPayload = new JSONObject(new JSONTokener(is)); + } else { + jsonPayload = new JSONArray(new JSONTokener(is)); + } + // throws a ValidationException if this object is invalid + schema.validate(jsonPayload); + LOG.debug("JSON is valid"); + } + } catch (ValidationException e) { + this.errorHandler.handleErrors(exchange, schema, e); + } catch (JSONException e) { + this.errorHandler.handleErrors(exchange, schema, e); + } finally { + IOHelper.close(is); + } + } + + private <T> T getContentToValidate(Exchange exchange, Class<T> clazz) { + if (shouldUseHeader()) { + return exchange.getIn().getHeader(headerName, clazz); + } else { + return exchange.getIn().getBody(clazz); + } + } + + private boolean shouldUseHeader() { + return headerName != null; + } + + // Properties + // ----------------------------------------------------------------------- + + + public JsonValidatorErrorHandler getErrorHandler() { + return errorHandler; + } + + public void setErrorHandler(JsonValidatorErrorHandler errorHandler) { + this.errorHandler = errorHandler; + } + + public boolean isFailOnNullBody() { + return failOnNullBody; + } + + public void setFailOnNullBody(boolean failOnNullBody) { + this.failOnNullBody = failOnNullBody; + } + + public boolean isFailOnNullHeader() { + return failOnNullHeader; + } + + public void setFailOnNullHeader(boolean failOnNullHeader) { + this.failOnNullHeader = failOnNullHeader; + } + + public String getHeaderName() { + return headerName; + } + + public void setHeaderName(String headerName) { + this.headerName = headerName; + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonValidatorErrorHandler.java ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonValidatorErrorHandler.java b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonValidatorErrorHandler.java new file mode 100644 index 0000000..4594e97 --- /dev/null +++ b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/JsonValidatorErrorHandler.java @@ -0,0 +1,38 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.everit.jsonschema; + +import org.apache.camel.Exchange; +import org.apache.camel.ValidationException; + +public interface JsonValidatorErrorHandler { + /** + * Resets any state within this error handler + */ + void reset(); + + /** + * Process any errors which may have occurred during validation + * + * @param exchange the exchange + * @param schema the schema + * @param e the exception triggering the error + * @throws ValidationException is thrown in case of validation errors + */ + void handleErrors(Exchange exchange, org.everit.json.schema.Schema schema, Exception e) throws ValidationException; + +} http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/NoJsonBodyValidationException.java ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/NoJsonBodyValidationException.java b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/NoJsonBodyValidationException.java new file mode 100644 index 0000000..3000579 --- /dev/null +++ b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/NoJsonBodyValidationException.java @@ -0,0 +1,37 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.everit.jsonschema; + +import org.apache.camel.Exchange; +import org.apache.camel.ValidationException; + +/** + * An exception found if no JSON body is available on the inbound message + * + * @version + */ +public class NoJsonBodyValidationException extends ValidationException { + private static final long serialVersionUID = 4502520681354358599L; + + public NoJsonBodyValidationException(Exchange exchange) { + super(exchange, "No JSON body could be found on the input message"); + } + + public NoJsonBodyValidationException(Exchange exchange, Throwable cause) { + super("No JSON body could be found on the input message", exchange, cause); + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/NoJsonHeaderValidationException.java ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/NoJsonHeaderValidationException.java b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/NoJsonHeaderValidationException.java new file mode 100644 index 0000000..582a685 --- /dev/null +++ b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/NoJsonHeaderValidationException.java @@ -0,0 +1,38 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.everit.jsonschema; + +import org.apache.camel.Exchange; +import org.apache.camel.ValidationException; + +/** + * An exception found if no JSON body is available on the inbound message + * + * @version + */ +public class NoJsonHeaderValidationException extends ValidationException { + private static final long serialVersionUID = 4502520681354358599L; + + public NoJsonHeaderValidationException(Exchange exchange, String header) { + this(exchange, header, null); + } + + public NoJsonHeaderValidationException(Exchange exchange, String header, Throwable cause) { + super("No JSON header \"" + header + "\" could be found on the input message", exchange, cause); + } +} + http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/package.html ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/package.html b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/package.html new file mode 100644 index 0000000..64cf1d8 --- /dev/null +++ b/components/camel-everit-json-schema/src/main/java/org/apache/camel/component/everit/jsonschema/package.html @@ -0,0 +1,25 @@ +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<html> +<head> +</head> +<body> + +The <a href="http://activemq.apache.org/camel/validator.html">Validator Component</a> for validating XML against some schema + +</body> +</html> http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/main/resources/META-INF/LICENSE.txt ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/main/resources/META-INF/LICENSE.txt b/components/camel-everit-json-schema/src/main/resources/META-INF/LICENSE.txt new file mode 100755 index 0000000..6b0b127 --- /dev/null +++ b/components/camel-everit-json-schema/src/main/resources/META-INF/LICENSE.txt @@ -0,0 +1,203 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/main/resources/META-INF/NOTICE.txt ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/main/resources/META-INF/NOTICE.txt b/components/camel-everit-json-schema/src/main/resources/META-INF/NOTICE.txt new file mode 100644 index 0000000..2e215bf --- /dev/null +++ b/components/camel-everit-json-schema/src/main/resources/META-INF/NOTICE.txt @@ -0,0 +1,11 @@ + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Apache Camel distribution. == + ========================================================================= + + This product includes software developed by + The Apache Software Foundation (http://www.apache.org/). + + Please read the different LICENSE files present in the licenses directory of + this distribution. http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/main/resources/META-INF/services/org/apache/camel/component/json-validator ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/main/resources/META-INF/services/org/apache/camel/component/json-validator b/components/camel-everit-json-schema/src/main/resources/META-INF/services/org/apache/camel/component/json-validator new file mode 100644 index 0000000..447b785 --- /dev/null +++ b/components/camel-everit-json-schema/src/main/resources/META-INF/services/org/apache/camel/component/json-validator @@ -0,0 +1,18 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +class=org.apache.camel.component.everit.jsonschema.JsonSchemaValidatorComponent http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/test/java/org/apache/camel/component/everit/jsonschema/FileValidatorRouteTest.java ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/test/java/org/apache/camel/component/everit/jsonschema/FileValidatorRouteTest.java b/components/camel-everit-json-schema/src/test/java/org/apache/camel/component/everit/jsonschema/FileValidatorRouteTest.java new file mode 100644 index 0000000..2979326 --- /dev/null +++ b/components/camel-everit-json-schema/src/test/java/org/apache/camel/component/everit/jsonschema/FileValidatorRouteTest.java @@ -0,0 +1,97 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.everit.jsonschema; + +import java.io.File; + +import org.apache.camel.Exchange; +import org.apache.camel.ValidationException; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.junit4.CamelTestSupport; +import org.apache.camel.util.FileUtil; +import org.junit.Before; +import org.junit.Test; + +/** + * + */ +public class FileValidatorRouteTest extends CamelTestSupport { + + protected MockEndpoint validEndpoint; + protected MockEndpoint finallyEndpoint; + protected MockEndpoint invalidEndpoint; + + @Test + public void testValidMessage() throws Exception { + validEndpoint.expectedMessageCount(1); + invalidEndpoint.expectedMessageCount(0); + finallyEndpoint.expectedMessageCount(1); + + template.sendBodyAndHeader("file:target/validator", + "{ \"name\": \"Joe Doe\", \"id\": 1, \"price\": 12.5 }", + Exchange.FILE_NAME, "valid.json"); + + MockEndpoint.assertIsSatisfied(validEndpoint, invalidEndpoint, finallyEndpoint); + + assertTrue("Should be able to delete the file", FileUtil.deleteFile(new File("target/validator/valid.json"))); + } + + @Test + public void testInvalidMessage() throws Exception { + validEndpoint.expectedMessageCount(0); + invalidEndpoint.expectedMessageCount(1); + finallyEndpoint.expectedMessageCount(1); + + template.sendBodyAndHeader("file:target/validator", + "{ \"name\": \"Joe Doe\", \"id\": \"AA1\", \"price\": 12.5 }", + Exchange.FILE_NAME, "invalid.json"); + + MockEndpoint.assertIsSatisfied(validEndpoint, invalidEndpoint, finallyEndpoint); + + // should be able to delete the file + assertTrue("Should be able to delete the file", FileUtil.deleteFile(new File("target/validator/invalid.json"))); + } + + @Before + public void setUp() throws Exception { + deleteDirectory("target/validator"); + super.setUp(); + validEndpoint = resolveMandatoryEndpoint("mock:valid", MockEndpoint.class); + invalidEndpoint = resolveMandatoryEndpoint("mock:invalid", MockEndpoint.class); + finallyEndpoint = resolveMandatoryEndpoint("mock:finally", MockEndpoint.class); + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + from("file:target/validator?noop=true") + .doTry() + .to("json-validator:org/apache/camel/component/everit/jsonschema/schema.json") + .to("mock:valid") + .doCatch(ValidationException.class) + .to("mock:invalid") + .doFinally() + .to("mock:finally") + .end(); + } + }; + } + +} http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/test/java/org/apache/camel/component/everit/jsonschema/ValidatorRouteTest.java ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/test/java/org/apache/camel/component/everit/jsonschema/ValidatorRouteTest.java b/components/camel-everit-json-schema/src/test/java/org/apache/camel/component/everit/jsonschema/ValidatorRouteTest.java new file mode 100644 index 0000000..fb41490 --- /dev/null +++ b/components/camel-everit-json-schema/src/test/java/org/apache/camel/component/everit/jsonschema/ValidatorRouteTest.java @@ -0,0 +1,174 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.everit.jsonschema; + +import org.apache.camel.EndpointInject; +import org.apache.camel.Exchange; +import org.apache.camel.ExchangePattern; +import org.apache.camel.ValidationException; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.junit4.CamelTestSupport; +import org.junit.Test; + +public class ValidatorRouteTest extends CamelTestSupport { + + @EndpointInject(uri = "mock:valid") + protected MockEndpoint validEndpoint; + + @EndpointInject(uri = "mock:finally") + protected MockEndpoint finallyEndpoint; + + @EndpointInject(uri = "mock:invalid") + protected MockEndpoint invalidEndpoint; + + @Test + public void testValidMessage() throws Exception { + validEndpoint.expectedMessageCount(1); + finallyEndpoint.expectedMessageCount(1); + + template.sendBody("direct:start", + "{ \"name\": \"Joe Doe\", \"id\": 1, \"price\": 12.5 }"); + + MockEndpoint.assertIsSatisfied(validEndpoint, invalidEndpoint, finallyEndpoint); + } + + @Test + public void testValidMessageInHeader() throws Exception { + validEndpoint.expectedMessageCount(1); + finallyEndpoint.expectedMessageCount(1); + + template.sendBodyAndHeader("direct:startHeaders", + null, + "headerToValidate", + "{ \"name\": \"Joe Doe\", \"id\": 1, \"price\": 12.5 }"); + + MockEndpoint.assertIsSatisfied(validEndpoint, invalidEndpoint, finallyEndpoint); + } + + @Test + public void testInvalidMessage() throws Exception { + invalidEndpoint.expectedMessageCount(1); + finallyEndpoint.expectedMessageCount(1); + + template.sendBody("direct:start", + "{ \"name\": \"Joe Doe\", \"id\": \"ABC123\", \"price\": 12.5 }"); + + MockEndpoint.assertIsSatisfied(validEndpoint, invalidEndpoint, finallyEndpoint); + } + + @Test + public void testInvalidMessageInHeader() throws Exception { + invalidEndpoint.expectedMessageCount(1); + finallyEndpoint.expectedMessageCount(1); + + template.sendBodyAndHeader("direct:startHeaders", + null, + "headerToValidate", + "{ \"name\": \"Joe Doe\", \"id\": \"ABC123\", \"price\": 12.5 }"); + + MockEndpoint.assertIsSatisfied(validEndpoint, invalidEndpoint, finallyEndpoint); + } + + @Test + public void testNullHeaderNoFail() throws Exception { + validEndpoint.expectedMessageCount(1); + + template.sendBodyAndHeader("direct:startNullHeaderNoFail", null, "headerToValidate", null); + + MockEndpoint.assertIsSatisfied(validEndpoint); + } + + @Test + public void testNullHeader() throws Exception { + validEndpoint.setExpectedMessageCount(0); + + Exchange in = resolveMandatoryEndpoint("direct:startNoHeaderException").createExchange(ExchangePattern.InOut); + + in.getIn().setBody(null); + in.getIn().setHeader("headerToValidate", null); + + Exchange out = template.send("direct:startNoHeaderException", in); + + MockEndpoint.assertIsSatisfied(validEndpoint, invalidEndpoint, finallyEndpoint); + + Exception exception = out.getException(); + assertTrue("Should be failed", out.isFailed()); + assertTrue("Exception should be correct type", exception instanceof NoJsonHeaderValidationException); + assertTrue("Exception should mention missing header", exception.getMessage().contains("headerToValidate")); + } + + @Test + public void testInvalideBytesMessage() throws Exception { + invalidEndpoint.expectedMessageCount(1); + finallyEndpoint.expectedMessageCount(1); + + template.sendBody("direct:start", + "{ \"name\": \"Joe Doe\", \"id\": \"ABC123\", \"price\": 12.5 }".getBytes()); + + MockEndpoint.assertIsSatisfied(validEndpoint, invalidEndpoint, finallyEndpoint); + } + + @Test + public void testInvalidBytesMessageInHeader() throws Exception { + invalidEndpoint.expectedMessageCount(1); + finallyEndpoint.expectedMessageCount(1); + + template.sendBodyAndHeader("direct:startHeaders", + null, + "headerToValidate", + "{ \"name\": \"Joe Doe\", \"id\": \"ABC123\", \"price\": 12.5 }".getBytes()); + + MockEndpoint.assertIsSatisfied(validEndpoint, invalidEndpoint, finallyEndpoint); + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + from("direct:start") + .doTry() + .to("json-validator:org/apache/camel/component/everit/jsonschema/schema.json") + .to("mock:valid") + .doCatch(ValidationException.class) + .to("mock:invalid") + .doFinally() + .to("mock:finally") + .end(); + + from("direct:startHeaders") + .doTry() + .to("json-validator:org/apache/camel/component/everit/jsonschema/schema.json?headerName=headerToValidate") + .to("mock:valid") + .doCatch(ValidationException.class) + .to("mock:invalid") + .doFinally() + .to("mock:finally") + .end(); + + from("direct:startNoHeaderException") + .to("json-validator:org/apache/camel/component/everit/jsonschema/schema.json?headerName=headerToValidate") + .to("mock:valid"); + + from("direct:startNullHeaderNoFail") + .to("json-validator:org/apache/camel/component/everit/jsonschema/schema.json?headerName=headerToValidate&failOnNullHeader=false") + .to("mock:valid"); + } + }; + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/test/resources/log4j2.properties ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/test/resources/log4j2.properties b/components/camel-everit-json-schema/src/test/resources/log4j2.properties new file mode 100644 index 0000000..9374f09 --- /dev/null +++ b/components/camel-everit-json-schema/src/test/resources/log4j2.properties @@ -0,0 +1,31 @@ +## --------------------------------------------------------------------------- +## Licensed to the Apache Software Foundation (ASF) under one or more +## contributor license agreements. See the NOTICE file distributed with +## this work for additional information regarding copyright ownership. +## The ASF licenses this file to You under the Apache License, Version 2.0 +## (the "License"); you may not use this file except in compliance with +## the License. You may obtain a copy of the License at +## +## http://www.apache.org/licenses/LICENSE-2.0 +## +## Unless required by applicable law or agreed to in writing, software +## distributed under the License is distributed on an "AS IS" BASIS, +## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +## See the License for the specific language governing permissions and +## limitations under the License. +## --------------------------------------------------------------------------- + +appender.file.type = File +appender.file.name = file +appender.file.fileName = target/camel-json-validator-test.log +appender.file.layout.type = PatternLayout +appender.file.layout.pattern = %d %-5p %c{1} - %m %n +appender.out.type = Console +appender.out.name = out +appender.out.layout.type = PatternLayout +appender.out.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m%n +logger.springframework.name = org.springframework +logger.springframework.level = WARN +rootLogger.level = INFO +rootLogger.appenderRef.file.ref = file +rootLogger.appenderRef.out.ref = out http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/camel-everit-json-schema/src/test/resources/org/apache/camel/component/everit/jsonschema/schema.json ---------------------------------------------------------------------- diff --git a/components/camel-everit-json-schema/src/test/resources/org/apache/camel/component/everit/jsonschema/schema.json b/components/camel-everit-json-schema/src/test/resources/org/apache/camel/component/everit/jsonschema/schema.json new file mode 100644 index 0000000..6fa28c3 --- /dev/null +++ b/components/camel-everit-json-schema/src/test/resources/org/apache/camel/component/everit/jsonschema/schema.json @@ -0,0 +1,34 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "definitions": {}, + "id": "http://example.com/example.json", + "properties": { + "id": { + "default": 1, + "description": "An explanation about the purpose of this instance.", + "id": "/properties/id", + "title": "The id schema", + "type": "integer" + }, + "name": { + "default": "A green door", + "description": "An explanation about the purpose of this instance.", + "id": "/properties/name", + "title": "The name schema", + "type": "string" + }, + "price": { + "default": 12.5, + "description": "An explanation about the purpose of this instance.", + "id": "/properties/price", + "title": "The price schema", + "type": "number" + } + }, + "required": [ + "name", + "id", + "price" + ], + "type": "object" +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/components/pom.xml ---------------------------------------------------------------------- diff --git a/components/pom.xml b/components/pom.xml index 83d4b52..60f3850 100644 --- a/components/pom.xml +++ b/components/pom.xml @@ -121,6 +121,7 @@ <module>camel-elsql</module> <module>camel-etcd</module> <module>camel-eventadmin</module> + <module>camel-everit-json-schema</module> <module>camel-exec</module> <module>camel-facebook</module> <module>camel-fastjson</module> http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/parent/pom.xml ---------------------------------------------------------------------- diff --git a/parent/pom.xml b/parent/pom.xml index 92cf7f1..ca1d8be 100644 --- a/parent/pom.xml +++ b/parent/pom.xml @@ -209,6 +209,7 @@ <!-- embedmongo 1.50.2 do not work --> <embedmongo-version>1.50.1</embedmongo-version> <etcd4j-version>2.13.0</etcd4j-version> + <everit-org-json-schema-version>1.6.0</everit-org-json-schema-version> <exec-maven-plugin-version>1.6.0</exec-maven-plugin-version> <ezmorph-bundle-version>1.0.6_1</ezmorph-bundle-version> <fabric8-maven-plugin-version>3.5.30</fabric8-maven-plugin-version> @@ -4485,6 +4486,13 @@ <version>${jira-rest-client-version}</version> </dependency> + <!-- Optional Everit.org JSON Schema --> + <dependency> + <groupId>com.github.everit-org.json-schema</groupId> + <artifactId>org.everit.json.schema</artifactId> + <version>${everit-org-json-schema-version}</version> + </dependency> + <!-- optional misc --> <dependency> <groupId>com.google.code.scriptengines</groupId> http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/platforms/spring-boot/components-starter/camel-everit-json-schema-starter/pom.xml ---------------------------------------------------------------------- diff --git a/platforms/spring-boot/components-starter/camel-everit-json-schema-starter/pom.xml b/platforms/spring-boot/components-starter/camel-everit-json-schema-starter/pom.xml new file mode 100644 index 0000000..5ee84a3 --- /dev/null +++ b/platforms/spring-boot/components-starter/camel-everit-json-schema-starter/pom.xml @@ -0,0 +1,69 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.apache.camel</groupId> + <artifactId>components-starter</artifactId> + <version>2.20.0-SNAPSHOT</version> + </parent> + <artifactId>camel-everit-json-schema-starter</artifactId> + <packaging>jar</packaging> + <name>Spring-Boot Starter :: Camel :: Everit Kft. JSON Schema validator</name> + <description>Spring-Boot Starter for Camel JSON Schema validation based on everit-org json-schema library</description> + <dependencies> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter</artifactId> + <version>${spring-boot-version}</version> + </dependency> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-everit-json-schema</artifactId> + <version>${project.version}</version> + <!--START OF GENERATED CODE--> + <exclusions> + <exclusion> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + </exclusion> + </exclusions> + <!--END OF GENERATED CODE--> + </dependency> + <!--START OF GENERATED CODE--> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-core-starter</artifactId> + </dependency> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-spring-boot-starter</artifactId> + </dependency> + <!--END OF GENERATED CODE--> + </dependencies> + <!--START OF GENERATED CODE--> + <repositories> + <repository> + <id>jitpack.io</id> + <url>https://jitpack.io</url> + </repository> + </repositories> + <!--END OF GENERATED CODE--> +</project> http://git-wip-us.apache.org/repos/asf/camel/blob/8ba38cf8/platforms/spring-boot/components-starter/camel-everit-json-schema-starter/src/main/java/org/apache/camel/component/everit/jsonschema/springboot/JsonSchemaValidatorComponentAutoConfiguration.java ---------------------------------------------------------------------- diff --git a/platforms/spring-boot/components-starter/camel-everit-json-schema-starter/src/main/java/org/apache/camel/component/everit/jsonschema/springboot/JsonSchemaValidatorComponentAutoConfiguration.java b/platforms/spring-boot/components-starter/camel-everit-json-schema-starter/src/main/java/org/apache/camel/component/everit/jsonschema/springboot/JsonSchemaValidatorComponentAutoConfiguration.java new file mode 100644 index 0000000..7d2decc --- /dev/null +++ b/platforms/spring-boot/components-starter/camel-everit-json-schema-starter/src/main/java/org/apache/camel/component/everit/jsonschema/springboot/JsonSchemaValidatorComponentAutoConfiguration.java @@ -0,0 +1,129 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.everit.jsonschema.springboot; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Generated; +import org.apache.camel.CamelContext; +import org.apache.camel.component.everit.jsonschema.JsonSchemaValidatorComponent; +import org.apache.camel.spi.ComponentCustomizer; +import org.apache.camel.spi.HasId; +import org.apache.camel.spring.boot.CamelAutoConfiguration; +import org.apache.camel.spring.boot.ComponentConfigurationProperties; +import org.apache.camel.spring.boot.util.CamelPropertiesHelper; +import org.apache.camel.spring.boot.util.ConditionalOnCamelContextAndAutoConfigurationBeans; +import org.apache.camel.spring.boot.util.GroupCondition; +import org.apache.camel.spring.boot.util.HierarchicalPropertiesEvaluator; +import org.apache.camel.util.IntrospectionSupport; +import org.apache.camel.util.ObjectHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; + +/** + * Generated by camel-package-maven-plugin - do not edit this file! + */ +@Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo") +@Configuration +@Conditional({ConditionalOnCamelContextAndAutoConfigurationBeans.class, + JsonSchemaValidatorComponentAutoConfiguration.GroupConditions.class}) +@AutoConfigureAfter(CamelAutoConfiguration.class) +@EnableConfigurationProperties({ComponentConfigurationProperties.class, + JsonSchemaValidatorComponentConfiguration.class}) +public class JsonSchemaValidatorComponentAutoConfiguration { + + private static final Logger LOGGER = LoggerFactory + .getLogger(JsonSchemaValidatorComponentAutoConfiguration.class); + @Autowired + private ApplicationContext applicationContext; + @Autowired + private CamelContext camelContext; + @Autowired + private JsonSchemaValidatorComponentConfiguration configuration; + @Autowired(required = false) + private List<ComponentCustomizer<JsonSchemaValidatorComponent>> customizers; + + static class GroupConditions extends GroupCondition { + public GroupConditions() { + super("camel.component", "camel.component.json-validator"); + } + } + + @Lazy + @Bean(name = "json-validator-component") + @ConditionalOnMissingBean(JsonSchemaValidatorComponent.class) + public JsonSchemaValidatorComponent configureJsonSchemaValidatorComponent() + throws Exception { + JsonSchemaValidatorComponent component = new JsonSchemaValidatorComponent(); + component.setCamelContext(camelContext); + Map<String, Object> parameters = new HashMap<>(); + IntrospectionSupport.getProperties(configuration, parameters, null, + false); + for (Map.Entry<String, Object> entry : parameters.entrySet()) { + Object value = entry.getValue(); + Class<?> paramClass = value.getClass(); + if (paramClass.getName().endsWith("NestedConfiguration")) { + Class nestedClass = null; + try { + nestedClass = (Class) paramClass.getDeclaredField( + "CAMEL_NESTED_CLASS").get(null); + HashMap<String, Object> nestedParameters = new HashMap<>(); + IntrospectionSupport.getProperties(value, nestedParameters, + null, false); + Object nestedProperty = nestedClass.newInstance(); + CamelPropertiesHelper.setCamelProperties(camelContext, + nestedProperty, nestedParameters, false); + entry.setValue(nestedProperty); + } catch (NoSuchFieldException e) { + } + } + } + CamelPropertiesHelper.setCamelProperties(camelContext, component, + parameters, false); + if (ObjectHelper.isNotEmpty(customizers)) { + for (ComponentCustomizer<JsonSchemaValidatorComponent> customizer : customizers) { + boolean useCustomizer = (customizer instanceof HasId) + ? HierarchicalPropertiesEvaluator.evaluate( + applicationContext.getEnvironment(), + "camel.component.customizer", + "camel.component.json-validator.customizer", + ((HasId) customizer).getId()) + : HierarchicalPropertiesEvaluator.evaluate( + applicationContext.getEnvironment(), + "camel.component.customizer", + "camel.component.json-validator.customizer"); + if (useCustomizer) { + LOGGER.debug("Configure component {}, with customizer {}", + component, customizer); + customizer.customize(component); + } + } + } + return component; + } +} \ No newline at end of file