The custom Beans Validation is not working

I'm trying to create a custom beans validation, but for some reason it's not working. Could anyone tell me what is the problem?

My Main class:

package validationtest;

import java.text.ParseException;

public class Main {

    /**
     * @param args the command line arguments
     * @throws java.text.ParseException
     * @throws java.lang.IllegalAccessException
     */
    public static void main(String[] args) throws ParseException, IllegalArgumentException, IllegalAccessException {
       Text msg = new Text();
       System.out.println(msg.getMessage(""));      
    }

}

class Text {
    public String getMessage(@NotEmpty(message = "Field message") String msg) {
        return msg;
    }
}

My validation interface

package validationtest;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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

@Documented
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = NotEmptyImpl.class)
public @interface NotEmpty {

    String message() default "";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default{};
}

My validation implement

package validationtest;

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

public class NotEmptyImpl implements ConstraintValidator<NotEmpty, String> {

    @Override
    public void initialize(NotEmpty annotation) {
        throw new RuntimeException("The field is not empty: " + annotation.message());
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return false;
        }
        return !"".equals(value);
    }

}

Note: I added the package validation-api-1.1.0.Final.jar to classpath.

Upvotes: 1

Views: 2251

Answers (1)

Rustam
Rustam

Reputation: 1407

You need add implementation of bean validation, for example - Hibernate Validator 5.0. Maven dependency:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.0.0.Final</version>
</dependency>

Then you need to initialize ValidatorFactory + Validator, and execute method with ExecutableValidator:

public static void main(String[] args) throws NoSuchMethodException {
    ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
    Validator validator = vf.getValidator();

    Text msg = new Text();

    String inParam = "";

    Method method = Text.class.getMethod("getMessage", String.class);
    ExecutableValidator methodValidator = validator. forExecutables();
    Set<ConstraintViolation<Text>> violations =
        methodValidator.validateParameters(msg, method, new Object[]{inParam});
    if (violations.size() > 0) {
        violations.forEach(v -> System.out.println(v.getMessage()));
    } else {
        //if ok - executing method
        msg.getMessage(inParam);
        //or if return value also need validation:
        //violations = methodValidator.validateReturnValue(msg, method, msg.getMessage(""));
        //violations.forEach(v -> System.out.println(v.getMessage()));
    }

    vf.close();
}

output:

Field message

P.S. And comment "throw new ..." in NotEmptyImpl

Upvotes: 1

Related Questions