Rechercher

Ce contenu n'est pas disponible dans la langue sélectionnée.

Chapter 16. Bean Validator

download PDF

Only producer is supported

The Validator component performs bean validation of the message body using the Java Bean Validation API (). Camel uses the reference implementation, which is Hibernate Validator.

16.1. Dependencies

When using bean-validator with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:

<dependency>
  <groupId>org.apache.camel.springboot</groupId>
  <artifactId>camel-bean-validator-starter</artifactId>
</dependency>

16.2. URI format

bean-validator:label[?options]

Where label is an arbitrary text value describing the endpoint. You can append query options to the URI in the following format,

?option=value&option=value&…​

16.3. Configuring Options

Camel components are configured on two levels:

  • Component level
  • Endpoint level

16.3.1. Component Level Options

The component level is the highest level. The configurations you define at this level are inherited by all the endpoints. For example, a component can have security settings, credentials for authentication, urls for network connection, and so on.

Since components typically have pre-configured defaults for the most common cases, you may need to only configure a few component options, or maybe none at all.

You can configure components with Component DSL in a configuration file (application.properties|yaml), or directly with Java code.

16.3.2. Endpoint Level Options

At the Endpoint level you have many options, which you can use to configure what you want the endpoint to do. The options are categorized according to whether the endpoint is used as a consumer (from) or as a producer (to) or used for both.

You can configure endpoints directly in the endpoint URI as path and query parameters. You can also use Endpoint DSL and DataFormat DSL as type safe ways of configuring endpoints and data formats in Java.

When configuring options, use Property Placeholders for urls, port numbers, sensitive information, and other settings.

Placeholders allows you to externalize the configuration from your code, giving you more flexible and reusable code.

16.4. Component Options

The Bean Validator component supports 8 options, which are listed below.

NameDescriptionDefaultType

ignoreXmlConfiguration (producer)

Whether to ignore data from the META-INF/validation.xml file.

false

boolean

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

constraintValidatorFactory (advanced)

To use a custom ConstraintValidatorFactory.

 

ConstraintValidatorFactory

messageInterpolator (advanced)

To use a custom MessageInterpolator.

 

MessageInterpolator

traversableResolver (advanced)

To use a custom TraversableResolver.

 

TraversableResolver

validationProviderResolver (advanced)

To use a a custom ValidationProviderResolver.

 

ValidationProviderResolver

validatorFactory (advanced)

Autowired To use a custom ValidatorFactory.

 

ValidatorFactory

16.5. Endpoint Options

The Bean Validator endpoint is configured using URI syntax:

bean-validator:label

with the following path and query parameters:

16.5.1. Path Parameters (1 parameters)

NameDescriptionDefaultType

label (producer)

Required Where label is an arbitrary text value describing the endpoint.

 

String

16.5.2. Query Parameters (8 parameters)

NameDescriptionDefaultType

group (producer)

To use a custom validation group.

javax.validation.groups.Default

String

ignoreXmlConfiguration (producer)

Whether to ignore data from the META-INF/validation.xml file.

false

boolean

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

constraintValidatorFactory (advanced)

To use a custom ConstraintValidatorFactory.

 

ConstraintValidatorFactory

messageInterpolator (advanced)

To use a custom MessageInterpolator.

 

MessageInterpolator

traversableResolver (advanced)

To use a custom TraversableResolver.

 

TraversableResolver

validationProviderResolver (advanced)

To use a a custom ValidationProviderResolver.

 

ValidationProviderResolver

validatorFactory (advanced)

To use a custom ValidatorFactory.

 

ValidatorFactory

16.6. OSGi deployment

To use Hibernate Validator in the OSGi environment use dedicated ValidationProviderResolver implementation, just as org.apache.camel.component.bean.validator.HibernateValidationProviderResolver. The snippet below demonstrates this approach. You can also use HibernateValidationProviderResolver.

Using HibernateValidationProviderResolver

from("direct:test").
  to("bean-validator://ValidationProviderResolverTest?validationProviderResolver=#myValidationProviderResolver");

<bean id="myValidationProviderResolver" class="org.apache.camel.component.bean.validator.HibernateValidationProviderResolver"/>

If no custom ValidationProviderResolver is defined and the validator component has been deployed into the OSGi environment, the HibernateValidationProviderResolver will be automatically used.

16.7. Example

Assumed we have a java bean with the following annotations

Car.java

public class Car {

    @NotNull
    private String manufacturer;

    @NotNull
    @Size(min = 5, max = 14, groups = OptionalChecks.class)
    private String licensePlate;

    // getter and setter
}

and an interface definition for our custom validation group

OptionalChecks.java

public interface OptionalChecks {
}

with the following Camel route, only the @NotNull constraints on the attributes manufacturer and licensePlate will be validated (Camel uses the default group javax.validation.groups.Default).

from("direct:start")
.to("bean-validator://x")
.to("mock:end")

If you want to check the constraints from the group OptionalChecks, you have to define the route like this

