Welcome!

AJAX & REA Authors: Trevor Parsons, ChandraShekar Dattatreya, Elizabeth White, Liz McMillan, David H Deans

Related Topics: Java, AJAX & REA

Java: Article

Be Standard, Be Free: Use JSR-303 for Validation

No matter what type of application we develop, coding validations is our everyday task

No matter what type of application we develop, coding validations is our everyday task. For years we have used a big variety of techniques and frameworks for validation with success. However, since some time we have a standard Java for validation, the Bean Validation specification (JSR-303). The question is: is it worth writing (or rewriting) our validations using the Bean Validation standard? Is there some practical advantage in use JSR-303?

First, let's write a validator (constraint in Bean Validation nomenclature) and then let's use it in our code, to see what we are talking about.

Creating a JSR-303 Constraint
A JSR-303 constraint is just a plain Java annotation. For example, if we want to validate ISBNs, we have to create an @ISBN annotation like the next one:

package org.openxava.books.constraints;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
import java.lang.annotation.*;
import javax.validation.*;
import org.openxava.books.constraints.impl.*;

@Constraint(validatedBy = ISBNValidator.class)
@Target({ METHOD, FIELD })
@Retention(RUNTIME)
public @interface ISBN {

String message() default
"{org.openxava.books.constraints.ISBN.message}";
Class[] groups() default { };
Class[] payload() default { };

}

The key part here is the @Constraint annotation. It marks this annotation as a constraint and indicates the validator class, ISBNValidator, that is the class with the validation logic:

package org.openxava.books.constraints.impl;

import javax.validation.*;
import org.openxava.books.constraints.*;

public class ISBNValidator implements ConstraintValidator<ISBN, String> {
    
    private static org.apache.commons.validator.ISBNValidator
validator =
        new org.apache.commons.validator.ISBNValidator();

    public void initialize(ISBN isbn) {        
    }

    public boolean isValid(String value, ConstraintValidatorContext ctx) { // The validation logic
        if (value == null || value.trim().equals("")) return true;
        return validator.isValid(value); // We simply delegate in commons validator
    }

}

The validator must implement ConstraintValidator, so it needs to have the initialize() and isValid() methods, the latter contains the validation logic. In this case we simply delegate in a validator from Apache Commons Validator project.

As we can see create a validator is pretty simple. Now, how can we use this validation in our application?

Using the Validator
The JSR-303 specification talks about how to define validators, but not about how they are used and behave in our application, this depends on the framework we are using JPA2 and JSF2 have Bean Validation integration, moreover many modern frameworks have support for JSR-303 as well. In this case we are going to develop a mini-application using the OpenXava framework that use the above @ISBN application. Don't panic, developing an OpenXava application is short (and sweet), given we only need to write the domain classes.

After creating a new OpenXava project (executing an ant target) we add the Author and Book classes to it.
Author.groovy:

package org.openxava.books.model

import javax.persistence.*
import org.openxava.model.*
import org.openxava.annotations.*

@Entity
class Author extends Identifiable {

    @Required
    String name
    
}

 

Book.groovy:

package org.openxava.books.model

import org.openxava.model.*;
import org.openxava.annotations.*;
import org.openxava.books.constraints.*;
import javax.persistence.*;

@Entity
class Book extends Identifiable {

    @Required @Column(length=60)
    String title
    
    @ManyToOne(fetch=FetchType.LAZY)
    @DescriptionsList
    Author author
    
    @Column(length=10)
    @ISBN
    String isbn
    
}


Although we could write the classes with Java, we have chosen Groovy. Yes, Groovy Web Development without Grails is possible. However, the important point here is the @ISBN annotation in isbn property. We do not need more work to see the validation working. If we go to http://localhost:8080/Books/modules/Book, and we try to add a Book with an incorrect ISBN, we'll get something like this:

As we can see using the @ISBN validation in our application is a completely declarative task, so dead easy.

Why Should I Use Bean Validation?
Though JSR-303 is easy to use and versatile enough to meet our validation needs, really is not something spectacular, and possibly not much better than our current validation framework, so, why should we use it? Because it is supported by JPA2, JSF2, Spring Roo, Wicket, Tapestry, etc. in addition to be included as part of Java EE 6. Therefore, it gives us more freedom, because our code is less dependent from the application framework we are using, thus it's easier to migrate our code (at least the model part) from Wicket to Tapestry, or from Spring Roo to OpenXava.

Use the Bean Validation standard. Be free!

Resources

More Stories By Javier Paniza

