cxf-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Andrew Redko (Confluence)" <conflue...@apache.org>
Subject [CONF] Apache CXF Documentation > ValidationFeature
Date Mon, 02 Dec 2013 23:35:00 GMT
<html>
<head>
    <base href="https://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/en/2176/1/1/_/styles/combined.css?spaceKey=CXF20DOC&amp;forWysiwyg=true"
type="text/css">
    </head>
<body style="background: white;" bgcolor="white" class="email-body">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
    <h2><a href="https://cwiki.apache.org/confluence/display/CXF20DOC/ValidationFeature">ValidationFeature</a></h2>
    <h4>Page <b>edited</b> by             <a href="https://cwiki.apache.org/confluence/display/~reta">Andrew
Redko</a>
    </h4>
        <br/>
                         <h4>Changes (3)</h4>
                                 
    
<div id="page-diffs">
                    <table class="diff" cellpadding="0" cellspacing="0">
    
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >Bean Validation API has been part
of JPA 2.0 (JSR-317) and has proven to be successful and very useful, helping developers to
delegate routine validation tasks to solid, very extensible framework. It is very easy to
create own constraints, including complex cross-field ones. <br> <br></td></tr>
            <tr><td class="diff-deleted-lines" style="color:#999;background-color:#fdd;text-decoration:line-through;">h2.
JAX-RS 2.0 and Bean Validation 1.1  <br>Among many other features, JAX-RS 2.0 specification
introduces Bean Validation 1.1 support as a mandatory part of implementation. In an effort
to fulfill this requirement, Apache CXF provides full-fledge validation support for JAX-RS
/ JAX-WS endpoints, both for request parameters and response values. <br> <br></td></tr>
            <tr><td class="diff-unchanged" >h1. Dependencies <br>Bean Validation
support in Apache CXF is implementation-independent and is built solely using API. As such,
the only required dependency is: <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >{noformat} <br> <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">h1.
Common Bean Validation 1.1 Interceptors <br> <br>Generic Bean Validation 1.1 implementation
is build around two interceptors and validation provider: <br> - org.apache.cxf.validation.BeanValidationInInterceptor:
validates every input message (request) arguments against validation constraints, raises org.apache.cxf.validation.ConstraintViolationException
if any violations are encountered <br> - org.apache.cxf.validation.BeanValidationOutInterceptor:
validates every output message (response) arguments against validation constraints, raises
org.apache.cxf.validation.ResponseConstraintViolationException if any violations are encountered
<br> - org.apache.cxf.validation.BeanValidationProvider: abstracts away Bean Validation
1.1 implementation and provides useful utility methods <br> <br>Feature-specific
implementation for JAX-RS / JAX-WS is built on top of these common blocks. <br> <br></td></tr>
            <tr><td class="diff-unchanged" >h1. Bean Validation 1.1 and JAX-RS
2.0 integration <br> <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">h2.
JAX-RS 2.0 and Bean Validation 1.1  <br>Among many other features, JAX-RS 2.0 specification
introduces Bean Validation 1.1 support as a mandatory part of implementation. In an effort
to fulfill this requirement, Apache CXF provides full-fledge validation support for JAX-RS
/ JAX-WS endpoints, both for request parameters and response values. <br> <br></td></tr>
            <tr><td class="diff-unchanged" >Bean Validation 1.1 support in JAX-RS
2.0 is built on top of three main components: <br> - in-interceptor (org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor):
validates REST/WS endpoint parameters before invoking the method <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
    
            </table>
    </div>                            <h4>Full Content</h4>
                    <div class="notificationGreySide">
        <p><span style="font-size:2em;font-weight:bold"> Bean Validation Feature
</span></p>

<div>
<ul>
    <li><a href='#ValidationFeature-Introduction'>Introduction</a></li>
    <li><a href='#ValidationFeature-Dependencies'>Dependencies</a></li>
<ul>
    <li><a href='#ValidationFeature-UsingHibernateValidatorasbeanvalidationprovider'>Using
Hibernate Validator as bean validation provider</a></li>
    <li><a href='#ValidationFeature-UsingApacheBValasbeanvalidationprovider'>Using
Apache BVal as bean validation provider</a></li>
</ul>
    <li><a href='#ValidationFeature-CommonBeanValidation1.1Interceptors'>Common
Bean Validation 1.1 Interceptors</a></li>
    <li><a href='#ValidationFeature-BeanValidation1.1andJAXRS2.0integration'>Bean
Validation 1.1 and JAX-RS 2.0 integration</a></li>
<ul>
    <li><a href='#ValidationFeature-JAXRS2.0andBeanValidation1.1'>JAX-RS 2.0 and
Bean Validation 1.1</a></li>
    <li><a href='#ValidationFeature-ConfiguringBeanValidation1.1usingJAXRSServerFactoryBean'>Configuring
