Validating constraints with microservices

duration 20 minutes

Prerequisites:

Explore the use of bean validation to validate user input data for microservices.

What you’ll learn

You will learn the basics of writing and testing a microservice that uses bean validation and the new functionality of Bean Validation 2.0. The service uses bean validation to validate that the supplied JavaBeans meet the defined constraints.

Bean Validation is a Java specification that simplifies data validation and error checking. Bean validation uses a standard way to validate data stored in JavaBeans. Validation can be performed manually or with integration with other specifications and frameworks, such as Contexts and Dependency Injection (CDI), Java Persistence API (JPA), or JavaServer Faces (JSF). To set rules on data, apply constraints by using annotations or XML configuration files. Bean validation provides both built-in constraints and the ability to create custom constraints. Bean validation allows for validation of both JavaBean fields and methods. For method-level validation, both the input parameters and return value can be validated.

Several additional built-in constraints are included in Bean Validation 2.0, which reduces the need for custom validation in common validation scenarios. Some of the new built-in constraints include @Email, @NotBlank, @Positive, and @Negative. Also in Bean Validation 2.0, you can now specify constraints on type parameters.

The example microservice uses both field-level and method-level validation as well as several of the built-in constraints and a custom constraint.

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone https://github.com/openliberty/guide-bean-validation.git
cd guide-bean-validation

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project that you will build.

Try what you’ll build

The finish directory in the root of this guide contains the finished application. Give it a try before you proceed.

To try out the application, first go to the finish directory and run the following Maven goal to build the application and deploy it to Open Liberty:

mvn liberty:run

After you see the following message, your application server is ready.

The defaultServer server is ready to run a smarter planet.

Point your browser to the http://localhost:9080/openapi/ui URL. You see the OpenAPI user interface documenting the REST endpoints used in this guide. If you are interested in learning more about OpenAPI, read Documenting RESTful APIs. Expand the /beanvalidation/validatespacecraft POST request to validate your spacecraft bean section and click Try it out. Copy the following example input into the text box:

{
  "astronaut": {
    "name": "Libby",
    "age": 25,
    "emailAddress": "[email protected]"
  },
  "destinations": {
    "Mars": 500
  },
  "serialNumber": "Liberty0001"
}

Click Execute and you receive the response No Constraint Violations because the values specified pass the constraints you will create in this guide. Now try copying the following value into the box:

{
  "astronaut": {
    "name": "Libby",
    "age": 12,
    "emailAddress": "[email protected]"
  },
  "destinations": {
    "Mars": 500
  },
  "serialNumber": "Liberty0001"
}

This time you receive Constraint Violation Found: must be greater than or equal to 18 as a response because the age specified was under the minimum age of 18. Try other combinations of values to get a feel for the constraints that will be defined in this guide.

After you are finished checking out the application, stop the Open Liberty server by pressing CTRL+C in the command-line session where you ran the server. Alternatively, you can run the liberty:stop goal from the finish directory in another shell session:

mvn liberty:stop

Applying constraints on the JavaBeans

Navigate to the start directory to begin.

When you run Open Liberty in development mode, known as dev mode, the server listens for file changes and automatically recompiles and deploys your updates whenever you save a new change. Run the following goal to start Open Liberty in dev mode:

mvn liberty:dev

After you see the following message, your application server in dev mode is ready:

Press the Enter key to run tests on demand.

Dev mode holds your command-line session to listen for file changes. Open another command-line session to continue, or open the project in your editor.

First, create the JavaBeans to be constrained.

Create the Astronaut class.
src/main/java/io/openliberty/guides/beanvalidation/Astronaut.java

Astronaut.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2019 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - initial API and implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.beanvalidation;
14
15import java.io.Serializable;
16import javax.validation.constraints.Max;
17import javax.validation.constraints.Min;
18import javax.validation.constraints.NotBlank;
19import javax.validation.constraints.Email;
20
21// tag::Astronaut[]
22public class Astronaut implements Serializable {
23
24    private static final long serialVersionUID = 1L;
25
26    // tag::not-blank[]
27    @NotBlank
28    // end::not-blank[]
29    // tag::Name[]
30    private String name;
31    // end::Name[]
32
33    // tag::Min[]
34    @Min(18)
35    // end::Min[]
36    // tag::Max[]
37    @Max(100)
38    // end::Max[]
39    // tag::age[]
40    private Integer age;
41    // end::age[]
42
43    // tag::Email[]
44    @Email
45    // end::Email[]
46    // tag::emailAddress[]
47    private String emailAddress;
48    // end::emailAddress[]
49
50    public Astronaut() {}
51
52    public String getName() {
53        return name;
54    }
55
56    public Integer getAge() {
57        return age;
58    }
59
60    public String getEmailAddress() {
61        return emailAddress;
62    }
63
64    public void setName(String name) {
65        this.name = name;
66    }
67
68    public void setAge(Integer age) {
69        this.age = age;
70    }
71
72    public void setEmailAddress(String emailAddress) {
73        this.emailAddress = emailAddress;
74    }
75}
76// end::Astronaut[]

The bean stores the attributes of an astronaut, name, age, and emailAddress, and provides getters and setters to access and set the values.

The Astronaut class has the following constraints applied:

  • The astronaut needs to have a name. Bean Validation 2.0 provides a built-in @NotBlank constraint, which ensures the value is not null and contains one non-whitespace character. The annotation constrains the name field.

  • The email supplied needs to be a valid email address. Another built-in constraint in Bean Validation 2.0 is @Email, which can validate that the Astronaut bean includes a correctly formatted email address. The annotation constrains the emailAddress field.

  • The astronaut needs to be between 18 and 100 years old. Bean validation allows you to specify multiple constraints on a single field. The @Min and @Max built-in constraints applied to the age field check that the astronaut is between the ages of 18 and 100.

In this example, the annotation is on the field value itself. You can also place the annotation on the getter method, which has the same effect.

Create the Spacecraft class.
src/main/java/io/openliberty/guides/beanvalidation/Spacecraft.java

Spacecraft.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2018 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - initial API and implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13package io.openliberty.guides.beanvalidation;
 14
 15import java.io.Serializable;
 16import java.util.Map;
 17import java.util.HashMap;
 18
 19import javax.validation.constraints.NotBlank;
 20import javax.validation.constraints.Positive;
 21import javax.validation.constraints.NotNull;
 22import javax.validation.constraints.AssertTrue;
 23import javax.inject.Named;
 24import javax.enterprise.context.RequestScoped;
 25import javax.validation.Valid;
 26
 27@Named
 28@RequestScoped
 29// tag::Spacecraft[]
 30public class Spacecraft implements Serializable {
 31
 32    private static final long serialVersionUID = 1L;
 33
 34    // tag::Valid[]
 35    @Valid
 36    // end::Valid[]
 37    // tag::Astronaut[]
 38    private Astronaut astronaut;
 39    // end::Astronaut[]
 40
 41    // tag::Map[]
 42    private Map<@NotBlank String, @Positive Integer> destinations;
 43    // end::Map[]
 44
 45    // tag::serial-num[]
 46    @SerialNumber
 47    // end::serial-num[]
 48    // tag::serialNumber[]
 49    private String serialNumber;
 50    // end::serialNumber[]
 51
 52    public Spacecraft() {
 53        destinations = new HashMap<String, Integer>();
 54    }
 55
 56    public void setAstronaut(Astronaut astronaut) {
 57        this.astronaut = astronaut;
 58    }
 59
 60    public void setDestinations(Map<String,Integer> destinations) {
 61        this.destinations = destinations;
 62    }
 63
 64    public void setSerialNumber(String serialNumber) {
 65        this.serialNumber = serialNumber;
 66    }
 67
 68    public Astronaut getAstronaut() {
 69        return astronaut;
 70    }
 71
 72    public Map<String, Integer> getDestinations() {
 73        return destinations;
 74    }
 75
 76    public String getSerialNumber() {
 77        return serialNumber;
 78    }
 79
 80    // tag::AssertTrue[]
 81    @AssertTrue
 82    // end::AssertTrue[]
 83    // tag::launchSpacecraft[]
 84    // tag::launchCode[]
 85    public boolean launchSpacecraft(@NotNull String launchCode) {
 86    // end::launchCode[]
 87        // tag::OpenLiberty[]
 88        if(launchCode.equals("OpenLiberty"))
 89        // end::OpenLiberty[]
 90            // tag::true[]
 91            return true;
 92            // end::true[]
 93        // tag::false[]
 94        return false;
 95        // end::false[]
 96    }
 97    // end::launchSpacecraft[]
 98}
 99// end::Spacecraft[]

The Spacecraft bean contains 3 fields, astronaut, serialNumber, and destinations. The JavaBean needs to be a CDI managed bean to allow for method-level validation, which uses CDI interceptions. Because the Spacecraft bean is a CDI managed bean, a scope is necessary. A request scope is used in this example. To learn more about CDI, see Injecting dependencies into microservices.

The Spacecraft class has the following constraints applied:

  • Every destination that is specified needs a name and a positive distance. In Bean Validation 2.0, you can specify constraints on type parameters. The @NotBlank and @Positive annotations constrain the destinations map so that the destination name is not blank, and the distance is positive. The @Positive constraint ensures that numeric value fields are greater than 0.

  • A correctly formatted serial number is required. In addition to specifying the built-in constraints, you can create custom constraints to allow user-defined validation rules. The @SerialNumber annotation that constrains the serialNumber field is a custom constraint, which will be created later.

Because you already specified constraints on the Astronaut bean, the constraints do not need to be respecified in the Spacecraft bean. Instead, because of the @Valid annotation on the field, all the nested constraints on the Astronaut bean are validated.

You can also use bean validation with CDI to provide method-level validation. The launchSpacecraft() method on the Spacecraft bean accepts a launchCode parameter, and if the launchCode parameter is OpenLiberty, the method returns true that the spacecraft is launched. Otherwise, the method returns false. The launchSpacecraft() method uses both parameter and return value validation. The @NotNull constraint eliminates the need to manually check within the method that the parameter is not null. Additionally, the method has the @AssertTrue return-level constraint to enforce that the method must return the true boolean.

Creating custom constraints

To create the custom constraint for @SerialNumber, begin by creating an annotation.

Spacecraft.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2018 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - initial API and implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13package io.openliberty.guides.beanvalidation;
 14
 15import java.io.Serializable;
 16import java.util.Map;
 17import java.util.HashMap;
 18
 19import javax.validation.constraints.NotBlank;
 20import javax.validation.constraints.Positive;
 21import javax.validation.constraints.NotNull;
 22import javax.validation.constraints.AssertTrue;
 23import javax.inject.Named;
 24import javax.enterprise.context.RequestScoped;
 25import javax.validation.Valid;
 26
 27@Named
 28@RequestScoped
 29// tag::Spacecraft[]
 30public class Spacecraft implements Serializable {
 31
 32    private static final long serialVersionUID = 1L;
 33
 34    // tag::Valid[]
 35    @Valid
 36    // end::Valid[]
 37    // tag::Astronaut[]
 38    private Astronaut astronaut;
 39    // end::Astronaut[]
 40
 41    // tag::Map[]
 42    private Map<@NotBlank String, @Positive Integer> destinations;
 43    // end::Map[]
 44
 45    // tag::serial-num[]
 46    @SerialNumber
 47    // end::serial-num[]
 48    // tag::serialNumber[]
 49    private String serialNumber;
 50    // end::serialNumber[]
 51
 52    public Spacecraft() {
 53        destinations = new HashMap<String, Integer>();
 54    }
 55
 56    public void setAstronaut(Astronaut astronaut) {
 57        this.astronaut = astronaut;
 58    }
 59
 60    public void setDestinations(Map<String,Integer> destinations) {
 61        this.destinations = destinations;
 62    }
 63
 64    public void setSerialNumber(String serialNumber) {
 65        this.serialNumber = serialNumber;
 66    }
 67
 68    public Astronaut getAstronaut() {
 69        return astronaut;
 70    }
 71
 72    public Map<String, Integer> getDestinations() {
 73        return destinations;
 74    }
 75
 76    public String getSerialNumber() {
 77        return serialNumber;
 78    }
 79
 80    // tag::AssertTrue[]
 81    @AssertTrue
 82    // end::AssertTrue[]
 83    // tag::launchSpacecraft[]
 84    // tag::launchCode[]
 85    public boolean launchSpacecraft(@NotNull String launchCode) {
 86    // end::launchCode[]
 87        // tag::OpenLiberty[]
 88        if(launchCode.equals("OpenLiberty"))
 89        // end::OpenLiberty[]
 90            // tag::true[]
 91            return true;
 92            // end::true[]
 93        // tag::false[]
 94        return false;
 95        // end::false[]
 96    }
 97    // end::launchSpacecraft[]
 98}
 99// end::Spacecraft[]
Replace the annotation.
src/main/java/io/openliberty/guides/beanvalidation/SerialNumber.java

SerialNumber.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - initial API and implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.beanvalidation;
14
15import java.lang.annotation.Documented;
16import java.lang.annotation.Retention;
17import java.lang.annotation.Target;
18import static java.lang.annotation.ElementType.FIELD;
19import static java.lang.annotation.RetentionPolicy.RUNTIME;
20
21import javax.validation.Constraint;
22import javax.validation.Payload;
23
24// tag::Target[]
25@Target({ FIELD })
26// end::Target[]
27// tag::Retention[]
28@Retention(RUNTIME)
29// end::Retention[]
30@Documented
31// tag::Constraint[]
32@Constraint(validatedBy = { SerialNumberValidator.class })
33// end::Constraint[]
34// tag::SerialNumber[]
35public @interface SerialNumber {
36
37    // tag::message[]
38    String message() default "serial number is not valid.";
39    // end::message[]
40
41    // tag::groups[]
42    Class<?>[] groups() default {};
43    // end::groups[]
44
45    // tag::payload[]
46    Class<? extends Payload>[] payload() default {};
47    // end::payload[]
48}
49// end::SerialNumber[]

The @Target annotation indicates the element types to which you can apply the custom constraint. Because the @SerialNumber constraint is used only on a field, only the FIELD target is specified.

When you define a constraint annotation, the specification requires the RUNTIME retention policy.

The @Constraint annotation specifies the class that contains the validation logic for the custom constraint.

In the SerialNumber body, the message() method provides the message that is output when a validation constraint is violated. The groups() and payload() methods associate this constraint only with certain groups or payloads. The defaults are used in the example.

Now, create the class that provides the validation for the @SerialNumber constraint.

Replace the SerialNumberValidator class.
src/main/java/io/openliberty/guides/beanvalidation/SerialNumberValidator.java

SerialNumberValidator.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - initial API and implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.beanvalidation;
14
15import javax.validation.ConstraintValidator;
16import javax.validation.ConstraintValidatorContext;
17
18// tag::SerialNumberValidator[]
19public class SerialNumberValidator
20    implements ConstraintValidator<SerialNumber,Object> {
21
22    @Override
23    // tag::isValid[]
24    public boolean isValid(Object arg0, ConstraintValidatorContext arg1) {
25        //Serial Numbers must start with Liberty followed by four numbers
26        boolean isValid = false;
27        if (arg0 == null)
28            return isValid;
29        String serialNumber = arg0.toString();
30        // tag::Liberty[]
31        isValid = serialNumber.length() == 11 && serialNumber.startsWith("Liberty");
32        // end::Liberty[]
33        try {
34            Integer.parseInt(serialNumber.substring(7));
35        } catch (Exception ex) {
36            isValid = false;
37        }
38        return isValid;
39    }
40    // end::isValid[]
41}
42// end::SerialNumberValidator[]

The SerialNumberValidator class has one method, isValid(), which contains the custom validation logic. In this case, the serial number must start with Liberty followed by 4 numbers, such as Liberty0001. If the supplied serial number matches the constraint, isValid() returns true. If the serial number does not match, it returns false.

Programmatically validating constraints

Finally, create a service that can be used to programmatically validate the constraints on the Spacecraft and Astronaut JavaBeans.

Spacecraft.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2018 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - initial API and implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13package io.openliberty.guides.beanvalidation;
 14
 15import java.io.Serializable;
 16import java.util.Map;
 17import java.util.HashMap;
 18
 19import javax.validation.constraints.NotBlank;
 20import javax.validation.constraints.Positive;
 21import javax.validation.constraints.NotNull;
 22import javax.validation.constraints.AssertTrue;
 23import javax.inject.Named;
 24import javax.enterprise.context.RequestScoped;
 25import javax.validation.Valid;
 26
 27@Named
 28@RequestScoped
 29// tag::Spacecraft[]
 30public class Spacecraft implements Serializable {
 31
 32    private static final long serialVersionUID = 1L;
 33
 34    // tag::Valid[]
 35    @Valid
 36    // end::Valid[]
 37    // tag::Astronaut[]
 38    private Astronaut astronaut;
 39    // end::Astronaut[]
 40
 41    // tag::Map[]
 42    private Map<@NotBlank String, @Positive Integer> destinations;
 43    // end::Map[]
 44
 45    // tag::serial-num[]
 46    @SerialNumber
 47    // end::serial-num[]
 48    // tag::serialNumber[]
 49    private String serialNumber;
 50    // end::serialNumber[]
 51
 52    public Spacecraft() {
 53        destinations = new HashMap<String, Integer>();
 54    }
 55
 56    public void setAstronaut(Astronaut astronaut) {
 57        this.astronaut = astronaut;
 58    }
 59
 60    public void setDestinations(Map<String,Integer> destinations) {
 61        this.destinations = destinations;
 62    }
 63
 64    public void setSerialNumber(String serialNumber) {
 65        this.serialNumber = serialNumber;
 66    }
 67
 68    public Astronaut getAstronaut() {
 69        return astronaut;
 70    }
 71
 72    public Map<String, Integer> getDestinations() {
 73        return destinations;
 74    }
 75
 76    public String getSerialNumber() {
 77        return serialNumber;
 78    }
 79
 80    // tag::AssertTrue[]
 81    @AssertTrue
 82    // end::AssertTrue[]
 83    // tag::launchSpacecraft[]
 84    // tag::launchCode[]
 85    public boolean launchSpacecraft(@NotNull String launchCode) {
 86    // end::launchCode[]
 87        // tag::OpenLiberty[]
 88        if(launchCode.equals("OpenLiberty"))
 89        // end::OpenLiberty[]
 90            // tag::true[]
 91            return true;
 92            // end::true[]
 93        // tag::false[]
 94        return false;
 95        // end::false[]
 96    }
 97    // end::launchSpacecraft[]
 98}
 99// end::Spacecraft[]

