Welcome!

Java IoT Authors: Liz McMillan, Elizabeth White, Pat Romanski, Yeshim Deniz, Jason Bloomberg

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
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...
"When we talk about cloud without compromise what we're talking about is that when people think about 'I need the flexibility of the cloud' - it's the ability to create applications and run them in a cloud environment that's far more flexible,” explained Matthew Finnie, CTO of Interoute, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
In his session at @ThingsExpo, Eric Lachapelle, CEO of the Professional Evaluation and Certification Board (PECB), provided an overview of various initiatives to certify the security of connected devices and future trends in ensuring public trust of IoT. Eric Lachapelle is the Chief Executive Officer of the Professional Evaluation and Certification Board (PECB), an international certification body. His role is to help companies and individuals to achieve professional, accredited and worldwide re...
Amazon started as an online bookseller 20 years ago. Since then, it has evolved into a technology juggernaut that has disrupted multiple markets and industries and touches many aspects of our lives. It is a relentless technology and business model innovator driving disruption throughout numerous ecosystems. Amazon’s AWS revenues alone are approaching $16B a year making it one of the largest IT companies in the world. With dominant offerings in Cloud, IoT, eCommerce, Big Data, AI, Digital Assista...
When growing capacity and power in the data center, the architectural trade-offs between server scale-up vs. scale-out continue to be debated. Both approaches are valid: scale-out adds multiple, smaller servers running in a distributed computing model, while scale-up adds fewer, more powerful servers that are capable of running larger workloads. It’s worth noting that there are additional, unique advantages that scale-up architectures offer. One big advantage is large memory and compute capacity...
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...
IoT solutions exploit operational data generated by Internet-connected smart “things” for the purpose of gaining operational insight and producing “better outcomes” (for example, create new business models, eliminate unscheduled maintenance, etc.). The explosive proliferation of IoT solutions will result in an exponential growth in the volume of IoT data, precipitating significant Information Governance issues: who owns the IoT data, what are the rights/duties of IoT solutions adopters towards t...
With the introduction of IoT and Smart Living in every aspect of our lives, one question has become relevant: What are the security implications? To answer this, first we have to look and explore the security models of the technologies that IoT is founded upon. In his session at @ThingsExpo, Nevi Kaja, a Research Engineer at Ford Motor Company, discussed some of the security challenges of the IoT infrastructure and related how these aspects impact Smart Living. The material was delivered interac...
No hype cycles or predictions of zillions of things here. IoT is big. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, Associate Partner at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He discussed the evaluation of communication standards and IoT messaging protocols, data analytics considerations, edge-to-cloud tec...
The Internet giants are fully embracing AI. All the services they offer to their customers are aimed at drawing a map of the world with the data they get. The AIs from these companies are used to build disruptive approaches that cannot be used by established enterprises, which are threatened by these disruptions. However, most leaders underestimate the effect this will have on their businesses. In his session at 21st Cloud Expo, Rene Buest, Director Market Research & Technology Evangelism at Ara...
Artificial intelligence, machine learning, neural networks. We’re in the midst of a wave of excitement around AI such as hasn’t been seen for a few decades. But those previous periods of inflated expectations led to troughs of disappointment. Will this time be different? Most likely. Applications of AI such as predictive analytics are already decreasing costs and improving reliability of industrial machinery. Furthermore, the funding and research going into AI now comes from a wide range of com...
We build IoT infrastructure products - when you have to integrate different devices, different systems and cloud you have to build an application to do that but we eliminate the need to build an application. Our products can integrate any device, any system, any cloud regardless of protocol," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that Enzu will exhibit at SYS-CON's 21st Int\ernational Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enzu’s mission is to be the leading provider of enterprise cloud solutions worldwide. Enzu enables online businesses to use its IT infrastructure to their competitive advantage. By offering a suite of proven hosting and management services, Enzu wants companies to focus on the core of their ...
SYS-CON Events announced today that Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
SYS-CON Events announced today that MobiDev, a client-oriented software development company, 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. MobiDev is a software company that develops and delivers turn-key mobile apps, websites, web services, and complex software systems for startups and enterprises. Since 2009 it has grown from a small group of passionate engineers and business...
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...
SYS-CON Events announced today that Ayehu will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara California. Ayehu provides IT Process Automation & Orchestration solutions for IT and Security professionals to identify and resolve critical incidents and enable rapid containment, eradication, and recovery from cyber security breaches. Ayehu provides customers greater control over IT infras...
In his session at Cloud Expo, Alan Winters, an entertainment executive/TV producer turned serial entrepreneur, presented a success story of an entrepreneur who has both suffered through and benefited from offshore development across multiple businesses: The smart choice, or how to select the right offshore development partner Warning signs, or how to minimize chances of making the wrong choice Collaboration, or how to establish the most effective work processes Budget control, or how to ma...
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...