Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Jakarta EE Cookbook

You're reading from   Jakarta EE Cookbook Practical recipes for enterprise Java developers to deliver large scale applications with Jakarta EE

Arrow left icon
Product type Paperback
Published in May 2020
Publisher Packt
ISBN-13 9781838642884
Length 380 pages
Edition 2nd Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
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 the Enterprise Architecture 6. Reducing Coding Effort by Relying on Standards 7. Deploying and Managing Applications on Major Jakarta 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 - Jakarta EE, Containers, and Cloud Computing 12. Other Books You May Enjoy Appendix - The Power of Sharing Knowledge

Running your first Jakarta Bean Validation 2.0 code

Jakarta 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 Jakarta EE.

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

Getting ready

First, you need to add the right Jakarta 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.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.15.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b11</version>
</dependency>
</dependencies>

How to do it...

We need to perform the following steps to try this recipe:

  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 UserTest 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());
}
}

After this, let's see how the recipe works.

How it works...

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

  • @NotBlank: This ensures 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: This allows only a valid email format. Forget those crazy JavaScript functions!
  • @NotEmpty: This ensures that a list has at least one item.
  • @PositiveOrZero: This guarantees that a number is equal to or greater than zero.

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

@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 the following:

  • Name not empty
  • Valid email
  • A profileId list only with integers greater than zero

This is shown in the following code snippet:

User user = new User(
"elder",
"elder@eldermoraes.com",
asList(1,2));

And finally, we have 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());

For the other methods that work with variations around this model, we have the following:

  • 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
Banner background image