Welcome!

Java IoT Authors: Stackify Blog, Derek Weeks, Liz McMillan, Elizabeth White, Pat Romanski

Related Topics: Java IoT, Industrial IoT, Microservices Expo, Open Source Cloud, Machine Learning , Agile Computing

Java IoT: Blog Post

JavaBean Validation with javax Annotation and Hibernate Validator

Java EE 6 platform provides a set of annotations for bean validation

As you know modern programming paradigm suggests validating a java bean with annotations. A java bean can be validated in many ways. You can refer to my earlier article on bean validation .But we have to opt for the simplest and the robust one. With the introduction of java annotation feature, programming has become easier and lets developers to write less code. In this article I will show you the significance of Hibernate validator and javax annotation in a java bean. The api provided by hibernate validator and javax annotation has made developer’s life much easier to put validation instantly.

Java EE 6 platform provides a set of annotations for bean validation. This bean validation API can be applied to field and method level to achieve validation. Apart from that Hibernate validator provides some extra validation annotation to ease the development and also it provides the shortcut way define your own custom validation constraints.  The javax bean validation api provides below the most frequently used annotations.

javax.validation.constraints.Digits

javax.validation.constraints.Min

javax.validation.constraints.Max

javax.validation.constraints.NotNull

javax.validation.constraints.DecimalMax

javax.validation.constraints.DecimalMin

javax.validation.constraints.Pattern

javax.validation.constraints.Null

javax.validation.constraints.Size

Hibernate validator provides below the commonly used annotations for validation.

org.hibernate.validator.constraints.URL

org.hibernate.validator.constraints.NotEmpty

org.hibernate.validator.constraints.NotBlank

org.hibernate.validator.constraints.Length

org.hibernate.validator.constraints.Email

org.hibernate.validator.constraints.CreditCardNumber

In case of product or project development we have to use both the annotations for bean validation. It is always recommended to use the relevant annotations in the field level of the java bean as it increases the readability and minimizes the burden of bug fixing and maintenance problem.

How to do

In order to achieve bean validation, you have to use javax bean validation api, hibernate validator api and logging api. For the usage of this validation, you have use the following jar files mentioned below.

hibernate-validator-4.3.1.Final.jar

jboss-logging-3.1.0.CR2.jar

validation-api-1.0.0.GA.jar

All the above jar files can be downloaded from the site “mvnrepository.com”. If you are using maven project, you have to use the following dependencies as mentioned below.

<dependencies>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.11</version>

<scope>test</scope>

</dependency>

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-validator</artifactId>

<version>4.3.1.Final</version>

</dependency>

</dependencies>

The dependency for junit is optional as it depends upon your project requirement.

Let us see a brief structure of a bean provided with various annotations.

public class Bean1 {

// ~~~~~~~~~~ javax annotations for validation ~~~~~~~~~~

@Digits(integer = 2, fraction = 0, message = "The value of age can not be more than 2 digits")

@Min(value = 18, message = "The minimum age should be 18")

@Max(value = 50, message = "The maximum age can not more than be 50")

private int age;

@NotNull(message = "First Name can not be null ... ")

private String firstName;

@DecimalMax(value = "99999.999", message = "The decimal value can not be more than 99999.999 ")

@DecimalMin(value = "1.00", message = "The decimal value can not be less than 1.00 digit ")

private float amount = 0f;

@NotNull

@Pattern(regexp = "^\\d{6}", message = "Invalid zip code, Indian zip code should be 6 digit")

private String zipCode;

// ~~~~~~~~~~ Hibernate provided annotations for validation ~~~~~~~~~~

@CreditCardNumber(message = "Invalid credit card number")

private String creditCard;

@Email(message = "Invalid email id")

private String emailId;

@Length(max = 50, min = 10, message = "The message description should be within 10 to 50 characters")

private String description;

@NotBlank(message = "SurName can not be blank")

// It is only applicable to String

private String surName;

@NotEmpty(message = "The list can not be empty")

private List<String> countryList;

@URL(message = "Invalid website address")

private String website;

// ~~~~~~~~~~ Custom annotations for validation ~~~~~~~~~~

@Password

private String password;

@IBAN

private String ibanActNo;

// ~~ getter and setter methods below

}

The above java class contains many fields which require validations. If the above bean is populated with data, we have to validate the bean with the default validator provided by hibernate api. The brief code structure is given below.

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

Validator validator = factory.getValidator();

Set<ConstraintViolation<Bean1>> set = validator.validate(bean);

noOfViolations = set.size();

if (noOfViolations != 0)

throw new BeanValidationFailedException(set);

The above code is very precise and provides the a set of violations. This is all about the default annotations provided. What about your own custom annotations which may be required as per your project requirements ? Javax bean validation api provides the easiest way to define and integrate your own annotations for validation. Let us take an example of password. The rule for password is it should be within 6 to 20 characters, one special character, one upper case and one numeric character. For this purpose we have define an annotation called “Password” and we have to define one java class called “PasswordValidator” by implementing “javax.validation.ConstraintValidator”. That’s it. You are done now. You can now freely use your annotation n any java bean. Let us see the brief code structure for the above.

@Target({ METHOD, FIELD, ANNOTATION_TYPE })

@Retention(RUNTIME)

@Constraint(validatedBy = PasswordValidator.class)

public @interface Password {

/**

* This method is used to provide a default message

*

* @return

*/

String message() default "{Invalid password, valid password : one Upper case, one special char, one number, total length 6 t0 20 chars}";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

}

The above is the password annotation, the password validator class is given below.

public class PasswordValidator implements ConstraintValidator<Password, String> {

public void initialize(Password pwd) {

// do nothing

}

public boolean isValid(String str, ConstraintValidatorContext ctx) {

//Write your own business logic

return validate(str);

}

}

The complete project for the validation can be downloaded from the following link.

Download project https://www.dropbox.com/s/r4dgtz49bxyrpvw/javaxbeanvalidation.zip

You can download the complete project, extract it and import the project as maven project. If you have internet you can run the project with the command “clean compile install”. If you want to manually run the project, run the java class “App.java”.  If you do not want maven project, download all the above mentioned jar files and put the jar files inside a folder called “lib” inside your eclipse project and set the eclipse build path. In this project I have defined two custom annotations, you can also define you own annotations and test the application.

Conclusion

This article is meant for the novice user. It will give you a cleaner approach of using javax annotation and hibernate validator for the bean validation. I hope you will enjoy my article, For any queries contact me on [email protected].

<>Refences

 

http://docs.oracle.com/javaee/6/api/javax/validation/constraints/package-tree.html

http://docs.oracle.com/javaee/6/api/javax/validation/constraints/package-summary.html

http://docs.jboss.org/hibernate/validator/4.1/api/org/hibernate/validator/constraints/package-summary.html

http://docs.oracle.com/javaee/6/tutorial/doc/gircz.html

More Stories By Debadatta Mishra

Debadatta Mishra is a senior Java developer with five years of experience in the field of Java and related technologies. He has written many articles on Java-related technologies on the Internet.

@ThingsExpo Stories
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
SYS-CON Events announced today that GrapeUp, the leading provider of rapid product development at the speed of business, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market acr...
In the enterprise today, connected IoT devices are everywhere – both inside and outside corporate environments. The need to identify, manage, control and secure a quickly growing web of connections and outside devices is making the already challenging task of security even more important, and onerous. In his session at @ThingsExpo, Rich Boyer, CISO and Chief Architect for Security at NTT i3, discussed new ways of thinking and the approaches needed to address the emerging challenges of security i...
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
There is only one world-class Cloud event on earth, and that is Cloud Expo – which returns to Silicon Valley for the 21st Cloud Expo at the Santa Clara Convention Center, October 31 - November 2, 2017. Every Global 2000 enterprise in the world is now integrating cloud computing in some form into its IT development and operations. Midsize and small businesses are also migrating to the cloud in increasing numbers. Companies are each developing their unique mix of cloud technologies and service...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, will introduce two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a...
Recently, IoT seems emerging as a solution vehicle for data analytics on real-world scenarios from setting a room temperature setting to predicting a component failure of an aircraft. Compared with developing an application or deploying a cloud service, is an IoT solution unique? If so, how? How does a typical IoT solution architecture consist? And what are the essential components and how are they relevant to each other? How does the security play out? What are the best practices in formulating...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics ...
In his session at @ThingsExpo, Arvind Radhakrishnen discussed how IoT offers new business models in banking and financial services organizations with the capability to revolutionize products, payments, channels, business processes and asset management built on strong architectural foundation. The following topics were covered: How IoT stands to impact various business parameters including customer experience, cost and risk management within BFS organizations.
SYS-CON Events announced today that Elastifile will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Elastifile Cloud File System (ECFS) is software-defined data infrastructure designed for seamless and efficient management of dynamic workloads across heterogeneous environments. Elastifile provides the architecture needed to optimize your hybrid cloud environment, by facilitating efficient...
SYS-CON Events announced today that Golden Gate University will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
"We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
21st International Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Me...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
SYS-CON Events announced today that Secure Channels, a cybersecurity firm, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Secure Channels, Inc. offers several products and solutions to its many clients, helping them protect critical data from being compromised and access to computer networks from the unauthorized. The company develops comprehensive data encryption security strategie...
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...