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

net.ofk.kutils.Executor Maven / Gradle / Ivy

The newest version!
package net.ofk.kutils;

import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * A set of lambda-function wrappers to help implementing code that throws checked exceptions.
 */
public class Executor {
   O convert(final Executor.Converter converter, final I param) throws E {
    O result = null;
    try {
      result = converter.convert(param);
    } catch (final RuntimeException ex) {
      throw ex;
    } catch (final Exception ex) {
      throw (E) ex;
    }
    return result;
  }

  /**
   * Wraps executable into runnable.
   * Checked exceptions will be wrapped into unchecked UndeclaredThrowableException.
   */
  public Runnable toRunnable(final Executor.Executable executable) {
    return () -> this.execute(executable);
  }

  /**
   * Wraps converter into function.
   * Checked exceptions will be wrapped into unchecked UndeclaredThrowableException.
   */
  public  Function toFunction(final Executor.Converter converter) {
    return param -> this.convert(converter, param);
  }

  /**
   * Wraps callable into supplier.
   * Checked exceptions will be wrapped into unchecked UndeclaredThrowableException.
   */
  public  Supplier toSupplier(final Callable provider) {
    return () -> this.provide(provider);
  }

  /**
   * Wraps processor into consumer.
   * Checked exceptions will be wrapped into unchecked UndeclaredThrowableException.
   */
  public  Consumer toConsumer(final Executor.Processor processor) {
    return param -> this.convert(p -> {
      processor.process(p);
      return null;
    }, param);
  }

  /**
   * Runs a code that doesn't return a value but is allowed to throw checked exceptions.
   */
  public void execute(final Executor.Executable executable) {
    this.convert(param -> {
      executable.execute();
      return null;
    }, null);
  }

  /**
   * Runs a code that returns a value and is allowed to throw checked exceptions.
   */
  public  T provide(final Callable callable) {
    return this.convert(param -> callable.call(), null);
  }

  /**
   * Wrapper for Runnable.
   */
  public interface Executable {
    void execute() throws Exception;
  }

  /**
   * Wrapper for Consumer.
   */
  public interface Processor {
    void process(T param) throws Exception;
  }

  /**
   * Wrapper for Function.
   */
  public interface Converter {
    O convert(I param) throws Exception;
  }

  //Callable is a standard wrapper for Supplier
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy