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

com.gtihub.awsjavakit.attempt.Try Maven / Gradle / Ivy

There is a newer version: 0.19.3
Show newest version
package com.gtihub.awsjavakit.attempt;

import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.function.Function;
import java.util.stream.Stream;

/**
 * Utility class for handling checked exceptions in map functions. Check tests for examples
 *
 * @param  the contained object.
 */
public abstract class Try {

  public static final String NULL_ACTION_MESSAGE = "Action cannot be null";

  @SuppressWarnings("PMD.ShortMethodName")
  public static  Try of(T input) {
    return new Success(input);
  }

  /**
   * A wrapper for actions that throw checked Exceptions. See:
   * "https://www.oreilly.com/content/handling-checked-exceptions-in-java-streams" Try to perform
   * the action. Any exception will be enclosed in a Failure.
   *
   * @param action a {@link Callable} action that throws or does not throw a checked Exception
   * @param     the resulting object
   * @return a new {@link Try} instance
   */
  public static  Try attempt(Callable action) {
    try {
      return new Success(action.call());
    } catch (Exception e) {
      return new Failure(e);
    }
  }

  /**
   * A wrapper for functions that throw checked Exceptions. See:
   * "https://www.oreilly.com/content/handling-checked-exceptions-in-java-streams" Try to perform
   * the action. Any exception will be enclosed in a Failure.
   *
   * @param fe  a {@link FunctionWithException} function that throws or does not throw a checked
   *            Exception
   * @param  the type of the argument of the function.
   * @param  the type of the result of the function
   * @param  the type of the thrown Exception
   * @return a new {@link Try} instance
   */
  public static  Function> attempt(
    FunctionWithException fe) {
    return arg -> {
      try {
        return new Success(fe.apply(arg));
      } catch (Exception e) {
        return new Failure(e);
      }
    };
  }

  public abstract Stream stream();

  public abstract boolean isSuccess();

  public abstract T get();

  public abstract Exception getException();

  public final boolean isFailure() {
    return !isSuccess();
  }

  public abstract  Try map(FunctionWithException action);

  public abstract  Try flatMap(
    FunctionWithException, E> action);

  public abstract  Try forEach(ConsumerWithException consumer);

  public abstract  T orElseThrow(Function, E> action) throws E;

  public T orElseThrow(RuntimeException e) {
    return orElseThrow(fail -> e);
  }

  public abstract T orElseThrow();

  public abstract  T orElse(FunctionWithException, T, E> action)
    throws E;

  public abstract  Optional toOptional(
    ConsumerWithException, E> action) throws E;

  public abstract Optional toOptional();

  @SuppressWarnings("PMD.ShortMethodName")
  public abstract Try or(Callable action);
}