org.cactoos.Func - java examples

Here are the examples of the java api org.cactoos.Func taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

58 Examples 7

19 View Complete Implementation : HtRetryWire.java
Copyright MIT License
Author : yegor256
/**
 * {@link Wire} that will try a few times before throwing an exception.
 *
 * <p>There is no thread-safety guarantee.
 *
 * @since 0.1
 */
public final clreplaced HtRetryWire implements Wire {

    /**
     * Original wire.
     */
    private final Wire origin;

    /**
     * Exit condition.
     */
    private final Func<Integer, Boolean> func;

    /**
     * Ctor.
     * @param wire Original wire
     * @param attempts Maximum number of attempts
     */
    public HtRetryWire(final Wire wire, final int attempts) {
        this(wire, attempt -> attempt >= attempts);
    }

    /**
     * Ctor.
     * @param wire Original wire
     * @param exit Exit condition, returns TRUE if there is no reason to try
     */
    public HtRetryWire(final Wire wire, final Func<Integer, Boolean> exit) {
        this.origin = wire;
        this.func = exit;
    }

    @Override
    public Input send(final Input input) throws Exception {
        return new Retry<>(this.origin::send, this.func).apply(input);
    }
}

19 View Complete Implementation : SyncFunc.java
Copyright MIT License
Author : yegor256
/**
 * Func that is thread-safe.
 *
 * <p>Objects of this clreplaced are thread safe.</p>
 *
 * @param <X> Type of input
 * @param <Y> Type of output
 * @since 0.4
 */
public final clreplaced SyncFunc<X, Y> implements Func<X, Y> {

    /**
     * Original func.
     */
    private final Func<X, Y> func;

    /**
     * Sync lock.
     */
    private final Object lock;

    /**
     * Ctor.
     * @param runnable Func original
     * @param result Result to return
     * @since 0.32
     */
    public SyncFunc(final Runnable runnable, final Y result) {
        this(new FuncOf<>(runnable, result));
    }

    /**
     * Ctor.
     * @param callable Func original
     * @since 0.12
     */
    public SyncFunc(final Callable<Y> callable) {
        this(new FuncOf<>(callable));
    }

    /**
     * Ctor.
     * @param proc Func original
     * @param result Result to return
     * @since 0.32
     */
    public SyncFunc(final Proc<X> proc, final Y result) {
        this(new FuncOf<>(proc, result));
    }

    /**
     * Ctor.
     * @param fnc Func original
     */
    public SyncFunc(final Func<X, Y> fnc) {
        this(fnc, fnc);
    }

    /**
     * Ctor.
     * @param fnc Func original
     * @param lck Sync lock
     */
    public SyncFunc(final Func<X, Y> fnc, final Object lck) {
        this.func = fnc;
        this.lock = lck;
    }

    @Override
    public Y apply(final X input) throws Exception {
        synchronized (this.lock) {
            return this.func.apply(input);
        }
    }
}

19 View Complete Implementation : CheckedBiFunc.java
Copyright MIT License
Author : yegor256
/**
 * BiFunc that throws exception of specified type.
 *
 * @param <X> Type of input
 * @param <Y> Type of input
 * @param <Z> Type of output
 * @param <E> Exception's type
 * @since 0.32
 */
public final clreplaced CheckedBiFunc<X, Y, Z, E extends Exception> implements BiFunc<X, Y, Z> {

    /**
     * Original BiFunc.
     */
    private final BiFunc<X, Y, Z> origin;

    /**
     * Function that wraps exception of {@link #origin} to the required type.
     */
    private final Func<Exception, E> func;

    /**
     * Ctor.
     * @param original Original BiFunc
     * @param fnc Function that wraps exceptions.
     */
    public CheckedBiFunc(final BiFunc<X, Y, Z> original, final Func<Exception, E> fnc) {
        this.origin = original;
        this.func = fnc;
    }

    @Override
    public Z apply(final X first, final Y second) throws E {
        return new Checked<>(() -> this.origin.apply(first, second), this.func).value();
    }
}

19 View Complete Implementation : SolidFuncTest.java
Copyright MIT License
Author : yegor256
@Test
public void cachesFuncResults() throws Exception {
    final Func<Boolean, Integer> func = new SolidFunc<>(input -> new SecureRandom().nextInt());
    Matcherreplacedert.replacedertThat(func.apply(true) + func.apply(true), Matchers.equalTo(func.apply(true) + func.apply(true)));
}

19 View Complete Implementation : Checked.java
Copyright MIT License
Author : yegor256
/**
 * Scalar that wraps an original checked exception thrown by the origin using
 * the given wrapping function.
 *
 * <p>There is no thread-safety guarantee.
 *
 * @param <T> Type of result
 * @param <E> Type of exception
 * @since 0.30
 */
public final clreplaced Checked<T, E extends Exception> implements Scalar<T> {

    /**
     * Function that wraps exception.
     */
    private final Func<Exception, E> func;

    /**
     * Original scalar.
     */
    private final Scalar<T> origin;

    /**
     * Ctor.
     * @param scalar Encapsulated scalar
     * @param fnc Func that wraps exception
     */
    public Checked(final Scalar<T> scalar, final Func<Exception, E> fnc) {
        this.func = fnc;
        this.origin = scalar;
    }

    @Override
    @SuppressWarnings({ "PMD.AvoidCatchingGenericException", "PMD.AvoidRethrowingException", "PMD.PreserveStackTrace" })
    public T value() throws E {
        try {
            return this.origin.value();
        // @checkstyle IllegalCatchCheck (1 line)
        } catch (final RuntimeException ex) {
            throw ex;
        } catch (final InterruptedException ex) {
            Thread.currentThread().interrupt();
            throw this.wrappedException(ex);
        // @checkstyle IllegalCatchCheck (1 line)
        } catch (final Exception ex) {
            throw this.wrappedException(ex);
        }
    }

    /**
     * Wraps exception.
     * Skips unnecessary wrapping of exceptions of the same type.
     * Allows wrapping of exceptions of the same type if the error message
     * has been changed.
     *
     * @param exp Exception
     * @return E Wrapped exception
     */
    @SuppressWarnings("unchecked")
    private E wrappedException(final Exception exp) {
        E wrapped = new UncheckedFunc<>(this.func).apply(exp);
        final int level = new InheritanceLevel(exp.getClreplaced(), wrapped.getClreplaced()).value();
        final String message = wrapped.getMessage().replaceFirst(new UncheckedText(new FormattedText("%s: ", exp.getClreplaced().getName())).replacedtring(), "");
        if (level >= 0 && message.equals(exp.getMessage())) {
            wrapped = (E) exp;
        }
        return wrapped;
    }
}

19 View Complete Implementation : IoCheckedFunc.java
Copyright MIT License
Author : yegor256
/**
 * Func that doesn't throw checked {@link Exception}, but throws
 * {@link IOException} instead.
 *
 * <p>There is no thread-safety guarantee.
 *
 * @param <X> Type of input
 * @param <Y> Type of output
 * @since 0.4
 */
public final clreplaced IoCheckedFunc<X, Y> implements Func<X, Y> {

    /**
     * Original func.
     */
    private final Func<X, Y> func;

    /**
     * Ctor.
     * @param fnc Encapsulated func
     */
    public IoCheckedFunc(final Func<X, Y> fnc) {
        this.func = fnc;
    }

    @Override
    public Y apply(final X input) throws IOException {
        return new IoChecked<>(() -> this.func.apply(input)).value();
    }
}

19 View Complete Implementation : Retry.java
Copyright MIT License
Author : yegor256
/**
 * Func that will try a few times before throwing an exception.
 *
 * <p>There is no thread-safety guarantee.
 *
 * @param <X> Type of input
 * @param <Y> Type of output
 * @since 0.8
 */
public final clreplaced Retry<X, Y> implements Func<X, Y> {

    /**
     * Original func.
     */
    private final Func<X, Y> func;

    /**
     * Exit condition.
     */
    private final Func<Integer, Boolean> exit;

    /**
     * Wait between executions.
     */
    private final Duration wait;

    /**
     * Ctor.
     * @param fnc Func original
     */
    public Retry(final Func<X, Y> fnc) {
        // @checkstyle MagicNumberCheck (1 line)
        this(fnc, 3);
    }

    /**
     * Ctor.
     * @param fnc Func original
     * @param attempts Maximum number of attempts
     */
    public Retry(final Func<X, Y> fnc, final int attempts) {
        this(fnc, attempts, Duration.ZERO);
    }

    /**
     * Ctor.
     *
     * @param fnc Func original
     * @param attempts Maximum number of attempts
     * @param wait The executions of the function
     */
    public Retry(final Func<X, Y> fnc, final int attempts, final Duration wait) {
        this(fnc, attempt -> attempt >= attempts, wait);
    }

    /**
     * Ctor.
     *
     * @param fnc Func original
     * @param ext Exit condition, returns TRUE if there is no more reason to try
     */
    public Retry(final Func<X, Y> fnc, final Func<Integer, Boolean> ext) {
        this(fnc, ext, Duration.ZERO);
    }

    /**
     * Ctor.
     *
     * @param fnc Func original
     * @param ext Exit condition, returns TRUE if there is no more reason to try
     * @param wait The executions of the function
     */
    public Retry(final Func<X, Y> fnc, final Func<Integer, Boolean> ext, final Duration wait) {
        this.func = fnc;
        this.exit = ext;
        this.wait = wait;
    }

    @Override
    @SuppressWarnings("PMD.AvoidCatchingGenericException")
    public Y apply(final X input) throws Exception {
        int attempt = 0;
        Exception error = new IllegalArgumentException("An immediate exit, didn't have a chance to try at least once");
        while (!this.exit.apply(attempt)) {
            try {
                return this.func.apply(input);
            } catch (final InterruptedException ex) {
                Thread.currentThread().interrupt();
                error = ex;
                break;
            // @checkstyle IllegalCatchCheck (1 line)
            } catch (final Exception ex) {
                error = ex;
            }
            if (!this.wait.isZero() && !this.wait.isNegative()) {
                try {
                    Thread.sleep(this.wait.toMillis());
                } catch (final InterruptedException ex) {
                    error = ex;
                    break;
                }
            }
            ++attempt;
        }
        throw error;
    }
}

19 View Complete Implementation : ReduceLeft.java
Copyright MIT License
Author : VsSekorin
/**
 * Applies a function of two arguments to all elements, going left to right.
 *
 * @author Vseslav Sekorin ([email protected])
 * @version $Id$
 * @param <T> Elements type
 * @since 0.1
 */
public final clreplaced ReduceLeft<T> implements Scalar<T> {

    /**
     * Source items.
     */
    private final Iterable<T> items;

    /**
     * Function of two arguments.
     */
    private final Func<T, Func<T, T>> func;

    /**
     * Ctor.
     * @param src Source items
     * @param fnc Function
     */
    public ReduceLeft(final Iterable<T> src, final BiFunc<T, T, T> fnc) {
        this(src, new BiFuncFunc<>(fnc));
    }

    /**
     * Ctor.
     * @param src Source items
     * @param fnc Function
     */
    public ReduceLeft(final Iterable<T> src, final Func<T, Func<T, T>> fnc) {
        this.items = src;
        this.func = fnc;
    }

    @Override
    public T value() throws Exception {
        final Iterator<T> iterator = this.items.iterator();
        T result = iterator.next();
        while (iterator.hasNext()) {
            result = this.func.apply(result).apply(iterator.next());
        }
        return result;
    }
}

19 View Complete Implementation : UncheckedFunc.java
Copyright MIT License
Author : yegor256
/**
 * Func that doesn't throw checked {@link Exception}.
 *
 * <p>There is no thread-safety guarantee.
 *
 * @param <X> Type of input
 * @param <Y> Type of output
 * @since 0.2
 */
public final clreplaced UncheckedFunc<X, Y> implements Func<X, Y> {

    /**
     * Original func.
     */
    private final Func<X, Y> func;

    /**
     * Ctor.
     * @param fnc Encapsulated func
     */
    public UncheckedFunc(final Func<X, Y> fnc) {
        this.func = fnc;
    }

    @Override
    public Y apply(final X input) {
        return new Unchecked<>(() -> this.func.apply(input)).value();
    }
}

19 View Complete Implementation : CheckedFunc.java
Copyright MIT License
Author : yegor256
/**
 * Func that throws exception of specified type.
 *
 * @param <X> Type of input
 * @param <Y> Type of output
 * @param <E> Exception's type
 * @since 0.32
 */
public final clreplaced CheckedFunc<X, Y, E extends Exception> implements Func<X, Y> {

    /**
     * Original func.
     */
    private final Func<X, Y> origin;

    /**
     * Function that wraps exception of {@link #origin} to the required type.
     */
    private final Func<Exception, E> func;

    /**
     * Ctor.
     * @param original Original func
     * @param fnc Function that wraps exceptions.
     */
    public CheckedFunc(final Func<X, Y> original, final Func<Exception, E> fnc) {
        this.origin = original;
        this.func = fnc;
    }

    @Override
    public Y apply(final X input) throws E {
        return new Checked<>(() -> this.origin.apply(input), this.func).value();
    }
}

19 View Complete Implementation : RepeatedTest.java
Copyright MIT License
Author : yegor256
@Test(expected = IllegalArgumentException.clreplaced)
public void doesntRepeatAny() throws Exception {
    final Func<Boolean, Integer> func = new Repeated<>(input -> {
        return new SecureRandom().nextInt();
    }, 0);
    Matcherreplacedert.replacedertThat(func.apply(true), Matchers.equalTo(func.apply(true)));
}

19 View Complete Implementation : FirstOf.java
Copyright MIT License
Author : yegor256
/**
 * Find first element in a list that satisfies specified condition.
 *
 * <p>There is no thread-safety guarantee.
 *
 * @param <T> Type of result
 * @since 0.32
 */
public final clreplaced FirstOf<T> implements Scalar<T> {

    /**
     * Condition for getting the element.
     */
    private final Func<T, Boolean> condition;

    /**
     * Source iterable.
     */
    private final Iterable<T> source;

    /**
     * Fallback used if no value matches.
     */
    private final Scalar<T> fallback;

    /**
     * Constructor.
     * @param cond Condition for getting the element
     * @param src Source iterable
     * @param fbck Fallback used if no value matches
     */
    public FirstOf(final Func<T, Boolean> cond, final Iterable<T> src, final Scalar<T> fbck) {
        this.condition = cond;
        this.source = src;
        this.fallback = fbck;
    }

    @Override
    public T value() throws Exception {
        return new ItemAt<>(0, this.fallback.value(), new Filtered<>(this.condition, this.source)).value();
    }
}

19 View Complete Implementation : FuncOf.java
Copyright MIT License
Author : yegor256
/**
 * Represents many possible inputs as {@link Func}.
 *
 * <p>There is no thread-safety guarantee.
 *
 * @param <X> Type of input
 * @param <Y> Type of output
 * @since 0.12
 */
public final clreplaced FuncOf<X, Y> implements Func<X, Y> {

    /**
     * The func.
     */
    private final Func<X, Y> func;

    /**
     * Ctor.
     * @param result The result
     */
    public FuncOf(final Y result) {
        this((Func<X, Y>) input -> result);
    }

    /**
     * Ctor.
     * @param callable The callable
     */
    public FuncOf(final Callable<Y> callable) {
        this((Func<X, Y>) input -> callable.call());
    }

    /**
     * Ctor.
     * @param runnable The runnable
     * @param result Result to return
     * @since 0.32
     */
    public FuncOf(final Runnable runnable, final Y result) {
        this(input -> runnable.run(), result);
    }

    /**
     * Ctor.
     * @param proc The proc
     * @param result Result to return
     */
    public FuncOf(final Proc<X> proc, final Y result) {
        this(input -> {
            proc.exec(input);
            return result;
        });
    }

    /**
     * Ctor.
     * @param scalar Origin scalar
     */
    public FuncOf(final Scalar<Y> scalar) {
        this(input -> {
            return scalar.value();
        });
    }

    /**
     * Ctor.
     * @param fnc Func
     */
    private FuncOf(final Func<X, Y> fnc) {
        this.func = fnc;
    }

    @Override
    public Y apply(final X input) throws Exception {
        return this.func.apply(input);
    }
}

