/** * Constructor for successful outcome of an operation * @param result * the return value of the operation */ public static <RESULTTYPE> ExecutionResult<RESULTTYPE> ofSuccess(RESULTTYPE result) { return new ExecutionResult<>(result, null); }
/** * Executes a specified task. If an exception occurs it will be wrapped in a RuntimeException * @param runnable * the task to be executed * @return * the result of the task execution */ public static void runUnchecked(Runnable runnable) { //NOSONAR runProtected(runnable).mapException(Exception.class, UncheckedException::new).get(); }
/** * Flattens the execution result to the actual outcome of the execution. If an exception occured, it is throw, * if it returned any result - including null - it is returned. * @return * the actual return value of the operation * @throws Exception * if the execution produced an exception, it is thrown */ public RESULTTYPE flatten() throws Exception { //NOSONAR if (!wasSuccess()) { throw this.exception.get(); } return get(); }
/** * Executes the specified task, handling a any exception that occurs. * @param runnable * the task to be executed * @return * the execution result monad */ public static ExecutionResult<Void> runProtected(Runnable runnable) { //NOSONAR try { runnable.run(); //NOSONAR return ExecutionResult.ofVoid(); } catch (Exception e) { return ExecutionResult.ofException(e); } }
/** * Executes the specified task and returnes an execution result. * @param callable * the task to be executed * @param <RESULTTYPE> * the return type of the operation * @return * the execution result monad */ public static <RESULTTYPE> ExecutionResult<RESULTTYPE> runProtected(Callable<RESULTTYPE> callable) { try { return ExecutionResult.ofSuccess(callable.call()); } catch (Exception e) { return ExecutionResult.ofException(e); } }
/** * Executes a specified task, regardless if it throws a checked or unchecked exception. * If an exception occurs it will be caught and wrapped in the execution result. * @param call * the task to be executed * @param <T> * the type of the return value * @return * the result of the task execution */ public static <T> T runUnchecked(Callable<T> call) { return runProtected(call).mapException(Exception.class, UncheckedException::new).get(); }
/** * Constructor for exceptional outcome of an operation * @param exception * the caught exception */ public static <RESULTTYPE> ExecutionResult<RESULTTYPE> ofException(Exception exception) { return new ExecutionResult<>(null, exception); }