Bean Validation 1.1 using JAXRSServerFactoryBean</a></li>
    <li><a href='#ValidationFeature-ConfiguringBeanValidation1.1usingSpringbeandefinitionsXML'>Configuring
Bean Validation 1.1 using Spring bean definitions XML</a></li>
    <li><a href='#ValidationFeature-ValidationExceptionsandHTTPstatuscodes'>Validation
Exceptions and HTTP status codes</a></li>
</ul>
    <li><a href='#ValidationFeature-Examples'>Examples</a></li>
<ul>
    <li><a href='#ValidationFeature-Validatingsimpleinputparameters'>Validating
simple input parameters</a></li>
    <li><a href='#ValidationFeature-Validatingcomplexinputparameters'>Validating
complex input parameters</a></li>
    <li><a href='#ValidationFeature-Validatingreturnvalues%28nonResponse%29'>Validating
return values (non-Response)</a></li>
    <li><a href='#ValidationFeature-Validatingreturnvalues%28Response%29'>Validating
return values (Response)</a></li>
</ul>
</ul></div>

<h1><a name="ValidationFeature-Introduction"></a>Introduction</h1>

<p>Bean Validation 1.1 (JSR-349), an evolution of Bean Validation 1.0 (JSR-303), introduces
a very powerful concepts of declarative constraints (based on Java annotations) to define
the expectation for:</p>
<ul class="alternate" type="square">
	<li>properties of JavaBeans</li>
	<li>method / contructor parameters</li>
	<li>method return values</li>
</ul>


<p>Here are couple of typical examples:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
public class Person {
    @NotNull private String firstName;
    @NotNull private String lastName;
    @Valid @NotNull private Person boss;

    public @NotNull String saveItem( @Valid @NotNull Person person, @Max( 23 ) BigDecimal
age ) {
        // ...
    }
}
</pre>
</div></div>

<p>Bean Validation API has been part of JPA 2.0 (JSR-317) and has proven to be successful
and very useful, helping developers to delegate routine validation tasks to solid, very extensible
framework. It is very easy to create own constraints, including complex cross-field ones.</p>

<h1><a name="ValidationFeature-Dependencies"></a>Dependencies</h1>
<p>Bean Validation support in Apache CXF is implementation-independent and is built
solely using API. As such, the only required dependency is:</p>
<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent
panelContent">
<pre>&lt;dependency&gt;
    &lt;groupId&gt;javax.validation&lt;/groupId&gt;
    &lt;artifactId&gt;validation-api&lt;/artifactId&gt;
    &lt;version&gt;1.1.0.Final&lt;/version&gt;
&lt;/dependency&gt;
</pre>
</div></div>

<p>API doesn't provide implementation but there are couple of choices to pick from.
Please notice that bean validation implementation is taken from the ones present in classpath.
If no implementation is detected, bean validation is not available for use and constraints
validation won't have any effect. </p>

<h2><a name="ValidationFeature-UsingHibernateValidatorasbeanvalidationprovider"></a>Using
Hibernate Validator as bean validation provider</h2>
<p><a href="http://www.hibernate.org/subprojects/validator.html" class="external-link"
rel="nofollow">http://www.hibernate.org/subprojects/validator.html</a></p>

<p>Hibernate Validator is mature and feature-rich validation provider with full support
of Bean Validation 1.1 (as of version 5.x.x which is the reference implementation for JSR
349 - Bean Validation 1.1 API). To use Hibernate Validator in your Apache CXF projects, couple
of additional dependencies should be included:</p>

<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent
panelContent">
<pre>&lt;dependency&gt;
    &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
    &lt;artifactId&gt;hibernate-validator&lt;/artifactId&gt;
    &lt;version&gt;5.0.1.Final&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;javax.el&lt;/groupId&gt;
    &lt;artifactId&gt;javax.el-api&lt;/artifactId&gt;
    &lt;version&gt;3.0-b02&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.glassfish&lt;/groupId&gt;
    &lt;artifactId&gt;javax.el&lt;/artifactId&gt;
    &lt;version&gt;3.0-b01/version&gt;
&lt;/dependency&gt;
</pre>
</div></div>

<p>Hibernate Validator uses Java Expression Language 3.0 in order to provide better
validation messages support so the respective EL 3.0 API and implementation dependencies should
be included.  </p>

<h2><a name="ValidationFeature-UsingApacheBValasbeanvalidationprovider"></a>Using
Apache BVal as bean validation provider</h2>
<p><a href="http://bval.apache.org/" class="external-link" rel="nofollow">http://bval.apache.org/</a></p>

<p>Current stable version of Apache BVal (0.5) doesn't support Bean Validation 1.1 but
the upcoming 1.1.0 should have it fully implemented (at the moment 1.1.0-alpha-SNAPSHOT could
be used).</p>
<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent
panelContent">
<pre>&lt;dependency&gt;
    &lt;groupId&gt;org.apache.bval&lt;/groupId&gt;
    &lt;artifactId&gt;bval-jsr&lt;/artifactId&gt;
    &lt;version&gt;1.1.0-alpha-SNAPSHOT&lt;/version&gt;
&lt;/dependency&gt;
</pre>
</div></div>

<h1><a name="ValidationFeature-CommonBeanValidation1.1Interceptors"></a>Common
Bean Validation 1.1 Interceptors</h1>

<p>Generic Bean Validation 1.1 implementation is build around two interceptors and validation
provider:</p>
<ul class="alternate" type="square">
	<li>org.apache.cxf.validation.BeanValidationInInterceptor: validates every input message
(request) arguments against validation constraints, raises org.apache.cxf.validation.ConstraintViolationException
if any violations are encountered</li>
	<li>org.apache.cxf.validation.BeanValidationOutInterceptor: validates every output
message (response) arguments against validation constraints, raises org.apache.cxf.validation.ResponseConstraintViolationException
if any violations are encountered</li>
	<li>org.apache.cxf.validation.BeanValidationProvider: abstracts away Bean Validation
1.1 implementation and provides useful utility methods</li>
</ul>


<p>Feature-specific implementation for JAX-RS / JAX-WS is built on top of these common
blocks.</p>

<h1><a name="ValidationFeature-BeanValidation1.1andJAXRS2.0integration"></a>Bean
Validation 1.1 and JAX-RS 2.0 integration</h1>

<h2><a name="ValidationFeature-JAXRS2.0andBeanValidation1.1"></a>JAX-RS
2.0 and Bean Validation 1.1 </h2>
<p>Among many other features, JAX-RS 2.0 specification introduces Bean Validation 1.1
support as a mandatory part of implementation. In an effort to fulfill this requirement, Apache
CXF provides full-fledge validation support for JAX-RS / JAX-WS endpoints, both for request
parameters and response values.</p>

<p>Bean Validation 1.1 support in JAX-RS 2.0 is built on top of three main components:</p>
<ul class="alternate" type="square">
	<li>in-interceptor (org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor):
validates REST/WS endpoint parameters before invoking the method</li>
	<li>out-interceptor (org.apache.cxf.jaxrs.validation.JAXRSBeanValidationOutInterceptor):
validates REST/WS endpoint return value after the method invocation</li>
	<li>exception mapper (org.apache.cxf.jaxrs.validation.ValidationExceptionMapper): transforms
any ValidationException to corresponding HTTP status code</li>
</ul>


<p>All these components may share the single instance of org.apache.cxf.validation.BeanValidationProvider
which actually delegates all validation logic to available Bean Validation 1.1 implementation.</p>

<h2><a name="ValidationFeature-ConfiguringBeanValidation1.1usingJAXRSServerFactoryBean"></a>Configuring
Bean Validation 1.1 using JAXRSServerFactoryBean</h2>

<p>It's quite easy to enable bean validation support using JAXRSServerFactoryBean as
following code snippet shows:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
sf.setResourceClasses( ... );
sf.setResourceProvider( ... );
sf.setProvider(new ValidationExceptionMapper());
sf.setInInterceptors(Arrays.&lt; Interceptor&lt; ? extends Message &gt; &gt;asList(new
new JAXRSBeanValidationInInterceptor()));
sf.setOutInterceptors(Arrays.&lt; Interceptor&lt; ? extends Message &gt; &gt;asList(new
JAXRSBeanValidationOutInterceptor()));
sf.create();
</pre>
</div></div>

<h2><a name="ValidationFeature-ConfiguringBeanValidation1.1usingSpringbeandefinitionsXML"></a>Configuring
Bean Validation 1.1 using Spring bean definitions XML</h2>

<p>Following the similar approach as for JAXRSServerFactoryBean, in case of Spring respective
bean definitions should be added under &lt;jaxrs:outInterceptors&gt;, &lt;jaxrs:inInterceptors&gt;
and &lt;jaxrs:providers&gt; sections, f.e.:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
&lt;jaxrs:server address="/"&gt;
    &lt;jaxrs:inInterceptors&gt;
        &lt;ref bean="validationInInterceptor" /&gt;
    &lt;/jaxrs:inInterceptors&gt;
        
    &lt;jaxrs:outInterceptors&gt;
        &lt;ref bean="validationOutInterceptor" /&gt;
    &lt;/jaxrs:outInterceptors&gt;
        
    &lt;jaxrs:serviceBeans&gt;
    ...
    &lt;/jaxrs:serviceBeans&gt;
        
    &lt;jaxrs:providers&gt;
        &lt;ref bean="exceptionMapper"/&gt;
    &lt;/jaxrs:providers&gt;