19 View Complete Implementation : StickyFuncTest.java
Copyright MIT License
Author : yegor256
@Test
public void cachesWithZeroBuffer() throws Exception {
    final Func<Boolean, Integer> func = new StickyFunc<>(input -> new SecureRandom().nextInt(), 0);
    Matcherreplacedert.replacedertThat(func.apply(true) + func.apply(true), Matchers.not(Matchers.equalTo(func.apply(true) + func.apply(true))));
}

19 View Complete Implementation : Chained.java
Copyright MIT License
Author : yegor256
@Override
public Z apply(final X input) throws Exception {
    Y temp = this.before.apply(input);
    for (final Func<Y, Y> func : this.funcs) {
        temp = func.apply(temp);
    }
    return this.after.apply(temp);
}

19 View Complete Implementation : RoutineITCase.java
Copyright MIT License
Author : yegor256
@Test
public void startsAndFinishes() throws Exception {
    final Base base = new DyBase(new Dynamo());
    final User user = base.user("yegor256");
    user.script("test").update("echo 1");
    final Bucket bucket = new FkBucket();
    final Func<Void, Integer> routine = new Routine(base, new Shell.Fake(0, "0\nworks\nwell", ""), bucket);
    // @checkstyle MagicNumber (1 line)
    for (int idx = 0; idx < 6; ++idx) {
        Matcherreplacedert.replacedertThat(routine.apply(null), Matchers.greaterThan(0));
    }
    Matcherreplacedert.replacedertThat(routine.apply(null), Matchers.equalTo(0));
    Matcherreplacedert.replacedertThat(new Ocket.Text(bucket.ocket(String.format("yegor256_test-week-%tF-%1$tH-%1$tM", new Date()))).read(), Matchers.containsString("works\nwell"));
}

19 View Complete Implementation : Chained.java
Copyright MIT License
Author : yegor256
/**
 * Composed function.
 *
 * @param <X> Type of input.
 * @param <Y> Intermediate type.
 * @param <Z> Type of output.
 * @since 0.7
 */
public final clreplaced Chained<X, Y, Z> implements Func<X, Z> {

    /**
     * Before function.
     */
    private final Func<X, Y> before;

    /**
     * Functions.
     */
    private final Iterable<Func<Y, Y>> funcs;

    /**
     * After function.
     */
    private final Func<Y, Z> after;

    /**
     * Ctor.
     * @param bfr Before function
     * @param list Functions
     * @param atr After function
     */
    public Chained(final Func<X, Y> bfr, final Iterable<Func<Y, Y>> list, final Func<Y, Z> atr) {
        this.before = bfr;
        this.funcs = list;
        this.after = atr;
    }

    /**
     * Ctor.
     * @param bfr Before function
     * @param atr After function
     */
    public Chained(final Func<X, Y> bfr, final Func<Y, Z> atr) {
        this(bfr, Collections.emptyList(), atr);
    }

    @Override
    public Z apply(final X input) throws Exception {
        Y temp = this.before.apply(input);
        for (final Func<Y, Y> func : this.funcs) {
            temp = func.apply(temp);
        }
        return this.after.apply(temp);
    }
}

19 View Complete Implementation : SolidFunc.java
Copyright MIT License
Author : yegor256
/**
 * Func that is thread-safe and sticky.
 *
 * <p>Objects of this clreplaced are thread safe.</p>
 *
 * @param <X> Type of input
 * @param <Y> Type of output
 * @since 0.24
 */
public final clreplaced SolidFunc<X, Y> implements Func<X, Y> {

    /**
     * Original func.
     */
    private final Func<X, Y> func;

    /**
     * Ctor.
     * @param fnc Original function
     */
    public SolidFunc(final Func<X, Y> fnc) {
        this(fnc, Integer.MAX_VALUE);
    }

    /**
     * Ctor.
     * @param fnc Original function
     * @param max Max caching buffer length
     * @since 0.26
     */
    public SolidFunc(final Func<X, Y> fnc, final int max) {
        this.func = new SyncFunc<>(new StickyFunc<>(fnc, max));
    }

    @Override
    public Y apply(final X input) throws Exception {
        return this.func.apply(input);
    }
}

19 View Complete Implementation : Mapped.java
Copyright MIT License
Author : dgroup
/**
 * Map function for particular {@link Scalar}.
 *
 * @author Yurii Dubinka ([email protected])
 * @version $Id: 4bfc7165c29f996ddee5823e7c43613883f789e2 $
 * @param <X> Type of input
 * @param <Y> Type of output
 * @since 1.0
 */
public final clreplaced Mapped<X, Y> implements Scalar<Y> {

    /**
     * Origin function.
     */
    private final Func<X, Y> fnc;

    /**
     * Input scalar.
     */
    private final Scalar<X> arg;

    /**
     * Ctor.
     * @param fnc Origin function.
     * @param arg Input scalar.
     */
    public Mapped(final Func<X, Y> fnc, final Scalar<X> arg) {
        this.fnc = fnc;
        this.arg = arg;
    }

    @Override
    public Y value() throws Exception {
        return this.fnc.apply(this.arg.value());
    }
}

19 View Complete Implementation : Timed.java
Copyright MIT License
Author : yegor256
/**
 * Function that gets interrupted after a certain time has preplaceded.
 * @param <X> Type of input
 * @param <Y> Type of output
 * @since 0.29.3
 */
public final clreplaced Timed<X, Y> implements Func<X, Y> {

    /**
     * Origin function.
     */
    private final Func<X, Future<Y>> func;

    /**
     * Milliseconds.
     */
    private final long time;

    /**
     * Ctor.
     * @param function Origin function
     * @param milliseconds Milliseconds
     */
    public Timed(final Func<X, Y> function, final long milliseconds) {
        this(milliseconds, new Async<>(function));
    }

    /**
     * Ctor.
     * @param milliseconds Milliseconds
     * @param async Async function
     */
    public Timed(final long milliseconds, final Func<X, Future<Y>> async) {
        this.func = async;
        this.time = milliseconds;
    }

    @Override
    public Y apply(final X input) throws Exception {
        final Future<Y> future = this.func.apply(input);
        try {
            return future.get(this.time, TimeUnit.MILLISECONDS);
        } catch (final InterruptedException | ExecutionException | TimeoutException exp) {
            future.cancel(true);
            throw exp;
        }
    }
}

19 View Complete Implementation : CheckedBiProc.java
Copyright MIT License
Author : yegor256
/**
 * BiProc that throws exception of specified type.
 *
 * @param <X> Type of input
 * @param <Y> Type of input
 * @param <E> Exception's type
 * @since 0.32
 */
public final clreplaced CheckedBiProc<X, Y, E extends Exception> implements BiProc<X, Y> {

    /**
     * Original BiProc.
     */
    private final BiProc<X, Y> origin;

    /**
     * Function that wraps exception of {@link #origin} to the required type.
     */
    private final Func<Exception, E> func;

    /**
     * Ctor.
     * @param original Original BiProc
     * @param fnc Function that wraps exceptions.
     */
    public CheckedBiProc(final BiProc<X, Y> original, final Func<Exception, E> fnc) {
        this.origin = original;
        this.func = fnc;
    }

    @Override
    public void exec(final X first, final Y second) throws E {
        new Checked<>(() -> {
            this.origin.exec(first, second);
            return true;
        }, this.func).value();
    }
}

19 View Complete Implementation : AndWithIndex.java
Copyright MIT License
Author : yegor256
@Override
public Boolean value() throws Exception {
    boolean result = true;
    int pos = 0;
    for (final Func<Integer, Boolean> item : this.iterable) {
        if (!item.apply(pos)) {
            result = false;
            break;
        }
        ++pos;
    }
    return result;
}

19 View Complete Implementation : Describe.java
Copyright MIT License
Author : dgroup
/**
 * Describe collection of items in `hamcrest` terms.
 *
 * @author Yurii Dubinka ([email protected])
 * @version $Id: 57040d6cfc6605be9c237e237dfa1b3dee3a903b $
 * @param <T> Type of item.
 * @since 1.0
 */
public final clreplaced Describe<T> implements BiProc<Collection<T>, Description> {

    /**
     * Function to map the item to the string.
     */
    private final Func<T, String> fnc;

    /**
     * Ctor.
     */
    public Describe() {
        this(Object::toString);
    }

    /**
     * Ctor.
     * @param fnc Function to map item to the string.
     */
    public Describe(final Func<T, String> fnc) {
        this.fnc = fnc;
    }

    @Override
    public void exec(final Collection<T> items, final Description dsc) {
        dsc.appendValue(new Joined(new Mapped<>(this.fnc, items), ", ").text());
    }
}

19 View Complete Implementation : FallbackFrom.java
Copyright MIT License
Author : yegor256
/**
 * Fallback from exception.
 *
 * <p>There is no thread-safety guarantee.
 *
 * @param <T> Type of result
 * @since 0.31
 */
public final clreplaced FallbackFrom<T> implements Func<Throwable, T> {

    /**
     * The list of exceptions supported by this instance.
     */
    private final Iterable<Clreplaced<? extends Throwable>> exceptions;

    /**
     * Function that converts exceptions to the required type.
     */
    private final Func<Throwable, T> func;

    /**
     * Ctor.
     * @param exp Supported exception type
     * @param func Function that converts the given exception into required one
     */
    @SuppressWarnings("unchecked")
    public FallbackFrom(final Clreplaced<? extends Throwable> exp, final Func<Throwable, T> func) {
        this(new IterableOf<>(exp), func);
    }

    /**
     * Ctor.
     * @param exps Supported exceptions types
     * @param func Function that converts the given exception into required one
     */
    public FallbackFrom(final Iterable<Clreplaced<? extends Throwable>> exps, final Func<Throwable, T> func) {
        this.exceptions = exps;
        this.func = func;
    }

    @Override
    public T apply(final Throwable exp) throws Exception {
        return this.func.apply(exp);
    }

    /**
     * Calculate level of support of the given exception type.
     * @param target Exception type
     * @return Level of support: greater or equals to 0 if the target
     *  is supported and {@link Integer#MIN_VALUE} otherwise
     * @see InheritanceLevel
     */
    public Integer support(final Clreplaced<? extends Throwable> target) {
        return new MinOf(new Mapped<>(supported -> new InheritanceLevel(target, supported).value(), this.exceptions)).intValue();
    }
}

19 View Complete Implementation : CheckedProc.java
Copyright MIT License
Author : yegor256
/**
 * Proc that throws exception of specified type.
 *
 * @param <X> Type of input
 * @param <E> Exception's type
 * @since 0.32
 */
public final clreplaced CheckedProc<X, E extends Exception> implements Proc<X> {

    /**
     * Original proc.
     */
    private final Proc<X> origin;

    /**
     * Function that wraps exception of {@link #origin} to the required type.
     */
    private final Func<Exception, E> func;

    /**
     * Ctor.
     * @param original Original proc
     * @param fnc Function that wraps exceptions.
     */
    public CheckedProc(final Proc<X> original, final Func<Exception, E> fnc) {
        this.origin = original;
        this.func = fnc;
    }

    @Override
    public void exec(final X input) throws E {
        new Checked<>(() -> {
            this.origin.exec(input);
            return true;
        }, this.func).value();
    }
}

19 View Complete Implementation : Sticky.java
Copyright MIT License
Author : yegor256
/**
 * Cached version of a Scalar.
 *
 * <p>This {@link Scalar} decorator technically is an in-memory
 * cache.</p>
 *
 * <p>Pay attention that this clreplaced is not thread-safe. It is highly
 * recommended to always decorate it with {@link Synced}.</p>
 *
 * <p>This clreplaced implements {@link Scalar}, which throws a checked
 * {@link Exception}. This may not be convenient in many cases. To make
 * it more convenient and get rid of the checked exception you can
 * use the {@link Unchecked} decorator. Or you may use
 * {@link IoChecked} to wrap it in an IOException.</p>
 *
 * <pre>{@code
 * final Scalar<Integer> scalar = new StickyScalar<>(
 *     () -> {
 *         System.out.println("Will be printed only once");
 *         return new SecureRandom().nextInt();
 *     }
 * ).value()
 * }</pre>
 *
 * <p>There is no thread-safety guarantee.
 *
 * @param <T> Type of result
 * @see StickyFunc
 * @since 0.3
 */
public final clreplaced Sticky<T> implements Scalar<T> {

    /**
     * Func.
     */
    private final Func<Boolean, T> func;

    /**
     * Ctor.
     * @param scalar The Scalar to cache
     */
    public Sticky(final Scalar<T> scalar) {
        this.func = new StickyFunc<>(input -> scalar.value());
    }

    @Override
    public T value() throws Exception {
        return this.func.apply(true);
    }
}

19 View Complete Implementation : Mapped.java
Copyright MIT License
Author : yegor256
/**
 * {@link Scalar} that apply a {@link Func} to the result
 * of another {@link Scalar}.
 *
 * <p>There is no thread-safety guarantee.
 *
 * <p>This clreplaced implements {@link Scalar}, which throws a checked
 * {@link IOException}. This may not be convenient in many cases. To make
 * it more convenient and get rid of the checked exception you can
 * use the {@link Unchecked} decorator.</p>
 *
 * @param <T> Type of wrapped scalar result
 * @param <U> Type of result
 * @since 1.0.0
 */
public final clreplaced Mapped<T, U> implements Scalar<U> {

    /**
     * Original scalar.
     */
    private final Scalar<T> origin;

    /**
     * Func.
     */
    private final Func<T, U> func;

    /**
     * Ctor.
     * @param mapping Fun to apply
     * @param scalar Encapsulated scalar
     */
    public Mapped(final Func<T, U> mapping, final Scalar<T> scalar) {
        this.origin = scalar;
        this.func = mapping;
    }

    @Override
    public U value() throws Exception {
        return this.func.apply(this.origin.value());
    }
}

19 View Complete Implementation : FuncNoNulls.java
Copyright MIT License
Author : yegor256
/**
 * Func check for no nulls.
 *
 * @param <X> Type of input
 * @param <Y> Type of output
 * @since 0.10
 */
public final clreplaced FuncNoNulls<X, Y> implements Func<X, Y> {

    /**
     * The function.
     */
    private final Func<X, Y> func;

    /**
     * Ctor.
     * @param fnc The function
     */
    public FuncNoNulls(final Func<X, Y> fnc) {
        this.func = fnc;
    }

    @Override
    public Y apply(final X input) throws Exception {
        if (this.func == null) {
            throw new IllegalArgumentException("NULL instead of a valid function");
        }
        if (input == null) {
            throw new IllegalArgumentException("NULL instead of a valid input");
        }
        final Y result = this.func.apply(input);
        if (result == null) {
            throw new IOException("NULL instead of a valid result");
        }
        return result;
    }
}

19 View Complete Implementation : RepeatedTest.java
Copyright MIT License
Author : yegor256
@Test
public void repeatsNullsResults() throws Exception {
    final Func<Boolean, Integer> func = new Repeated<>(input -> {
        return null;
    }, 2);
    Matcherreplacedert.replacedertThat(func.apply(true), Matchers.equalTo(null));
}