from("direct:start")
.to("bean-validator://x?group=OptionalChecks")
.to("mock:end")

If you want to check the constraints from both groups, you have to define a new interface first

AllChecks.java

@GroupSequence({Default.class, OptionalChecks.class})
public interface AllChecks {
}

and then your route definition should looks like this

from("direct:start")
.to("bean-validator://x?group=AllChecks")
.to("mock:end")

And if you have to provide your own message interpolator, traversable resolver and constraint validator factory, you have to write a route like this

<bean id="myMessageInterpolator" class="my.ConstraintValidatorFactory" />
<bean id="myTraversableResolver" class="my.TraversableResolver" />
<bean id="myConstraintValidatorFactory" class="my.ConstraintValidatorFactory" />
from("direct:start")
.to("bean-validator://x?group=AllChecks&messageInterpolator=#myMessageInterpolator
&traversableResolver=#myTraversableResolver&constraintValidatorFactory=#myConstraintValidatorFactory")
.to("mock:end")

It’s also possible to describe your constraints as XML and not as Java annotations. In this case, you have to provide the file META-INF/validation.xml which could looks like this

validation.xml

<validation-config
    xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration">

    <default-provider>org.hibernate.validator.HibernateValidator</default-provider>
    <message-interpolator>org.hibernate.validator.engine.ResourceBundleMessageInterpolator</message-interpolator>
    <traversable-resolver>org.hibernate.validator.engine.resolver.DefaultTraversableResolver</traversable-resolver>
    <constraint-validator-factory>org.hibernate.validator.engine.ConstraintValidatorFactoryImpl</constraint-validator-factory>
    <constraint-mapping>/constraints-car.xml</constraint-mapping>

</validation-config>

and the constraints-car.xml file

constraints-car.xml

<constraint-mappings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.0.xsd"
    xmlns="http://jboss.org/xml/ns/javax/validation/mapping">

    <default-package>org.apache.camel.component.bean.validator</default-package>

    <bean class="CarWithoutAnnotations" ignore-annotations="true">
        <field name="manufacturer">
            <constraint annotation="javax.validation.constraints.NotNull" />
        </field>

        <field name="licensePlate">
            <constraint annotation="javax.validation.constraints.NotNull" />

            <constraint annotation="javax.validation.constraints.Size">
                <groups>
                    <value>org.apache.camel.component.bean.validator.OptionalChecks</value>
                </groups>
                <element name="min">5</element>
                <element name="max">14</element>
            </constraint>
        </field>
    </bean>
</constraint-mappings>

Here is the XML syntax for the example route definition for OrderedChecks.

Note that the body should include an instance of a class to validate.

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

    <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
        <route>
            <from uri="direct:start"/>
            <to uri="bean-validator://x?group=org.apache.camel.component.bean.validator.OrderedChecks"/>
        </route>
    </camelContext>
</beans>

16.8. Spring Boot Auto-Configuration

The component supports 9 options, which are listed below.

NameDescriptionDefaultType

camel.component.bean-validator.autowired-enabled

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

camel.component.bean-validator.constraint-validator-factory

To use a custom ConstraintValidatorFactory. The option is a javax.validation.ConstraintValidatorFactory type.

 

ConstraintValidatorFactory

camel.component.bean-validator.enabled

Whether to enable auto configuration of the bean-validator component. This is enabled by default.

 

Boolean

camel.component.bean-validator.ignore-xml-configuration

Whether to ignore data from the META-INF/validation.xml file.

false

Boolean

camel.component.bean-validator.lazy-start-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

camel.component.bean-validator.message-interpolator

To use a custom MessageInterpolator. The option is a javax.validation.MessageInterpolator type.

 

MessageInterpolator

camel.component.bean-validator.traversable-resolver

To use a custom TraversableResolver. The option is a javax.validation.TraversableResolver type.

 

TraversableResolver

camel.component.bean-validator.validation-provider-resolver

To use a a custom ValidationProviderResolver. The option is a javax.validation.ValidationProviderResolver type.

 

ValidationProviderResolver

camel.component.bean-validator.validator-factory

To use a custom ValidatorFactory. The option is a javax.validation.ValidatorFactory type.

 

ValidatorFactory

Red Hat logoGithubRedditYoutubeTwitter

Apprendre

Essayez, achetez et vendez

Communautés

À propos de la documentation Red Hat

Nous aidons les utilisateurs de Red Hat à innover et à atteindre leurs objectifs grâce à nos produits et services avec un contenu auquel ils peuvent faire confiance.

Rendre l’open source plus inclusif

Red Hat s'engage à remplacer le langage problématique dans notre code, notre documentation et nos propriétés Web. Pour plus de détails, consultez leBlog Red Hat.

À propos de Red Hat

Nous proposons des solutions renforcées qui facilitent le travail des entreprises sur plusieurs plates-formes et environnements, du centre de données central à la périphérie du réseau.

© 2024 Red Hat, Inc.