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 *      https://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 */
017package org.apache.commons.lang3;
018
019import java.io.IOException;
020import java.io.UncheckedIOException;
021import java.lang.reflect.UndeclaredThrowableException;
022import java.util.Arrays;
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.Streams.FailableStream;
036import org.apache.commons.lang3.exception.ExceptionUtils;
037import org.apache.commons.lang3.function.Failable;
038import org.apache.commons.lang3.function.FailableBooleanSupplier;
039
040/**
041 * This class provides utility functions, and classes for working with the {@code java.util.function} package, or more
042 * generally, with Java 8 lambdas. More specifically, it attempts to address the fact that lambdas are supposed not to
043 * throw Exceptions, at least not checked Exceptions, AKA instances of {@link Exception}. This enforces the use of
044 * constructs like:
045 *
046 * <pre>
047 * {@code
048 *     Consumer<java.lang.reflect.Method> consumer = m -> {
049 *         try {
050 *             m.invoke(o, args);
051 *         } catch (Throwable t) {
052 *             throw Functions.rethrow(t);
053 *         }
054 *     };
055 * }</pre>
056 *
057 * <p>
058 * By replacing a {@link java.util.function.Consumer Consumer&lt;O&gt;} with a {@link FailableConsumer
059 * FailableConsumer&lt;O,? extends Throwable&gt;}, this can be written like follows:
060 * </p>
061 *
062 * <pre>
063 * {@code
064 *   Functions.accept((m) -> m.invoke(o,args));
065 * }</pre>
066 *
067 * <p>
068 * Obviously, the second version is much more concise and the spirit of Lambda expressions is met better than the second
069 * version.
070 * </p>
071 *
072 * @since 3.9
073 * @deprecated Use {@link org.apache.commons.lang3.function.Failable}.
074 */
075@Deprecated
076public class Functions {
077
078    /**
079     * A functional interface like {@link BiConsumer} that declares a {@link Throwable}.
080     *
081     * <p>
082     * TODO for 4.0: Move to org.apache.commons.lang3.function.
083     * </p>
084     *
085     * @param <O1> Consumed type 1.
086     * @param <O2> Consumed type 2.
087     * @param <T> Thrown exception.
088     * @deprecated Use {@link org.apache.commons.lang3.function.FailableBiConsumer}.
089     */
090    @Deprecated
091    @FunctionalInterface
092    public interface FailableBiConsumer<O1, O2, T extends Throwable> {
093
094        /**
095         * Accepts the consumer.
096         *
097         * @param object1 The first parameter for the consumable to accept
098         * @param object2 The second parameter for the consumable to accept
099         * @throws T Thrown when the consumer fails.
100         */
101        void accept(O1 object1, O2 object2) throws T;
102    }
103
104    /**
105     * A functional interface like {@link BiFunction} that declares a {@link Throwable}.
106     *
107     * <p>
108     * TODO for 4.0: Move to org.apache.commons.lang3.function.
109     * </p>
110     *
111     * @param <O1> Input type 1.
112     * @param <O2> Input type 2.
113     * @param <R> Return type.
114     * @param <T> Thrown exception.
115     * @deprecated Use {@link org.apache.commons.lang3.function.FailableBiFunction}.
116     */
117    @Deprecated
118    @FunctionalInterface
119    public interface FailableBiFunction<O1, O2, R, T extends Throwable> {
120
121        /**
122         * Applies this function.
123         *
124         * @param input1 The first input for the function
125         * @param input2 The second input for the function
126         * @return The result of the function
127         * @throws T Thrown when the function fails.
128         */
129        R apply(O1 input1, O2 input2) throws T;
130    }
131
132    /**
133     * A functional interface like {@link BiPredicate} that declares a {@link Throwable}.
134     *
135     * <p>
136     * TODO for 4.0: Move to org.apache.commons.lang3.function.
137     * </p>
138     *
139     * @param <O1> Predicate type 1.
140     * @param <O2> Predicate type 2.
141     * @param <T> Thrown exception.
142     * @deprecated Use {@link org.apache.commons.lang3.function.FailableBiPredicate}.
143     */
144    @Deprecated
145    @FunctionalInterface
146    public interface FailableBiPredicate<O1, O2, T extends Throwable> {
147
148        /**
149         * Tests the predicate.
150         *
151         * @param object1 The first object to test the predicate on
152         * @param object2 The second object to test the predicate on
153         * @return The predicate's evaluation
154         * @throws T Thrown if the predicate fails.
155         */
156        boolean test(O1 object1, O2 object2) throws T;
157    }
158
159    /**
160     * A functional interface like {@link java.util.concurrent.Callable} that declares a {@link Throwable}.
161     *
162     * <p>
163     * TODO for 4.0: Move to org.apache.commons.lang3.function.
164     * </p>
165     *
166     * @param <R> Return type.
167     * @param <T> Thrown exception.
168     * @deprecated Use {@link org.apache.commons.lang3.function.FailableCallable}.
169     */
170    @Deprecated
171    @FunctionalInterface
172    public interface FailableCallable<R, T extends Throwable> {
173
174        /**
175         * Calls the callable.
176         *
177         * @return The value returned from the callable
178         * @throws T Thrown if the callable fails.
179         */
180        R call() throws T;
181    }
182
183    /**
184     * A functional interface like {@link Consumer} that declares a {@link Throwable}.
185     *
186     * <p>
187     * TODO for 4.0: Move to org.apache.commons.lang3.function.
188     * </p>
189     *
190     * @param <O> Consumed type 1.
191     * @param <T> Thrown exception.
192     * @deprecated Use {@link org.apache.commons.lang3.function.FailableConsumer}.
193     */
194    @Deprecated
195    @FunctionalInterface
196    public interface FailableConsumer<O, T extends Throwable> {
197
198        /**
199         * Accepts the consumer.
200         *
201         * @param object The parameter for the consumable to accept
202         * @throws T Thrown when the consumer fails.
203         */
204        void accept(O object) throws T;
205    }
206
207    /**
208     * A functional interface like {@link Function} that declares a {@link Throwable}.
209     *
210     * <p>
211     * TODO for 4.0: Move to org.apache.commons.lang3.function.
212     * </p>
213     *
214     * @param <I> Input type 1.
215     * @param <R> Return type.
216     * @param <T> Thrown exception.
217     * @deprecated Use {@link org.apache.commons.lang3.function.FailableFunction}.
218     */
219    @Deprecated
220    @FunctionalInterface
221    public interface FailableFunction<I, R, T extends Throwable> {
222
223        /**
224         * Applies this function.
225         *
226         * @param input The input for the function
227         * @return The result of the function
228         * @throws T Thrown when the function fails.
229         */
230        R apply(I input) throws T;
231    }
232
233    /**
234     * A functional interface like {@link Predicate} that declares a {@link Throwable}.
235     *
236     * <p>
237     * TODO for 4.0: Move to org.apache.commons.lang3.function.
238     * </p>
239     *
240     * @param <I> Predicate type 1.
241     * @param <T> Thrown exception.
242     * @deprecated Use {@link org.apache.commons.lang3.function.FailablePredicate}.
243     */
244    @Deprecated
245    @FunctionalInterface
246    public interface FailablePredicate<I, T extends Throwable> {
247
248        /**
249         * Tests the predicate.
250         *
251         * @param object The object to test the predicate on
252         * @return The predicate's evaluation
253         * @throws T Thrown if the predicate fails.
254         */
255        boolean test(I object) throws T;
256    }
257
258    /**
259     * A functional interface like {@link Runnable} that declares a {@link Throwable}.
260     *
261     * <p>
262     * TODO for 4.0: Move to org.apache.commons.lang3.function.
263     * </p>
264     *
265     * @param <T> Thrown exception.
266     * @deprecated Use {@link org.apache.commons.lang3.function.FailableRunnable}.
267     */
268    @Deprecated
269    @FunctionalInterface
270    public interface FailableRunnable<T extends Throwable> {
271
272        /**
273         * Runs the function.
274         *
275         * @throws T Thrown when the function fails.
276         */
277        void run() throws T;
278    }
279
280    /**
281     * A functional interface like {@link Supplier} that declares a {@link Throwable}.
282     *
283     * <p>
284     * TODO for 4.0: Move to org.apache.commons.lang3.function.
285     * </p>
286     *
287     * @param <R> Return type.
288     * @param <T> Thrown exception.
289     * @deprecated Use {@link org.apache.commons.lang3.function.FailableSupplier}.
290     */
291    @Deprecated
292    @FunctionalInterface
293    public interface FailableSupplier<R, T extends Throwable> {
294
295        /**
296         * Gets an object.
297         *
298         * @return A result
299         * @throws T Thrown if the supplier fails.
300         */
301        R get() throws T;
302    }
303
304    /**
305     * Consumes a consumer and rethrows any exception as a {@link RuntimeException}.
306     *
307     * @param consumer The consumer to consume
308     * @param object1 The first object to consume by {@code consumer}
309     * @param object2 The second object to consume by {@code consumer}
310     * @param <O1> the type of the first argument the consumer accepts
311     * @param <O2> the type of the second argument the consumer accepts
312     * @param <T> The type of checked exception the consumer may throw
313     */
314    public static <O1, O2, T extends Throwable> void accept(final FailableBiConsumer<O1, O2, T> consumer,
315        final O1 object1, final O2 object2) {
316        run(() -> consumer.accept(object1, object2));
317    }
318
319    /**
320     * Consumes a consumer and rethrows any exception as a {@link RuntimeException}.
321     *
322     * @param consumer The consumer to consume
323     * @param object The object to consume by {@code consumer}
324     * @param <O> The type the consumer accepts
325     * @param <T> The type of checked exception the consumer may throw
326     */
327    public static <O, T extends Throwable> void accept(final FailableConsumer<O, T> consumer, final O object) {
328        run(() -> consumer.accept(object));
329    }
330
331    /**
332     * Applies a function and rethrows any exception as a {@link RuntimeException}.
333     *
334     * @param function The function to apply
335     * @param input1 The first input to apply {@code function} on
336     * @param input2 The second input to apply {@code function} on
337     * @param <O1> the type of the first argument the function accepts
338     * @param <O2> the type of the second argument the function accepts
339     * @param <O> The return type of the function
340     * @param <T> The type of checked exception the function may throw
341     * @return The value returned from the function
342     */
343    public static <O1, O2, O, T extends Throwable> O apply(final FailableBiFunction<O1, O2, O, T> function,
344        final O1 input1, final O2 input2) {
345        return get(() -> function.apply(input1, input2));
346    }
347
348    /**
349     * Applies a function and rethrows any exception as a {@link RuntimeException}.
350     *
351     * @param function The function to apply
352     * @param input The input to apply {@code function} on
353     * @param <I> The type of the argument the function accepts
354     * @param <O> The return type of the function
355     * @param <T> The type of checked exception the function may throw
356     * @return The value returned from the function
357     */
358    public static <I, O, T extends Throwable> O apply(final FailableFunction<I, O, T> function, final I input) {
359        return get(() -> function.apply(input));
360    }
361
362    /**
363     * Converts the given {@link FailableBiConsumer} into a standard {@link BiConsumer}.
364     *
365     * @param <O1> the type of the first argument of the consumers
366     * @param <O2> the type of the second argument of the consumers
367     * @param consumer A failable {@link BiConsumer}
368     * @return A standard {@link BiConsumer}
369     * @since 3.10
370     */
371    public static <O1, O2> BiConsumer<O1, O2> asBiConsumer(final FailableBiConsumer<O1, O2, ?> consumer) {
372        return (input1, input2) -> accept(consumer, input1, input2);
373    }
374
375    /**
376     * Converts the given {@link FailableBiFunction} into a standard {@link BiFunction}.
377     *
378     * @param <O1> the type of the first argument of the input of the functions
379     * @param <O2> the type of the second argument of the input of the functions
380     * @param <O> The type of the output of the functions
381     * @param function A {@link FailableBiFunction}
382     * @return A standard {@link BiFunction}
383     * @since 3.10
384     */
385    public static <O1, O2, O> BiFunction<O1, O2, O> asBiFunction(final FailableBiFunction<O1, O2, O, ?> function) {
386        return (input1, input2) -> apply(function, input1, input2);
387    }
388
389    /**
390     * Converts the given {@link FailableBiPredicate} into a standard {@link BiPredicate}.
391     *
392     * @param <O1> the type of the first argument used by the predicates
393     * @param <O2> the type of the second argument used by the predicates
394     * @param predicate A {@link FailableBiPredicate}
395     * @return A standard {@link BiPredicate}
396     * @since 3.10
397     */
398    public static <O1, O2> BiPredicate<O1, O2> asBiPredicate(final FailableBiPredicate<O1, O2, ?> predicate) {
399        return (input1, input2) -> test(predicate, input1, input2);
400    }
401
402    /**
403     * Converts the given {@link FailableCallable} into a standard {@link Callable}.
404     *
405     * @param <O> The type used by the callables
406     * @param callable A {@link FailableCallable}
407     * @return A standard {@link Callable}
408     * @since 3.10
409     */
410    public static <O> Callable<O> asCallable(final FailableCallable<O, ?> callable) {
411        return () -> call(callable);
412    }
413
414    /**
415     * Converts the given {@link FailableConsumer} into a standard {@link Consumer}.
416     *
417     * @param <I> The type used by the consumers
418     * @param consumer A {@link FailableConsumer}
419     * @return A standard {@link Consumer}
420     * @since 3.10
421     */
422    public static <I> Consumer<I> asConsumer(final FailableConsumer<I, ?> consumer) {
423        return input -> accept(consumer, input);
424    }
425
426    /**
427     * Converts the given {@link FailableFunction} into a standard {@link Function}.
428     *
429     * @param <I> The type of the input of the functions
430     * @param <O> The type of the output of the functions
431     * @param function A {code FailableFunction}
432     * @return A standard {@link Function}
433     * @since 3.10
434     */
435    public static <I, O> Function<I, O> asFunction(final FailableFunction<I, O, ?> function) {
436        return input -> apply(function, input);
437    }
438
439    /**
440     * Converts the given {@link FailablePredicate} into a standard {@link Predicate}.
441     *
442     * @param <I> The type used by the predicates
443     * @param predicate A {@link FailablePredicate}
444     * @return A standard {@link Predicate}
445     * @since 3.10
446     */
447    public static <I> Predicate<I> asPredicate(final FailablePredicate<I, ?> predicate) {
448        return input -> test(predicate, input);
449    }
450
451    /**
452     * Converts the given {@link FailableRunnable} into a standard {@link Runnable}.
453     *
454     * @param runnable A {@link FailableRunnable}
455     * @return A standard {@link Runnable}
456     * @since 3.10
457     */
458    public static Runnable asRunnable(final FailableRunnable<?> runnable) {
459        return () -> run(runnable);
460    }
461
462    /**
463     * Converts the given {@link FailableSupplier} into a standard {@link Supplier}.
464     *
465     * @param <O> The type supplied by the suppliers
466     * @param supplier A {@link FailableSupplier}
467     * @return A standard {@link Supplier}
468     * @since 3.10
469     */
470    public static <O> Supplier<O> asSupplier(final FailableSupplier<O, ?> supplier) {
471        return () -> get(supplier);
472    }
473
474    /**
475     * Calls a callable and rethrows any exception as a {@link RuntimeException}.
476     *
477     * @param callable The callable to call
478     * @param <O> The return type of the callable
479     * @param <T> The type of checked exception the callable may throw
480     * @return The value returned from the callable
481     */
482    public static <O, T extends Throwable> O call(final FailableCallable<O, T> callable) {
483        return get(callable::call);
484    }
485
486    /**
487     * Gets the result of invoking the supplier.
488     *
489     * @param supplier The supplier to invoke.
490     * @param <O> The supplier's output type.
491     * @param <T> The type of checked exception, which the supplier can throw.
492     * @return The object, which has been created by the supplier
493     * @since 3.10
494     */
495    public static <O, T extends Throwable> O get(final FailableSupplier<O, T> supplier) {
496        try {
497            return supplier.get();
498        } catch (final Throwable t) {
499            throw rethrow(t);
500        }
501    }
502
503    /**
504     * Gets the result of invoking the boolean supplier.
505     *
506     * @param supplier The boolean supplier to invoke.
507     * @param <T> The type of checked exception, which the supplier can throw.
508     * @return The boolean, which has been created by the supplier
509     */
510    private static <T extends Throwable> boolean getAsBoolean(final FailableBooleanSupplier<T> supplier) {
511        try {
512            return supplier.getAsBoolean();
513        } catch (final Throwable t) {
514            throw rethrow(t);
515        }
516    }
517
518    /**
519     * Rethrows a {@link Throwable} as an unchecked exception. If the argument is already unchecked, namely a
520     * {@link RuntimeException} or {@link Error} then the argument will be rethrown without modification. If the
521     * exception is {@link IOException} then it will be wrapped into a {@link UncheckedIOException}. In every other
522     * cases the exception will be wrapped into a {@code
523     * UndeclaredThrowableException}
524     *
525     * <p>
526     * Note that there is a declared return type for this method, even though it never returns. The reason for that is
527     * to support the usual pattern:
528     * </p>
529     *
530     * <pre>
531     * throw rethrow(myUncheckedException);</pre>
532     *
533     * <p>
534     * instead of just calling the method. This pattern may help the Java compiler to recognize that at that point an
535     * exception will be thrown and the code flow analysis will not demand otherwise mandatory commands that could
536     * follow the method call, like a {@code return} statement from a value returning method.
537     * </p>
538     *
539     * @param throwable The throwable to rethrow possibly wrapped into an unchecked exception
540     * @return Never returns anything, this method never terminates normally.
541     */
542    public static RuntimeException rethrow(final Throwable throwable) {
543        Objects.requireNonNull(throwable, "throwable");
544        ExceptionUtils.throwUnchecked(throwable);
545        if (throwable instanceof IOException) {
546            throw new UncheckedIOException((IOException) throwable);
547        }
548        throw new UndeclaredThrowableException(throwable);
549    }
550
551    /**
552     * Runs a runnable and rethrows any exception as a {@link RuntimeException}.
553     *
554     * @param runnable The runnable to run
555     * @param <T> The type of checked exception the runnable may throw
556     */
557    public static <T extends Throwable> void run(final FailableRunnable<T> runnable) {
558        try {
559            runnable.run();
560        } catch (final Throwable t) {
561            throw rethrow(t);
562        }
563    }
564
565    /**
566     * Converts the given collection into a {@link FailableStream}. The {@link FailableStream} consists of the
567     * collections elements. Shortcut for
568     *
569     * <pre>
570     * Functions.stream(collection.stream());</pre>
571     *
572     * @param collection The collection, which is being converted into a {@link FailableStream}.
573     * @param <O> The collections element type. (In turn, the result streams element type.)
574     * @return The created {@link FailableStream}.
575     * @since 3.10
576     */
577    public static <O> FailableStream<O> stream(final Collection<O> collection) {
578        return new FailableStream<>(collection.stream());
579    }
580
581    /**
582     * Converts the given stream into a {@link FailableStream}. The {@link FailableStream} consists of the same
583     * elements, than the input stream. However, failable lambdas, like {@link FailablePredicate},
584     * {@link FailableFunction}, and {@link FailableConsumer} may be applied, rather than {@link Predicate},
585     * {@link Function}, {@link Consumer}, etc.
586     *
587     * @param stream The stream, which is being converted into a {@link FailableStream}.
588     * @param <O> The streams element type.
589     * @return The created {@link FailableStream}.
590     * @since 3.10
591     */
592    public static <O> FailableStream<O> stream(final Stream<O> stream) {
593        return new FailableStream<>(stream);
594    }
595
596    /**
597     * Tests a predicate and rethrows any exception as a {@link RuntimeException}.
598     *
599     * @param predicate The predicate to test
600     * @param object1 The first input to test by {@code predicate}
601     * @param object2 The second input to test by {@code predicate}
602     * @param <O1> the type of the first argument the predicate tests
603     * @param <O2> the type of the second argument the predicate tests
604     * @param <T> The type of checked exception the predicate may throw
605     * @return The boolean value returned by the predicate
606     */
607    public static <O1, O2, T extends Throwable> boolean test(final FailableBiPredicate<O1, O2, T> predicate,
608        final O1 object1, final O2 object2) {
609        return getAsBoolean(() -> predicate.test(object1, object2));
610    }
611
612    /**
613     * Tests a predicate and rethrows any exception as a {@link RuntimeException}.
614     *
615     * @param predicate The predicate to test
616     * @param object The input to test by {@code predicate}
617     * @param <O> The type of argument the predicate tests
618     * @param <T> The type of checked exception the predicate may throw
619     * @return The boolean value returned by the predicate
620     */
621    public static <O, T extends Throwable> boolean test(final FailablePredicate<O, T> predicate, final O object) {
622        return getAsBoolean(() -> predicate.test(object));
623    }
624
625    /**
626     * A simple try-with-resources implementation, that can be used, if your objects do not implement the
627     * {@link AutoCloseable} interface. The method executes the {@code action}. The method guarantees, that <em>all</em>
628     * the {@code resources} are being executed, in the given order, afterwards, and regardless of success, or failure.
629     * If either the original action, or any of the resource action fails, then the <em>first</em> failure (AKA
630     * {@link Throwable}) is rethrown. Example use:
631     *
632     * <pre>
633     * {@code
634     *     final FileInputStream fis = new FileInputStream("my.file");
635     *     Functions.tryWithResources(useInputStream(fis), null, () -> fis.close());
636     * }</pre>
637     *
638     * @param action The action to execute. This object <em>will</em> always be invoked.
639     * @param errorHandler An optional error handler, which will be invoked finally, if any error occurred. The error
640     *        handler will receive the first error, AKA {@link Throwable}.
641     * @param resources The resource actions to execute. <em>All</em> resource actions will be invoked, in the given
642     *        order. A resource action is an instance of {@link FailableRunnable}, which will be executed.
643     * @see #tryWithResources(FailableRunnable, FailableRunnable...)
644     */
645    @SafeVarargs
646    public static void tryWithResources(final FailableRunnable<? extends Throwable> action,
647        final FailableConsumer<Throwable, ? extends Throwable> errorHandler,
648        final FailableRunnable<? extends Throwable>... resources) {
649        final org.apache.commons.lang3.function.FailableRunnable<?>[] fr = new org.apache.commons.lang3.function.FailableRunnable[resources.length];
650        Arrays.setAll(fr, i -> () -> resources[i].run());
651        Failable.tryWithResources(action::run, errorHandler != null ? errorHandler::accept : null, fr);
652    }
653
654    /**
655     * A simple try-with-resources implementation, that can be used, if your objects do not implement the
656     * {@link AutoCloseable} interface. The method executes the {@code action}. The method guarantees, that <em>all</em>
657     * the {@code resources} are being executed, in the given order, afterwards, and regardless of success, or failure.
658     * If either the original action, or any of the resource action fails, then the <em>first</em> failure (AKA
659     * {@link Throwable}) is rethrown. Example use:
660     *
661     * <pre>
662     * {@code
663     *     final FileInputStream fis = new FileInputStream("my.file");
664     *     Functions.tryWithResources(useInputStream(fis), () -> fis.close());
665     * }</pre>
666     *
667     * @param action The action to execute. This object <em>will</em> always be invoked.
668     * @param resources The resource actions to execute. <em>All</em> resource actions will be invoked, in the given
669     *        order. A resource action is an instance of {@link FailableRunnable}, which will be executed.
670     * @see #tryWithResources(FailableRunnable, FailableConsumer, FailableRunnable...)
671     */
672    @SafeVarargs
673    public static void tryWithResources(final FailableRunnable<? extends Throwable> action,
674        final FailableRunnable<? extends Throwable>... resources) {
675        tryWithResources(action, null, resources);
676    }
677
678    /**
679     * Constructs a new instance.
680     */
681    public Functions() {
682        // empty
683    }
684}