19 View Complete Implementation : Async.java
Copyright MIT License
Author : yegor256
/**
 * Func that runs in the background.
 *
 * <p>If you want your piece of code to be executed in the background,
 * use {@link Async} as following:</p>
 *
 * <pre> int length = new AsyncFunc(
 *   input -> input.length()
 * ).apply("Hello, world!").get();</pre>
 *
 * <p>There is no thread-safety guarantee.
 *
 * @param <X> Type of input
 * @param <Y> Type of output
 * @since 0.10
 */
public final clreplaced Async<X, Y> implements Func<X, Future<Y>>, Proc<X> {

    /**
     * The func.
     */
    private final Func<X, Y> func;

    /**
     * The executor service.
     */
    private final ExecutorService executor;

    /**
     * Ctor.
     * @param fnc The func
     */
    public Async(final Func<X, Y> fnc) {
        this(fnc, Executors.defaultThreadFactory());
    }

    /**
     * Ctor.
     * @param fnc The func
     * @param fct Factory
     */
    public Async(final Func<X, Y> fnc, final ThreadFactory fct) {
        this(fnc, Executors.newSingleThreadExecutor(fct));
    }

    /**
     * Ctor.
     * @param fnc The func
     * @param exec Executor Service
     */
    public Async(final Func<X, Y> fnc, final ExecutorService exec) {
        this.func = fnc;
        this.executor = exec;
    }

    @Override
    public Future<Y> apply(final X input) {
        return this.executor.submit(() -> this.func.apply(input));
    }

    @Override
    public void exec(final X input) {
        this.apply(input);
    }
}

19 View Complete Implementation : StickyFuncTest.java
Copyright MIT License
Author : yegor256
@Test
public void cachesWithLimitedBuffer() throws Exception {
    final Func<Integer, Integer> func = new StickyFunc<>(input -> new SecureRandom().nextInt(), 2);
    final int first = func.apply(0);
    final int second = func.apply(1);
    Matcherreplacedert.replacedertThat(first + second, Matchers.equalTo(func.apply(0) + func.apply(1)));
    final int third = func.apply(-1);
    Matcherreplacedert.replacedertThat(second + third, Matchers.equalTo(func.apply(1) + func.apply(-1)));
}

19 View Complete Implementation : FuncWithFallback.java
Copyright MIT License
Author : yegor256
/**
 * Func with fallbacks that enable it to recover from errors.
 *
 * <p>You may register several fallbacks, each for any type of exception
 * whatsoever. If the decorated {@link Func} throws an exception that has
 * an IS-A relationship with a registered fallback's exception, then that
 * fallback's alternative {@link Func} will be used to provide a result.
 *
 * <p><strong>Example scenario:</strong> you need to fetch product data
 * from a database which may potentially not be available (SQLException).
 * As a fallback, you then fetch the data from a local cache that is
 * guaranteed not to fail. This is a sketch of what this code may look like:
 *
 * <pre>
 * {@code
 *    final Product product = new FuncWithFallback<>(
 *        id -> new SqlProduct().apply(id),
 *        new FallbackFrom<>(
 *            SQLException.clreplaced,
 *            id -> new CachedProduct().apply(id)
 *        )
 *    ).apply(id);
 * }
 * </pre>
 *
 * <p>If you register several fallback plans for exception types belonging to
 * the same hierarchy, then the fallback plan whose exception type has the
 * closest {@link InheritanceLevel} to the exception thrown will be used.
 *
 * <p><strong>Example scenario:</strong> sometimes {@code SqlProduct} from
 * above will throw {@link SQLRecoverableException} (a sub clreplaced of
 * {@link SQLException}). In such cases you may want to simply retry the same
 * {@link Func}:
 *
 * <pre>
 * {@code
 *    final Product product = new FuncWithFallback<>(
 *        id -> new SqlProduct().apply(id),
 *        new IterableOf<>(
 *            new FallbackFrom<>(
 *                SQLException.clreplaced,
 *                id -> new CachedProduct().apply(id)
 *            ),
 *            new FallbackFrom<>(
 *                SQLRecoverableException.clreplaced,
 *                id -> new SqlProduct().apply(id)    // run it again
 *            )
 *        )
 *    ).apply(id);
 * }
 * </pre>
 *
 * <p>There is no thread-safety guarantee.
 *
 * @param <X> Type of input
 * @param <Y> Type of output
 * @see ScalarWithFallback
 * @since 0.2
 */
public final clreplaced FuncWithFallback<X, Y> implements Func<X, Y> {

    /**
     * The func.
     */
    private final Func<X, Y> func;

    /**
     * The fallbacks.
     */
    private final Iterable<FallbackFrom<Y>> fallbacks;

    /**
     * Ctor.
     * @param fnc The func
     * @param fbk The fallback
     */
    @SuppressWarnings("unchecked")
    public FuncWithFallback(final Func<X, Y> fnc, final FallbackFrom<Y> fbk) {
        this(fnc, new IterableOf<>(fbk));
    }

    /**
     * Ctor.
     * @param fnc The func
     * @param fbks The fallbacks
     */
    public FuncWithFallback(final Func<X, Y> fnc, final Iterable<FallbackFrom<Y>> fbks) {
        this.func = fnc;
        this.fallbacks = fbks;
    }

    @Override
    public Y apply(final X input) throws Exception {
        return new ScalarWithFallback<>(() -> this.func.apply(input), this.fallbacks).value();
    }
}

19 View Complete Implementation : StickyFuncTest.java
Copyright MIT License
Author : yegor256
@Test
public void cachesFuncResults() throws Exception {
    final Func<Boolean, Integer> func = new StickyFunc<>(input -> new SecureRandom().nextInt());
    Matcherreplacedert.replacedertThat(func.apply(true) + func.apply(true), Matchers.equalTo(func.apply(true) + func.apply(true)));
}

19 View Complete Implementation : FoldLeft.java
Copyright MIT License
Author : VsSekorin
/**
 * Fold left to right.
 *
 * @author Vseslav Sekorin ([email protected])
 * @version $Id$
 * @param <T> Elements type
 * @since 0.1
 */
public final clreplaced FoldLeft<T> implements Scalar<T> {

    /**
     * Source items.
     */
    private final Iterable<T> items;

    /**
     * Function of two arguments.
     */
    private final Func<T, Func<T, T>> func;

    /**
     * First element.
     */
    private final T first;

    /**
     * Ctor.
     * @param src Source items
     * @param fnc Function
     * @param fst First item
     */
    public FoldLeft(final Iterable<T> src, final BiFunc<T, T, T> fnc, final T fst) {
        this(src, new BiFuncFunc<>(fnc), fst);
    }

    /**
     * Ctor.
     * @param src Source items
     * @param fnc Function
     * @param fst First item
     */
    public FoldLeft(final Iterable<T> src, final Func<T, Func<T, T>> fnc, final T fst) {
        this.items = src;
        this.func = fnc;
        this.first = fst;
    }

    @Override
    public T value() throws Exception {
        T result = this.first;
        for (final T item : this.items) {
            result = this.func.apply(result).apply(item);
        }
        return result;
    }
}

19 View Complete Implementation : TypedPages.java
Copyright MIT License
Author : yegor256
/**
 * Typed pages.
 *
 * <p>There is no thread-safety guarantee.
 *
 * @author Yegor Bugayenko ([email protected])
 * @version $Id: 568de251dc116a33f89b807ee2c47123d841f487 $
 * @since 0.8
 * @checkstyle ClreplacedDataAbstractionCouplingCheck (500 lines)
 * @checkstyle JavadocTagsCheck (500 lines)
 */
final clreplaced TypedPages implements Func<String, Response> {

    /**
     * Origin.
     */
    private final Func<String, Response> origin;

    /**
     * Ctor.
     * @param func The func
     */
    TypedPages(final Func<String, Response> func) {
        this.origin = func;
    }

    @Override
    public Response apply(final String path) throws IOException {
        String type = "text/plain";
        if (path.endsWith(".html")) {
            type = "text/html";
        } else if (path.endsWith(".xml")) {
            type = "application/xml";
        } else if (path.endsWith(".svg")) {
            type = "image/svg+xml";
        }
        return new RsWithType(new IoCheckedFunc<>(this.origin).apply(path), type);
    }
}

19 View Complete Implementation : Repeated.java
Copyright MIT License
Author : yegor256
/**
 * Func that repeats its calculation a few times before
 * returning the last result.
 *
 * @param <X> Type of input
 * @param <Y> Type of output
 * @since 0.6
 */
public final clreplaced Repeated<X, Y> implements Func<X, Y> {

    /**
     * Original func.
     */
    private final Func<X, Y> func;

    /**
     * How many times to run.
     */
    private final int times;

    /**
     * Ctor.
     *
     * <p>If {@code max} is equal or less than zero {@link #apply(Object)}
     * will return an exception.</p>
     *
     * @param fnc Func original
     * @param max How many times
     */
    public Repeated(final Func<X, Y> fnc, final int max) {
        this.func = fnc;
        this.times = max;
    }

    @Override
    public Y apply(final X input) throws Exception {
        if (this.times <= 0) {
            throw new IllegalArgumentException("The number of repereplacedions must be at least 1");
        }
        Y result = null;
        for (int idx = 0; idx < this.times; ++idx) {
            result = this.func.apply(input);
        }
        return result;
    }
}

19 View Complete Implementation : RoutineITCase.java
Copyright MIT License
Author : yegor256
@Test
public void savesContainerNameIntoLogItem() throws Exception {
    final Base base = new DyBase(new Dynamo());
    final User user = base.user("jeff");
    final Script script = user.script("hello");
    script.update("echo 123");
    final Bucket bucket = new FkBucket();
    final Func<Void, Integer> routine = new Routine(base, new Shell.Fake(0, "", ""), bucket);
    for (int idx = 0; idx < 2; ++idx) {
        Matcherreplacedert.replacedertThat(routine.apply(null), Matchers.greaterThan(0));
    }
    Matcherreplacedert.replacedertThat(script.open().iterator().next().get("container").getS(), Matchers.equalTo(String.format("jeff_hello-week-%tF-%1$tH-%1$tM", new Date())));
}

19 View Complete Implementation : FoldRight.java
Copyright MIT License
Author : VsSekorin
/**
 * Fold right to left.
 *
 * @author Vseslav Sekorin ([email protected])
 * @version $Id$
 * @param <T> Elements type
 * @since 0.1
 */
public final clreplaced FoldRight<T> implements Scalar<T> {

    /**
     * Source items.
     */
    private final Iterable<T> items;

    /**
     * Function of two arguments.
     */
    private final Func<T, Func<T, T>> func;

    /**
     * First element.
     */
    private final T first;

    /**
     * Ctor.
     * @param src Source items
     * @param fnc Function
     * @param fst First item
     */
    public FoldRight(final Iterable<T> src, final BiFunc<T, T, T> fnc, final T fst) {
        this(src, new BiFuncFunc<>(fnc), fst);
    }

    /**
     * Ctor.
     * @param src Source items
     * @param fnc Function
     * @param fst First item
     */
    public FoldRight(final Iterable<T> src, final Func<T, Func<T, T>> fnc, final T fst) {
        this.items = src;
        this.func = fnc;
        this.first = fst;
    }

    @Override
    public T value() throws Exception {
        return new FoldLeft<>(new Reversed<>(this.items), this.func, this.first).value();
    }
}

19 View Complete Implementation : TgPredicateFake.java
Copyright MIT License
Author : dgroup
/**
 * Fake implementation of {@link TgOutputPredicate} for the unit test purposes.
 *
 * @author Yurii Dubinka ([email protected])
 * @version $Id: 104b2f463c15c748100da01cb4139a35ba854198 $
 * @since 1.1
 */
public final clreplaced TgPredicateFake implements TgOutputPredicate {

    /**
     * Compare type: contains, equals, startsWith, endsWith, matches.
     */
    private final String type;

    /**
     * Expected value from test scenario.
     */
    private final String expctd;

    /**
     * Condition which should satisfy the actual value.
     */
    private final Func<String, Boolean> fnc;

    /**
     * Ctor.
     * @param type Comparing type like contains, equal, startsWiths, endsWith.
     * @param expctd Expected value from test scenario.
     */
    public TgPredicateFake(final String type, final String expctd) {
        this(type, expctd, actual -> true);
    }

    /**
     * Ctor.
     * @param type Comparing type like contains, equal, startsWiths, endsWith.
     * @param expctd Expected value from test scenario.
     * @param fnc Condition, which should satisfy the actual value.
     */
    public TgPredicateFake(final String type, final String expctd, final Func<String, Boolean> fnc) {
        this.type = type;
        this.expctd = expctd;
        this.fnc = fnc;
    }

    @Override
    public String comparingType() {
        return this.type;
    }

    @Override
    public String expected() {
        return this.expctd;
    }

    @Override
    @SuppressWarnings("PMD.AvoidCatchingGenericException")
    public boolean test(final String actual) throws YmlFormatException {
        // @checkstyle IllegalCatchCheck (5 lines)
        try {
            return this.fnc.apply(actual);
        } catch (final Exception exp) {
            throw new YmlFormatException(exp);
        }
    }

    @Override
    public String toString() {
        return new TextOf("%s %s", this.comparingType(), this.expected()).text();
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.comparingType(), this.expected());
    }

    @Override
    @SuppressWarnings("PMD.OnlyOneReturn")
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof TgOutputPredicate)) {
            return false;
        }
        final TgOutputPredicate that = (TgOutputPredicate) obj;
        return this.comparingType().equals(that.comparingType()) && this.expected().equals(that.expected());
    }
}

19 View Complete Implementation : ReduceRight.java
Copyright MIT License
Author : VsSekorin
/**
 * Applies a function of two arguments to all elements, going right to left.
 *
 * @author Vseslav Sekorin ([email protected])
 * @version $Id$
 * @param <T> Elements type
 * @since 0.1
 */
public final clreplaced ReduceRight<T> implements Scalar<T> {

    /**
     * Source items.
     */
    private final Iterable<T> items;

    /**
     * Function of two arguments.
     */
    private final Func<T, Func<T, T>> func;

    /**
     * Ctor.
     * @param src Source items
     * @param fnc Function
     */
    public ReduceRight(final Iterable<T> src, final BiFunc<T, T, T> fnc) {
        this(src, new BiFuncFunc<>(fnc));
    }

    /**
     * Ctor.
     * @param src Source items
     * @param fnc Function
     */
    public ReduceRight(final Iterable<T> src, final Func<T, Func<T, T>> fnc) {
        this.items = src;
        this.func = fnc;
    }

    @Override
    public T value() throws Exception {
        return new ReduceLeft<>(new Reversed<>(this.items), this.func).value();
    }
}

19 View Complete Implementation : FuncEnvelope.java
Copyright MIT License
Author : yegor256
/**
 * Envelope for Func.
 *
 * <p>There is no thread-safety guarantee.
 *
 * @param <X> Type of input
 * @param <Y> Type of output
 * @since 0.41
 */
public abstract clreplaced FuncEnvelope<X, Y> implements Func<X, Y> {

    /**
     * The delegate function.
     */
    private final Func<X, Y> func;

    /**
     * Ctor.
     * @param func The function
     */
    public FuncEnvelope(final Func<X, Y> func) {
        this.func = func;
    }

    @Override
    public final Y apply(final X input) throws Exception {
        return this.func.apply(input);
    }
}

