Validating constraints with microservices

duration 20 minutes

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, which is what 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 navigate to the finish directory and then run the following Maven goal to build the application and run it inside Open Liberty:

cd finish
mvn install liberty:start-server

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": "libbybot@openliberty.io"
  },
  "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": "libbybot@openliberty.io"
  },
  "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 done checking out the application, stop the Open Liberty server:

mvn liberty:stop-server

Applying constraints on the JavaBeans

Navigate to the start directory to begin.

First, create the JavaBeans to be constrained. Create the Astronaut bean class in the src/main/java/io/openliberty/guides/beanvalidation/Astronaut.java file:

package io.openliberty.guides.beanvalidation;

import java.io.Serializable;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Email;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;

public class Astronaut implements Serializable {

    private static final long serialVersionUID = 1L;

    @NotBlank
    private String name;

    @Min(18)
    @Max(100)
    private Integer age;

    @Email
    private String emailAddress;

    public Astronaut() {}

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }
  }

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 email 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 another class to represent a spacecraft in the src/main/java/io/openliberty/guides/beanvalidation/Spacecraft.java file:

package io.openliberty.guides.beanvalidation;

import java.io.Serializable;
import java.util.Map;
import java.util.HashMap;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.AssertTrue;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.validation.Valid;

@Named
@RequestScoped
public class Spacecraft implements Serializable {

    private static final long serialVersionUID = 1L;

    @Valid
    private Astronaut astronaut;

    private Map<@NotBlank String, @Positive Integer> destinations;

    @SerialNumber
    private String serialNumber;

    public Spacecraft() {
        destinations = new HashMap<String, Integer>();
    }

    public void setAstronaut(Astronaut astronaut) {
        this.astronaut = astronaut;
    }

    public void setDestinations(Map<String,Integer> destinations) {
        this.destinations = destinations;
    }

    public void setSerialNumber(String serialNumber) {
        this.serialNumber = serialNumber;
    }

    public Astronaut getAstronaut() {
        return astronaut;
    }

    public Map<String, Integer> getDestinations() {
        return destinations;
    }

    public String getSerialNumber() {
        return serialNumber;
    }

    @AssertTrue
    public boolean launchSpacecraft(@NotNull String launchCode) {
        if(launchCode.equals("OpenLiberty"))
            return true;
        return false;
    }
}

The Spacecraft bean contains 3 fields, astronaut, serialNumber, and destination. 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 destination 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 in the src/main/java/io/openliberty/guides/beanvalidation/SerialNumber.java file:

package io.openliberty.guides.beanvalidation;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ FIELD })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { SerialNumberValidator.class })
public @interface SerialNumber {

    String message() default "serial number is not valid.";

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

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

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 in the src/main/java/io/openliberty/guides/beanvalidation/SerialNumberValidator.java file:

package io.openliberty.guides.beanvalidation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class SerialNumberValidator implements ConstraintValidator<SerialNumber,
                                                                  Object> {

    @Override
    public boolean isValid(Object arg0, ConstraintValidatorContext arg1) {
        //Serial Numbers must start with Liberty followed by four numbers
        boolean isValid = false;
        if (arg0 == null)
            return isValid;
        String serialNumber = arg0.toString();
        isValid = serialNumber.length() == 11 && serialNumber.startsWith("Liberty");
        try {
            Integer.parseInt(serialNumber.substring(7));
        } catch (Exception ex) {
            isValid = false;
        }
        return isValid;
    }
}

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 in the src/main/java/io/openliberty/guides/beanvalidation/BeanValidationEndpoint.java file:

package io.openliberty.guides.beanvalidation;

import java.util.Set;

import javax.inject.Inject;
import javax.validation.Validator;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.media.Content;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;

@Path("/")
public class BeanValidationEndpoint {

    @Inject
    Validator validator;

    @Inject
    Spacecraft bean;

    @POST
    @Path("/validatespacecraft")
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes(MediaType.APPLICATION_JSON)
    @Operation(summary = "POST request to validate your spacecraft bean")
    public String validateSpacecraft(
                @RequestBody(description = "Specify the values to create the "
                           + "Astronaut and Spacecraft beans.",
                       content = @Content(mediaType = "application/json",
                schema = @Schema(implementation = Spacecraft.class)))
                Spacecraft spacecraft) {

        Set<ConstraintViolation<Spacecraft>> violations
        = validator.validate(spacecraft);

        if(violations.size() == 0) {
            return "No Constraint Violations";
        }

        StringBuilder sb = new StringBuilder();
        for(ConstraintViolation<Spacecraft> violation : violations) {
            sb.append("Constraint Violation Found: ").append(violation.getMessage())
            .append(System.lineSeparator());
        }
        return sb.toString();
        }

    @POST
    @Path("/launchspacecraft")
    @Produces(MediaType.TEXT_PLAIN)
    @Operation(summary = "POST request to specify a launch code")
    public String launchSpacecraft(
            @RequestBody(description = "Enter the launch code.  Must not be "
                            + "null and must equal OpenLiberty for successful launch.",
            content = @Content(mediaType = "text/plain"))
            String launchCode) {
        try {
            bean.launchSpacecraft(launchCode);
            return "launched";
        } catch(ConstraintViolationException ex) {
            return ex.getMessage();
        }
    }
}

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.

Building and running the application

To build the application, run the Maven install phase from the command line in the start directory:

mvn install

This command builds the application and creates a .war file in the target directory. It also configures and installs Open Liberty into the target/liberty/wlp directory.

Next, run the Maven liberty:start-server goal:

mvn liberty:start-server

This goal starts an Open Liberty server instance. Your Maven pom.xml is already configured to start the application in this server instance.

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": "libbybot@openliberty.io"
  },
  "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.

