Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Java EE 8 Cookbook

You're reading from   Java EE 8 Cookbook Build reliable applications with the most robust and mature technology for enterprise development

Arrow left icon
Product type Paperback
Published in Apr 2018
Publisher Packt
ISBN-13 9781788293037
Length 382 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Edson Yanaga Edson Yanaga
Author Profile Icon Edson Yanaga
Edson Yanaga
Elder Moraes Elder Moraes
Author Profile Icon Elder Moraes
Elder Moraes
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. New Features and Improvements 2. Server-Side Development FREE CHAPTER 3. Building Powerful Services with JSON and RESTful Features 4. Web- and Client-Server Communication 5. Security of Enterprise Architecture 6. Reducing the Coding Effort by Relying on Standards 7. Deploying and Managing Applications on Major Java EE Servers 8. Building Lightweight Solutions Using Microservices 9. Using Multithreading on Enterprise Context 10. Using Event-Driven Programming to Build Reactive Applications 11. Rising to the Cloud – Java EE, Containers, and Cloud Computing 12. Other Books You May Enjoy Appendix: The Power of Sharing Knowledge

Running your first Bean Validation 2.0 code

Bean Validation is a Java specification that basically helps you to protect your data. Through its API, you can validate fields and parameters, express constraints using annotations, and extend your customs' validation rules.

It can be used both with Java SE and Java EE.

In this recipe, you will have a glimpse of Bean Validation 2.0. It doesn't matter whether you are new to it or already using version 1.1; this content will help you get familiar with some of its new features.

Getting ready

First, you need to add the right Bean Validation dependency to your project, as follows:

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.8.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b10</version>
</dependency>
</dependencies>

How to do it...

  1. First, we need to create an object with some fields to be validated:
public class User {

@NotBlank
private String name;

@Email
private String email;

@NotEmpty
private List<@PositiveOrZero Integer> profileId;

public User(String name, String email, List<Integer> profileId) {
this.name = name;
this.email = email;
this.profileId = profileId;
}
}
  1. Then we create a test class to validate those constraints:
public class UserTest {

private static Validator validator;

@BeforeClass
public static void setUpClass() {
validator = Validation.buildDefaultValidatorFactory()
.getValidator();
}

@Test
public void validUser() {
User user = new User(
"elder",
"elder@eldermoraes.com",
asList(1,2));

Set<ConstraintViolation<User>> cv = validator
.validate(user);
assertTrue(cv.isEmpty());
}

@Test
public void invalidName() {
User user = new User(
"",
"elder@eldermoraes.com",
asList(1,2));

Set<ConstraintViolation<User>> cv = validator
.validate(user);
assertEquals(1, cv.size());
}

@Test
public void invalidEmail() {
User user = new User(
"elder",
"elder-eldermoraes_com",
asList(1,2));

Set<ConstraintViolation<User>> cv = validator
.validate(user);
assertEquals(1, cv.size());
}

@Test
public void invalidId() {
User user = new User(
"elder",
"elder@eldermoraes.com",
asList(-1,-2,1,2));

Set<ConstraintViolation<User>> cv = validator
.validate(user);
assertEquals(2, cv.size());
}
}

How it works...

Our User class uses three of the new constraints introduced by Bean Validation 2.0:

  • @NotBlank: Assures that the value is not null, empty, or an empty string (it trims the value before evaluation, to make sure there aren't spaces).
  • @Email: Allows only a valid email format. Forget those crazy JavaScript functions!
  • @NotEmpty: Ensures that a list has at least one item.
  • @PositiveOrZero: Guarantees that a number is equal or greater than zero.

Then we create a test class (using JUnit) to test our validations. It first instantiates Validator:

@BeforeClass
public static void setUpClass() {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}

Validator is an API that validates beans according to the constraints defined for them.

Our first test method tests a valid user, which is a User object that has:

  • Name not empty
  • Valid email
  • profileId list only with integers greater than zero:
User user = new User(
"elder",
"elder@eldermoraes.com",
asList(1,2));

And finally, the validation:

Set<ConstraintViolation<User>> cv = validator.validate(user);

The validate() method from Validator returns a set of constraint violations found, if any, or an empty set if there are no violations at all.

So, for a valid user it should return an empty set:

assertTrue(cv.isEmpty());

And the other methods work with variations around this model:

  • invalidName(): Uses an empty name
  • invalidEmail(): Uses a malformed email
  • invalidId(): Adds some negative numbers to the list

Note that the invalidId() method adds two negative numbers to the list:

asList(-1,-2,1,2));

So, we expect two constraint violations:

assertEquals(2, cv.size());

In other words, Validator checks not only the constraints violated, but how many times they are violated.

See also

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime