<?xml version="1.0" encoding="UTF-8"?>
<!--
	~ JBoss, Home of Professional Open Source
	~ Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
	~ by the @authors tag. See the copyright.txt in the distribution for a
	~ full listing of individual contributors.
	~
	~ 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.
-->
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "../hv.ent">
%BOOK_ENTITIES;
]>
<chapter id="validator-integration">
  <title>Integrating with other frameworks</title>

  <para>Hibernate Validator is intended to be used to implement multi-layered
  data validation, where constraints are expressed in a single place (the
  annotated domain model) and checked in various different layers of the
  application. For this reason there are multiple integration points with
  other technologies.</para>

  <section id="validator-checkconstraints-orm">
    <title>ORM integration</title>

    <para>Hibernate Validator integrates with both Hibernate and all pure Java
    Persistence providers.</para>

    <tip>
      <para>When lazy loaded associations are supposed to be validated it is
      recommended to place the constraint on the getter of the association.
      Hibernate replaces lazy loaded associations with proxy instances which
      get initialized/loaded when requested via the getter. If, in such a
      case, the constraint is placed on field level the actual proxy instance
      is used which will lead to validation errors.</para>
    </tip>

    <section id="validator-checkconstraints-db">
      <title>Database schema-level validation</title>

      <para>Out of the box, Hibernate (as of version 3.5.x) will translate the
      constraints you have defined for your entities into mapping metadata.
      For example, if a property of your entity is annotated
      <literal>@NotNull</literal>, its columns will be declared as
      <literal>not null</literal> in the DDL schema generated by
      Hibernate.</para>

      <para>If, for some reason, the feature needs to be disabled, set
      <literal>hibernate.validator.apply_to_ddl</literal> to
      <literal>false</literal>. See also <xref
      linkend="table-spec-constraints"/> and <xref
      linkend="table-custom-constraints"/>.</para>

      <para>You can also limit the DDL constraint generation to a subset of
      the defined constraints by setting the property
      <property>org.hibernate.validator.group.ddl</property>. The property
      specifies the comma-separated, fully specified class names of the groups
      a constraint has to be part of in order to be considered for DDL schema
      generation.</para>
    </section>

    <section id="validator-checkconstraints-orm-hibernateevent">
      <title>Hibernate event-based validation</title>

      <para>Hibernate Validator has a built-in Hibernate event listener -
      <ulink
      url="http://fisheye.jboss.org/browse/Hibernate/core/trunk/annotations/src/main/java/org/hibernate/cfg/beanvalidation/BeanValidationEventListener.java"><classname>org.hibernate.cfg.beanvalidation.BeanValidationEventListener</classname></ulink>
      - which is part of Hibernate Annotations (as of Hibernate 3.5.x).
      Whenever a <literal>PreInsertEvent</literal>,
      <literal>PreUpdateEvent</literal> or
      <classname>PreDeleteEvent</classname> occurs, the listener will verify
      all constraints of the entity instance and throw an exception if any
      constraint is violated. Per default objects will be checked before any
      inserts or updates are made by Hibernate. Pre deletion events will per
      default not trigger a validation. You can configure the groups to be
      validated per event type using the properties
      <property>javax.persistence.validation.group.pre-persist</property>,
      <property>javax.persistence.validation.group.pre-update</property> and
      <property>javax.persistence.validation.group.pre-remove</property>. The
      values of these properties are the comma-separated, fully specified
      class names of the groups to validate. <xref
      linkend="example-beanvalidationeventlistener-config"/> shows the default
      values for these properties. In this case they could also be
      omitted.</para>

      <para>On constraint violation, the event will raise a runtime
      <classname>ConstraintViolationException</classname> which contains a set
      of <literal>ConstraintViolation</literal>s describing each
      failure.</para>

      <para>If Hibernate Validator is present in the classpath, Hibernate
      Annotations (or Hibernate EntityManager) will use it transparently. To
      avoid validation even though Hibernate Validator is in the classpath set
      <property>javax.persistence.validation.mode</property> to
      <constant>none</constant>.</para>

      <para><note>
          <para>If the beans are not annotated with validation annotations,
          there is no runtime performance cost.</para>
        </note></para>

      <para>In case you need to manually set the event listeners for Hibernate
      Core, use the following configuration in
      <literal>hibernate.cfg.xml</literal>:</para>

      <example id="example-beanvalidationeventlistener-config">
        <title>Manual configuration of
        <classname>BeanValidationEvenListener</classname></title>

        <programlisting language="XML" role="XML">&lt;hibernate-configuration&gt;
    &lt;session-factory&gt;
        ...
        &lt;property name="javax.persistence.validation.group.pre-persist"&gt;
            javax.validation.groups.Default
        &lt;/property&gt;
        &lt;property name="javax.persistence.validation.group.pre-update"&gt;
            javax.validation.groups.Default
        &lt;/property&gt;
        &lt;property name="javax.persistence.validation.group.pre-remove"&gt;&lt;/property&gt;
        ...
        &lt;event type="pre-update"&gt;
            &lt;listener class="org.hibernate.cfg.beanvalidation.BeanValidationEventListener"/&gt;
        &lt;/event&gt;
        &lt;event type="pre-insert"&gt;
            &lt;listener class="org.hibernate.cfg.beanvalidation.BeanValidationEventListener"/&gt;
        &lt;/event&gt;
        &lt;event type="pre-delete"&gt;
            &lt;listener class="org.hibernate.cfg.beanvalidation.BeanValidationEventListener"/&gt;
        &lt;/event&gt;
    &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;</programlisting>
      </example>
    </section>

    <section>
      <title>JPA</title>

      <para>If you are using JPA 2 and Hibernate Validator is in the classpath
      the JPA2 specification requires that Bean Validation gets enabled. The
      properties
      <property>javax.persistence.validation.group.pre-persist</property>,
      <property>javax.persistence.validation.group.pre-update</property> and
      <property>javax.persistence.validation.group.pre-remove</property> as
      described in <xref
      linkend="validator-checkconstraints-orm-hibernateevent"/> can in this
      case be configured in <filename>persistence.xml</filename>.
      <filename>persistence.xml</filename> also defines a node validation-mode
      which can be set to <constant>AUTO</constant>,
      <constant>CALLBACK</constant>, <constant>NONE</constant>. The default is
      <constant>AUTO</constant>.</para>

      <para>In a JPA 1 you will have to create and register Hibernate
      Validator yourself. In case you are using Hibernate EntityManager you
      can add a customized version of the
      <classname>BeanValidationEventListener</classname> described in <xref
      linkend="validator-checkconstraints-orm-hibernateevent"/> to your
      project and register it manually.</para>
    </section>
  </section>

  <section id="section-presentation-layer">
    <title>JSF &amp; Seam</title>

    <para>When working with JSF2 or <productname>JBoss Seam</productname> and
    Hibernate Validator (Bean Validation) is present in the runtime
    environment, validation is triggered for every field in the application.
    <xref linkend="example-jsf2"/> shows an example of the f:validateBean tag
    in a JSF page. The <property>validationGroups</property> attribute is
    optional and can be used to specify a comma seperated list of validation
    groups. The default is
    <classname>javax.validation.groups.Default</classname>. For more
    information refer to the Seam documentation or the JSF 2
    specification.</para>

    <example id="example-jsf2">
      <title>Usage of Bean Validation within JSF2</title>

      <programlisting language="XML" role="XML">&lt;h:form&gt;
  <emphasis role="bold">&lt;f:validateBean validationGroups="javax.validation.groups.Default"&gt;</emphasis>
    &lt;h:inputText value=”#{model.property}” /&gt;
    &lt;h:selectOneRadio value=”#{model.radioProperty}” &gt; ... &lt;/h:selectOneRadio&gt;
    &lt;!-- other input components here --&gt;
  <emphasis role="bold">&lt;/f:validateBean&gt;</emphasis>
&lt;/h:form&gt;
</programlisting>
    </example>

    <tip>
      <para>The integration between JSF 2 and Bean Validation is described in
      the "Bean Validation Integration" chapter of <ulink
      url="http://jcp.org/en/jsr/detail?id=314">JSR-314</ulink>. It is
      interesting to know that JSF 2 implements a custom
      <classname>MessageInterpolator</classname> to ensure ensure proper
      localization. To encourage the use of the Bean Validation message
      facility, JSF 2 will per default only display the generated Bean
      Validation message. This can, however, be configured via the application
      resource bundle by providing the following configuration
      (<parameter>{0}</parameter> is replaced with the Bean Validation message
      and <parameter>{1}</parameter> is replaced with the JSF component
      label):</para>

      <programlisting>javax.faces.validator.BeanValidator.MESSAGE={1}: {0}</programlisting>

      <para>The default is:</para>

      <programlisting>javax.faces.validator.BeanValidator.MESSAGE={0}</programlisting>
    </tip>
  </section>

  <section id="section-integration-with-cdi">
    <title>CDI</title>

    <para>As of version 1.1, Bean Validation is integrated with CDI (Contexts
    and Dependency Injection for Java<superscript>TM</superscript> EE).</para>

    <para>This integration provides CDI managed beans for
    <classname>Validator</classname> and
    <classname>ValidatorFactory</classname> and enables dependency injection
    in constraint validators as well as custom message interpolators,
    traversable resolvers, constraint validator factories and parameter name
    providers.</para>

    <para>Furthermore, parameter and return value constraints on the methods
    and constructors of CDI managed beans will automatically be validated upon
    invocation.</para>

    <para>When your application runs on a Jave EE container, this integration
    is enabled by default. When working with CDI in a Servlet container or in
    a pure Java SE environment, you can use the CDI portable extension
    provided by Hibernate Validator. To do so, add the portable extension to
    your class path as described in <xref
    linkend="section-getting-started-cdi"/>.</para>

    <section>
      <title>Dependency injection</title>

      <para>CDI's dependency injection mechanism makes it very easy to
      retrieve <classname>ValidatorFactory</classname> and
      <classname>Validator</classname> instances and use them in your managed
      beans. Just annotate instance fields of your bean with
      <classname>@javax.inject.Inject</classname> as shown in <xref
      linkend="example-dependency-injection"/>.</para>

      <example id="example-dependency-injection">
        <title>Retrieving validator factory and validator via
        <classname>@Inject</classname></title>

        <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter10.cdi.validator;