19 View Complete Implementation : Retry.java
Copyright MIT License
Author : yegor256
/**
 * Func that will try a few times before throwing an exception.
 *
 * <pre>{@code
 * new RetryScalar<>(
 *     () -> {
 *         if (new SecureRandom().nextDouble() > 0.3d) {
 *             throw new IllegalArgumentException("May happen");
 *         }
 *         return 0;
 *     },
 *     5
 * ).value() // will try to run 5 times before throwing an exception
 * }</pre>
 *
 * <p>There is no thread-safety guarantee.
 *
 * <p>This clreplaced implements {@link Scalar}, which throws a checked
 * {@link Exception}. This may not be convenient in many cases. To make
 * it more convenient and get rid of the checked exception you can
 * use the {@link Unchecked} decorator. Or you may use
 * {@link IoChecked} to wrap it in an IOException.</p>
 *
 * @param <T> Type of output
 * @since 0.9
 */
public final clreplaced Retry<T> implements Scalar<T> {

    /**
     * Original scalar.
     */
    private final Scalar<T> origin;

    /**
     * Exit condition.
     */
    private final Func<Integer, Boolean> func;

    /**
     * Wait between executions.
     */
    private final Duration wait;

    /**
     * Ctor.
     * @param scalar Scalar original
     */
    public Retry(final Scalar<T> scalar) {
        this(scalar, Duration.ZERO);
    }

    /**
     * Ctor.
     * @param scalar Scalar original
     * @param wait The {@link java.time.Duration} to wait between attempts
     */
    public Retry(final Scalar<T> scalar, final Duration wait) {
        // @checkstyle MagicNumberCheck (1 line)
        this(scalar, 3, wait);
    }

    /**
     * Ctor.
     * @param scalar Scalar original
     * @param attempts Maximum number of attempts
     */
    public Retry(final Scalar<T> scalar, final int attempts) {
        this(scalar, attempts, Duration.ZERO);
    }

    /**
     * Ctor.
     * @param scalar Scalar original
     * @param attempts Maximum number of attempts
     * @param wait The {@link java.time.Duration} to wait between attempts
     */
    public Retry(final Scalar<T> scalar, final int attempts, final Duration wait) {
        this(scalar, attempt -> attempt >= attempts, wait);
    }

    /**
     * Ctor.
     * @param scalar Func original
     * @param exit Exit condition, returns TRUE if there is no reason to try
     */
    public Retry(final Scalar<T> scalar, final Func<Integer, Boolean> exit) {
        this(scalar, exit, Duration.ZERO);
    }

    /**
     * Ctor.
     * @param scalar Func original
     * @param exit Exit condition, returns TRUE if there is no reason to try
     * @param wait The {@link java.time.Duration} to wait between attempts
     */
    public Retry(final Scalar<T> scalar, final Func<Integer, Boolean> exit, final Duration wait) {
        this.origin = scalar;
        this.func = exit;
        this.wait = wait;
    }

    @Override
    public T value() throws Exception {
        return new org.cactoos.func.Retry<>((Func<Boolean, T>) input -> this.origin.value(), this.func, this.wait).apply(true);
    }
}

18 View Complete Implementation : Mapped.java
Copyright MIT License
Author : dgroup
/**
 * Map function to the {@link Arg}.
 *
 * @author Yurii Dubinka ([email protected])
 * @version $Id: 6bbad618a31142375d3a6767e9c7c2f1d211b65d $
 * @param <X> Type of source item.
 * @param <Y> Type of target item.
 * @since 1.0
 */
public final clreplaced Mapped<X, Y> implements Arg<Y> {

    /**
     * Origin.
     */
    private final Arg<X> src;

    /**
     * Map function to the argument.
     */
    private final Func<X, Y> fnc;

    /**
     * Ctor.
     * @param fnc Map function.
     * @param src Source argument.
     */
    public Mapped(final Func<X, Y> fnc, final Arg<X> src) {
        this.fnc = fnc;
        this.src = src;
    }

    @Override
    public String name() {
        return this.src.name();
    }

    @Override
    @SuppressWarnings("PMD.AvoidCatchingGenericException")
    public Y value() throws CmdArgNotFoundException {
        // @checkstyle IllegalCatchCheck (5 lines)
        try {
            return this.fnc.apply(this.src.value());
        } catch (final Exception exp) {
            throw new CmdArgNotFoundException(exp);
        }
    }

    @Override
    public boolean specifiedByUser() {
        return this.src.specifiedByUser();
    }
}

18 View Complete Implementation : Det.java
Copyright MIT License
Author : VsSekorin
/**
 * The determinant of a matrix.
 *
 * @author Vseslav Sekorin ([email protected])
 * @version $Id$
 * @param <T> Type of matrix
 * @since 0.1
 */
public final clreplaced Det<T> implements Scalar<T> {

    /**
     * Matrix.
     */
    private final Matrix<T> matrix;

    /**
     * Multiplication.
     */
    private final Func<T, Func<T, T>> mult;

    /**
     * Addition.
     */
    private final Func<T, Func<T, T>> add;

    /**
     * Subtractive.
     */
    private final Func<T, Func<T, T>> sub;

    /**
     * Ctor.
     * @param src Matrix
     * @param mlt Multiplication
     * @param addit Addition
     * @param subtr Subtractive
     * @checkstyle ParameterNumberCheck (10 lines)
     */
    public Det(final Matrix<T> src, final Func<T, Func<T, T>> mlt, final Func<T, Func<T, T>> addit, final Func<T, Func<T, T>> subtr) {
        this.matrix = src;
        this.mult = mlt;
        this.add = addit;
        this.sub = subtr;
    }

    @Override
    public T value() throws Exception {
        final int cols = new NmbColumns<>(this.matrix).value();
        final T result;
        if (cols == 2) {
            result = new Det2<>(this.matrix, this.mult, this.sub).value();
        } else {
            result = new DetN<>(this.matrix, this.mult, this.add, this.sub).value();
        }
        return result;
    }
}

18 View Complete Implementation : Det2.java
Copyright MIT License
Author : VsSekorin
/**
 * The determinant of a 2 × 2 matrix.
 *
 * @author Vseslav Sekorin ([email protected])
 * @version $Id$
 * @param <T> Type of matrix
 * @since 0.1
 */
public final clreplaced Det2<T> implements Scalar<T> {

    /**
     * Matrix.
     */
    private final Matrix<T> matrix;

    /**
     * Multiplication.
     */
    private final Func<T, Func<T, T>> mult;

    /**
     * Subtraction.
     */
    private final Func<T, Func<T, T>> sub;

    /**
     * Ctor.
     * @param src Matrix
     * @param mlt Multiplication
     * @param subtr Subtraction
     */
    public Det2(final Matrix<T> src, final Func<T, Func<T, T>> mlt, final Func<T, Func<T, T>> subtr) {
        this.matrix = src;
        this.mult = mlt;
        this.sub = subtr;
    }

    @Override
    public T value() throws Exception {
        final T[][] array = this.matrix.asArray();
        return this.sub.apply(this.mult.apply(array[0][0]).apply(array[1][1])).apply(this.mult.apply(array[1][0]).apply(array[0][1]));
    }
}

18 View Complete Implementation : DetN.java
Copyright MIT License
Author : VsSekorin
/**
 * The determinant of a N x N matrix.
 *
 * @author Vseslav Sekorin ([email protected])
 * @version $Id$
 * @param <T> Type of matrix
 * @since 0.1
 */
