org.cactoos.Scalar Java Examples
The following examples show how to use
org.cactoos.Scalar.
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 File: RsPrint.java From takes with MIT License | 6 votes |
/** * Ctor. * @param res Original response */ public RsPrint(final Response res) { super(res); this.text = new IoChecked<>( new Sticky<>( new Scalar<String>() { private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); @Override public String value() throws Exception { RsPrint.this.printHead(this.baos); RsPrint.this.printBody(this.baos); return new TextOf( this.baos.toByteArray() ).asString(); } } ) ); }
Example #2
Source File: MainTest.java From jpeek with MIT License | 6 votes |
@Test @SuppressWarnings({"unchecked", "rawtypes"}) public void crashesIfMetricsHaveInvalidNames(@TempDir final Path target) { new Assertion( "Must throw an exception", (Scalar<Boolean>) () -> { Main.main( "--sources", Paths.get(".").toString(), "--target", target.toString(), "--metrics", "#%$!" ); return true; }, new Throws( "Invalid metric name: '#%$!'", IllegalArgumentException.class ) ).affirm(); }
Example #3
Source File: PhonesSql.java From cactoos-jdbc with MIT License | 6 votes |
@Override public Phone get(final int index) throws Exception { final Scalar<String> number = new ResultSetAsValue<>( new StatementSelect( this.session, new QuerySimple( new FormattedText( new Joined( " ", "SELECT number FROM phone WHERE", "contact_id = :contact_id", "FETCH FIRST %d ROWS ONLY" ), index ) ) ) ); return new PhoneSql(this.session, this.id, number.value()); }
Example #4
Source File: ReducedTest.java From cactoos with MIT License | 6 votes |
@Test public void lastAtIterable() throws Exception { final Character one = 'A'; final Character two = 'B'; final Character three = 'O'; new Assertion<>( "Must find the last", new Reduced<>( (first, last) -> last, new IterableOf<Scalar<Character>>( () -> one, () -> two, () -> three ) ).value(), Matchers.equalTo(three) ).affirm(); }
Example #5
Source File: Timed.java From cactoos with MIT License | 6 votes |
/** * Ctor. * @param threads The quantity of threads which will be used within the * {@link ExecutorService}. * @param tasks The tasks to be executed concurrently. * @param timeout The maximum time to wait. * @param unit The time unit of the timeout argument. * @checkstyle IndentationCheck (20 lines) * @checkstyle ParameterNumberCheck (5 lines) */ public Timed( final int threads, final Iterable<Scalar<T>> tasks, final long timeout, final TimeUnit unit ) { this( todo -> { final ExecutorService executor = Executors.newFixedThreadPool( threads ); try { return executor.invokeAll(new ListOf<>(todo), timeout, unit); } finally { executor.shutdown(); } }, tasks ); }
Example #6
Source File: Sub.java From cactoos with MIT License | 6 votes |
/** * Ctor. * @param text The Text * @param start Start position in the text * @param end End position in the text */ @SuppressWarnings({"PMD.CallSuperInConstructor", "PMD.ConstructorOnlyInitializesOrCallOtherConstructors"}) public Sub(final Text text, final Unchecked<Integer> start, final Unchecked<Integer> end) { super((Scalar<String>) () -> { int begin = start.value(); if (begin < 0) { begin = 0; } int finish = end.value(); final String origin = text.asString(); if (origin.length() < finish) { finish = origin.length(); } return origin.substring(begin, finish); }); }
Example #7
Source File: MainTest.java From jpeek with MIT License | 6 votes |
@Test @SuppressWarnings({"unchecked", "rawtypes"}) public void crashesIfOverwriteAndSourceEqualsToTarget(@TempDir final Path source) { new Assertion( "Must throw an exception", (Scalar<Boolean>) () -> { Main.main( "--sources", source.toString(), "--target", source.toString(), "--overwrite" ); return true; }, new Throws( "Invalid paths - can't be equal if overwrite option is set.", IllegalArgumentException.class ) ).affirm(); }
Example #8
Source File: MapOfTest.java From cactoos with MIT License | 6 votes |
@Test public void createsMapWithFunctions() { MatcherAssert.assertThat( "Can't create a map with functions as values", new MapOf<Integer, Scalar<Boolean>>( new MapEntry<>(0, () -> true), new MapEntry<>( 1, () -> { throw new IOException("oops"); } ) ), new IsMapContaining<>(new IsEqual<>(0), new IsAnything<>()) ); }
Example #9
Source File: AvgOf.java From cactoos with MIT License | 6 votes |
/** * Ctor. * @param src The iterable * @checkstyle ExecutableStatementCountCheck (150 lines) */ public AvgOf(final Iterable<Scalar<Number>> src) { super( new Ternary<>( new LengthOf(src).longValue(), len -> len > 0, len -> new Folded<>( BigDecimal.ZERO, (sum, value) -> sum.add(value, MathContext.DECIMAL128), new Mapped<>( number -> BigDecimal.valueOf( number.value().doubleValue() ), src ) ).value().divide( BigDecimal.valueOf(len), MathContext.DECIMAL128 ).doubleValue(), len -> 0.0 ) ); }
Example #10
Source File: FormattedText.java From cactoos with MIT License | 6 votes |
/** * New formatted string with specified locale. * * @param ptn Pattern * @param locale Format locale * @param args Arguments */ public FormattedText( final Text ptn, final Locale locale, final Collection<Object> args ) { super(new Scalar<String>() { @Override public String value() throws Exception { final StringBuilder out = new StringBuilder(0); try (Formatter fmt = new Formatter(out, locale)) { fmt.format( ptn.asString(), args.toArray() ); } return out.toString(); } }); }
Example #11
Source File: Abbreviated.java From cactoos with MIT License | 6 votes |
/** * Ctor. * @param text The Text * @param max Max width of the result string */ @SuppressWarnings({ "PMD.CallSuperInConstructor", "PMD.ConstructorOnlyInitializesOrCallOtherConstructors" }) public Abbreviated(final Text text, final int max) { super((Scalar<String>) () -> { final Text abbreviated; if (text.asString().length() <= max) { abbreviated = text; } else { abbreviated = new FormattedText( "%s...", new Sub( text, 0, max - Abbreviated.ELLIPSES_WIDTH ).asString() ); } return abbreviated.asString(); }); }
Example #12
Source File: Randomized.java From cactoos with MIT License | 6 votes |
/** * Ctor. * @param len Length of generated text. */ public Randomized(final Scalar<Integer> len) { this( new ListOf<>( '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~' ), len ); }
Example #13
Source File: RsWithStatusTest.java From takes with MIT License | 6 votes |
/** * RsWithStatus can add status multiple times. */ @SuppressWarnings( { "PMD.JUnitTestContainsTooManyAsserts", "PMD.ProhibitPlainJunitAssertionsRule" } ) @Test public void addsStatusMultipleTimes() { final Response response = new RsWithStatus( new RsWithStatus( new RsEmpty(), HttpURLConnection.HTTP_NOT_FOUND ), HttpURLConnection.HTTP_SEE_OTHER ); final Assertion<Scalar<Iterable<?>>> assertion = new Assertion<>( "Head with one line", response::head, new ScalarHasValue<>(new HasSize(1)) ); assertion.affirm(); assertion.affirm(); }
Example #14
Source File: SwappedCase.java From cactoos with MIT License | 6 votes |
/** * Ctor. * @param text The text */ @SuppressWarnings({"PMD.CallSuperInConstructor", "PMD.ConstructorOnlyInitializesOrCallOtherConstructors"}) public SwappedCase(final Text text) { super((Scalar<String>) () -> { final String origin = text.asString(); final char[] chars = origin.toCharArray(); for (int idx = 0; idx < chars.length; idx += 1) { final char chr = chars[idx]; if (Character.isUpperCase(chr)) { chars[idx] = Character.toLowerCase(chr); } else if (Character.isLowerCase(chr)) { chars[idx] = Character.toUpperCase(chr); } } return new String(chars); }); }
Example #15
Source File: HighestOf.java From cactoos with MIT License | 5 votes |
/** * Ctor. * @param iterable The items */ public HighestOf(final Iterable<Scalar<T>> iterable) { this.result = new Reduced<>( (first, second) -> { final T value; if (first.compareTo(second) > 0) { value = first; } else { value = second; } return value; }, iterable ); }
Example #16
Source File: AndInThreadsTest.java From cactoos with MIT License | 5 votes |
@Test public void iteratesList() { final List<String> list = new Synced<>(new ListOf<>()); new Assertion<>( "Must iterate a list with a procedure", new AndInThreads( new Mapped<String, Scalar<Boolean>>( new FuncOf<>(list::add, () -> true), new IterableOf<>("hello", "world") ) ), new ScalarHasValue<>(true) ).affirm(); new Assertion<>( "Iterable must contain elements in any order", list, new IsIterableContainingInAnyOrder<String>( new ListOf<Matcher<? super String>>( new MatcherOf<>( text -> { return "hello".equals(text); } ), new MatcherOf<>( text -> { return "world".equals(text); } ) ) ) ).affirm(); }
Example #17
Source File: AndTest.java From cactoos with MIT License | 5 votes |
@Test public void emptyIterator() throws Exception { new Assertion<>( "Iterator must be empty", new And(new IterableOf<Scalar<Boolean>>()), new ScalarHasValue<>(true) ).affirm(); }
Example #18
Source File: TempFile.java From cactoos with MIT License | 5 votes |
/** * Ctor. * @param dir The directory in which to create the temp file * @param prefix The temp filename's prefix * @param suffix The temp filename's suffix * @since 1.0 */ public TempFile( final Scalar<Path> dir, final String prefix, final String suffix) { this( dir, new TextOf(prefix), new TextOf(suffix) ); }
Example #19
Source File: AndInThreads.java From cactoos with MIT License | 5 votes |
/** * Ctor. * @param svc Executable service to run thread in * @param src The iterable * @param sht Shut it down */ private AndInThreads(final ExecutorService svc, final Iterable<Scalar<Boolean>> src, final boolean sht) { this.service = svc; this.iterable = src; this.shut = sht; }
Example #20
Source File: Base64Encoded.java From cactoos with MIT License | 5 votes |
/** * Ctor. * * @param origin Origin text */ public Base64Encoded(final Text origin) { super((Scalar<String>) () -> new TextOf( new BytesBase64( new BytesOf(origin) ) ).asString()); }
Example #21
Source File: And.java From cactoos with MIT License | 5 votes |
/** * Ctor. * @param func Func to map * @param src The iterable * @param <X> Type of items in the iterable * @since 0.24 */ public <X> And(final Func<X, Boolean> func, final Iterable<X> src) { this( new Mapped<>( item -> (Scalar<Boolean>) () -> func.apply(item), src ) ); }
Example #22
Source File: ReaderOf.java From cactoos with MIT License | 5 votes |
/** * Ctor. * @param src Source */ private ReaderOf(final Scalar<Reader> src) { super(); this.source = new Unchecked<>( new Sticky<>(src) ); }
Example #23
Source File: NumberEnvelope.java From cactoos with MIT License | 5 votes |
/** * Ctor. * @param dnm Double scalar */ public NumberEnvelope(final Scalar<Double> dnm) { this( () -> dnm.value().longValue(), () -> dnm.value().intValue(), () -> dnm.value().floatValue(), dnm ); }
Example #24
Source File: NumberEnvelope.java From cactoos with MIT License | 5 votes |
/** * Ctor. * @param lnm Long scalar * @param inm Integer scalar * @param fnm Float scalar * @param dnm Long scalar * @checkstyle ParameterNumberCheck (5 lines) */ public NumberEnvelope(final Scalar<Long> lnm, final Scalar<Integer> inm, final Scalar<Float> fnm, final Scalar<Double> dnm) { super(); this.lnum = lnm; this.inum = inm; this.fnum = fnm; this.dnum = dnm; }
Example #25
Source File: StickyTest.java From cactoos with MIT License | 5 votes |
@Test public void cachesScalarResults() throws Exception { final Scalar<Integer> scalar = new Sticky<>( () -> new SecureRandom().nextInt() ); new Assertion<>( "must compute value only once", scalar.value() + scalar.value(), new IsEqual<>(scalar.value() + scalar.value()) ).affirm(); }
Example #26
Source File: TextOf.java From cactoos with MIT License | 5 votes |
/** * Formats the date using the provided formatter. * @param date The date to format. * @param formatter The formatter to use. */ public TextOf( final ZonedDateTime date, final DateTimeFormatter formatter ) { super((Scalar<String>) () -> formatter.format(date)); }
Example #27
Source File: TextOf.java From cactoos with MIT License | 5 votes |
/** * Formats the date using the provided formatter. * @param date The date to format. * @param formatter The formatter to use. */ public TextOf( final OffsetDateTime date, final DateTimeFormatter formatter ) { super((Scalar<String>) () -> formatter.format(date)); }
Example #28
Source File: ReducedTest.java From cactoos with MIT License | 5 votes |
@Test public void singleAtSingleIterable() throws Exception { final Integer single = 10; new Assertion<>( "Must find the single", new Reduced<>( (first, last) -> first, new IterableOf<Scalar<Integer>>(() -> single) ).value(), Matchers.equalTo(single) ).affirm(); }
Example #29
Source File: SolidTest.java From cactoos with MIT License | 5 votes |
@Test public void cachesScalarResults() throws Exception { final Scalar<Integer> scalar = new Solid<>( () -> new SecureRandom().nextInt() ); new Assertion<>( "must compute value only once", scalar.value() + scalar.value(), new IsEqual<>(scalar.value() + scalar.value()) ).affirm(); }
Example #30
Source File: And.java From cactoos with MIT License | 5 votes |
/** * Ctor. * @param subject The subject * @param conditions Funcs to map * @param <X> Type of items in the iterable * @since 0.34 */ @SafeVarargs public <X> And(final X subject, final Func<X, Boolean>... conditions) { this( new Mapped<>( item -> (Scalar<Boolean>) () -> item.apply(subject), new IterableOf<>(conditions) ) ); }