Astronaut.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2019 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - initial API and implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.beanvalidation;
14
15import java.io.Serializable;
16import javax.validation.constraints.Max;
17import javax.validation.constraints.Min;
18import javax.validation.constraints.NotBlank;
19import javax.validation.constraints.Email;
20
21// tag::Astronaut[]
22public class Astronaut implements Serializable {
23
24    private static final long serialVersionUID = 1L;
25
26    // tag::not-blank[]
27    @NotBlank
28    // end::not-blank[]
29    // tag::Name[]
30    private String name;
31    // end::Name[]
32
33    // tag::Min[]
34    @Min(18)
35    // end::Min[]
36    // tag::Max[]
37    @Max(100)
38    // end::Max[]
39    // tag::age[]
40    private Integer age;
41    // end::age[]
42
43    // tag::Email[]
44    @Email
45    // end::Email[]
46    // tag::emailAddress[]
47    private String emailAddress;
48    // end::emailAddress[]
49
50    public Astronaut() {}
51
52    public String getName() {
53        return name;
54    }
55
56    public Integer getAge() {
57        return age;
58    }
59
60    public String getEmailAddress() {
61        return emailAddress;
62    }
63
64    public void setName(String name) {
65        this.name = name;
66    }
67
68    public void setAge(Integer age) {
69        this.age = age;
70    }
71
72    public void setEmailAddress(String emailAddress) {
73        this.emailAddress = emailAddress;
74    }
75}
76// end::Astronaut[]
Create the BeanValidationEndpoint class.
src/main/java/io/openliberty/guides/beanvalidation/BeanValidationEndpoint.java

BeanValidationEndpoint.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2019 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - initial API and implementation
11 *******************************************************************************/
12// end::copyright[]
13package io.openliberty.guides.beanvalidation;
14
15import java.util.Set;
16
17import javax.inject.Inject;
18import javax.validation.Validator;
19import javax.validation.ConstraintViolation;
20import javax.validation.ConstraintViolationException;
21import javax.ws.rs.Consumes;
22import javax.ws.rs.POST;
23import javax.ws.rs.Path;
24import javax.ws.rs.Produces;
25import javax.ws.rs.core.MediaType;
26
27import org.eclipse.microprofile.openapi.annotations.Operation;
28import org.eclipse.microprofile.openapi.annotations.media.Content;
29import org.eclipse.microprofile.openapi.annotations.media.Schema;
30import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;
31
32@Path("/")
33public class BeanValidationEndpoint {
34
35    @Inject
36    Validator validator;
37
38    @Inject
39    // tag::Spacecraft[]
40    Spacecraft bean;
41    // end::Spacecraft[]
42
43    @POST
44    @Path("/validatespacecraft")
45    @Produces(MediaType.TEXT_PLAIN)
46    @Consumes(MediaType.APPLICATION_JSON)
47    @Operation(summary = "POST request to validate your spacecraft bean")
48    // tag::validate-Spacecraft[]
49    public String validateSpacecraft(
50        @RequestBody(description = "Specify the values to create the "
51                + "Astronaut and Spacecraft beans.",
52            content = @Content(mediaType = "application/json",
53                schema = @Schema(implementation = Spacecraft.class)))
54        Spacecraft spacecraft) {
55
56            // tag::ConstraintViolation[]
57            Set<ConstraintViolation<Spacecraft>> violations
58            // end::ConstraintViolation[]
59            // tag::validate[]
60                = validator.validate(spacecraft);
61            // end::validate[]
62
63            if (violations.size() == 0) {
64                return "No Constraint Violations";
65            }
66
67            StringBuilder sb = new StringBuilder();
68            for (ConstraintViolation<Spacecraft> violation : violations) {
69                sb.append("Constraint Violation Found: ")
70                .append(violation.getMessage())
71                .append(System.lineSeparator());
72            }
73            return sb.toString();
74    }
75    // end::validate-Spacecraft[]
76
77    @POST
78    @Path("/launchspacecraft")
79    @Produces(MediaType.TEXT_PLAIN)
80    @Operation(summary = "POST request to specify a launch code")
81    // tag::launchSpacecraft[]
82    public String launchSpacecraft(
83        @RequestBody(description = "Enter the launch code.  Must not be "
84                + "null and must equal OpenLiberty for successful launch.",
85            content = @Content(mediaType = "text/plain"))
86        String launchCode) {
87            try {
88                bean.launchSpacecraft(launchCode);
89                return "launched";
90            } catch(ConstraintViolationException ex) {
91                return ex.getMessage();
92            }
93    }
94    // end::launchSpacecraft[]
95}

Two resources, a validator and an instance of the Spacecraft JavaBean, are injected into the class. The default validator is used and is obtained through CDI injection. However, you can also obtain the default validator with resource injection or a JNDI lookup. The Spacecraft JavaBean is injected so that the method-level constraints can be validated.

The programmatic validation takes place in the validateSpacecraft() method. To validate the data, the validate() method is called on the Spacecraft bean. Because the Spacecraft bean contains the @Valid constraint on the Astronaut bean, both JavaBeans are validated. Any constraint violations found during the call to the validate() method are returned as a set of ConstraintViolation objects.

The method level validation occurs in the launchSpacecraft() method. A call is then made to the launchSpacecraft() method on the Spacecraft bean, which throws a ConstraintViolationException exception if either of the method-level constraints is violated.

Running the application

You started the Open Liberty server in dev mode at the beginning of the guide, so all the changes were automatically picked up.

Navigate to the http://localhost:9080/openapi/ui URL. Expand the /beanvalidation/validatespacecraft POST request to validate your spacecraft bean section and click Try it out. Copy the following example input into the text box:

{
  "astronaut": {
    "name": "Libby",
    "age": 25,
    "emailAddress": "[email protected]"
  },
  "destinations": {
    "Mars": 500
  },
  "serialNumber": "Liberty0001"
}

Click Execute and you receive the response No Constraint Violations because the values specified pass previously defined constraints.

Next, modify the following values, all of which break the previously defined constraints:

Age = 10
Email = libbybot
SerialNumber = Liberty1

After you click Execute, the response contains the following constraint violations:

Constraint Violation Found: serial number is not valid.
Constraint Violation Found: must be greater than or equal to 18
Constraint Violation Found: must be a well-formed email address

To try the method-level validation expand the /beanvalidation/launchspacecraft POST request to specify a launch code section. Enter OpenLiberty in the text box to note that launched is returned because the launch code passes the defined constraints. Replace OpenLiberty with anything else to note that a constraint violation is returned.

Testing the constraints

Now, write automated tests to drive the previously created service.

Create BeanValidationIT class.
src/test/java/it/io/openliberty/guides/beanvalidation/BeanValidationIT.java

BeanValidationIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2018, 2019 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12 // end::copyright[]
 13package it.io.openliberty.guides.beanvalidation;
 14
 15import static org.junit.jupiter.api.Assertions.assertEquals;
 16import static org.junit.jupiter.api.Assertions.assertTrue;
 17
 18import io.openliberty.guides.beanvalidation.Astronaut;
 19import io.openliberty.guides.beanvalidation.Spacecraft;
 20
 21import java.util.HashMap;
 22
 23import javax.json.bind.Jsonb;
 24import javax.json.bind.JsonbBuilder;
 25import javax.ws.rs.client.Client;
 26import javax.ws.rs.client.ClientBuilder;
 27import javax.ws.rs.client.Entity;
 28import javax.ws.rs.core.MediaType;
 29import javax.ws.rs.core.Response;
 30
 31import org.junit.jupiter.api.AfterEach;
 32import org.junit.jupiter.api.BeforeEach;
 33import org.junit.jupiter.api.Test;
 34
 35public class BeanValidationIT {
 36
 37    private Client client;
 38    private static String port;
 39
 40    // tag::BeforeEach[]
 41    @BeforeEach
 42    // end::BeforeEach[]
 43    // tag::setup[]
 44    public void setup() {
 45        // tag::Client[]
 46        client = ClientBuilder.newClient();
 47        // end::Client[]
 48        port = System.getProperty("http.port");
 49    }
 50    // end::setup[]
 51
 52    @AfterEach
 53    public void teardown() {
 54        client.close();
 55    }
 56
 57    @Test
 58    // tag::testNoFieldLevelConstraintViolations[]
 59    public void testNoFieldLevelConstraintViolations() throws Exception {
 60        // tag::Astronaut[]
 61        Astronaut astronaut = new Astronaut();
 62        astronaut.setAge(25);
 63        astronaut.setEmailAddress("[email protected]");
 64        astronaut.setName("Libby");
 65        // end::Astronaut[]
 66        // tag::Spacecraft[]
 67        Spacecraft spacecraft = new Spacecraft();
 68        spacecraft.setAstronaut(astronaut);
 69        spacecraft.setSerialNumber("Liberty1001");
 70        // end::Spacecraft[]
 71        HashMap<String, Integer> destinations = new HashMap<String, Integer>();
 72        destinations.put("Mars", 1500);
 73        destinations.put("Pluto", 10000);
 74        spacecraft.setDestinations(destinations);
 75
 76        Jsonb jsonb = JsonbBuilder.create();
 77        String spacecraftJSON = jsonb.toJson(spacecraft);
 78        Response response = postResponse(getURL(port, "validatespacecraft"),
 79                spacecraftJSON, false);
 80        String actualResponse = response.readEntity(String.class);
 81        String expectedResponse = "No Constraint Violations";
 82
 83        assertEquals(expectedResponse, actualResponse,
 84                "Unexpected response when validating beans.");
 85    }
 86    // end::testNoFieldLevelConstraintViolations[]
 87
 88    @Test
 89    // tag::testFieldLevelConstraintViolation[]
 90    public void testFieldLevelConstraintViolation() throws Exception {
 91        Astronaut astronaut = new Astronaut();
 92        astronaut.setAge(25);
 93        astronaut.setEmailAddress("libby");
 94        astronaut.setName("Libby");
 95
 96        Spacecraft spacecraft = new Spacecraft();
 97        spacecraft.setAstronaut(astronaut);
 98        spacecraft.setSerialNumber("Liberty123");
 99
100        HashMap<String, Integer> destinations = new HashMap<String, Integer>();
101        destinations.put("Mars", -100);
102        spacecraft.setDestinations(destinations);
103
104        Jsonb jsonb = JsonbBuilder.create();
105        String spacecraftJSON = jsonb.toJson(spacecraft);
106        // tag::Response[]
107        Response response = postResponse(getURL(port, "validatespacecraft"),
108                spacecraftJSON, false);
109        // end::Response[]
110        String actualResponse = response.readEntity(String.class);
111        // tag::expectedDestinationResponse[]
112        String expectedDestinationResponse = "must be greater than 0";
113        // end::expectedDestinationResponse[]
114        assertTrue(actualResponse.contains(expectedDestinationResponse),
115                "Expected response to contain: " + expectedDestinationResponse);
116        // tag::expectedEmailResponse[]
117        String expectedEmailResponse = "must be a well-formed email address";
118        // end::expectedEmailResponse[]
119        assertTrue(actualResponse.contains(expectedEmailResponse),
120                "Expected response to contain: " + expectedEmailResponse);
121        // tag::expectedSerialNumberResponse[]
122        String expectedSerialNumberResponse = "serial number is not valid";
123        // end::expectedSerialNumberResponse[]
124        assertTrue(actualResponse.contains(expectedSerialNumberResponse),
125                "Expected response to contain: " + expectedSerialNumberResponse);
126    }
127    // end::testFieldLevelConstraintViolation[]
128
129    @Test
130    // tag::testNoMethodLevelConstraintViolations[]
131    public void testNoMethodLevelConstraintViolations() throws Exception {
132        // tag::OpenLiberty[]
133        String launchCode = "OpenLiberty";
134        // end::OpenLiberty[]
135        // tag::launchSpacecraft[]
136        Response response = postResponse(getURL(port, "launchspacecraft"),
137                launchCode, true);
138        // end::launchSpacecraft[]
139
140        String actualResponse = response.readEntity(String.class);
141        String expectedResponse = "launched";
142
143        assertEquals(expectedResponse, actualResponse,
144                "Unexpected response from call to launchSpacecraft");
145
146    }
147    // end::testNoMethodLevelConstraintViolations[]
148
149    // tag::testMethodLevelConstraintViolation[]
150    @Test
151    public void testMethodLevelConstraintViolation() throws Exception {
152        // tag::incorrectCode[]
153        String launchCode = "incorrectCode";
154        // end::incorrectCode[]
155        Response response = postResponse(getURL(port, "launchspacecraft"),
156                launchCode, true);
157
158        String actualResponse = response.readEntity(String.class);
159        assertTrue(
160                // tag::actualResponse[]
161                actualResponse.contains("must be true"),
162                // end::actualResponse[]
163                "Unexpected response from call to launchSpacecraft");
164    }
165    // end::testMethodLevelConstraintViolation[]
166
167    private Response postResponse(String url, String value,
168                                  boolean isMethodLevel) {
169        if(isMethodLevel)
170            return client.target(url).request().post(Entity.text(value));
171        else
172            return client.target(url).request().post(Entity.entity(value,
173                MediaType.APPLICATION_JSON));
174    }
175
176    private String getURL(String port, String function) {
177        return "http://localhost:" + port + "/Spacecraft/beanvalidation/" +
178                function;
179    }
180}