If you make changes to the code, use the Maven compile goal to rebuild the application and have the running Open Liberty server pick them up automatically:

mvn compile

To stop the Open Liberty server, run the Maven liberty:stop-server goal:

mvn liberty:stop-server

Testing the constraints

Now, write automated tests to drive the previously created service. Create the test class in the src/test/java/it/io/openliberty/guides/beanvalidation/BeanValidationTest.java file:

package it.io.openliberty.guides.beanvalidation;

import org.junit.Test;

import io.openliberty.guides.beanvalidation.Astronaut;
import io.openliberty.guides.beanvalidation.Spacecraft;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.junit.After;
import org.junit.Before;

public class BeanValidationTest {

        private Client client;
        private static String port;


    @Before
    public void setup() {
            client = ClientBuilder.newClient();
        port = System.getProperty("liberty.test.port");
    }

    @After
    public void teardown() {
        client.close();
    }

    @Test
    public void testNoFieldLevelConstraintViolations() throws Exception {
        Astronaut astronaut = new Astronaut();
        astronaut.setAge(25);
        astronaut.setEmailAddress("libby@openliberty.io");
        astronaut.setName("Libby");

        Spacecraft spacecraft = new Spacecraft();
        spacecraft.setAstronaut(astronaut);
        spacecraft.setSerialNumber("Liberty1001");

            HashMap<String, Integer> destinations = new HashMap<String, Integer>();
            destinations.put("Mars", 1500);
            destinations.put("Pluto", 10000);
        spacecraft.setDestinations(destinations);

        Jsonb jsonb = JsonbBuilder.create();
        String spacecraftJSON = jsonb.toJson(spacecraft);
        Response response = postResponse(getURL(port, "validatespacecraft"),
                spacecraftJSON, false);
        String actualResponse = response.readEntity(String.class);
        String expectedResponse = "No Constraint Violations";

        assertEquals("Unexpected response when validating beans.",
                expectedResponse, actualResponse);
    }

    @Test
    public void testFieldLevelConstraintViolation() throws Exception {
        Astronaut astronaut = new Astronaut();
        astronaut.setAge(25);
        astronaut.setEmailAddress("libby");
        astronaut.setName("Libby");

        Spacecraft spacecraft = new Spacecraft();
        spacecraft.setAstronaut(astronaut);
        spacecraft.setSerialNumber("Liberty123");

        HashMap<String, Integer> destinations = new HashMap<String, Integer>();
            destinations.put("Mars", -100);
        spacecraft.setDestinations(destinations);

        Jsonb jsonb = JsonbBuilder.create();
        String spacecraftJSON = jsonb.toJson(spacecraft);
        Response response = postResponse(getURL(port, "validatespacecraft"),
                spacecraftJSON, false);
        String actualResponse = response.readEntity(String.class);

        String expectedDestinationResponse = "must be greater than 0";
        assertTrue("Expected response to contain: " + expectedDestinationResponse,
                         actualResponse.contains(expectedDestinationResponse));

        String expectedEmailResponse = "must be a well-formed email address";
        assertTrue("Expected response to contain: " + expectedEmailResponse,
                        actualResponse.contains(expectedEmailResponse));

        String expectedSerialNumberResponse = "serial number is not valid";
        assertTrue("Expected response to contain: " + expectedSerialNumberResponse,
                           actualResponse.contains(expectedSerialNumberResponse));
    }

    @Test
    public void testNoMethodLevelConstraintViolations() throws Exception {
        String launchCode = "OpenLiberty";
        Response response = postResponse(getURL(port, "launchspacecraft"),
                launchCode, true);

        String actualResponse = response.readEntity(String.class);
        String expectedResponse = "launched";

        assertEquals("Unexpected response from call to launchSpacecraft",
                expectedResponse, actualResponse);

    }

    @Test
    public void testMethodLevelConstraintViolation() throws Exception {
        String launchCode = "incorrectCode";
        Response response = postResponse(getURL(port, "launchspacecraft"),
                launchCode, true);

        String actualResponse = response.readEntity(String.class);
        assertTrue("Unexpected response from call to launchSpacecraft",
        actualResponse.contains("must be true"));
    }

    private Response postResponse(String url, String value,
                                  boolean isMethodLevel) {
            if(isMethodLevel)
            return client.target(url).request().post(Entity.text(value));
            else
                    return client.target(url).request().post(Entity.entity(value,
                            MediaType.APPLICATION_JSON));
    }

    private String getURL(String port, String function) {
            return "http://localhost:" + port + "/Spacecraft/beanvalidation/" +
                function;
    }
}

The @Before 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.

Running the tests

If the server is still running from the previous steps, stop it using the Maven liberty:stop-server goal from command line in the start directory:

mvn liberty:stop-server

Then, verify that the tests pass using the Maven verify goal:

mvn verify

It may take some time before build is complete. If the tests pass, you will see a similar output to the following:

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

Results :

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

Great work! You’re done!

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

Contribute to this guide

Is something missing or broken? Raise an issue, or send us a pull request.