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 boolean, 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 boolean, 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 boolean, 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     * <p>
369     * Rethrows a {@link Throwable} as an unchecked exception. If the argument is already unchecked, namely a
370     * {@code RuntimeException} or {@code Error} then the argument will be rethrown without modification. If the
371     * exception is {@code IOException} then it will be wrapped into a {@code UncheckedIOException}. In every other
372     * cases the exception will be wrapped into a {@code
373     * UndeclaredThrowableException}
374     * </p>
375     *
376     * <p>
377     * Note that there is a declared return type for this method, even though it never returns. The reason for that is
378     * to support the usual pattern:
379     * </p>
380     *
381     * <pre>
382     * throw rethrow(myUncheckedException);
383     * </pre>
384     *
385     * <p>
386     * instead of just calling the method. This pattern may help the Java compiler to recognize that at that point an
387     * exception will be thrown and the code flow analysis will not demand otherwise mandatory commands that could
388     * follow the method call, like a {@code return} statement from a value returning method.
389     * </p>
390     *
391     * @param throwable The throwable to rethrow ossibly wrapped into an unchecked exception
392     * @return Never returns anything, this method never terminates normally.
393     */
394    public static RuntimeException rethrow(final Throwable throwable) {
395        Objects.requireNonNull(throwable, "throwable");
396        if (throwable instanceof RuntimeException) {
397            throw (RuntimeException) throwable;
398        } else if (throwable instanceof Error) {
399            throw (Error) throwable;
400        } else if (throwable instanceof IOException) {
401            throw new UncheckedIOException((IOException) throwable);
402        } else {
403            throw new UndeclaredThrowableException(throwable);
404        }
405    }
406
407    /**
408     * Runs a runnable and rethrows any exception as a {@link RuntimeException}.
409     *
410     * @param runnable The runnable to run
411     * @param <E> the type of checked exception the runnable may throw
412     */
413    public static <E extends Throwable> void run(final FailableRunnable<E> runnable) {
414        try {
415            runnable.run();
416        } catch (final Throwable t) {
417            throw rethrow(t);
418        }
419    }
420
421    /**
422     * Converts the given collection into a {@link FailableStream}. The {@link FailableStream} consists of the
423     * collections elements. Shortcut for
424     *
425     * <pre>
426     * Functions.stream(collection.stream());
427     * </pre>
428     *
429     * @param collection The collection, which is being converted into a {@link FailableStream}.
430     * @param <E> The collections element type. (In turn, the result streams element type.)
431     * @return The created {@link FailableStream}.
432     */
433    public static <E> FailableStream<E> stream(final Collection<E> collection) {
434        return new FailableStream<>(collection.stream());
435    }
436
437    /**
438     * Converts the given stream into a {@link FailableStream}. The {@link FailableStream} consists of the same
439     * elements, than the input stream. However, failable lambdas, like {@link FailablePredicate},
440     * {@link FailableFunction}, and {@link FailableConsumer} may be applied, rather than {@link Predicate},
441     * {@link Function}, {@link Consumer}, etc.
442     *
443     * @param stream The stream, which is being converted into a {@link FailableStream}.
444     * @param <T> The streams element type.
445     * @return The created {@link FailableStream}.
446     */
447    public static <T> FailableStream<T> stream(final Stream<T> stream) {
448        return new FailableStream<>(stream);
449    }
450
451    /**
452     * Tests a predicate and rethrows any exception as a {@link RuntimeException}.
453     *
454     * @param predicate the predicate to test
455     * @param object1 the first input to test by {@code predicate}
456     * @param object2 the second input to test by {@code predicate}
457     * @param <T> the type of the first argument the predicate tests
458     * @param <U> the type of the second argument the predicate tests
459     * @param <E> the type of checked exception the predicate may throw
460     * @return the boolean value returned by the predicate
461     */
462    public static <T, U, E extends Throwable> boolean test(final FailableBiPredicate<T, U, E> predicate,
463        final T object1, final U object2) {
464        return getAsBoolean(() -> predicate.test(object1, object2));
465    }
466
467    /**
468     * Tests a predicate and rethrows any exception as a {@link RuntimeException}.
469     *
470     * @param predicate the predicate to test
471     * @param object the input to test by {@code predicate}
472     * @param <T> the type of argument the predicate tests
473     * @param <E> the type of checked exception the predicate may throw
474     * @return the boolean value returned by the predicate
475     */
476    public static <T, E extends Throwable> boolean test(final FailablePredicate<T, E> predicate, final T object) {
477        return getAsBoolean(() -> predicate.test(object));
478    }
479
480    /**
481     * A simple try-with-resources implementation, that can be used, if your objects do not implement the
482     * {@link AutoCloseable} interface. The method executes the {@code action}. The method guarantees, that <em>all</em>
483     * the {@code resources} are being executed, in the given order, afterwards, and regardless of success, or failure.
484     * If either the original action, or any of the resource action fails, then the <em>first</em> failure (AKA
485     * {@link Throwable} is rethrown. Example use:
486     *
487     * <pre>
488     * final FileInputStream fis = new FileInputStream("my.file");
489     * Functions.tryWithResources(useInputStream(fis), null, () -&gt; fis.close());
490     * </pre>
491     *
492     * @param action The action to execute. This object <em>will</em> always be invoked.
493     * @param errorHandler An optional error handler, which will be invoked finally, if any error occurred. The error
494     *        handler will receive the first error, AKA {@link Throwable}.
495     * @param resources The resource actions to execute. <em>All</em> resource actions will be invoked, in the given
496     *        order. A resource action is an instance of {@link FailableRunnable}, which will be executed.
497     * @see #tryWithResources(FailableRunnable, FailableRunnable...)
498     */
499    @SafeVarargs
500    public static void tryWithResources(final FailableRunnable<? extends Throwable> action,
501        final FailableConsumer<Throwable, ? extends Throwable> errorHandler,
502        final FailableRunnable<? extends Throwable>... resources) {
503        final FailableConsumer<Throwable, ? extends Throwable> actualErrorHandler;
504        if (errorHandler == null) {
505            actualErrorHandler = Failable::rethrow;
506        } else {
507            actualErrorHandler = errorHandler;
508        }
509        if (resources != null) {
510            for (final FailableRunnable<? extends Throwable> failableRunnable : resources) {
511                Objects.requireNonNull(failableRunnable, "runnable");
512            }
513        }
514        Throwable th = null;
515        try {
516            action.run();
517        } catch (final Throwable t) {
518            th = t;
519        }
520        if (resources != null) {
521            for (final FailableRunnable<?> runnable : resources) {
522                try {
523                    runnable.run();
524                } catch (final Throwable t) {
525                    if (th == null) {
526                        th = t;
527                    }
528                }
529            }
530        }
531        if (th != null) {
532            try {
533                actualErrorHandler.accept(th);
534            } catch (final Throwable t) {
535                throw rethrow(t);
536            }
537        }
538    }
539
540    /**
541     * A simple try-with-resources implementation, that can be used, if your objects do not implement the
542     * {@link AutoCloseable} interface. The method executes the {@code action}. The method guarantees, that <em>all</em>
543     * the {@code resources} are being executed, in the given order, afterwards, and regardless of success, or failure.
544     * If either the original action, or any of the resource action fails, then the <em>first</em> failure (AKA
545     * {@link Throwable} is rethrown. Example use:
546     *
547     * <pre>
548     * final FileInputStream fis = new FileInputStream("my.file");
549     * Functions.tryWithResources(useInputStream(fis), () -&gt; fis.close());
550     * </pre>
551     *
552     * @param action The action to execute. This object <em>will</em> always be invoked.
553     * @param resources The resource actions to execute. <em>All</em> resource actions will be invoked, in the given
554     *        order. A resource action is an instance of {@link FailableRunnable}, which will be executed.
555     * @see #tryWithResources(FailableRunnable, FailableConsumer, FailableRunnable...)
556     */
557    @SafeVarargs
558    public static void tryWithResources(final FailableRunnable<? extends Throwable> action,
559        final FailableRunnable<? extends Throwable>... resources) {
560        tryWithResources(action, null, resources);
561    }
562
563    private Failable() {
564        // empty
565    }
566
567}