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

com.slimgears.util.stream.Safe Maven / Gradle / Ivy

There is a newer version: 0.7.58
Show newest version
package com.slimgears.util.stream;

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

@SuppressWarnings("WeakerAccess")
public class Safe {
    public interface UnsafeSupplier {
        T get() throws Exception;
    }

    public interface UnsafeConsumer {
        void accept(T val) throws Exception;
    }

    public interface UnsafeRunnable {
        void run() throws Exception;
    }

    public interface UnsafeFunction {
        R apply(T from) throws Exception;
    }

    public interface Closeable extends AutoCloseable {
        void close();
    }

    public static  T safely(Callable callable) {
        try {
            return callable.call();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static  Supplier ofCallable(Callable callable) {
        return () -> safely(callable);
    }

    public static Closeable ofClosable(AutoCloseable closeable) {
        return ofRunnable(closeable::close)::run;
    }

    public static  Supplier ofSupplier(UnsafeSupplier supplier) {
        return () -> safely(supplier::get);
    }

    public static Runnable ofRunnable(UnsafeRunnable runnable) {
        return () -> safely(() -> { runnable.run(); return null; });
    }

    public static  Function ofFunction(UnsafeFunction function) {
        return val -> safely(() -> function.apply(val));
    }

    public static  Consumer ofConsumer(UnsafeConsumer consumer) {
        return val -> safely(() -> { consumer.accept(val); return null; });
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy