    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017
    018package org.apache.commons.lang3.function;
    019
    020import java.io.IOException;
    021import java.io.UncheckedIOException;
    022import java.lang.reflect.UndeclaredThrowableException;
    023import java.util.Collection;
    024import java.util.Objects;
    025import java.util.concurrent.Callable;
    026import java.util.function.BiConsumer;
    027import java.util.function.BiFunction;
    028import java.util.function.BiPredicate;
    029import java.util.function.Consumer;
    030import java.util.function.Function;
    031import java.util.function.Predicate;
    032import java.util.function.Supplier;
    033import java.util.stream.Stream;
    034
    035import org.apache.commons.lang3.stream.Streams.FailableStream;
    036
    037/**
    038 * This class provides utility functions, and classes for working with the {@code java.util.function} package, or more
    039 * generally, with Java 8 lambdas. More specifically, it attempts to address the fact that lambdas are supposed not to
    040 * throw Exceptions, at least not checked Exceptions, AKA instances of {@link Exception}. This enforces the use of
    041 * constructs like:
    042 *
    043 * <pre>
    044 * Consumer&lt;java.lang.reflect.Method-&gt; consumer = m -&gt; {
    045 *     try {
    046 *         m.invoke(o, args);
    047 *     } catch (Throwable t) {
    048 *         throw Failable.rethrow(t);
    049 *     }
    050 * };
    051 * </pre>
    052 *
    053 * <p>
    054 * By replacing a {@link java.util.function.Consumer Consumer&lt;O&gt;} with a {@link FailableConsumer
    055 * FailableConsumer&lt;O,? extends Throwable&gt;}, this can be written like follows:
    056 * </p>
    057 *
    058 * <pre>
    059 * Functions.accept((m) -&gt; m.invoke(o, args));
    060 * </pre>
    061 *
    062 * <p>
    063 * Obviously, the second version is much more concise and the spirit of Lambda expressions is met better than the second
    064 * version.
    065 * </p>
    066 *
    067 * @since 3.11
    068 */
    069public class Failable {
    070
    071    /**
    072     * Consumes a consumer and rethrows any exception as a {@link RuntimeException}.
    073     *
    074     * @param consumer the consumer to consume
    075     * @param object1 the first object to consume by {@code consumer}
    076     * @param object2 the second object to consume by {@code consumer}
    077     * @param <T> the type of the first argument the consumer accepts
    078     * @param <U> the type of the second argument the consumer accepts
    079     * @param <E> the type of checked exception the consumer may throw
    080     */
    081    public static <T, U, E extends Throwable> void accept(final FailableBiConsumer<T, U, E> consumer, final T object1,
    082        final U object2) {
    083        run(() -> consumer.accept(object1, object2));
    084    }
    085
    086    /**
    087     * Consumes a consumer and rethrows any exception as a {@link RuntimeException}.
    088     *
    089     * @param consumer the consumer to consume
    090     * @param object the object to consume by {@code consumer}
    091     * @param <T> the type the consumer accepts
    092     * @param <E> the type of checked exception the consumer may throw
    093     */
    094    public static <T, E extends Throwable> void accept(final FailableConsumer<T, E> consumer, final T object) {
    095        run(() -> consumer.accept(object));
    096    }
    097
    098    /**
    099     * Consumes a consumer and rethrows any exception as a {@link RuntimeException}.
    100     *
    101     * @param consumer the consumer to consume
    102     * @param value the value to consume by {@code consumer}
    103     * @param <E> the type of checked exception the consumer may throw
    104     */
    105    public static <E extends Throwable> void accept(final FailableDoubleConsumer<E> consumer, final double value) {
    106        run(() -> consumer.accept(value));
    107    }
    108
    109    /**
    110     * Consumes a consumer and rethrows any exception as a {@link RuntimeException}.
    111     *
    112     * @param consumer the consumer to consume
    113     * @param value the value to consume by {@code consumer}
    114     * @param <E> the type of checked exception the consumer may throw
    115     */
    116    public static <E extends Throwable> void accept(final FailableIntConsumer<E> consumer, final int value) {
    117        run(() -> consumer.accept(value));
    118    }
    119
    120    /**
    121     * Consumes a consumer and rethrows any exception as a {@link RuntimeException}.
    122     *
    123     * @param consumer the consumer to consume
    124     * @param value the value to consume by {@code consumer}
    125     * @param <E> the type of checked exception the consumer may throw
    126     */
    127    public static <E extends Throwable> void accept(final FailableLongConsumer<E> consumer, final long value) {
    128        run(() -> consumer.accept(value));
    129    }
    130
    131    /**
    132     * Applies a function and rethrows any exception as a {@link RuntimeException}.
    133     *
    134     * @param function the function to apply
    135     * @param input1 the first input to apply {@code function} on
    136     * @param input2 the second input to apply {@code function} on
    137     * @param <T> the type of the first argument the function accepts
    138     * @param <U> the type of the second argument the function accepts
    139     * @param <R> the return type of the function
    140     * @param <E> the type of checked exception the function may throw
    141     * @return the value returned from the function
    142     */
    143    public static <T, U, R, E extends Throwable> R apply(final FailableBiFunction<T, U, R, E> function, final T input1,
    144        final U input2) {
    145        return get(() -> function.apply(input1, input2));
    146    }
    147
    148    /**
    149     * Applies a function and rethrows any exception as a {@link RuntimeException}.
    150     *
    151     * @param function the function to apply
    152     * @param input the input to apply {@code function} on
    153     * @param <T> the type of the argument the function accepts
    154     * @param <R> the return type of the function
    155     * @param <E> the type of checked exception the function may throw
    156     * @return the value returned from the function
    157     */
    158    public static <T, R, E extends Throwable> R apply(final FailableFunction<T, R, E> function, final T input) {
    159        return get(() -> function.apply(input));
    160    }
    161
    162    /**
    163     * Applies a function and rethrows any exception as a {@link RuntimeException}.
    164     *
    165     * @param function the function to apply
    166     * @param left the first input to apply {@code function} on
    167     * @param right the second input to apply {@code function} on
    168     * @param <E> the type of checked exception the function may throw
    169     * @return the value returned from the function
    170     */
    171    public static <E extends Throwable> double applyAsDouble(final FailableDoubleBinaryOperator<E> function,
    172        final double left, final double right) {
    173        return getAsDouble(() -> function.applyAsDouble(left, right));
    174    }
    175
    176    /**
    177     * Converts the given {@link FailableBiConsumer} into a standard {@link BiConsumer}.
    178     *
    179     * @param <T> the type of the first argument of the consumers
    180     * @param <U> the type of the second argument of the consumers
    181     * @param consumer a failable {@code BiConsumer}
    182     * @return a standard {@code BiConsumer}
    183     */
    184    public static <T, U> BiConsumer<T, U> asBiConsumer(final FailableBiConsumer<T, U, ?> consumer) {
    185        return (input1, input2) -> accept(consumer, input1, input2);
    186    }
    187
    188    /**
    189     * Converts the given {@link FailableBiFunction} into a standard {@link BiFunction}.
    190     *
    191     * @param <T> the type of the first argument of the input of the functions
    192     * @param <U> the type of the second argument of the input of the functions
    193     * @param <R> the type of the output of the functions
    194     * @param function a {@code FailableBiFunction}
    195     * @return a standard {@code BiFunction}
    196     */
    197    public static <T, U, R> BiFunction<T, U, R> asBiFunction(final FailableBiFunction<T, U, R, ?> function) {
    198        return (input1, input2) -> apply(function, input1, input2);
    199    }
    200
    201    /**
    202     * Converts the given {@link FailableBiPredicate} into a standard {@link BiPredicate}.
    203     *
    204     * @param <T> the type of the first argument used by the predicates
    205     * @param <U> the type of the second argument used by the predicates
    206     * @param predicate a {@code FailableBiPredicate}
    207     * @return a standard {@code BiPredicate}
    208     */
    209    public static <T, U> BiPredicate<T, U> asBiPredicate(final FailableBiPredicate<T, U, ?> predicate) {
    210        return (input1, input2) -> test(predicate, input1, input2);
    211    }
    212
    213    /**
    214     * Converts the given {@link FailableCallable} into a standard {@link Callable}.
    215     *
    216     * @param <V> the type used by the callables
    217     * @param callable a {@code FailableCallable}
    218     * @return a standard {@code Callable}
    219     */
    220    public static <V> Callable<V> asCallable(final FailableCallable<V, ?> callable) {
    221        return () -> call(callable);
    222    }
    223
    224    /**
    225     * Converts the given {@link FailableConsumer} into a standard {@link Consumer}.
    226     *
    227     * @param <T> the type used by the consumers
    228     * @param consumer a {@code FailableConsumer}
    229     * @return a standard {@code Consumer}
    230     */
    231    public static <T> Consumer<T> asConsumer(final FailableConsumer<T, ?> consumer) {
    232        return input -> accept(consumer, input);
    233    }
    234
    235    /**
    236     * Converts the given {@link FailableFunction} into a standard {@link Function}.
    237     *
    238     * @param <T> the type of the input of the functions
    239     * @param <R> the type of the output of the functions
    240     * @param function a {code FailableFunction}
    241     * @return a standard {@code Function}
    242     */
    243    public static <T, R> Function<T, R> asFunction(final FailableFunction<T, R, ?> function) {
    244        return input -> apply(function, input);
    245    }
    246
    247    /**
    248     * Converts the given {@link FailablePredicate} into a standard {@link Predicate}.
    249     *
    250     * @param <T> the type used by the predicates
    251     * @param predicate a {@code FailablePredicate}
    252     * @return a standard {@code Predicate}
    253     */
    254    public static <T> Predicate<T> asPredicate(final FailablePredicate<T, ?> predicate) {
    255        return input -> test(predicate, input);
    256    }
    257
    258    /**
    259     * Converts the given {@link FailableRunnable} into a standard {@link Runnable}.
    260     *
    261     * @param runnable a {@code FailableRunnable}
    262     * @return a standard {@code Runnable}
    263     */
    264    public static Runnable asRunnable(final FailableRunnable<?> runnable) {
    265        return () -> run(runnable);
    266    }
    267
    268    /**
    269     * Converts the given {@link FailableSupplier} into a standard {@link Supplier}.
    270     *
    271     * @param <T> the type supplied by the suppliers
    272     * @param supplier a {@code FailableSupplier}
    273     * @return a standard {@code Supplier}
    274     */
    275    public static <T> Supplier<T> asSupplier(final FailableSupplier<T, ?> supplier) {
    276        return () -> get(supplier);
    277    }
    278
    279    /**
    280     * Calls a callable and rethrows any exception as a {@link RuntimeException}.
    281     *
    282     * @param callable the callable to call
    283     * @param <V> the return type of the callable
    284     * @param <E> the type of checked exception the callable may throw
    285     * @return the value returned from the callable
    286     */
    287    public static <V, E extends Throwable> V call(final FailableCallable<V, E> callable) {
    288        return get(callable::call);
    289    }
    290
    291    /**
    292     * Invokes a supplier, and returns the result.
    293     *
    294     * @param supplier The supplier to invoke.
    295     * @param <T> The suppliers output type.
    296     * @param <E> The type of checked exception, which the supplier can throw.
    297     * @return The object, which has been created by the supplier
    298     */
    299    public static <T, E extends Throwable> T get(final FailableSupplier<T, E> supplier) {
    300        try {
    301            return supplier.get();
    302        } catch (final Throwable t) {
    303            throw rethrow(t);
    304        }
    305    }
    306
    307    /**
    308     * Invokes a boolean supplier, and returns the result.
    309     *
    310     * @param supplier The boolean supplier to invoke.
    311     * @param <E> The type of checked exception, which the supplier can throw.
    312     * @return The boolean, which has been created by the supplier
    313     */
    314    public static <E extends Throwable> boolean getAsBoolean(final FailableBooleanSupplier<E> supplier) {
    315        try {
    316            return supplier.getAsBoolean();
    317        } catch (final Throwable t) {
    318            throw rethrow(t);
    319        }
    320    }
    321
    322    /**
    323     * Invokes a double supplier, and returns the result.
    324     *
    325     * @param supplier The double supplier to invoke.
    326     * @param <E> The type of checked exception, which the supplier can throw.
    327     * @return The double, which has been created by the supplier
    328     */
    329    public static <E extends Throwable> double getAsDouble(final FailableDoubleSupplier<E> supplier) {
    330        try {
    331            return supplier.getAsDouble();
    332        } catch (final Throwable t) {
    333            throw rethrow(t);
    334        }
    335    }
    336
    337    /**
    338     * Invokes an int supplier, and returns the result.
    339     *
    340     * @param supplier The int supplier to invoke.
    341     * @param <E> The type of checked exception, which the supplier can throw.
    342     * @return The int, which has been created by the supplier
    343     */
    344    public static <E extends Throwable> int getAsInt(final FailableIntSupplier<E> supplier) {
    345        try {
    346            return supplier.getAsInt();
    347        } catch (final Throwable t) {
    348            throw rethrow(t);
    349        }
    350    }
    351
    352    /**
    353     * Invokes a long supplier, and returns the result.
    354     *
    355     * @param supplier The long supplier to invoke.
    356     * @param <E> The type of checked exception, which the supplier can throw.
    357     * @return The long, which has been created by the supplier
    358     */
    359    public static <E extends Throwable> long getAsLong(final FailableLongSupplier<E> supplier) {
    360        try {
    361            return supplier.getAsLong();
    362        } catch (final Throwable t) {
    363            throw rethrow(t);
    364        }
    365    }
    366
    367    /**
    368     * Invokes a short supplier, and returns the result.
    369     *
    370     * @param supplier The short supplier to invoke.
    371     * @param <E> The type of checked exception, which the supplier can throw.
    372     * @return The short, which has been created by the supplier
    373     */
    374    public static <E extends Throwable> short getAsShort(final FailableShortSupplier<E> supplier) {
    375        try {
    376            return supplier.getAsShort();
    377        } catch (final Throwable t) {
    378            throw rethrow(t);
    379        }
    380    }
    381
    382    /**
    383     * <p>
    384     * Rethrows a {@link Throwable} as an unchecked exception. If the argument is already unchecked, namely a
    385     * {@code RuntimeException} or {@code Error} then the argument will be rethrown without modification. If the
    386     * exception is {@code IOException} then it will be wrapped into a {@code UncheckedIOException}. In every other
    387     * cases the exception will be wrapped into a {@code
    388     * UndeclaredThrowableException}
    389     * </p>
    390     *
    391     * <p>
    392     * Note that there is a declared return type for this method, even though it never returns. The reason for that is
    393     * to support the usual pattern:
    394     * </p>
    395     *
    396     * <pre>
    397     * throw rethrow(myUncheckedException);
    398     * </pre>
    399     *
    400     * <p>
    401     * instead of just calling the method. This pattern may help the Java compiler to recognize that at that point an
    402     * exception will be thrown and the code flow analysis will not demand otherwise mandatory commands that could
    403     * follow the method call, like a {@code return} statement from a value returning method.
    404     * </p>
    405     *
    406     * @param throwable The throwable to rethrow ossibly wrapped into an unchecked exception
    407     * @return Never returns anything, this method never terminates normally.
    408     */
    409    public static RuntimeException rethrow(final Throwable throwable) {
    410        Objects.requireNonNull(throwable, "throwable");
    411        if (throwable instanceof RuntimeException) {
    412            throw (RuntimeException) throwable;
    413        } else if (throwable instanceof Error) {
    414            throw (Error) throwable;
    415        } else if (throwable instanceof IOException) {
    416            throw new UncheckedIOException((IOException) throwable);
    417        } else {
    418            throw new UndeclaredThrowableException(throwable);
    419        }
    420    }
    421
    422    /**
    423     * Runs a runnable and rethrows any exception as a {@link RuntimeException}.
    424     *
    425     * @param runnable The runnable to run
    426     * @param <E> the type of checked exception the runnable may throw
    427     */
    428    public static <E extends Throwable> void run(final FailableRunnable<E> runnable) {
    429        try {
    430            runnable.run();
    431        } catch (final Throwable t) {
    432            throw rethrow(t);
    433        }
    434    }
    435
    436    /**
    437     * Converts the given collection into a {@link FailableStream}. The {@link FailableStream} consists of the
    438     * collections elements. Shortcut for
    439     *
    440     * <pre>
    441     * Functions.stream(collection.stream());
    442     * </pre>
    443     *
    444     * @param collection The collection, which is being converted into a {@link FailableStream}.
    445     * @param <E> The collections element type. (In turn, the result streams element type.)
    446     * @return The created {@link FailableStream}.
    447     */
    448    public static <E> FailableStream<E> stream(final Collection<E> collection) {
    449        return new FailableStream<>(collection.stream());
    450    }
    451
    452    /**
    453     * Converts the given stream into a {@link FailableStream}. The {@link FailableStream} consists of the same
    454     * elements, than the input stream. However, failable lambdas, like {@link FailablePredicate},
    455     * {@link FailableFunction}, and {@link FailableConsumer} may be applied, rather than {@link Predicate},
    456     * {@link Function}, {@link Consumer}, etc.
    457     *
    458     * @param stream The stream, which is being converted into a {@link FailableStream}.
    459     * @param <T> The streams element type.
    460     * @return The created {@link FailableStream}.
    461     */
    462    public static <T> FailableStream<T> stream(final Stream<T> stream) {
    463        return new FailableStream<>(stream);
    464    }
    465
    466    /**
    467     * Tests a predicate and rethrows any exception as a {@link RuntimeException}.
    468     *
    469     * @param predicate the predicate to test
    470     * @param object1 the first input to test by {@code predicate}
    471     * @param object2 the second input to test by {@code predicate}
    472     * @param <T> the type of the first argument the predicate tests
    473     * @param <U> the type of the second argument the predicate tests
    474     * @param <E> the type of checked exception the predicate may throw
    475     * @return the boolean value returned by the predicate
    476     */
    477    public static <T, U, E extends Throwable> boolean test(final FailableBiPredicate<T, U, E> predicate,
    478        final T object1, final U object2) {
    479        return getAsBoolean(() -> predicate.test(object1, object2));
    480    }
    481
    482    /**
    483     * Tests a predicate and rethrows any exception as a {@link RuntimeException}.
    484     *
    485     * @param predicate the predicate to test
    486     * @param object the input to test by {@code predicate}
    487     * @param <T> the type of argument the predicate tests
    488     * @param <E> the type of checked exception the predicate may throw
    489     * @return the boolean value returned by the predicate
    490     */
    491    public static <T, E extends Throwable> boolean test(final FailablePredicate<T, E> predicate, final T object) {
    492        return getAsBoolean(() -> predicate.test(object));
    493    }
    494
    495    /**
    496     * A simple try-with-resources implementation, that can be used, if your objects do not implement the
    497     * {@link AutoCloseable} interface. The method executes the {@code action}. The method guarantees, that <em>all</em>
    498     * the {@code resources} are being executed, in the given order, afterwards, and regardless of success, or failure.
    499     * If either the original action, or any of the resource action fails, then the <em>first</em> failure (AKA
    500     * {@link Throwable} is rethrown. Example use:
    501     *
    502     * <pre>
    503     * final FileInputStream fis = new FileInputStream("my.file");
    504     * Functions.tryWithResources(useInputStream(fis), null, () -&gt; fis.close());
    505     * </pre>
    506     *
    507     * @param action The action to execute. This object <em>will</em> always be invoked.
    508     * @param errorHandler An optional error handler, which will be invoked finally, if any error occurred. The error
    509     *        handler will receive the first error, AKA {@link Throwable}.
    510     * @param resources The resource actions to execute. <em>All</em> resource actions will be invoked, in the given
    511     *        order. A resource action is an instance of {@link FailableRunnable}, which will be executed.
    512     * @see #tryWithResources(FailableRunnable, FailableRunnable...)
    513     */
    514    @SafeVarargs
    515    public static void tryWithResources(final FailableRunnable<? extends Throwable> action,
    516        final FailableConsumer<Throwable, ? extends Throwable> errorHandler,
    517        final FailableRunnable<? extends Throwable>... resources) {
    518        final FailableConsumer<Throwable, ? extends Throwable> actualErrorHandler;
    519        if (errorHandler == null) {
    520            actualErrorHandler = Failable::rethrow;
    521        } else {
    522            actualErrorHandler = errorHandler;
    523        }
    524        if (resources != null) {
    525            for (final FailableRunnable<? extends Throwable> failableRunnable : resources) {
    526                Objects.requireNonNull(failableRunnable, "runnable");
    527            }
    528        }
    529        Throwable th = null;
    530        try {
    531            action.run();
    532        } catch (final Throwable t) {
    533            th = t;
    534        }
    535        if (resources != null) {
    536            for (final FailableRunnable<?> runnable : resources) {
    537                try {
    538                    runnable.run();
    539                } catch (final Throwable t) {
    540                    if (th == null) {
    541                        th = t;
    542                    }
    543                }
    544            }
    545        }
    546        if (th != null) {
    547            try {
    548                actualErrorHandler.accept(th);
    549            } catch (final Throwable t) {
    550                throw rethrow(t);
    551            }
    552        }
    553    }
    554
    555    /**
    556     * A simple try-with-resources implementation, that can be used, if your objects do not implement the
    557     * {@link AutoCloseable} interface. The method executes the {@code action}. The method guarantees, that <em>all</em>
    558     * the {@code resources} are being executed, in the given order, afterwards, and regardless of success, or failure.
    559     * If either the original action, or any of the resource action fails, then the <em>first</em> failure (AKA
    560     * {@link Throwable} is rethrown. Example use:
    561     *
    562     * <pre>
    563     * final FileInputStream fis = new FileInputStream("my.file");
    564     * Functions.tryWithResources(useInputStream(fis), () -&gt; fis.close());
    565     * </pre>
    566     *
    567     * @param action The action to execute. This object <em>will</em> always be invoked.
    568     * @param resources The resource actions to execute. <em>All</em> resource actions will be invoked, in the given
    569     *        order. A resource action is an instance of {@link FailableRunnable}, which will be executed.
    570     * @see #tryWithResources(FailableRunnable, FailableConsumer, FailableRunnable...)
    571     */
    572    @SafeVarargs
    573    public static void tryWithResources(final FailableRunnable<? extends Throwable> action,
    574        final FailableRunnable<? extends Throwable>... resources) {
    575        tryWithResources(action, null, resources);
    576    }
    577
    578    private Failable() {
    579        // empty
    580    }
    581
    582}