Javier Paniza is the project lead for OpenXava project. He works as software developer at Gestión 400, a software company for public administration in Spain. He has been developing with Java Enterprise since 1998. Also he has been J2EE mentor for development teams in banking projects.

@CloudExpo Stories
SYS-CON Events announced today that AIC, a leading provider of OEM/ODM server and storage solutions, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. AIC is a leading provider of both standard OTS, off-the-shelf, and OEM/ODM server and storage solutions. With expert in-house design capabilities, validation, manufacturing and production, AIC's broad selection of products are highly flexible and are conf...
SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada...
The cloud is becoming the de-facto way for enterprises to leverage common infrastructure while innovating and one of the biggest obstacles facing public cloud computing is security. In his session at 15th Cloud Expo, Jeff Aliber, a global marketing executive at Verizon, discussed how the best place for web security is in the cloud. Benefits include: Functions as the first layer of defense Easy operation –CNAME change Implement an integrated solution Best architecture for addressing network-l...
“We help people build clusters, in the classical sense of the cluster. We help people put a full stack on top of every single one of those machines. We do the full bare metal install," explained Greg Bruno, Vice President of Engineering and co-founder of StackIQ, in this SYS-CON.tv interview at 15th Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Leysin American School is an exclusive, private boarding school located in Leysin, Switzerland. Leysin selected an OpenStack-powered, private cloud as a service to manage multiple applications and provide development environments for students across the institution. Seeking to meet rigid data sovereignty and data integrity requirements while offering flexible, on-demand cloud resources to users, Leysin identified OpenStack as the clear choice to round out the school's cloud strategy. Additional...
DevOps Summit 2015 New York, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce software that is obsolete...
“DevOps is really about the business. The business is under pressure today, competitively in the marketplace to respond to the expectations of the customer. The business is driving IT and the problem is that IT isn't responding fast enough," explained Mark Levy, Senior Product Marketing Manager at Serena Software, in this SYS-CON.tv interview at DevOps Summit, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Mobile commerce traffic is surpassing desktop, yet less than 20% of sales in the U.S. are mobile commerce sales. In his session at 15th Cloud Expo, Dan Franklin, Segment Manager, Commerce, at Verizon Digital Media Services, defined mobile devices and discussed how next generation means simplification. It means taking your digital content and turning it into instantly gratifying experiences.
“In the past year we've seen a lot of stabilization of WebRTC. You can now use it in production with a far greater degree of certainty. A lot of the real developments in the past year have been in things like the data channel, which will enable a whole new type of application," explained Peter Dunkley, Technical Director at Acision, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, p...
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com...
Verizon Enterprise Solutions is simplifying the cloud-purchasing experience for its clients, with the launch of Verizon Cloud Marketplace, a key foundational component of the company's robust ecosystem of enterprise-class technologies. The online storefront will initially feature pre-built cloud-based services from AppDynamics, Hitachi Data Systems, Juniper Networks, PfSense and Tervela. Available globally to enterprises using Verizon Cloud, Verizon Cloud Marketplace provides a one-stop shop fo...
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover ...
"BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The move in recent years to cloud computing services and architectures has added significant pace to the application development and deployment environment. When enterprise IT can spin up large computing instances in just minutes, developers can also design and deploy in small time frames that were unimaginable a few years ago. The consequent move toward lean, agile, and fast development leads to the need for the development and operations sides to work very closely together. Thus, DevOps become...

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's

"Our premise is Docker is not enough. That's not a bad thing - we actually love Docker. At ActiveState all our products are based on open source technology and Docker is an up-and-coming piece of open source technology," explained Bart Copeland, President & CEO of ActiveState Software, in this SYS-CON.tv interview at DevOps Summit at Cloud Expo®, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
"People are a lot more knowledgeable about APIs now. There are two types of people who work with APIs - IT people who want to use APIs for something internal and the product managers who want to do something outside APIs for people to connect to them," explained Roberto Medrano, Executive Vice President at SOA Software, in this SYS-CON.tv interview at Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
“We are a managed services company. We have taken the key aspects of the cloud and the purposed data center and merged the two together and launched the Purposed Cloud about 18–24 months ago," explained Chetan Patwardhan, CEO of Stratogent, in this SYS-CON.tv interview at 15th Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The Internet of Things is a misnomer. That implies that everything is on the Internet, and that simply should not be - especially for things that are blurring the line between medical devices that stimulate like a pacemaker and quantified self-sensors like a pedometer or pulse tracker. The mesh of things that we manage must be segmented into zones of trust for sensing data, transmitting data, receiving command and control administrative changes, and peer-to-peer mesh messaging. In his session a...