org.cactoos.text.FormattedText Java Examples

The following examples show how to use org.cactoos.text.FormattedText. 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: MetricsTest.java    From jpeek with MIT License 7 votes vote down vote up
@ParameterizedTest
@CsvFileSource(resources = "/org/jpeek/metricstest-params.csv")
public void testsTarget(final String target, final String metric, final double value,
    @TempDir final Path output)
    throws Exception {
    new XslReport(
        new Skeleton(new FakeBase(target)).xml(), new XslCalculus(),
        new ReportData(metric)
    ).save(output);
    final String xpath;
    if (Double.isNaN(value)) {
        xpath = "//class[@id='%s' and @value='NaN']";
    } else {
        xpath = "//class[@id='%s' and number(@value)=%.4f]";
    }
    new Assertion<>(
        new FormattedText(
            "Must exists with target '%s' and value '%s'",
            target, value
        ).asString(),
        XhtmlMatchers.xhtml(
            new TextOf(
                output.resolve(String.format("%s.xml", metric))
            ).asString()
        ),
        XhtmlMatchers.hasXPaths(
            String.format(
                xpath,
                target, value
            )
        )
    ).affirm();
}
 
Example #3
Source File: ContactsSql.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
@Override
public Contact get(final int index) throws Exception {
    return new ContactSql(
        this.session,
        new ResultSetAsValue<UUID>(
            new StatementSelect(
                this.session,
                new QuerySimple(
                    new FormattedText(
                        "SELECT id FROM contact FETCH FIRST %d ROWS ONLY",
                        index
                    )
                )
            )
        ).value()
    );
}
 
Example #4
Source File: Logged.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
@Override
public void setLong(final int index, final long value) throws SQLException {
    this.origin.setLong(index, value);
    this.logger.log(
        this.level,
        new UncheckedText(
            new FormattedText(
                new Joined(
                    " ",
                    "[%s] PreparedStatement[#%d] changed at",
                    "parameter[#%d] with '%d' value."
                ),
                this.source,
                this.id,
                index,
                value
            )
        ).asString()
    );
}
 
Example #5
Source File: ProcOfTest.java    From cactoos with MIT License 6 votes vote down vote up
@Test
public void worksWithRunnable() throws Exception {
    final String str = "test string";
    final List<String> list = new ArrayList<>(1);
    new ProcOf<String>(
        new Runnable() {
            @Override
            public void run() {
                list.add(str);
            }
        }
    ).exec("You can use any input in a Runnable.");
    MatcherAssert.assertThat(
        new FormattedText(
            "Wrong result when created with a Runnable. Expected %s",
            str
        ).asString(),
        list,
        Matchers.contains(str)
    );
}
 
Example #6
Source File: StickyTest.java    From cactoos with MIT License 6 votes vote down vote up
@Test
public void extendsExistingMapWithTwoFuncs() throws Exception {
    MatcherAssert.assertThat(
        "Can't transform and decorate a list of entries with two funcs",
        new Sticky<>(
            color -> new FormattedText("[%s]", color).asString(),
            String::toUpperCase,
            new Sticky<String, String>(
                new MapEntry<>("black!", "Black!"),
                new MapEntry<>("white!", "White!")
            ),
            new IterableOf<>("yellow!", "red!", "blue!")
        ),
        new IsMapContaining<>(
            new IsAnything<>(),
            new IsEqual<>("BLUE!")
        )
    );
}
 
Example #7
Source File: ProcOfTest.java    From cactoos with MIT License 6 votes vote down vote up
@Test
public void worksWithFunc() throws Exception {
    final String str = "test input";
    final List<String> list = new ArrayList<>(1);
    new ProcOf<String>(
        input -> {
            list.add(input);
            return list.size();
        }
    ).exec(str);
    MatcherAssert.assertThat(
        new FormattedText(
            "Wrong result when created with a Func. Expected %s",
            str
        ).asString(),
        list,
        Matchers.contains(str)
    );
}
 
Example #8
Source File: Logged.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
@Override
public boolean execute(final String sql) throws SQLException {
    final Instant start = Instant.now();
    final boolean result = this.origin.execute(sql);
    final Instant end = Instant.now();
    final long millis = Duration.between(start, end).toMillis();
    this.logger.log(
        this.level,
        new UncheckedText(
            new FormattedText(
                "[%s] PreparedStatement[#%d] executed SQL '%s' in %dms.",
                this.source,
                this.id,
                sql,
                millis
            )
        ).asString()
    );
    return result;
}
 
Example #9
Source File: MetricBase.java    From jpeek with MIT License 6 votes vote down vote up
/**
 * Asserts the main metric value.
 * @param value Expected value of the metric
 * @param error Rounding tolerance since the metric is float number
 * @throws IOException String format exception
 */
public void assertValue(final double value, final double error)
    throws IOException {
    new Assertion<>(
        "The metric value is not calculated properly",
        Double.parseDouble(
            this.xml.xpath(
                new FormattedText(
                    "//class[@id='%s']/@value",
                    this.name
                ).asString()
            ).get(0)
        ),
        new IsCloseTo(
            value,
            error
        )
    ).affirm();
}
 
Example #10
Source File: Logged.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
@Override
public int[] executeBatch() throws SQLException {
    final int[] counts = this.origin.executeBatch();
    this.logger.log(
        this.level,
        new UncheckedText(
            new FormattedText(
                "[%s] PreparedStatement[#%d] returned '%d' counts.",
                this.source,
                this.id,
                counts.length
            )
        ).asString()
    );
    return counts;
}
 
Example #11
Source File: Logged.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
@Override
public PreparedStatement prepareStatement(final String sql) throws
    SQLException {
    final PreparedStatement stmt = this.origin.prepareStatement(sql);
    this.logger.log(
        this.level,
        new UncheckedText(
            new FormattedText(
                "[%s] PreparedStatement[#%d] created using SQL '%s'.",
                this.source,
                this.statements.get(),
                sql
            )
        ).asString()
    );
    return new com.github.fabriciofx.cactoos.jdbc.prepared.Logged(
        stmt,
        this.source,
        this.logger,
        this.level,
        this.statements.getAndIncrement()
    );
}
 
Example #12
Source File: Logged.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
@Override
public ResultSet executeQuery() throws SQLException {
    final Instant start = Instant.now();
    final ResultSet rset = this.origin.executeQuery();
    final Instant end = Instant.now();
    final long millis = Duration.between(start, end).toMillis();
    this.logger.log(
        this.level,
        new UncheckedText(
            new FormattedText(
                new Joined(
                    " ",
                    "[%s] PreparedStatement[#%d] retrieved a",
                    "ResultSet in %dms."
                ),
                this.source,
                this.id,
                millis
            )
        ).asString()
    );
    return rset;
}
 
Example #13
Source File: Logged.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
@Override
public String nativeSQL(final String sql) throws SQLException {
    final String nat = this.origin.nativeSQL(sql);
    this.logger.log(
        this.level,
        new UncheckedText(
            new FormattedText(
                "[%s] SQL '%s' converted to '%s.",
                this.source,
                sql,
                nat
            )
        ).asString()
    );
    return nat;
}
 
Example #14
Source File: Logged.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
@Override
public void rollback() throws SQLException {
    final Instant start = Instant.now();
    this.origin.rollback();
    final Instant end = Instant.now();
    final long millis = Duration.between(start, end).toMillis();
    this.logger.log(
        this.level,
        new UncheckedText(
            new FormattedText(
                "[%s] executed in %dms.",
                this.source,
                millis
            )
        ).asString()
    );
}
 
Example #15
Source File: Logged.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
@Override
public Statement createStatement(
    final int resultSetType,
    final int resultSetConcurrency
) throws SQLException {
    final Statement stmt = this.origin.createStatement(
        resultSetType,
        resultSetConcurrency
    );
    this.logger.log(
        this.level,
        new UncheckedText(
            new FormattedText(
                // @checkstyle LineLengthCheck (1 line)
                "[%s] Statement[#%d] created with type '%d' and concurrency '%d'.",
                this.source,
                this.statements.get(),
                resultSetType,
                resultSetConcurrency
            )
        ).asString()
    );
    return stmt;
}
 
Example #16
Source File: LoggingOutputStream.java    From cactoos with MIT License 6 votes vote down vote up
@Override
public void write(final byte[] buf, final int offset,
    final int len) throws IOException {
    final Instant start = Instant.now();
    this.origin.write(buf, offset, len);
    final Instant end = Instant.now();
    final long millis = Duration.between(start, end).toMillis();
    this.bytes.getAndAdd(len);
    this.time.getAndAdd(millis);
    final Level level = this.logger.getLevel();
    if (!level.equals(Level.INFO)) {
        this.logger.log(
            level,
            new UncheckedText(
                new FormattedText(
                    "Written %d byte(s) to %s in %dms.",
                    this.bytes.get(),
                    this.destination,
                    this.time.get()
                )
            ).asString()
        );
    }
}
 
Example #17
Source File: LoggingInputStream.java    From cactoos with MIT License 6 votes vote down vote up
@Override
public boolean markSupported() {
    final boolean supported = this.origin.markSupported();
    final String msg;
    if (supported) {
        msg = "Mark and reset are supported from %s";
    } else {
        msg = "Mark and reset NOT supported from %s";
    }
    this.logger.log(
        this.level.value(),
        new UncheckedText(
            new FormattedText(
                msg,
                this.source
            )
        ).asString()
    );
    return supported;
}
 
Example #18
Source File: Logged.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
@Override
public CallableStatement prepareCall(final String sql) throws SQLException {
    final CallableStatement stmt = this.origin.prepareCall(sql);
    this.logger.log(
        this.level,
        new UncheckedText(
            new FormattedText(
                "[%s] CallableStatement[#%d] created using SQL '%s'.",
                this.source,
                this.statements.get(),
                sql
            )
        ).asString()
    );
    return stmt;
}
 
Example #19
Source File: PhonesSql.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
@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 #20
Source File: ServerMysql.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
@Override
public void start() throws Exception {
    new StatementUpdate(
        new SessionAuth(
            new SourceMysql(
                this.host,
                this.port,
                ""
            ),
            this.username,
            this.password
        ),
        new QuerySimple(
            new FormattedText(
                new Joined(
                    " ",
                    "CREATE DATABASE IF NOT EXISTS %s CHARACTER",
                    "SET utf8mb4 COLLATE utf8mb4_unicode_ci"
                ),
                this.dbname.value()
            )
        )
    ).result();
    this.script.run(this.session());
}
 
Example #21
Source File: ServerMysql.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
@Override
public void stop() throws Exception {
    new StatementUpdate(
        new SessionAuth(
            new SourceMysql(
                this.host,
                this.port,
                ""
            ),
            this.username,
            this.password
        ),
        new QuerySimple(
            new FormattedText(
                "DROP DATABASE IF EXISTS %s",
                this.dbname.value()
            )
        )
    ).result();
}
 
Example #22
Source File: ServerPgsql.java    From cactoos-jdbc with MIT License 6 votes vote down vote up
@Override
public void stop() throws Exception {
    new StatementUpdate(
        new SessionAuth(
            new SourcePgsql(
                this.host,
                this.port,
                ""
            ),
            this.username,
            this.password
        ),
        new QuerySimple(
            new FormattedText(
                "DROP DATABASE IF EXISTS %s",
                this.dbname.value()
            )
        )
    ).result();
}
 
