Camel Components

Validator

Since Camel 1.1

Only producer is supported

The Validation component performs XML validation of the message body using the JAXP Validation API and based on any of the supported XML schema languages, which defaults to XML Schema.

URI format

validator:someLocalOrRemoteResource

Where someLocalOrRemoteResource 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 XSD to validate against. For example:

  • validator:com/mypackage/myschema.xsd

The Validation component is provided directly in the camel-core.

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The Validator component supports the following options which are listed below.

Name Description Default Type

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

resourceResolverFactory (advanced)

The factory that creates the LSResourceResolver of each endpoint that has no resourceResolverFactory of its own. The resolver loads the schemas that the schema of the endpoint imports or includes. When not set, DefaultValidatorResourceResolverFactory is used, which resolves them relative to the location of the schema of the endpoint.

ValidatorResourceResolverFactory

Endpoint Options

The Validator endpoint is configured using URI syntax:

validator:resourceUri

With the following path and query parameters:

Path Parameters

Name Description Default Type

resourceUri (producer)

Required The location of the XML schema to validate against. Without a prefix, the resource is loaded from the classpath; use file: for the file system, http: or https: for a remote URL, or ref: for a String bean in the Registry that holds the schema. The schema is read and compiled when the producer is created, so a missing or invalid schema fails then.

String

Query Parameters

Name Description Default Type

failOnNullBody (producer)

Whether to fail with a NoXmlBodyValidationException when the message body is null. When false, a null body is not validated and the message passes. The option also decides what happens to a body (or, with headerName, a header) that cannot be converted to a javax.xml.transform.Source: when true, it fails with an ExpectedBodyTypeException; when false, it is validated as an empty document and passes.

true

boolean

failOnNullHeader (producer)

Whether to fail with a NoXmlHeaderValidationException when headerName is set and the header is missing or null. When false, the message passes without validation. Not used when headerName is not set.

true

boolean

headerName (producer)

The name of the header to validate instead of the message body. The header can hold the same types as the body: text, bytes, a stream, a file, a DOM or another javax.xml.transform.Source. The body is then not validated.

String

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

errorHandler (advanced)

A custom org.apache.camel.support.processor.validation.ValidatorErrorHandler, a SAX ErrorHandler that collects the warnings and errors that the Validator reports, and then decides in handleErrors() whether the message fails. Camel creates a new instance of its class for each message with the public no-argument constructor, so the state of the configured instance is not used. The default, DefaultValidationErrorHandler, throws a SchemaValidationException when there is an error or a fatal error; warnings do not fail the message. XML that is not well-formed always fails with a SchemaValidationException.

ValidatorErrorHandler

resourceResolver (advanced)

A custom org.w3c.dom.ls.LSResourceResolver that the SchemaFactory uses to load the schemas that the schema refers to with xs:import, xs:include and xs:redefine. It is used only to compile the schema, not to validate the messages. Takes precedence over resourceResolverFactory. Not used when schemaFactory is set.

LSResourceResolver

resourceResolverFactory (advanced)

A factory that creates the LSResourceResolver of this endpoint from the CamelContext and the resourceUri, so that the resolver can load the imported and included schemas relative to the location of the schema. The default factory resolves a schemaLocation relative to the folder of resourceUri (an http: or https: schemaLocation as it is) and loads it the same way as resourceUri. When not set, the factory of the component is used. Not used when resourceResolver or schemaFactory is set.

ValidatorResourceResolverFactory

schemaFactory (advanced)

A custom javax.xml.validation.SchemaFactory to compile the schema with. By default, Camel creates one for schemaLanguage, sets the resource resolver on it and sets its accessExternalDTD and accessExternalSchema properties to empty, so the schema can load other schemas only through the resource resolver. Camel uses a custom SchemaFactory as it is: it sets neither the resource resolver nor these properties. The Validator of each message gets accessExternalDTD and accessExternalSchema set to empty in both cases, so a message cannot load an external DTD or external entity (unless the global option CamelXmlValidatorAccessExternalDTD is true, which turns off all these restrictions).

SchemaFactory

schemaLanguage (advanced)

The schema language, as the namespace URI that SchemaFactory.newInstance() looks up a javax.xml.validation.SchemaFactory for. The JDK supports only W3C XML Schema (http://www.w3.org/2001/XMLSchema); another language, such as RELAX NG, needs a SchemaFactory implementation for it on the classpath. Not used when schemaFactory is set.

http://www.w3.org/2001/XMLSchema

String

useSharedSchema (advanced)

Whether to compile the schema once and share the javax.xml.validation.Schema instance between all messages (a Schema is thread-safe). When false, Camel reads the schema resource and compiles a new Schema for every message, which is slow but picks up changes of the resource. A shared schema can be reloaded with the JMX operation clearCachedSchema.

true

boolean

Message Body

The message body at each side of the Validator component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Producer input

text, bytes, stream, file or pojo, as xml

The XML to validate: text, bytes, a stream, a file, a DOM or another javax.xml.transform.Source. A Map, a List or no body fails; with headerName the header is validated instead.

  • With failOnNullBody=false: null, text, bytes, stream, file or pojo

Not known when headerName is set.

Producer output

unchanged

Unchanged: XML that is not valid fails with a SchemaValidationException.

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Example

The following example shows how to configure a route from endpoint direct:start which then goes to one of two endpoints, either mock:valid or mock:invalid based on whether the XML matches the given schema (which is supplied on the classpath). When the XML does not match the schema, the validator throws an org.apache.camel.ValidationException, which the doCatch handles:

- route:
    from:
      uri: direct:start
      steps:
        - doTry:
            steps:
              - to:
                  uri: validator:org/apache/camel/component/validator/schema.xsd
              - to:
                  uri: mock:valid
            doCatch:
              - exception:
                  - org.apache.camel.ValidationException
                steps:
                  - to:
                      uri: mock:invalid
            doFinally:
              steps:
                - to:
                    uri: mock:finally

To validate a header instead of the message body, set the headerName option:

- route:
    from:
      uri: direct:startHeaders
      steps:
        - to:
            uri: validator:org/apache/camel/component/validator/schema.xsd
            parameters:
              headerName: headerToValidate
        - to:
            uri: mock:valid

Advanced: JMX method clearCachedSchema

You can force that the cached schema in the validator endpoint is cleared and reread with the next process call with the JMX operation clearCachedSchema. You can also use this method to programmatically clear the cache. This method is available on the ValidatorEndpoint class.