@ApplicationScoped
public class RentalStation {

	@Inject
	private ValidatorFactory validatorFactory;

	@Inject
	private Validator validator;

	//...
}</programlisting>
      </example>

      <para>The injected beans are the default validator factory and validator
      instances. In order to configure them - e.g. to use a custom message
      interpolator - you can use the Bean Validation XML descriptors as
      discussed in <xref linkend="chapter-xml-configuration"/>.</para>

      <para>If you are working with several Bean Validation providers you can
      make sure that factory and validator from Hibernate Validator are
      injected by annotating the injection points with the
      <classname>@HibernateValidator</classname> qualifier which is
      demonstrated in <xref
      linkend="example-dependency-injection-using-hv"/>.</para>

      <example id="example-dependency-injection-using-hv">
        <title>Using the @HibernateValidator qualifier annotation</title>

        <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter10.cdi.validator.qualifier;

@ApplicationScoped
public class RentalStation {

	@Inject
	@HibernateValidator
	private ValidatorFactory validatorFactory;

	@Inject
	@HibernateValidator
	private Validator validator;

	//...
}</programlisting>
      </example>

      <tip>
        <para>The fully-qualified name of the qualifier annotation is
        <classname>org.hibernate.validator.cdi.HibernateValidator</classname>.
        Be sure to not import
        <classname>org.hibernate.validator.HibernateValidator</classname>
        instead which is the <classname>ValidationProvider</classname>
        implementation used for selecting Hibernate Validator when working
        with the bootstrapping API (see <xref
        linkend="section-retrieving-validator-factory-validator"/>).</para>
      </tip>

      <para>Via <classname>@Inject</classname> you also can inject
      dependencies into constraint validators and other Bean Validation
      objects such as <classname>MessageInterpolator</classname>
      implementations etc.</para>

      <para><xref linkend="example-constraint-validator-injected-bean"/>
      demonstrates how an injected CDI bean is used in a
      <classname>ConstraintValidator</classname> implementation to determine
      whether the given constraint is valid or not. As the example shows, you
      also can work with the <classname>@PostConstruct</classname> and
      <classname>@PreDestroy</classname> callbacks to implement any required
      construction and destruction logic.</para>

      <example id="example-constraint-validator-injected-bean">
        <title>Constraint validator with injected bean</title>

        <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter10.cdi.injection;