Example #23
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 #24
Source File: Get.java    From cactoos-http with MIT License 6 votes vote down vote up
/**
 * Ctor.
 *
 * @param url Url to GET.
 */
public Get(final URI url) {
    super(new InputOf(
        new Joined(
            new TextOf("\r\n"),
            new FormattedText(
                "GET %s HTTP/1.1",
                url.getPath()
            ),
            new FormattedText(
                "Host: %s",
                url.getHost()
            )
        )
    ));
}
 
Example #25
Source File: HtKeepAliveResponse.java    From cactoos-http with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param wre The wire
 * @param mtimeout The timeout for the connection usage in milliseconds
 * @param rmax The maximum quantity of the requests within the connection
 *  timeout
 * @param req The request
 * @checkstyle ParameterNumberCheck (2 lines)
 */
public HtKeepAliveResponse(
    final Wire wre, final long mtimeout, final int rmax, final String req
) {
    super(
        new HtResponse(
            wre,
            new InputOf(
                new FormattedText(
                    HtKeepAliveResponse.TEMPLATE,
                    req,
                    mtimeout,
                    rmax
                )
            )
        )
    );
}
 
Example #26
Source File: HtAutoRedirectTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void redirectsRequestAutomatically() throws Exception {
    new FtRemote(new TkText("redirected ok")).exec(
        home -> MatcherAssert.assertThat(
            "Does not redirects automatically",
            new TextOf(
                new HtAutoRedirect(
                    new InputOf(
                        new Joined(
                            new TextOf("\r\n"),
                            new TextOf("HTTP/1.1 301"),
                            new FormattedText(
                                "Location: %s", home
                            )
                        )
                    )
                )
            ),
            new TextHasString("HTTP/1.1 200 ")
        )
    );
}
 
Example #27
Source File: NoNulls.java    From cactoos with MIT License 6 votes vote down vote up
@Override
public final V get(final Object key) {
    if (key == null) {
        throw new IllegalStateException(
            "Key at #get(K) is NULL"
        );
    }
    final V value = this.map.get(key);
    if (value == null) {
        throw new IllegalStateException(
            new UncheckedText(
                new FormattedText(
                    "Value returned by #get(%s) is NULL",
                    key
                )
            ).asString()
        );
    }
    return value;
}
 
Example #28
Source File: MetricBase.java    From jpeek with MIT License 6 votes vote down vote up
/**
 * Asserts the variable produced.
 * @param variable Variable name
 * @param expected Expected value
 * @throws Exception String format exception
 */
public void assertVariable(final String variable,
    final int expected) throws Exception {
    new Assertion<>(
        new FormattedText(
            "Variable '%s' is not calculated correctly for class '%s'",
            variable,
            this.name
        ).asString(),
        new TextOf(
            this.xml.xpath(
                new FormattedText(
                    "//class[@id='%s']/vars/var[@id='%s']/text()",
                    this.name,
                    variable
                ).asString()
            ).get(0)
        ),
        new TextIs(
            String.valueOf(
                expected
            )
        )
    ).affirm();
}
 
Example #29
Source File: NoNulls.java    From cactoos with MIT License 6 votes vote down vote up
@Override
public final V remove(final Object key) {
    if (key == null) {
        throw new IllegalStateException(
            "Key at #remove(K) is NULL"
        );
    }
    final V result = this.map.remove(key);
    if (result == null) {
        throw new IllegalStateException(
            new UncheckedText(
                new FormattedText(
                    "Value returned by #remove(%s) is NULL",
                    key
                )
            ).asString()
        );
    }
    return result;
}
 
Example #30
Source File: NoNulls.java    From cactoos with MIT License 6 votes vote down vote up
@Override
public T get(final int index) {
    final T item = this.list.get(index);
    if (item == null) {
        throw new IllegalStateException(
            new UncheckedText(
                new FormattedText(
                    "Item #%d of %s is NULL",
                    index,
                    this.list
                )
            ).asString()
        );
    }
    return item;
}