org.cactoos.scalar.Unchecked Java Examples

The following examples show how to use org.cactoos.scalar.Unchecked. 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: SourcePgsql.java    From cactoos-jdbc with MIT License 7 votes vote down vote up
/**
 * Ctor.
 * @param hostname Server hostname or IPv4 Address
 * @param port Server port
 * @param dbname Database name
 */
public SourcePgsql(
    final String hostname,
    final int port,
    final String dbname
) {
    this.origin = new Unchecked<>(
        new Solid<>(
            () -> {
                final PGSimpleDataSource pds = new PGSimpleDataSource();
                pds.setUrl(
                    new FormattedText(
                        "jdbc:postgresql://%s:%d/%s",
                        hostname,
                        port,
                        dbname
                    ).asString()
                );
                return pds;
            }
        )
    );
}
 
Example #2
Source File: RsPrettyXml.java    From takes with MIT License 6 votes vote down vote up
@Override
@SuppressFBWarnings("EQ_UNUSUAL")
public boolean equals(final Object that) {
    return new Unchecked<>(
        new Or(
            () -> this == that,
            new And(
                () -> that != null,
                () -> RsPrettyXml.class.equals(that.getClass()),
                () -> {
                    final RsPrettyXml other = (RsPrettyXml) that;
                    return new And(
                        () -> this.origin.equals(other.origin),
                        () -> this.transformed.equals(other.transformed)
                    ).value();
                }
            )
        )
    ).value();
}
 
Example #3
Source File: Sub.java    From cactoos with MIT License 6 votes vote down vote up
/**
 * 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 #4
Source File: PhonesSql.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
@Override
public Iterator<Phone> iterator() {
    final Unchecked<List<String>> numbers = new Unchecked<>(
        new ResultSetAsValues<>(
            new StatementSelect(
                this.session,
                new QuerySimple(
                    new Joined(
                        " ",
                        "SELECT number FROM phone WHERE",
                        "contact_id = :contact_id"
                    ),
                    new ParamUuid("contact_id", this.id)
                )
            )
        )
    );
    return new Mapped<>(
        number -> new PhoneSql(this.session, this.id, number),
        numbers.value().iterator()
    );
}
 
Example #5
Source File: ServerMysql.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param hst Hostname
 * @param prt Port
 * @param srnm Username
 * @param psswrd User password
 * @param scrpt SQL Script to initialize the database
 * @checkstyle ParameterNumberCheck (10 lines)
 */
public ServerMysql(
    final String hst,
    final int prt,
    final String srnm,
    final String psswrd,
    final ScriptSql scrpt
) {
    this.dbname = new Unchecked<>(
        new Sticky<>(
            () -> new DatabaseName().asString()
        )
    );
    this.host = hst;
    this.port = prt;
    this.username = srnm;
    this.password = psswrd;
    this.script = scrpt;
}
 
Example #6
Source File: ServerPgsql.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param hst Hostname
 * @param prt Port
 * @param srnm Username
 * @param psswrd User password
 * @param scrpt SQL Script to initialize the database
 * @checkstyle ParameterNumberCheck (10 lines)
 */
public ServerPgsql(
    final String hst,
    final int prt,
    final String srnm,
    final String psswrd,
    final ScriptSql scrpt
) {
    this.dbname = new Unchecked<>(
        new Sticky<>(
            () -> new DatabaseName().asString()
        )
    );
    this.host = hst;
    this.port = prt;
    this.username = srnm;
    this.password = psswrd;
    this.script = scrpt;
}
 
Example #7
Source File: SourceH2.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
/**
 * Public ctor.
 * @param drvr H2 Driver
 * @param dbname DB name
 */
public SourceH2(final Driver drvr, final String dbname) {
    this.driver = drvr;
    this.url = new Unchecked<>(
        new Sticky<>(
            () -> new FormattedText(
                new Joined(
                    "",
                    "jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;",
                    "INIT=CREATE SCHEMA IF NOT EXISTS %s\\;SET SCHEMA %s"
                ),
                dbname,
                dbname,
                dbname
            ).asString()
        )
    );
}
 
Example #8
Source File: MapEnvelope.java    From cactoos with MIT License 6 votes vote down vote up
/**
 * Indicates whether contents of an other {@code Map} is the same
 * as contents of this one on entry-by-entry basis.
 * @param other Another instance of {@code Map} to compare with
 * @return True if contents are equal false otherwise
 */
private Boolean contentsEqual(final Map<?, ?> other) {
    return new Unchecked<>(
        new And(
            entry -> {
                return new And(
                    () -> other.containsKey(entry.getKey()),
                    () -> new EqualsNullable(
                        () -> other.get(entry.getKey()),
                        entry.getValue()
                    ).value()
                ).value();
            }, this.entrySet()
        )
    ).value();
}
 
Example #9
Source File: TextEnvelope.java    From cactoos with MIT License 5 votes vote down vote up
@Override
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings("EQ_UNUSUAL")
public final boolean equals(final Object obj) {
    return new Unchecked<>(
        new Or(
            () -> this == obj,
            new And(
                () -> obj instanceof Text,
                () -> new UncheckedText(this)
                    .asString()
                    .equals(new UncheckedText((Text) obj).asString())
            )
        )
    ).value();
}
 
Example #10
Source File: Logged.java    From cactoos-jdbc with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param session A Session
 * @param src Where the data comes from
 * @param lgr A logger
 */
public Logged(
    final Session session,
    final String src,
    final Logger lgr
) {
    this.origin = session;
    this.source = src;
    this.logger = lgr;
    this.level = new Unchecked<>(
        new Sticky<>(
            () -> {
                Level lvl = lgr.getLevel();
                if (lvl == null) {
                    Logger parent = lgr;
                    while (lvl == null) {
                        parent = parent.getParent();
                        lvl = parent.getLevel();
                    }
                }
                return lvl;
            }
        )
    );
    this.connections = new AtomicInteger();
    this.statements = new AtomicInteger();
}
 
Example #11
Source File: ResponseOf.java    From takes with MIT License 5 votes vote down vote up
@Override
@SuppressFBWarnings("EQ_UNUSUAL")
public boolean equals(final Object that) {
    return new Unchecked<>(
        new Or(
            () -> this == that,
            new And(
                () -> that != null,
                () -> ResponseOf.class.equals(that.getClass()),
                () -> {
                    final ResponseOf other = (ResponseOf) that;
                    return new And(
                        () -> {
                            final Iterator<String> iter = other.head()
                                .iterator();
                            return new And(
                                (String hdr) -> hdr.equals(iter.next()),
                                this.head()
                            ).value();
                        },
                        () -> new Equality<>(
                            new BytesOf(this.body()),
                            new BytesOf(other.body())
                        ).value() == 0
                    ).value();
                }
            )
        )
    ).value();
}
 
Example #12
Source File: Equality.java    From takes with MIT License 5 votes vote down vote up
@Override
public Boolean value() {
    return Objects.equals(
        new Unchecked<>(this.first).value(),
        new Unchecked<>(this.second).value()
    );
}
 
Example #13
Source File: XmlGraph.java    From jpeek with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param skeleton XMl representation on whiwh to build the graph
 */
public XmlGraph(final Skeleton skeleton) {
    this.nds = new Unchecked<>(
        new Sticky<>(
            () -> XmlGraph.build(skeleton)
        )
    );
}
 
Example #14
Source File: Repeated.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param total The total number of repetitions
 * @param item The element to repeat
 */
public Repeated(final int total, final Unchecked<T> item) {
    super(
        new IterableOf<>(
            () -> new org.cactoos.iterator.Repeated<>(total, item)
        )
    );
}
 
Example #15
Source File: Skeleton.java    From jpeek with MIT License 5 votes vote down vote up
/**
 * Calculate Xembly for all packages.
 * @return XML for all packages (one by one)
 */
@SuppressWarnings({
    "PMD.AvoidInstantiatingObjectsInLoops",
    "PMD.GuardLogStatement"
})
private Iterable<Map.Entry<String, Directives>> packages() {
    final long start = System.currentTimeMillis();
    final Collection<Map.Entry<String, Directives>> all =
        new CopyOnWriteArrayList<>();
    new Unchecked<>(
        new AndInThreads(
            new Mapped<>(
                clz -> () -> all.add(Skeleton.xembly(clz)),
                new Classes(this.base)
            )
        )
    ).value();
    final Map<String, Directives> map = new HashMap<>(0);
    for (final Map.Entry<String, Directives> ent : all) {
        map.putIfAbsent(ent.getKey(), new Directives());
        map.get(ent.getKey()).append(ent.getValue());
    }
    Logger.debug(
        this, "%d classes parsed via ASM in %[ms]s",
        map.size(), System.currentTimeMillis() - start
    );
    return map.entrySet();
}
 
Example #16
Source File: IterableOf.java    From cactoos with MIT License 5 votes vote down vote up
@Override
public int hashCode() {
    return new Unchecked<>(
        new Folded<>(
            42,
            (hash, entry) -> new SumOfInt(
                () -> 37 * hash,
                entry::hashCode
            ).value(),
            this
        )
    ).value();
}
 
Example #17
Source File: Sorted.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param comparator The comparator
 * @param iterator The underlying iterator
 */
public Sorted(final Comparator<T> comparator, final Iterator<T> iterator) {
    this.scalar = new Unchecked<>(
        new Sticky<>(
            () -> {
                final List<T> items = new LinkedList<>();
                while (iterator.hasNext()) {
                    items.add(iterator.next());
                }
                items.sort(comparator);
                return items.iterator();
            }
        )
    );
}
 
Example #18
Source File: OutputStreamTo.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param tgt Target
 */
private OutputStreamTo(final Scalar<OutputStream> tgt) {
    super();
    this.target = new Unchecked<>(
        new Sticky<>(tgt)
    );
}
 
Example #19
Source File: ReaderOf.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param src Source
 */
private ReaderOf(final Scalar<Reader> src) {
    super();
    this.source = new Unchecked<>(
        new Sticky<>(src)
    );
}
 
Example #20
Source File: Shuffled.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param iterator The original iterator
 */
public Shuffled(final Iterator<T> iterator) {
    this.scalar = new Unchecked<>(
        new Sticky<>(
            () -> {
                final List<T> items = new LinkedList<>();
                while (iterator.hasNext()) {
                    items.add(iterator.next());
                }
                Collections.shuffle(items);
                return items.iterator();
            }
        )
    );
}
 
Example #21
Source File: WriterTo.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param tgt Target
 */
private WriterTo(final Scalar<Writer> tgt) {
    super();
    this.target = new Unchecked<>(
        new Sticky<>(tgt)
    );
}
 
Example #22
Source File: LoggingInputStream.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param input Source of data
 * @param src The name of source data
 * @param lgr The message logger
 */
public LoggingInputStream(
    final InputStream input,
    final String src,
    final Logger lgr
) {
    super();
    this.origin = input;
    this.source = src;
    this.logger = lgr;
    this.level = new Unchecked<>(
        new Sticky<>(
            () -> {
                Level lvl = lgr.getLevel();
                if (lvl == null) {
                    Logger parent = lgr;
                    while (lvl == null) {
                        parent = parent.getParent();
                        lvl = parent.getLevel();
                    }
                }
                return lvl;
            }
        )
    );
    this.bytes = new AtomicLong();
    this.time = new AtomicLong();
}
 
Example #23
Source File: InputOf.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Ctor.
 *
 * @param file The file
 */