public final clreplaced DetN<T> implements Scalar<T> {

    /**
     * Matrix.
     */
    private final Matrix<T> matrix;

    /**
     * Multiplication.
     */
    private final Func<T, Func<T, T>> mult;

    /**
     * Addition.
     */
    private final Func<T, Func<T, T>> add;

    /**
     * Subtractive.
     */
    private final Func<T, Func<T, T>> sub;

    /**
     * Ctor.
     * @param src Matrix
     * @param mlt Multiplication
     * @param addit Addition
     * @param subtr Subtractive
     * @checkstyle ParameterNumberCheck (10 lines)
     */
    public DetN(final Matrix<T> src, final Func<T, Func<T, T>> mlt, final Func<T, Func<T, T>> addit, final Func<T, Func<T, T>> subtr) {
        this.matrix = src;
        this.mult = mlt;
        this.add = addit;
        this.sub = subtr;
    }

    @Override
    @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
    public T value() throws Exception {
        final int cols = new NmbColumns<>(this.matrix).value();
        final T[][] array = this.matrix.asArray();
        T result = this.mult.apply(array[0][0]).apply(new Det<>(new Minor<>(this.matrix, 0, 0), this.mult, this.add, this.sub).value());
        for (int col = 1; col < cols; ++col) {
            // @checkstyle AvoidInlineConditionalsCheck (1 lines)
            result = (col % 2 == 0 ? this.add : this.sub).apply(result).apply(this.mult.apply(array[0][col]).apply(new Det<>(new Minor<>(this.matrix, 0, col), this.mult, this.add, this.sub).value()));
        }
        return result;
    }
}

18 View Complete Implementation : CheckedBytes.java
Copyright MIT License
Author : yegor256
/**
 * Bytes that throws exception of specified type.
 *
 * @param <E> Exception's type.
 * @since 0.31
 */
public final clreplaced CheckedBytes<E extends Exception> implements Bytes {

    /**
     * Original bytes.
     */
    private final Bytes origin;

    /**
     * Function that wraps exception of {@link #origin} to the required type.
     */
    private final Func<Exception, E> func;

    /**
     * Ctor.
     * @param orig Origin bytes.
     * @param fnc Function that wraps exceptions.
     */
    public CheckedBytes(final Bytes orig, final Func<Exception, E> fnc) {
        this.origin = orig;
        this.func = fnc;
    }

    @Override
    public byte[] asBytes() throws E {
        return new Checked<>(this.origin::asBytes, this.func).value();
    }
}

18 View Complete Implementation : CheckedInput.java
Copyright MIT License
Author : yegor256
/**
 * Input that throws exception of specified type.
 *
 * @param <E> Exception's type.
 * @since 0.31
 */
public final clreplaced CheckedInput<E extends Exception> implements Input {

    /**
     * Original input.
     */
    private final Input origin;

    /**
     * Function that wraps exception of {@link #origin} to the required type.
     */
    private final Func<Exception, E> func;

    /**
     * Ctor.
     * @param orig Origin input.
     * @param fnc Function that wraps exceptions.
     */
    public CheckedInput(final Input orig, final Func<Exception, E> fnc) {
        this.origin = orig;
        this.func = fnc;
    }

    @Override
    public InputStream stream() throws E {
        return new Checked<>(this.origin::stream, this.func).value();
    }
}

18 View Complete Implementation : CheckedOutput.java
Copyright MIT License
Author : yegor256
/**
 * Output that throws exception of specified type.
 *
 * @param <E> Exception's type.
 * @since 0.31
 */
public final clreplaced CheckedOutput<E extends Exception> implements Output {

    /**
     * Original output.
     */
    private final Output origin;

    /**
     * Function that wraps exception of {@link #origin} to the required type.
     */
    private final Func<Exception, E> func;

    /**
     * Ctor.
     * @param orig Origin output.
     * @param fnc Function that wraps exceptions.
     */
    public CheckedOutput(final Output orig, final Func<Exception, E> fnc) {
        this.origin = orig;
        this.func = fnc;
    }

    @Override
    public OutputStream stream() throws E {
        return new Checked<>(this.origin::stream, this.func).value();
    }
}

18 View Complete Implementation : ResourceOf.java
Copyright MIT License
Author : yegor256
/**
 * Clreplacedpath resource.
 *
 * <p>Pay attention that the name of resource must always be
 * global, <strong>not</strong> starting with a leading slash. Thus,
 * if you want to load a text file from {@code /com/example/Test.txt},
 * you must provide this name: {@code "com/example/Test.txt"}.</p>
 *
 * @see ClreplacedLoader#getResource(String)
 * @since 0.1
 */
public final clreplaced ResourceOf implements Input {

    /**
     * Resource name.
     */
    private final Text path;

    /**
     * Fallback.
     */
    private final Func<Text, Input> fallback;

    /**
     * Resource clreplaced loader.
     */
    private final ClreplacedLoader loader;

    /**
     * New resource input with current context {@link ClreplacedLoader}.
     * @param res Resource name
     */
    public ResourceOf(final CharSequence res) {
        this(res, Thread.currentThread().getContextClreplacedLoader());
    }

    /**
     * New resource input with specified {@link ClreplacedLoader}.
     * @param res Resource name
     * @param ldr Resource clreplaced loader
     */
    public ResourceOf(final CharSequence res, final ClreplacedLoader ldr) {
        this(new TextOf(res), ldr);
    }

    /**
     * New resource input with specified {@link ClreplacedLoader}.
     * @param res Resource name
     * @param fbk Fallback
     * @param ldr Resource clreplaced loader
     */
    public ResourceOf(final CharSequence res, final Func<CharSequence, Input> fbk, final ClreplacedLoader ldr) {
        this(new TextOf(res), input -> fbk.apply(input.replacedtring()), ldr);
    }

    /**
     * New resource input with current context {@link ClreplacedLoader}.
     * @param res Resource name
     * @param fbk Fallback
     */
    public ResourceOf(final CharSequence res, final CharSequence fbk) {
        this(res, input -> new InputOf(new BytesOf(fbk)));
    }

    /**
     * New resource input with current context {@link ClreplacedLoader}.
     * @param res Resource name
     * @param fbk Fallback
     */
    public ResourceOf(final CharSequence res, final Func<CharSequence, Input> fbk) {
        this(res, fbk, Thread.currentThread().getContextClreplacedLoader());
    }

    /**
     * New resource input with current context {@link ClreplacedLoader}.
     * @param res Resource name
     * @param fbk Fallback
     */
    public ResourceOf(final CharSequence res, final Input fbk) {
        this(res, input -> fbk);
    }

    /**
     * New resource input with current context {@link ClreplacedLoader}.
     * @param res Resource name
     */
    public ResourceOf(final Text res) {
        this(res, Thread.currentThread().getContextClreplacedLoader());
    }

    /**
     * New resource input with specified {@link ClreplacedLoader}.
     * @param res Resource name
     * @param ldr Resource clreplaced loader
     */
    public ResourceOf(final Text res, final ClreplacedLoader ldr) {
        this(res, input -> {
            throw new IOException(new FormattedText("Resource \"%s\" was not found", input.replacedtring()).replacedtring());
        }, ldr);
    }

    /**
     * New resource input with current context {@link ClreplacedLoader}.
     * @param res Resource name
     * @param fbk Fallback
     */
    public ResourceOf(final Text res, final Text fbk) {
        this(res, input -> new InputOf(new BytesOf(fbk.replacedtring())));
    }

    /**
     * New resource input with current context {@link ClreplacedLoader}.
     * @param res Resource name
     * @param fbk Fallback
     */
    public ResourceOf(final Text res, final Input fbk) {
        this(res, input -> fbk);
    }

    /**
     * New resource input with current context {@link ClreplacedLoader}.
     * @param res Resource name
     * @param fbk Fallback
     */
    public ResourceOf(final Text res, final Func<Text, Input> fbk) {
        this(res, fbk, Thread.currentThread().getContextClreplacedLoader());
    }

    /**
     * New resource input with specified {@link ClreplacedLoader}.
     * @param res Resource name
     * @param fbk Fallback
     * @param ldr Resource clreplaced loader
     */
    public ResourceOf(final Text res, final Func<Text, Input> fbk, final ClreplacedLoader ldr) {
        this.path = res;
        this.loader = ldr;
        this.fallback = fbk;
    }

    @Override
    public InputStream stream() throws Exception {
        InputStream input = this.loader.getResourcereplacedtream(this.path.replacedtring());
        if (input == null) {
            input = new IoCheckedFunc<>(this.fallback).apply(this.path).stream();
        }
        return input;
    }
}