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

pl.ais.commons.bean.validation.Validatable Maven / Gradle / Ivy

package pl.ais.commons.bean.validation;

import pl.ais.commons.bean.validation.constrainable.Constrainable;
import pl.ais.commons.bean.validation.event.ValidationListener;
import pl.ais.commons.domain.specification.Specifications;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.function.Supplier;

/**
 * Defines the API contract for validatable value.
 *
 * @param  the type of the validatable values
 * @author Warlock, AIS.PL
 * @since 1.0.1
 */
public interface Validatable extends Supplier> {

    static  Validatable validatable(@Nonnull final Constrainable constrainable,
                                          @Nonnull final ValidationListener listener,
                                          @Nullable final Runnable callback) {
        return new Validatable() {

            /**
             * {@inheritDoc}
             */
            @Override
            public Constrainable get() {
                return constrainable;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public boolean satisfies(@Nonnull final Constraint first, final Constraint... rest) {
                try {
                    return first.apply(constrainable, listener) && Arrays.stream(rest)
                                                                         .map(constraint -> constraint.apply(constrainable, listener))
                                                                         .allMatch(Specifications.isEqual(true));
                } finally {
                    if (null != callback) {
                        callback.run();
                    }
                }
            }
        };
    }

    /**
     * Verifies if this validatable satisfies given constraints.
     *
     * @param first constraint which should be satisfied
     * @param rest  remaining constraints which should be satisfied
     * @return {@code true} if all constraints are satisfied by this validatable, {@code false} otherwise
     */
    boolean satisfies(@Nonnull Constraint first, Constraint... rest);

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy