001/*
002 * (C) Copyright 2019 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Kevin Leturc <kleturc@nuxeo.com>
018 */
019package org.nuxeo.common.function;
020
021/**
022 * @param <E> the type of exception to throw
023 * @since 11.1
024 */
025@FunctionalInterface
026public interface ThrowableRunnable<E extends Throwable> {
027
028    void run() throws E;
029
030    /**
031     * @return this {@link ThrowableRunnable} as a {@link Runnable} throwing the checked exception as an unchecked one
032     */
033    default Runnable toRunnable() {
034        return asRunnable(this);
035    }
036
037    /**
038     * @return this {@link ThrowableRunnable} as a {@link ThrowableSupplier} returning {@link Void}
039     */
040    default ThrowableSupplier<Void, E> toThrowableSupplier() {
041        return asThrowableSupplier(this);
042    }
043
044    /**
045     * @return the given {@link ThrowableRunnable} as a {@link Runnable} throwing the checked exception as an unchecked
046     *         one
047     */
048    static <E extends Throwable> Runnable asRunnable(ThrowableRunnable<E> throwableRunnable) {
049        return () -> {
050            try {
051                throwableRunnable.run();
052            } catch (Throwable t) { // NOSONAR
053                FunctionUtils.sneakyThrow(t);
054            }
055        };
056    }
057
058    /**
059     * @return the given {@link ThrowableRunnable} as a {@link ThrowableSupplier} returning {@link Void}
060     */
061    static <E extends Throwable> ThrowableSupplier<Void, E> asThrowableSupplier(
062            ThrowableRunnable<E> throwableRunnable) {
063        return () -> {
064            throwableRunnable.run();
065            return null;
066        };
067    }
068
069}