http://git-wip-us.apache.org/repos/asf/camel/blob/1fa64e6d/components/camel-json-validator/pom.xml ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/pom.xml b/components/camel-json-validator/pom.xml new file mode 100644 index 0000000..cb03513 --- /dev/null +++ b/components/camel-json-validator/pom.xml @@ -0,0 +1,91 @@ +<?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-json-validator</artifactId> + <name>Camel :: JSON validator</name> + <description>Camel JSON Schema validation based on Everit JSON-schema library</description> + <packaging>jar</packaging> + + <properties> + <camel.osgi.export.pkg>org.apache.camel.component.jsonvalidator.*</camel.osgi.export.pkg> + <camel.osgi.export.service> + org.apache.camel.spi.ComponentResolver;component=json-validator + </camel.osgi.export.service> + </properties> + + <!-- everit is distributed in jitpack and not Maven central --> + <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> + <version>${everit-org-json-schema-version}</version> + </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/1fa64e6d/components/camel-json-validator/src/main/docs/json-validator-component.adoc ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/main/docs/json-validator-component.adoc b/components/camel-json-validator/src/main/docs/json-validator-component.adoc new file mode 100644 index 0000000..d0e6d56 --- /dev/null +++ b/components/camel-json-validator/src/main/docs/json-validator-component.adoc @@ -0,0 +1,127 @@ +== JSON Schema Validator Component + +*Available as of Camel version * + +The JSON Schema 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] +---- +json-validator:resourceUri[?options] +---- + + +Where *resourceUri* is some URL to a local resource on the classpath or a +full URL to a remote resource or resource on the file system which contains +the JSON Schema to validate against. + +=== 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* Path to the resource. You can prefix with: classpath file http ref or bean. classpath file and http loads the resource using these protocols (classpath is default). ref will lookup the resource in the registry. bean will call a method on a bean to be used as the resource. For bean you can specify the method name after dot eg bean:myBean.myMethod. | | String +|=== + +==== Query Parameters (7 parameters): + +[width="100%",cols="2,5,^1,2",options="header"] +|=== +| Name | Description | Default | Type +| *contentCache* (producer) | Sets whether to use resource content cache or not | false | boolean +| *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 ValidatorErrorHandler. The default error handler captures the errors and throws an exception. | | JsonValidatorError Handler +| *schemaLoader* (advanced) | To use a custom schema loader allowing for adding custom format validation. See Everit JSON Schema documentation. The default implementation will create a schema loader builder with draft v6 support. | | JsonSchemaLoader +| *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 + +*myschema.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 incoming JSON with the following Camel route, where `myschema.json` is loaded from the classpath. + +[source,java] +---- +from("direct:start") + .to("json-validator:myschema.json") + .to("mock:end") +---- \ No newline at end of file http://git-wip-us.apache.org/repos/asf/camel/blob/1fa64e6d/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/DefaultJsonSchemaLoader.java ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/DefaultJsonSchemaLoader.java b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/DefaultJsonSchemaLoader.java new file mode 100644 index 0000000..6746c10 --- /dev/null +++ b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/DefaultJsonSchemaLoader.java @@ -0,0 +1,40 @@ +/** + * 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.jsonvalidator; + +import java.io.IOException; +import java.io.InputStream; + +import org.apache.camel.CamelContext; +import org.everit.json.schema.Schema; +import org.everit.json.schema.loader.SchemaLoader; +import org.everit.json.schema.loader.SchemaLoader.SchemaLoaderBuilder; +import org.json.JSONObject; +import org.json.JSONTokener; + +public class DefaultJsonSchemaLoader implements JsonSchemaLoader { + + @Override + public Schema createSchema(CamelContext camelContext, InputStream schemaInputStream) throws IOException { + SchemaLoaderBuilder schemaLoaderBuilder = SchemaLoader.builder().draftV6Support(); + try (InputStream inputStream = schemaInputStream) { + JSONObject rawSchema = new JSONObject(new JSONTokener(inputStream)); + return schemaLoaderBuilder.schemaJson(rawSchema).build().load().build(); + } + } + +} http://git-wip-us.apache.org/repos/asf/camel/blob/1fa64e6d/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/DefaultJsonValidationErrorHandler.java ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/DefaultJsonValidationErrorHandler.java b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/DefaultJsonValidationErrorHandler.java new file mode 100644 index 0000000..da96a77 --- /dev/null +++ b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/DefaultJsonValidationErrorHandler.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.jsonvalidator; + +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 JsonValidationException(exchange, schema, (org.everit.json.schema.ValidationException)e); + } else { + throw new JsonValidationException(exchange, schema, e); + } + } + +} http://git-wip-us.apache.org/repos/asf/camel/blob/1fa64e6d/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonSchemaLoader.java ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonSchemaLoader.java b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonSchemaLoader.java new file mode 100644 index 0000000..045052d --- /dev/null +++ b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonSchemaLoader.java @@ -0,0 +1,44 @@ +/** + * 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.jsonvalidator; + +import java.io.InputStream; + +import org.apache.camel.CamelContext; +import org.everit.json.schema.FormatValidator; +import org.everit.json.schema.Schema; + +/** + * Can be used to create custom schema for the JSON validator endpoint. + * This interface is useful to add custom {@link FormatValidator} to the {@link Schema} + * + * For more information see + * <a href="https://github.com/everit-org/json-schema#format-validators">Format Validators</a> + * in the Everit JSON Schema documentation. + */ +public interface JsonSchemaLoader { + + /** + * Create a new Schema based on the schema input stream. + * + * @param camelContext camel context + * @param schemaInputStream the resource input stream + * @return a Schema to be used when validating incoming requests + */ + Schema createSchema(CamelContext camelContext, InputStream schemaInputStream) throws Exception; + +} http://git-wip-us.apache.org/repos/asf/camel/blob/1fa64e6d/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidationException.java ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidationException.java b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidationException.java new file mode 100644 index 0000000..d027f2e --- /dev/null +++ b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidationException.java @@ -0,0 +1,36 @@ +/** + * 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.jsonvalidator; + +import java.util.stream.Collectors; + +import org.apache.camel.Exchange; +import org.apache.camel.ValidationException; +import org.everit.json.schema.Schema; + +public class JsonValidationException extends ValidationException { + + private static final long serialVersionUID = 1L; + + public JsonValidationException(Exchange exchange, Schema schema, org.everit.json.schema.ValidationException e) { + super(e.getAllMessages().stream().collect(Collectors.joining(", ")), exchange, e); + } + + public JsonValidationException(Exchange exchange, Schema schema, Exception e) { + super(e.getMessage(), exchange, e); + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/1fa64e6d/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidatorComponent.java ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidatorComponent.java b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidatorComponent.java new file mode 100644 index 0000000..bdc2d34 --- /dev/null +++ b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidatorComponent.java @@ -0,0 +1,35 @@ +/** + * 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.jsonvalidator; + +import java.util.Map; + +import org.apache.camel.Endpoint; +import org.apache.camel.impl.DefaultComponent; + +/** + * The JSON Schema Validator Component is for validating JSON against a schema. + */ +public class JsonValidatorComponent extends DefaultComponent { + + protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { + JsonValidatorEndpoint endpoint = new JsonValidatorEndpoint(uri, this, remaining); + setProperties(endpoint, parameters); + return endpoint; + } + +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/camel/blob/1fa64e6d/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidatorEndpoint.java ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidatorEndpoint.java b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidatorEndpoint.java new file mode 100644 index 0000000..c301508 --- /dev/null +++ b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidatorEndpoint.java @@ -0,0 +1,201 @@ +/** + * 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.jsonvalidator; + +import java.io.InputStream; + +import org.apache.camel.Component; +import org.apache.camel.Exchange; +import org.apache.camel.ExchangePattern; +import org.apache.camel.api.management.ManagedResource; +import org.apache.camel.component.ResourceEndpoint; +import org.apache.camel.spi.UriEndpoint; +import org.apache.camel.spi.UriParam; +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; + +/** + * Validates the payload of a message using Everit JSON schema validator. + */ +@ManagedResource(description = "Managed JsonValidatorEndpoint") +@UriEndpoint(scheme = "json-validator", title = "JSON Schema Validator", syntax = "json-validator:resourceUri", producerOnly = true, label = "validation,json") +public class JsonValidatorEndpoint extends ResourceEndpoint { + + private static final Logger LOG = LoggerFactory.getLogger(JsonValidatorEndpoint.class); + + private volatile Schema schema; + + @UriParam(defaultValue = "true") + private boolean failOnNullBody = true; + @UriParam(defaultValue = "true") + private boolean failOnNullHeader = true; + @UriParam(description = "To validate against a header instead of the message body.") + private String headerName; + @UriParam(label = "advanced") + private JsonValidatorErrorHandler errorHandler = new DefaultJsonValidationErrorHandler(); + @UriParam(label = "advanced") + private JsonSchemaLoader schemaLoader = new DefaultJsonSchemaLoader(); + + public JsonValidatorEndpoint(String endpointUri, Component component, String resourceUri) { + super(endpointUri, component, resourceUri); + } + + @Override + public void clearContentCache() { + this.schema = null; + super.clearContentCache(); + } + + @Override + public ExchangePattern getExchangePattern() { + return ExchangePattern.InOut; + } + + @Override + protected void onExchange(Exchange exchange) throws Exception { + Object jsonPayload; + InputStream is = null; + // Get a local copy of the current schema to improve concurrency. + Schema localSchema = this.schema; + if (localSchema == null) { + localSchema = getOrCreateSchema(); + } + 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 | 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; + } + + /** + * Synchronized method to create a schema if is does not already exist. + * + * @return The currently loaded schema + */ + private Schema getOrCreateSchema() throws Exception { + synchronized (this) { + if (this.schema == null) { + this.schema = this.schemaLoader.createSchema(getCamelContext(), this.getResourceAsInputStream()); + } + } + return this.schema; + } + + @Override + protected String createEndpointUri() { + return "json-validator:" + getResourceUri(); + } + + public JsonValidatorErrorHandler getErrorHandler() { + return errorHandler; + } + + /** + * To use a custom ValidatorErrorHandler. + * <p/> + * The default error handler captures the errors and throws an exception. + */ + public void setErrorHandler(JsonValidatorErrorHandler errorHandler) { + this.errorHandler = errorHandler; + } + + public JsonSchemaLoader getSchemaLoader() { + return schemaLoader; + } + + /** + * To use a custom schema loader allowing for adding custom format validation. See Everit JSON Schema documentation. + * The default implementation will create a schema loader builder with draft v6 support. + */ + public void setSchemaLoader(JsonSchemaLoader schemaLoader) { + this.schemaLoader = schemaLoader; + } + + 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/1fa64e6d/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidatorErrorHandler.java ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidatorErrorHandler.java b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidatorErrorHandler.java new file mode 100644 index 0000000..830ccd4 --- /dev/null +++ b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/JsonValidatorErrorHandler.java @@ -0,0 +1,39 @@ +/** + * 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.jsonvalidator; + +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/1fa64e6d/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/NoJsonBodyValidationException.java ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/NoJsonBodyValidationException.java b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/NoJsonBodyValidationException.java new file mode 100644 index 0000000..1257c04 --- /dev/null +++ b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/NoJsonBodyValidationException.java @@ -0,0 +1,35 @@ +/** + * 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.jsonvalidator; + +import org.apache.camel.Exchange; +import org.apache.camel.ValidationException; + +/** + * An exception found if no JSON body is available on the inbound message + */ +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/1fa64e6d/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/NoJsonHeaderValidationException.java ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/NoJsonHeaderValidationException.java b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/NoJsonHeaderValidationException.java new file mode 100644 index 0000000..ae29d9f --- /dev/null +++ b/components/camel-json-validator/src/main/java/org/apache/camel/component/jsonvalidator/NoJsonHeaderValidationException.java @@ -0,0 +1,36 @@ +/** + * 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.jsonvalidator; + +import org.apache.camel.Exchange; +import org.apache.camel.ValidationException; + +/** + * An exception found if no JSON body is available on the inbound message + */ +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/1fa64e6d/components/camel-json-validator/src/main/resources/META-INF/LICENSE.txt ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/main/resources/META-INF/LICENSE.txt b/components/camel-json-validator/src/main/resources/META-INF/LICENSE.txt new file mode 100755 index 0000000..6b0b127 --- /dev/null +++ b/components/camel-json-validator/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/1fa64e6d/components/camel-json-validator/src/main/resources/META-INF/NOTICE.txt ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/main/resources/META-INF/NOTICE.txt b/components/camel-json-validator/src/main/resources/META-INF/NOTICE.txt new file mode 100644 index 0000000..2e215bf --- /dev/null +++ b/components/camel-json-validator/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/1fa64e6d/components/camel-json-validator/src/main/resources/META-INF/services/org/apache/camel/component/json-validator ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/main/resources/META-INF/services/org/apache/camel/component/json-validator b/components/camel-json-validator/src/main/resources/META-INF/services/org/apache/camel/component/json-validator new file mode 100644 index 0000000..9830fb8 --- /dev/null +++ b/components/camel-json-validator/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.jsonvalidator.JsonValidatorComponent http://git-wip-us.apache.org/repos/asf/camel/blob/1fa64e6d/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/CustomSchemaLoaderValidatorRouteTest.java ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/CustomSchemaLoaderValidatorRouteTest.java b/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/CustomSchemaLoaderValidatorRouteTest.java new file mode 100644 index 0000000..a509f81 --- /dev/null +++ b/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/CustomSchemaLoaderValidatorRouteTest.java @@ -0,0 +1,84 @@ +/** + * 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.jsonvalidator; + +import org.apache.camel.EndpointInject; +import org.apache.camel.ValidationException; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.impl.JndiRegistry; +import org.apache.camel.test.junit4.CamelTestSupport; +import org.junit.Test; + +public class CustomSchemaLoaderValidatorRouteTest 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\": \"Even Joe\", \"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\": \"Odd Joe\", \"id\": 1, \"price\": 12.5 }"); + + MockEndpoint.assertIsSatisfied(validEndpoint, invalidEndpoint, finallyEndpoint); + } + + @Override + protected JndiRegistry createRegistry() throws Exception { + JndiRegistry jndiRegistry = super.createRegistry(); + jndiRegistry.bind("customSchemaLoader", new TestCustomSchemaLoader()); + return jndiRegistry; + } + + @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/jsonvalidator/schemawithformat.json?schemaLoader=#customSchemaLoader") + .to("mock:valid") + .doCatch(ValidationException.class) + .to("mock:invalid") + .doFinally() + .to("mock:finally") + .end(); + } + }; + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/1fa64e6d/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/EvenCharNumValidator.java ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/EvenCharNumValidator.java b/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/EvenCharNumValidator.java new file mode 100644 index 0000000..6b995ac --- /dev/null +++ b/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/EvenCharNumValidator.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.jsonvalidator; + +import java.util.Optional; + +import org.everit.json.schema.FormatValidator; + +public class EvenCharNumValidator implements FormatValidator { + + @Override + public Optional<String> validate(final String subject) { + if (subject.length() % 2 == 0) { + return Optional.empty(); + } else { + return Optional.of(String.format("the length of string [%s] is odd", subject)); + } + } + + @Override + public String formatName() { + return "evenlength"; + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/camel/blob/1fa64e6d/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/FileValidatorRouteTest.java ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/FileValidatorRouteTest.java b/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/FileValidatorRouteTest.java new file mode 100644 index 0000000..9ee87fd --- /dev/null +++ b/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/FileValidatorRouteTest.java @@ -0,0 +1,94 @@ +/** + * 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.jsonvalidator; + +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/jsonvalidator/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/1fa64e6d/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/TestCustomSchemaLoader.java ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/TestCustomSchemaLoader.java b/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/TestCustomSchemaLoader.java new file mode 100644 index 0000000..b7367eb --- /dev/null +++ b/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/TestCustomSchemaLoader.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.jsonvalidator; + +import java.io.IOException; +import java.io.InputStream; + +import org.apache.camel.CamelContext; +import org.everit.json.schema.Schema; +import org.everit.json.schema.loader.SchemaLoader; +import org.everit.json.schema.loader.SchemaLoader.SchemaLoaderBuilder; +import org.json.JSONObject; +import org.json.JSONTokener; + +public class TestCustomSchemaLoader implements JsonSchemaLoader { + + @Override + public Schema createSchema(CamelContext camelContext, InputStream schemaInputStream) throws IOException { + + SchemaLoaderBuilder schemaLoaderBuilder = SchemaLoader.builder().draftV6Support(); + + try (InputStream inputStream = schemaInputStream) { + JSONObject rawSchema = new JSONObject(new JSONTokener(inputStream)); + return schemaLoaderBuilder.schemaJson(rawSchema).addFormatValidator(new EvenCharNumValidator()).build().load().build(); + } + } + +} http://git-wip-us.apache.org/repos/asf/camel/blob/1fa64e6d/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/ValidatorRouteTest.java ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/ValidatorRouteTest.java b/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/ValidatorRouteTest.java new file mode 100644 index 0000000..f1542ab --- /dev/null +++ b/components/camel-json-validator/src/test/java/org/apache/camel/component/jsonvalidator/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.jsonvalidator; + +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/jsonvalidator/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/jsonvalidator/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/jsonvalidator/schema.json?headerName=headerToValidate") + .to("mock:valid"); + + from("direct:startNullHeaderNoFail") + .to("json-validator:org/apache/camel/component/jsonvalidator/schema.json?headerName=headerToValidate&failOnNullHeader=false") + .to("mock:valid"); + } + }; + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/1fa64e6d/components/camel-json-validator/src/test/resources/log4j2.properties ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/test/resources/log4j2.properties b/components/camel-json-validator/src/test/resources/log4j2.properties new file mode 100644 index 0000000..8af6faa --- /dev/null +++ b/components/camel-json-validator/src/test/resources/log4j2.properties @@ -0,0 +1,29 @@ +## --------------------------------------------------------------------------- +## 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 +rootLogger.level = INFO +rootLogger.appenderRef.file.ref = file + http://git-wip-us.apache.org/repos/asf/camel/blob/1fa64e6d/components/camel-json-validator/src/test/resources/org/apache/camel/component/jsonvalidator/schema.json ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/test/resources/org/apache/camel/component/jsonvalidator/schema.json b/components/camel-json-validator/src/test/resources/org/apache/camel/component/jsonvalidator/schema.json new file mode 100644 index 0000000..021640d --- /dev/null +++ b/components/camel-json-validator/src/test/resources/org/apache/camel/component/jsonvalidator/schema.json @@ -0,0 +1,34 @@ +{ + "$schema": "http://json-schema.org/draft-06/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/1fa64e6d/components/camel-json-validator/src/test/resources/org/apache/camel/component/jsonvalidator/schemawithformat.json ---------------------------------------------------------------------- diff --git a/components/camel-json-validator/src/test/resources/org/apache/camel/component/jsonvalidator/schemawithformat.json b/components/camel-json-validator/src/test/resources/org/apache/camel/component/jsonvalidator/schemawithformat.json new file mode 100644 index 0000000..a365115 --- /dev/null +++ b/components/camel-json-validator/src/test/resources/org/apache/camel/component/jsonvalidator/schemawithformat.json @@ -0,0 +1,35 @@ +{ + "$schema": "http://json-schema.org/draft-06/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. Must have even number of characters", + "id": "/properties/name", + "title": "The name schema", + "type": "string", + "format": "evenlength" + }, + "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/1fa64e6d/components/pom.xml ---------------------------------------------------------------------- diff --git a/components/pom.xml b/components/pom.xml index 60f3850..6b7f26d 100644 --- a/components/pom.xml +++ b/components/pom.xml @@ -121,7 +121,7 @@ <module>camel-elsql</module> <module>camel-etcd</module> <module>camel-eventadmin</module> - <module>camel-everit-json-schema</module> + <module>camel-json-validator</module> <module>camel-exec</module> <module>camel-facebook</module> <module>camel-fastjson</module> http://git-wip-us.apache.org/repos/asf/camel/blob/1fa64e6d/parent/pom.xml ---------------------------------------------------------------------- diff --git a/parent/pom.xml b/parent/pom.xml index 0a3cacc..b75a109 100644 --- a/parent/pom.xml +++ b/parent/pom.xml @@ -1147,11 +1147,6 @@ </dependency> <dependency> <groupId>org.apache.camel</groupId> - <artifactId>camel-everit-json-schema</artifactId> - <version>${project.version}</version> - </dependency> - <dependency> - <groupId>org.apache.camel</groupId> <artifactId>camel-exec</artifactId> <version>${project.version}</version> </dependency> @@ -1502,6 +1497,11 @@ </dependency> <dependency> <groupId>org.apache.camel</groupId> + <artifactId>camel-json-validator</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.apache.camel</groupId> <artifactId>camel-jsonpath</artifactId> <version>${project.version}</version> </dependency> @@ -2591,11 +2591,6 @@ </dependency> <dependency> <groupId>org.apache.camel</groupId> - <artifactId>camel-everit-json-schema-starter</artifactId> - <version>${project.version}</version> - </dependency> - <dependency> - <groupId>org.apache.camel</groupId> <artifactId>camel-exec-starter</artifactId> <version>${project.version}</version> </dependency> @@ -2931,6 +2926,11 @@ </dependency> <dependency> <groupId>org.apache.camel</groupId> + <artifactId>camel-json-validator-starter</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.apache.camel</groupId> <artifactId>camel-jsonpath-starter</artifactId> <version>${project.version}</version> </dependency> http://git-wip-us.apache.org/repos/asf/camel/blob/1fa64e6d/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 deleted file mode 100644 index 5ee84a3..0000000 --- a/platforms/spring-boot/components-starter/camel-everit-json-schema-starter/pom.xml +++ /dev/null @@ -1,69 +0,0 @@ -<?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/1fa64e6d/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 deleted file mode 100644 index 7d2decc..0000000 --- a/platforms/spring-boot/components-starter/camel-everit-json-schema-starter/src/main/java/org/apache/camel/component/everit/jsonschema/springboot/JsonSchemaValidatorComponentAutoConfiguration.java +++ /dev/null @@ -1,129 +0,0 @@ -/** - * 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