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

walled.api.interfaces.ValueValidation Maven / Gradle / Ivy

The newest version!
package walled.api.interfaces;

import java.text.MessageFormat;
import java.util.Optional;
import java.util.function.Predicate;

public class ValueValidation {
  private Optional target;

  private String message;

  private ValueValidation(Value value, Predicate predicate, String message) {
    this.target = Optional.ofNullable(value).filter(predicate);
    this.message = message;
  }

  public static  ValueValidation of(T value, Predicate predicate) {
    return new ValueValidation<>(value, predicate, "");
  }

  public static ValueValidation notEmpty(String value) {
    return new ValueValidation<>(value, notEmpty(), "Value cannot be empty.");
  }

  public static ValueValidation notZero(Number value) {
    return new ValueValidation<>(value, notZero(), "Value cannot be zero.");
  }

  public static  ValueValidation notNull(T value) {
    return new ValueValidation<>(value, notNull(), "Value cannot be null.");
  }

  static Predicate notZero() {
    return ((value) -> value != null && value.intValue() != 0);
  }

  static Predicate notEmpty() {
    return ((value) -> value != null && !value.isEmpty());
  }

  static  Predicate notNull() {
    return ((value) -> value != null);
  }

  public ValueValidation withMessage(String messsage, Object... args) {
    String validationMessage = MessageFormat.format(message, args);
    this.message = validationMessage;
    return this;
  }

  public Value get() {
    return this.target.orElseThrow(() -> new IllegalStateException(this.message));
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy