org.cactoos.Func Java Examples

The following examples show how to use org.cactoos.Func. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: cactoos   Author: yegor256   File: RangeOfTest.java    License: MIT License 6 votes vote down vote up
@Test
public final void testIntegerFibonacciRange() {
    MatcherAssert.assertThat(
        "Can't generate a range of fibonacci integers",
        new ListOf<>(
            new RangeOf<>(
                1,
                100,
                new Func<Integer, Integer>() {
                    private int last;
                    @Override
                    public Integer apply(
                        final Integer input) throws Exception {
                        final int next = this.last + input;
                        this.last = input;
                        return next;
                    }
                }
            )
        ),
        Matchers.contains(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
    );
}
 
Example #2
Source Project: cactoos   Author: yegor256   File: StickyFuncTest.java    License: MIT License 6 votes vote down vote up
@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);
    MatcherAssert.assertThat(
        first + second,
        Matchers.equalTo(func.apply(0) + func.apply(1))
    );
    final int third = func.apply(-1);
    MatcherAssert.assertThat(
        second + third,
        Matchers.equalTo(func.apply(1) + func.apply(-1))
    );
}
 
Example #3
Source Project: cactoos   Author: yegor256   File: ChainedTest.java    License: MIT License 6 votes vote down vote up
@Test
public void withIterable() throws Exception {
    new Assertion<>(
        "Must work with iterable",
        new LengthOf(
            new Filtered<>(
                input -> !input.startsWith("st"),
                new Mapped<>(
                    new Chained<>(
                        input -> input.concat("1"),
                        new IterableOf<Func<String, String>>(
                            input -> input.concat("2"),
                            input -> input.replaceAll("a", "b")
                        ),
                        String::trim
                    ),
                    new IterableOf<>("private", "static", "String")
                )
            )
        ).intValue(),
        new IsEqual<>(2)
    ).affirm();
}
 
Example #4
Source Project: cactoos   Author: yegor256   File: UncheckedFuncTest.java    License: MIT License 5 votes vote down vote up
@Test(expected = UncheckedIOException.class)
public void rethrowsCheckedToUncheckedException() {
    new UncheckedFunc<>(
        (Func<Integer, String>) i -> {
            throw new IOException("intended");
        }
    ).apply(1);
}
 
Example #5
Source Project: cactoos   Author: yegor256   File: ScalarWithFallback.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param origin Original scalar
 * @param exceptions Supported exceptions types
 * @param fallback Function that converts the given exception into fallback value
 */
public ScalarWithFallback(
    final Scalar<T> origin,
    final Iterable<Class<? extends Throwable>> exceptions,
    final Func<Throwable, T> fallback
) {
    this(
        origin,
        new IterableOf<FallbackFrom<T>>(
            new FallbackFrom<>(
                exceptions, fallback
            )
        )
    );
}
 
Example #6
Source Project: cactoos   Author: yegor256   File: RepeatedTest.java    License: MIT License 5 votes vote down vote up
@Test
public void repeatsNullsResults() throws Exception {
    final Func<Boolean, Integer> func = new Repeated<>(
        input -> {
            return null;
        },
        2
    );
    MatcherAssert.assertThat(
        func.apply(true),
        Matchers.equalTo(null)
    );
}
 
Example #7
Source Project: cactoos   Author: yegor256   File: StickyFuncTest.java    License: MIT License 5 votes vote down vote up
@Test
public void cachesWithZeroBuffer() throws Exception {
    final Func<Boolean, Integer> func = new StickyFunc<>(
        input -> new SecureRandom().nextInt(), 0
    );
    MatcherAssert.assertThat(
        func.apply(true) + func.apply(true),
        Matchers.not(Matchers.equalTo(func.apply(true) + func.apply(true)))
    );
}
 
Example #8
Source Project: cactoos   Author: yegor256   File: ScalarWithFallback.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param origin Original scalar
 * @param exception Supported exception type
 * @param fallback Function that converts the given exception into fallback value
 */
public ScalarWithFallback(
    final Scalar<T> origin,
    final Class<? extends Throwable> exception,
    final Func<Throwable, T> fallback
) {
    this(origin, new IterableOf<Class<? extends Throwable>>(exception), fallback);
}
 
Example #9
Source Project: cactoos   Author: yegor256   File: RepeatedTest.java    License: MIT License 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void doesntRepeatAny() throws Exception {
    final Func<Boolean, Integer> func = new Repeated<>(
        input -> {
            return new SecureRandom().nextInt();
        },
        0
    );
    MatcherAssert.assertThat(
        func.apply(true),
        Matchers.equalTo(func.apply(true))
    );
}
 
Example #10
Source Project: cactoos   Author: yegor256   File: FallbackFrom.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param exps Supported exceptions types
 * @param func Function that converts the given exception into required one
 */
public FallbackFrom(
    final Iterable<Class<? extends Throwable>> exps,
    final Func<Throwable, T> func) {
    this.exceptions = exps;
    this.func = func;
}
 
Example #11
Source Project: cactoos   Author: yegor256   File: Retry.java    License: MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #12
Source Project: cactoos   Author: yegor256   File: AndInThreads.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param svc Executable service to run thread in
 * @param func Func to map
 * @param src The iterable
 * @param <X> Type of items in the iterable
 */
public <X> AndInThreads(final ExecutorService svc,
    final Func<X, Boolean> func, final Iterable<X> src) {
    this(
        svc,
        new Mapped<>(
            item -> (Scalar<Boolean>) () -> func.apply(item), src
        )
    );
}
 
Example #13
Source Project: cactoos   Author: yegor256   File: AndInThreads.java    License: MIT License 5 votes vote down vote up
@Override
public Boolean value() throws Exception {
    final Collection<Future<Boolean>> futures = new LinkedList<>();
    for (final Scalar<Boolean> item : this.iterable) {
        futures.add(this.service.submit(item::value));
    }
    final boolean result = new And(
        (Func<Future<Boolean>, Boolean>) Future::get,
        futures
    ).value();
    if (this.shut) {
        this.service.shutdown();
        try {
            if (!this.service.awaitTermination(1L, TimeUnit.MINUTES)) {
                throw new IllegalStateException(
                    new FormattedText(
                        "Can't terminate the service, result=%b",
                        result
                    ).asString()
                );
            }
        } catch (final InterruptedException ex) {
            Thread.currentThread().interrupt();
            throw new IllegalStateException(ex);
        }
    }
    return result;
}
 
Example #14
Source Project: cactoos   Author: yegor256   File: AndWithIndex.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example #15
Source Project: jpeek   Author: yegor256   File: ReportsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void rendersOneReport(@TempDir final File folder) throws Exception {
    final BiFunc<String, String, Func<String, Response>> reports = new Reports(folder.toPath());
    new Assertion<>(
        "Must return HTTP 200 OK status",
        reports.apply("com.jcabi", "jcabi-urn").apply("index.html"),
        new HmRsStatus(HttpURLConnection.HTTP_OK)
    ).affirm();
    new Assertion<>(
        "Must return HTTP 200 OK status",
        reports.apply("com.jcabi", "jcabi-urn").apply("index.html"),
        new HmRsStatus(HttpURLConnection.HTTP_OK)
    ).affirm();
}
 
Example #16
Source Project: cactoos   Author: yegor256   File: IoCheckedFuncTest.java    License: MIT License 5 votes vote down vote up
@Test
public void rethrowsIoException() {
    final IOException exception = new IOException("intended");
    try {
        new IoCheckedFunc<>(
            (Func<Integer, String>) i -> {
                throw exception;
            }
        ).apply(1);
    } catch (final IOException ex) {
        MatcherAssert.assertThat(
            ex, Matchers.is(exception)
        );
    }
}
 
Example #17
Source Project: cactoos   Author: yegor256   File: ResourceOf.java    License: MIT License 5 votes vote down vote up
/**
 * New resource input with specified {@link ClassLoader}.
 * @param res Resource name
 * @param fbk Fallback
 * @param ldr Resource class loader
 */
public ResourceOf(final Text res,
    final Func<Text, Input> fbk, final ClassLoader ldr) {
    this.path = res;
    this.loader = ldr;
    this.fallback = fbk;
}
 
Example #18
Source Project: cactoos   Author: yegor256   File: RangeOf.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param min Start of the range.
 * @param max End of the range.
 * @param incrementor The {@link Func} to process for the next value.
 */
@SuppressWarnings({
    "PMD.CallSuperInConstructor",
    "PMD.ConstructorOnlyInitializesOrCallOtherConstructors"
    }
)
public RangeOf(final T min, final T max, final Func<T, T> incrementor) {
    super(
        new IterableOf<>(
            () -> new Iterator<T>() {
                private final UncheckedFunc<T, T> inc =
                    new UncheckedFunc<>(incrementor);
                private T value = min;

                @Override
                public boolean hasNext() {
                    return this.value.compareTo(max) < 1;
                }

                @Override
                public T next() {
                    if (!this.hasNext()) {
                        throw new NoSuchElementException();
                    }
                    final T result = this.value;
                    this.value = this.inc.apply(this.value);
                    return result;
                }
            }
        )
    );
}
 
Example #19
Source Project: cactoos   Author: yegor256   File: Filtered.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param fnc Predicate
 * @param src Source iterable
 */
public Filtered(final Func<X, Boolean> fnc, final Iterable<X> src) {
    super(
        new IterableOf<>(
            () -> new org.cactoos.iterator.Filtered<>(fnc, src.iterator())
        )
    );
}
 
Example #20
Source Project: cactoos   Author: yegor256   File: ItemAt.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 *
 * @param position Position
 * @param fallback Fallback value
 * @param iterable Iterable
 */
public ItemAt(
    final int position,
    final Func<Iterable<T>, T> fallback,
    final Iterable<T> iterable
) {
    this.saved = new Sticky<T>(
        () -> {
            final T ret;
            if (position < 0) {
                throw new IOException(
                    new FormattedText(
                        "The position must be non-negative: %d",
                        position
                    ).asString()
                );
            }
            final Iterator<T> src = iterable.iterator();
            int cur;
            for (cur = 0; cur < position && src.hasNext(); ++cur) {
                src.next();
            }
            if (cur == position && src.hasNext()) {
                ret = src.next();
            } else {
                ret = fallback.apply(() -> src);
            }
            return ret;
        }
    );
}
 
Example #21
Source Project: cactoos   Author: yegor256   File: Or.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param func Func to map
 * @param src The iterable
 * @param <X> Type of items in the iterable
 */
public <X> Or(final Func<X, Boolean> func, final Iterable<X> src) {
    this(
        new Mapped<>(
            item -> (Scalar<Boolean>) () -> func.apply(item), src
        )
    );
}
 
Example #22
Source Project: cactoos   Author: yegor256   File: Or.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param subject The subject
 * @param conditions Funcs to map
 * @param <X> Type of items in the iterable
 */
@SafeVarargs
public <X> Or(final X subject, final Func<X, Boolean>... conditions) {
    this(
        new Mapped<>(
            item -> (Scalar<Boolean>) () -> item.apply(subject),
            new IterableOf<>(conditions)
        )
    );
}
 
Example #23
Source Project: cactoos   Author: yegor256   File: AndInThreads.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param func Func to map
 * @param src The iterable
 * @param <X> Type of items in the iterable
 */
public <X> AndInThreads(final Func<X, Boolean> func,
    final Iterable<X> src) {
    this(
        new Mapped<>(
            item -> (Scalar<Boolean>) () -> func.apply(item), src
        )
    );
}
 
Example #24
Source Project: cactoos   Author: yegor256   File: FallbackFrom.java    License: MIT License 4 votes vote down vote up
/**
 * Ctor.
 * @param exp Supported exception type
 * @param func Function that converts the given exception into required one
 */
@SuppressWarnings("unchecked")
public FallbackFrom(final Class<? extends Throwable> exp,
    final Func<Throwable, T> func) {
    this(new IterableOf<>(exp), func);
}
 
Example #25
Source Project: excel-io   Author: Vatavuk   File: XsSheet.java    License: MIT License 4 votes vote down vote up
/**
 * Ctor.
 * @param function Function
 * @param elements Elements
 */
public ReadFrom(final Func<Workbook, Sheet> function,
    final Iterable<ERow> elements) {
    this.func = function;
    this.rows = new Array<>(elements);
}
 
Example #26
Source Project: cactoos   Author: yegor256   File: AndWithIndex.java    License: MIT License 4 votes vote down vote up
/**
 * Ctor.
 * @param src The iterable
 */
@SafeVarargs
public AndWithIndex(final Func<Integer, Boolean>... src) {
    this(new IterableOf<>(src));
}
 
Example #27
Source Project: cactoos   Author: yegor256   File: Filtered.java    License: MIT License 4 votes vote down vote up
/**
 * Ctor.
 * @param fnc Predicate
 * @param src Source iterable
 */
public Filtered(final Func<X, Boolean> fnc, final Iterator<X> src) {
    this.iterator = src;
    this.func = fnc;
    this.buffer = new LinkedList<>();
}
 
Example #28
Source Project: cactoos   Author: yegor256   File: Mapped.java    License: MIT License 4 votes vote down vote up
/**
 * Ctor.
 * @param fnc Func
 * @param src Source iterable
 */
public Mapped(final Func<X, Y> fnc, final Iterable<X> src) {
    super(new ListOf<>(
        new org.cactoos.iterable.Mapped<>(fnc, src)
    ));
}
 
Example #29
Source Project: jpeek   Author: yegor256   File: AsyncReports.java    License: MIT License 4 votes vote down vote up
/**
 * Ctor.
 * @param func Original bi-function
 */
AsyncReports(
    final BiFunc<String, String, Future<Func<String, Response>>> func) {
    this.cache = func;
    this.starts = new ConcurrentHashMap<>(0);
}
 
Example #30
Source Project: cactoos   Author: yegor256   File: Retry.java    License: MIT License 4 votes vote down vote up
/**
 * Ctor.
 * @param fnc Func original
 */
public Retry(final Func<X, Y> fnc) {
    // @checkstyle MagicNumberCheck (1 line)
    this(fnc, 3);
}