&lt;/jaxrs:server&gt;

&lt;bean id="exceptionMapper" class="org.apache.cxf.jaxrs.validation.ValidationExceptionMapper"/&gt;
&lt;bean id="validationProvider" class="org.apache.cxf.validation.BeanValidationProvider"
/&gt;

&lt;bean id="validationInInterceptor" class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor"&gt;
    &lt;property name="provider" ref="validationProvider" /&gt;
&lt;/bean&gt;

&lt;bean id="validationOutInterceptor" class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationOutInterceptor"&gt;
    &lt;property name="provider" ref="validationProvider" /&gt;
&lt;/bean&gt;   
</pre>
</div></div>

<h2><a name="ValidationFeature-ValidationExceptionsandHTTPstatuscodes"></a>Validation
Exceptions and HTTP status codes</h2>

<p>As per JAX-RS 2.0 specification, any input parameter validation violation is mapped
to HTTP status code 400 Bad Request and any return value validation violation (or internal
validation violation) is mapped to HTTP status code 500 Internal Server Error. This is essentially
what org.apache.cxf.jaxrs.validation.ValidationExceptionMapper does.</p>
<div class='panelMacro'><table class='noteMacro'><colgroup><col width='24'><col></colgroup><tr><td
valign='top'><img src="/confluence/images/icons/emoticons/warning.gif" width="16" height="16"
align="absmiddle" alt="" border="0"></td><td>At the moment, the details of
validation exceptions are not included into the response. The reason why is that error reporting
logic is application-specific and may vary from application to application (f.e. it could
be simple 'text/html' with error message, or 'application/json', or HTTP custom headers, ...).
Application developers are encouraged to provide own implementation of this particular functionality.</td></tr></table></div>

<h1><a name="ValidationFeature-Examples"></a>Examples</h1>

<p>You can use any predefined validation annotation as well as define your own as far
as it follows Bean Validation 1.1 specification. This section includes couple of typical scenarios.</p>

<h2><a name="ValidationFeature-Validatingsimpleinputparameters"></a>Validating
simple input parameters</h2>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
@POST
@Path("/books")
public Response addBook(
        @NotNull @Pattern(regexp = "\\d+") @FormParam("id") String id,
        @NotNull @Size(min = 1, max = 50) @FormParam("name") String name) {
    // ...
}
</pre>
</div></div>

<h2><a name="ValidationFeature-Validatingcomplexinputparameters"></a>Validating
complex input parameters</h2>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
@POST
@Path("/books")
public Response addBook( @Valid Book book ) {
    // ...
}
</pre>
</div></div>

<p>This example assumes that class Book has validation constraints defined, f.e.:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
public class Book {
    @NotNull @Pattern(regexp = "\\d+") private String id;
    @NotNull @Size(min = 1, max = 50) private String name;

    // ...
}
</pre>
</div></div>

<h2><a name="ValidationFeature-Validatingreturnvalues%28nonResponse%29"></a>Validating
return values (non-Response)</h2>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
@GET
@Path("/books/{bookId}")
@Override    
@NotNull @Valid
public Book getBook(@PathParam("bookId") String id) {
    // ...     
}
</pre>
</div></div>

<p>This example assumes that class Book has validation constraints defined (as in example
above).</p>

<h2><a name="ValidationFeature-Validatingreturnvalues%28Response%29"></a>Validating
return values (Response)</h2>

<p>Returning Response object stands aside from all other usage scenarios. Usually, Response
is a holder for another object (entity) but because Response has no validation constraints
defined, the inner object (entity) is not validatable even if it has full set of validation
constraints . Unfortunately, this particular use case is not described in JAX-RS 2.0 specification.
Nevertheless, Apache CXF team thinks that such a validation would be beneficial and performs
a simple trick: whenever Response is being returned, all defined for it validation constraints
will be applied not to Response instance itself but to the entity it holds.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family:
ConfluenceInstalledFont,monospace;">
@GET
@Path("/books/{bookId}")
@Valid @NotNull
public Response getBookResponse(@PathParam("bookId") String id) {
    return Response.ok( new Book( id ) ).build();
}
</pre>
</div></div>
    </div>
        <div id="commentsSection" class="wiki-content pageSection">
        <div style="float: right;" class="grey">
                        <a href="https://cwiki.apache.org/confluence/users/removespacenotification.action?spaceKey=CXF20DOC">Stop
watching space</a>
            <span style="padding: 0px 5px;">|</span>
                <a href="https://cwiki.apache.org/confluence/users/editmyemailsettings.action">Change
email notification preferences</a>
</div>
        <a href="https://cwiki.apache.org/confluence/display/CXF20DOC/ValidationFeature">View
Online</a>
        |
        <a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=34842111&revisedVersion=8&originalVersion=7">View
Changes</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message