public InputOf(final File file) {
    this(
        () -> new FileInputStream(
            new Unchecked<>(() -> file).value()
        )
    );
}
 
Example #24
Source File: Randomized.java    From cactoos with MIT License 5 votes vote down vote up
@Override
public String asString() {
    final int len = new Unchecked<>(this.length).value();
    final StringBuilder builder = new StringBuilder(len);
    final int bound = this.characters.size();
    for (int index = 0; index < len; index = index + 1) {
        builder.append(this.characters.get(this.indices.nextInt(bound)));
    }
    return builder.toString();
}
 
Example #25
Source File: LocalDateTimeOf.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Parses the date using the formatter to create
 *  {@link LocalDateTime} instances.
 * @param date The date to parse.
 * @param formatter The formatter to use.
 */
public LocalDateTimeOf(final CharSequence date,
    final DateTimeFormatter formatter) {
    this.parsed = new Unchecked<>(
        () -> LocalDateTime.from(formatter.parse(date))
    );
}
 
Example #26
Source File: DateOf.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Parsing the date using the provided formatter.
 * @param date The date to parse.
 * @param formatter The formatter to use.
 */
public DateOf(final CharSequence date, final DateTimeFormatter formatter) {
    this.parsed = new Unchecked<>(
        () -> Date.from(
            LocalDateTime.parse(
                date,
                new DateTimeFormatterBuilder()
                    .append(formatter)
                    .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                    .toFormatter()
            ).toInstant(ZoneOffset.UTC)
        )
    );
}
 
Example #27
Source File: OffsetDateTimeOf.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Parses the date using the formatter to create
 *  {@link OffsetDateTime} instances.
 * @param date The date to parse.
 * @param formatter The formatter to use.
 */
public OffsetDateTimeOf(final CharSequence date,
    final DateTimeFormatter formatter) {
    this.parsed = new Unchecked<>(
        () -> ZonedDateTime.from(formatter.parse(date)).toOffsetDateTime()
    );
}
 
Example #28
Source File: ZonedDateTimeOf.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Parses the date using the formatter to create
 *  {@link ZonedDateTime} instances.
 * @param date The date to parse.
 * @param formatter The formatter to use.
 */
public ZonedDateTimeOf(final CharSequence date,
    final DateTimeFormatter formatter) {
    this.parsed = new Unchecked<>(
        () -> ZonedDateTime.from(formatter.parse(date))
    );
}
 
Example #29
Source File: ParamsNamed.java    From cactoos-jdbc with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param prms List of Param
 */
public ParamsNamed(final Param... prms) {
    this.prms = new Unchecked<>(
        new Sticky<>(
            () -> new ListOf<>(prms)
        )
    );
}
 
Example #30
Source File: ChunkedInputStream.java    From takes with MIT License 5 votes vote down vote up
/**
 * Expects the stream to start with a chunksize in hex with optional
 * comments after a semicolon. The line must end with a CRLF: "a3; some
 * comment\r\n" Positions the stream at the start of the next line.
 * @param stream The new input stream.
 * @return The chunk size as integer
 * @throws IOException when the chunk size could not be parsed
 */
private static int chunkSize(final InputStream stream)
    throws IOException {
    final ByteArrayOutputStream baos = ChunkedInputStream.sizeLine(stream);
    final String data = baos.toString(Charset.defaultCharset().name());
    final int separator = data.indexOf(';');
    final Text number = new Trimmed(
        new Unchecked<>(
            new Ternary<>(
                separator > 0,
                new Sub(data, 0, separator),
                new TextOf(data)
            )
        ).value()
    );
    try {
        // @checkstyle MagicNumberCheck (10 lines)
        return Integer.parseInt(
            new UncheckedText(
                number
            ).asString(),
            16
        );
    } catch (final NumberFormatException ex) {
        throw new IOException(
            String.format(
                "Bad chunk size: %s",
                baos.toString(Charset.defaultCharset().name())
            ),
            ex
        );
    }
}