public class ValidLicensePlateValidator
		implements ConstraintValidator&lt;ValidLicensePlate, String&gt; {

	@Inject
	private VehicleRegistry vehicleRegistry;

	@PostConstruct
	public void postConstruct() {
		//do initialization logic...
	}

	@PreDestroy
	public void preDestroy() {
		//do destruction logic...
	}

	@Override
	public void initialize(ValidLicensePlate constraintAnnotation) {
	}

	@Override
	public boolean isValid(String licensePlate, ConstraintValidatorContext constraintContext) {
		return vehicleRegistry.isValidLicensePlate( licensePlate );
	}
}</programlisting>
      </example>
    </section>

    <section>
      <title>Method validation</title>

      <para>The method interception facilities of CDI allow for a very tight
      integration with Bean Validation's method validation functionality. Just
      put constraint annotations to the parameters and return values of the
      executables of your CDI beans and they will be validated automatically
      before (parameter constraints) and after (return value constraints) a
      method or constructor is invoked.</para>

      <para>Note that no explicit interceptor binding is required, instead the
      required method validation interceptor will automatically be registered
      for all managed beans with constrained methods and constructors.</para>

      <para>You can see an example in <xref
      linkend="example-cdi-method-validation"/>.</para>

      <example id="example-cdi-method-validation">
        <title>CDI managed beans with method-level constraints</title>

        <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter10.cdi.methodvalidation;

@ApplicationScoped
public class RentalStation {

	@Valid
	public RentalStation() {
		//...
	}

	@NotNull
	@Valid
	public Car rentCar(
			@NotNull Customer customer,
			@NotNull @Future Date startDate,
			@Min(1) int durationInDays) {
		//...
	}

	@NotNull
	List&lt;Car&gt; getAvailableCars() {
		//...
	}
}</programlisting>

        <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter10.cdi.methodvalidation;

@RequestScoped
public class RentCarRequest {

	@Inject
	private RentalStation rentalStation;

	public void rentCar(String customerId, Date startDate, int duration) {
		//causes ConstraintViolationException
		rentalStation.rentCar( null, null, -1 );
	}
}</programlisting>
      </example>

      <para>Here the <classname>RentalStation</classname> bean hosts several
      method constraints. When invoking one of the
      <classname>RentalStation</classname> methods from another bean such as
      <classname>RentCarRequest</classname>, the constraints of the invoked
      method are automatically validated. If any illegal parameter values are
      passed as in the example, a
      <classname>ConstraintViolationException</classname> will be thrown by
      the method interceptor, providing detailed information on the violated
      constraints. The same is the case if the method's return value violates
      any return value constraints.</para>

      <para>Similarly, constructor constraints are validated automatically
      upon invocation. In the example the <classname>RentalStation</classname>
      object returned by the constructor will be validated since the
      constructor return value is marked with
      <classname>@Valid</classname>.</para>

      <section>
        <title>Validated executable types</title>

        <para>Bean Validation allows for a fine-grained control of the
        executable types which are automatically validated. By default,
        constraints on constructors and non-getter methods are validated.
        Therefore the <classname>@NotNull</classname> constraint on the method
        <classname>RentalStation#getAvailableCars()</classname> in <xref
        linkend="example-cdi-method-validation"/> gets not validated when the
        method is invoked.</para>

        <para>You have the following options to configure which types of
        executables are validated upon invocation:</para>

        <itemizedlist>
          <listitem>
            <para>Configure the executable types globally via the XML
            descriptor <filename>META-INF/validation.xml</filename>; see <xref
            linkend="section-configuration-validation-xml"/> for an
            example</para>
          </listitem>

          <listitem>
            <para>Use the <classname>@ValidateOnExecution</classname>
            annotation on the executable or type level</para>
          </listitem>
        </itemizedlist>

        <para>If several sources of configuration are specified for a given
        executable, <classname>@ValidateOnExecution</classname> on the
        executable level takes precedence over
        <classname>@ValidateOnExecution</classname> on the type level and
        <classname>@ValidateOnExecution</classname> generally takes precedence
        over the globally configured types in
        <filename><filename>META-INF/validation.xml</filename></filename>.</para>

        <para><xref linkend="example-using-validateonexecution"/> shows how to
        use the <classname>@ValidateOnExecution</classname> annotation:</para>

        <example id="example-using-validateonexecution">
          <title>Using <classname>@ValidateOnExecution</classname></title>

          <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter10.cdi.methodvalidation.configuration;

@ApplicationScoped
@ValidateOnExecution(type = ExecutableType.ALL)
public class RentalStation {

	@Valid
	public RentalStation() {
		//...
	}