The @BeforeEach annotation causes the setup() method to execute before the test cases. The setup() method retrieves the port number for the Open Liberty server and creates a Client that is used throughout the tests, which are described as follows:

  • The testNoFieldLevelConstraintViolations() test case verifies that constraint violations do not occur when valid data is supplied to the Astronaut and Spacecraft bean attributes.

  • The testFieldLevelConstraintViolation() test case verifies that the appropriate constraint violations occur when data that is supplied to the Astronaut and Spacecraft attributes violates the defined constraints. Because 3 constraint violations are defined, 3 ConstraintViolation objects are returned as a set from the validate call. The 3 expected messages are "must be greater than 0" for the negative distance specified in the destination map, "must be a well-formed email address" for the incorrect email address, and the custom "serial number is not valid" message for the serial number.

  • The testNoMethodLevelConstraintViolations() test case verifies that the method-level constraints that are specified on the launchSpacecraft() method of the Spacecraft bean are validated when the method is called with no violations. In this test, the call to the launchSpacecraft() method is made with the OpenLiberty argument. A value of true is returned, which passes the specified constraints.

  • The testMethodLevelConstraintViolation() test case verifies that a ConstraintViolationException exception is thrown when one of the method-level constraints is violated. A call with an incorrect parameter, incorrectCode, is made to the launchSpacecraft() method of the Spacecraft bean. The method returns false, which violates the defined constraint, and a ConstraintViolationException exception is thrown. The exception includes the constraint violation message, which is must be true in this example.

Spacecraft.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2018 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - initial API and implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13package io.openliberty.guides.beanvalidation;
 14
 15import java.io.Serializable;
 16import java.util.Map;
 17import java.util.HashMap;
 18
 19import javax.validation.constraints.NotBlank;
 20import javax.validation.constraints.Positive;
 21import javax.validation.constraints.NotNull;
 22import javax.validation.constraints.AssertTrue;
 23import javax.inject.Named;
 24import javax.enterprise.context.RequestScoped;
 25import javax.validation.Valid;
 26
 27@Named
 28@RequestScoped
 29// tag::Spacecraft[]
 30public class Spacecraft implements Serializable {
 31
 32    private static final long serialVersionUID = 1L;
 33
 34    // tag::Valid[]
 35    @Valid
 36    // end::Valid[]
 37    // tag::Astronaut[]
 38    private Astronaut astronaut;
 39    // end::Astronaut[]
 40
 41    // tag::Map[]
 42    private Map<@NotBlank String, @Positive Integer> destinations;
 43    // end::Map[]
 44
 45    // tag::serial-num[]
 46    @SerialNumber
 47    // end::serial-num[]
 48    // tag::serialNumber[]
 49    private String serialNumber;
 50    // end::serialNumber[]
 51
 52    public Spacecraft() {
 53        destinations = new HashMap<String, Integer>();
 54    }
 55
 56    public void setAstronaut(Astronaut astronaut) {
 57        this.astronaut = astronaut;
 58    }
 59
 60    public void setDestinations(Map<String,Integer> destinations) {
 61        this.destinations = destinations;
 62    }
 63
 64    public void setSerialNumber(String serialNumber) {
 65        this.serialNumber = serialNumber;
 66    }
 67
 68    public Astronaut getAstronaut() {
 69        return astronaut;
 70    }
 71
 72    public Map<String, Integer> getDestinations() {
 73        return destinations;
 74    }
 75
 76    public String getSerialNumber() {
 77        return serialNumber;
 78    }
 79
 80    // tag::AssertTrue[]
 81    @AssertTrue
 82    // end::AssertTrue[]
 83    // tag::launchSpacecraft[]
 84    // tag::launchCode[]
 85    public boolean launchSpacecraft(@NotNull String launchCode) {
 86    // end::launchCode[]
 87        // tag::OpenLiberty[]
 88        if(launchCode.equals("OpenLiberty"))
 89        // end::OpenLiberty[]
 90            // tag::true[]
 91            return true;
 92            // end::true[]
 93        // tag::false[]
 94        return false;
 95        // end::false[]
 96    }
 97    // end::launchSpacecraft[]
 98}
 99// end::Spacecraft[]

Running the tests

Since you started Open Liberty in dev mode, press the enter/return key to run the tests.

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.beanvalidation.BeanValidationIT
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.493 sec - in
it.io.openliberty.guides.beanvalidation.BeanValidationIT

Results :

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0

When you are done checking out the service, exit dev mode by pressing CTRL+C in the command-line session where you ran the server, or by typing q and then pressing the enter/return key.

Great work! You’re done!

You developed and tested a Java microservice by using bean validation and Open Liberty.

Guide Attribution

Validating constraints with microservices by Open Liberty is licensed under CC BY-ND 4.0

Copied to clipboard
Copy code block
Copy file contents

Prerequisites:

Nice work! Where to next?

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

Like Open Liberty? Star our repo on GitHub.

Star