Friday, 16 June 2017

JEE Bean Validation

Starting from JEE 6, Java starts to offer bean validation annotations, which may constrain property values.

JEE bean validation provides built-in constrain annotations, and a way to build custom-constrains too.

Bean validation annotations define how to validate bean properties. However, the validation need to be triggered from externally.

Or using annotation @Valid before the request or response body.

If a javax.validation.ValidationException or any subclass of ValidationException except ConstraintValidationException is thrown, the JAX-RS runtime will respond to the client request with a 500 (Internal Server Error) HTTP status code.

If a ConstraintValidationException is thrown, the JAX-RS runtime will respond to the client with one of the following HTTP status codes:

500 (Internal Server Error) if the exception was thrown while validating a method return type

400 (Bad Request) in all other cases



@Valid may throw
ConstraintValidationException 


import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author YNZ
 */
public class LoginInfoIT {

    private final Logger logger;

    private static ValidatorFactory validatorFactory;
    private static Validator validator;

    public LoginInfoIT() {
        logger = LoggerFactory.getLogger(this.getClass());
    }

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

    @Test
    public void testEmailConstraintValidation() {
        logger.info("Test Email Pattern Validation! ");
        LoginInfo instance = new LoginInfo("zyc@gmail", "Obhh2017");
        Set> violations = validator.validate(instance);
        assertEquals(1, violations.size());
    }

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import lombok.Data;

/**
 *
 * @author YNZ
 */
@Embeddable
@Data
public class LoginInfo implements Serializable {

    @Pattern(regexp = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+"
            + "(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$",
            message = " invalid email address! ")
    @NotNull
    @Column(name = "LOGIN_NAME", unique = true)
    protected String email;




Reference:
JEE 7 Bean Validation

No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...