	@NotNull
	@Valid
	@ValidateOnExecution(type = ExecutableType.NONE)
	public Car rentCar(
			@NotNull Customer customer,
			@NotNull @Future Date startDate,
			@Min(1) int durationInDays) {
		//...
	}

	@NotNull
	public List&lt;Car&gt; getAvailableCars() {
		//...
	}
}</programlisting>
        </example>

        <para>Here the method <methodname>rentCar()</methodname> won't be
        validated upon invocation because it is annotated with
        <classname>@ValidateOnExecution(type =
        ExecutableType.NONE)</classname>. In contrast, the constructor and the
        method <methodname>getAvailableCars()</methodname> will be validated
        due to <classname>@ValidateOnExecution(type =
        ExecutableType.ALL)</classname> being given on the type level.
        <classname>ExecutableType.ALL</classname> is a more compact form for
        explicitly specifying all the types
        <classname>CONSTRUCTORS</classname>,
        <classname>GETTER_METHODS</classname> and
        <classname>NON_GETTER_METHODS</classname>.</para>

        <tip>
          <para>Executable validation can be turned off globally by specifying
          <literal>&lt;executable-validation enabled="false"/&gt;</literal> in
          <filename>META-INF/validation.xml</filename>. In this case, any
          <classname>@ValidateOnExecution</classname> annotations are
          ignored.</para>
        </tip>

        <para>Note that when a method overrides or implements a super-type
        method the configuration will be taken from that overridden or
        implemented method (as given via
        <classname>@ValidateOnExecution</classname> on the method itself or on
        the super-type). This protects a client of the super-type method from
        an unexpected alteration of the configuration, e.g. disabling
        validation of an overridden executable in a sub-type.</para>

        <para>In case a CDI managed bean overrides or implements a super-type
        method and this super-type method hosts any constraints, it can happen
        that the validation interceptor is not properly registered with the
        bean, resulting in the bean's methods not being validated upon
        invocation. In this case you can specify the executable type IMPLICIT
        on the sub-class as shown in <xref
        linkend="example-using-executabletype-implicit"/>, which makes sure
        that all required metadata is discovered an the validation interceptor
        kicks in when the methods on
        <classname>ExpressRentalStation</classname> are invoked.</para>

        <example id="example-using-executabletype-implicit">
          <title>Using <classname>ExecutableType.IMPLICIT</classname></title>

          <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter10.cdi.methodvalidation.implicit;

@ValidateOnExecution(type = ExecutableType.ALL)
public interface RentalStation {

	@NotNull
	@Valid
	Car rentCar(
			@NotNull Customer customer,
			@NotNull @Future Date startDate,
			@Min(1) int durationInDays);
}</programlisting>

          <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter10.cdi.methodvalidation.implicit;

@ApplicationScoped
@ValidateOnExecution(type = ExecutableType.IMPLICIT)
public class ExpressRentalStation implements RentalStation {

	@Override
	public Car rentCar(Customer customer, Date startDate, @Min(1) int durationInDays) {
		//...
	}
}</programlisting>
        </example>
      </section>
    </section>
  </section>

  <section>
    <title>Java EE</title>

    <para>When your application runs on a Java EE application server such as
    WildFly, you also can obtain <classname>Validator</classname> and
    <classname>ValidatorFactory</classname> instances via
    <classname>@Resource</classname> injection in managed objects such as EJBs
    etc., as shown in <xref
    linkend="example-validator-resource-injection"/>.</para>

    <example id="example-validator-resource-injection">
      <title>Retrieving <classname>Validator</classname> and
      <classname>ValidatorFactory</classname> via
      <classname>@Resource</classname> injection</title>

      <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter10.javaee;

@Stateless
public class RentalStationBean {

	@Resource
	private ValidatorFactory validatorFactory;

	@Resource
	private Validator validator;

	//...
}</programlisting>
    </example>

    <para>Alternatively you can obtain a validator and a validator factory
    from JNDI under the names "java:comp/Validator" and
    "java:comp/ValidatorFactory", respectively.</para>

    <para>Similar to CDI-based injection via <classname>@Inject</classname>,
    these objects represent default validator and validator factory and thus
    can be configured using the XML descriptor
    <filename>META-INF/validation.xml</filename> (see <xref
    linkend="chapter-xml-configuration"/>).</para>

    <para>When your application is CDI-enabled, the injected objects are
    CDI-aware as well and e.g. support dependency injection in constraint
    validators.</para>
  </section>
</chapter>
