Machine Learning Authors: Yeshim Deniz, Liz McMillan, Pat Romanski, Elizabeth White, Zakia Bouachraoui

Related Topics: Java IoT, Machine Learning

Java IoT: 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 })
public @interface ISBN {

String message() default
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.

package org.openxava.books.model

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

class Author extends Identifiable {

    String name



package org.openxava.books.model

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

class Book extends Identifiable {

    @Required @Column(length=60)
    String title
    Author author
    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!


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
David Friend is the co-founder and CEO of Wasabi, the hot cloud storage company that delivers fast, low-cost, and reliable cloud storage. Prior to Wasabi, David co-founded Carbonite, one of the world's leading cloud backup companies. A successful tech entrepreneur for more than 30 years, David got his start at ARP Instruments, a manufacturer of synthesizers for rock bands, where he worked with leading musicians of the day like Stevie Wonder, Pete Townsend of The Who, and Led Zeppelin. David has also co-founded five other companies including Computer Pictures Corporation - an early player in computer graphics, Pilot Software - a company that pioneered multidimensional databases for crunching large amounts of customer data for major retail companies, Faxnet - which became the world's largest provider of fax-to-email services, as well as Sonexis - a VoIP conferencing company.
When applications are hosted on servers, they produce immense quantities of logging data. Quality engineers should verify that apps are producing log data that is existent, correct, consumable, and complete. Otherwise, apps in production are not easily monitored, have issues that are difficult to detect, and cannot be corrected quickly. Tom Chavez presents the four steps that quality engineers should include in every test plan for apps that produce log output or other machine data. Learn the steps so your team's apps not only function but also can be monitored and understood from their machine data when running in production.
With the mainstreaming of IoT, connected devices, and sensors, data is being generated at a phenomenal rate, particularly at the edge of the network. IDC's FutureScape for IoT report found that by 2019, 40% of IoT data will be stored, processed, analyzed and acted upon at the edge of the network where it is created. Why at the edge? Turns out that sensor data, in most cases, is perishable. Its value is realized within a narrow window after its creation. Further, analytics at the edge provides other benefits.
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by FTC, CUI/DFARS, EU-GDPR and the underlying National Cybersecurity Framework suggest the need for a ground-up re-thinking of security strategies and compliance actions. This session offers actionable advice based on case studies to demonstrate the impact of security and privacy attributes for the cloud-backed IoT and AI ecosystem.
Enterprises that want to take advantage of the Digital Economy are faced with the challenge of addressing the demands of multi speed IT and omni channel enablement. They are often burdened with applications that are complex, brittle monoliths. This is usually coupled with the need to remediate an existing services layer that is not well constructed with inadequate governance and management. These enterprises need to face tremendous disruption as they get re-defined and re-invented to meet the demands of the Digital Economy. The use of a microservices approach exposed through APIs can be the solution these enterprises need to enable them to meet the increased business demands to quickly add new functionality.