All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.itroadlabs.apicross.beanvalidation.RequiredPropertiesValidator Maven / Gradle / Ivy

The newest version!
package io.github.itroadlabs.apicross.beanvalidation;

import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class RequiredPropertiesValidator implements ConstraintValidator {
    private String[] requiredProperties;

    @Override
    public void initialize(RequiredProperties constraintAnnotation) {
        this.requiredProperties = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(HasSpecifiedProperties value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }

        Set specifiedProperties = new HashSet<>(value.$specifiedProperties());
        Set unspecifiedProperties = new HashSet<>(Arrays.asList(this.requiredProperties));
        unspecifiedProperties.removeAll(specifiedProperties);
        if (!unspecifiedProperties.isEmpty()) {
            HibernateConstraintValidatorContext hibernateConstraintValidatorContext = context.unwrap(HibernateConstraintValidatorContext.class);
            hibernateConstraintValidatorContext.addMessageParameter("requiredProperties", this.requiredProperties);
            hibernateConstraintValidatorContext.addMessageParameter("specifiedProperties", specifiedProperties);
            return false;
        } else {
            return true;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy