org.cactoos.Text Java Examples

The following examples show how to use org.cactoos.Text. 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: OpsOf.java    From jpeek with MIT License 6 votes vote down vote up
@Override
public void visitMethodInsn(final int opcode,
    final String owner, final String mtd,
    final String dsc, final boolean itf) {
    super.visitMethodInsn(opcode, owner, mtd, dsc, itf);
    this.target.strict(1).addIf("ops").add("op");
    this.target
        .attr("code", "call")
        .add("name")
        .set(owner.replace("/", ".").concat(".").concat(mtd))
        .up().add("args");
    final Iterable<Text> args = new Split(
        new Sub(dsc, dsc.indexOf('(') + 1, dsc.indexOf(')')),
        ";"
    );
    for (final Text arg : args) {
        this.target.add("arg").attr("type", arg).set("?").up();
    }
    this.target.up().up().up();
}
 
Example #2
Source File: FormattedText.java    From cactoos with MIT License 6 votes vote down vote up
/**
 * 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 #3
Source File: HmHeader.java    From takes with MIT License 6 votes vote down vote up
@Override
public boolean matchesSafely(final T item) {
    try {
        final Iterator<String> headers = HmHeader.headers(item).iterator();
        final Collection<String> values = new ArrayList<>(0);
        while (headers.hasNext()) {
            final String[] parts = HmHeader.split(headers.next());
            final UncheckedText first = new UncheckedText(
                new Trimmed(new TextOf(parts[0]))
            );
            if (this.header.matches(first.asString())) {
                final Text second = new Trimmed(new TextOf(parts[1]));
                values.add(new UncheckedText(second).asString());
            }
        }
        final boolean result = this.value.matches(values);
        if (!result) {
            this.failed = values;
        }
        return result;
    } catch (final IOException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example #4
Source File: NoNulls.java    From cactoos with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param text The text
 */
public NoNulls(final Text text) {
    super(new Scalar<String>() {
        @Override
        public String value() throws Exception {
            if (text == null) {
                throw new IllegalArgumentException(
                    "NULL instead of a valid text"
                );
            }
            final String string = text.asString();
            if (string == null) {
                throw new IllegalStateException(
                    "NULL instead of a valid result string"
                );
            }
            return string;
        }
    });
}
 
Example #5
Source File: TempFolder.java    From cactoos with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * Creates new folder in temporary directory.
 * @param path Relative path to new directory.
 * @since 1.0
 */
public TempFolder(final Text path) {
    this(
        new Sticky<>(
            () -> Files.createDirectory(
                Paths.get(
                    new Joined(
                        File.separator,
                        System.getProperty("java.io.tmpdir"),
                        path.asString()
                    ).asString()
                )
            )
        )
    );
}
 
Example #6
Source File: NumberOf.java    From cactoos with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param text Number-text
 */
public NumberOf(final Text text) {
    this.envelope = new Sealed(
        new Sticky<>(
            () -> Long.parseLong(text.asString())
        ),
        new Sticky<>(
            () -> Integer.parseInt(text.asString())
        ),
        new Sticky<>(
            () -> Float.parseFloat(text.asString())
        ),
        new Sticky<>(
            () -> Double.parseDouble(text.asString())
        )
    );
}
 
Example #7
Source File: Abbreviated.java    From cactoos with MIT License 6 votes vote down vote up
/**
 * 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 #8
Source File: MediaTypes.java    From takes with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param text Text to parse
 * @return List of media types
 */
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
private static SortedSet<MediaType> parse(final String text) {
    final SortedSet<MediaType> list = new TreeSet<>();
    final Iterable<Text> parts = new Split(
        new UncheckedText(new Lowered(text)),
        ","
    );
    for (final Text part : parts) {
        final String name = new UncheckedText(part).asString();
        if (!name.isEmpty()) {
            list.add(new MediaType(name));
        }
    }
    return list;
}
 
Example #9
Source File: HtHeaders.java    From cactoos-http with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param head Response head part
 */
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public HtHeaders(final Input head) {
    super(() -> {
        final Map<String, List<String>> map = new HashMap<>();
        final ListOf<Text> texts = new ListOf<>(
            new Split(new TextOf(head), "\r\n")
        );
        for (final Text line : texts.subList(1, texts.size())) {
            final String[] parts = line.asString().split(":", 2);
            map.merge(
                new Lowered(
                    new Trimmed(new TextOf(parts[0])), Locale.ENGLISH
                ).asString(),
                new ListOf<>(
                    new Trimmed(new TextOf(parts[1])).asString()
                ),
                (first, second) -> new Joined<String>(first, second)
            );
        }
        return map;
    });
}
 
Example #10
Source File: Rotated.java    From cactoos with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param text The text
 * @param shift The shift
 */
@SuppressWarnings({"PMD.CallSuperInConstructor",
    "PMD.ConstructorOnlyInitializesOrCallOtherConstructors"})
public Rotated(final Text text, final int shift) {
    super((Scalar<String>) () -> {
        String origin = text.asString();
        final int length = origin.length();
        if (length != 0 && shift != 0 && shift % length != 0) {
            final StringBuilder builder = new StringBuilder(length);
            int offset = -(shift % length);
            if (offset < 0) {
                offset = origin.length() + offset;
            }
            origin = builder.append(
                origin.substring(offset)
            ).append(
                origin.substring(0, offset)
            ).toString();
        }
        return origin;
    });
}
 
Example #11
Source File: RsXsltTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * RsXSLT can load XSL stylesheets from the web.
 * @throws IOException If some problem inside
 */
@Test
public void loadsExternalImports() throws IOException {
    final Text xml = new Joined(
        " ",
        "<?xml-stylesheet   ",
        " href='/org/takes/rs/stylesheet-with-include.xsl'",
        " type='text/xsl'?><page sla='0.324'/>"
    );
    MatcherAssert.assertThat(
        IOUtils.toString(
            new RsXslt(
                new RsText(new InputStreamOf(xml))
            ).body(),
            StandardCharsets.UTF_8
        ),
        XhtmlMatchers.hasXPath(
            "/xhtml:html/xhtml:span[starts-with(@class, 'sla ')]"
        )
    );
}
 
Example #12
Source File: MappedTest.java    From cactoos with MIT License 5 votes vote down vote up
@Test
public void transformsList() throws Exception {
    MatcherAssert.assertThat(
        "Can't transform an iterable",
        new Mapped<String, Text>(
            input -> new Upper(new TextOf(input)),
            new IterableOf<>("hello", "world", "друг")
        ).iterator().next().asString(),
        new IsEqual<>("HELLO")
    );
}
 
Example #13
Source File: FormattedText.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * New formatted string with specified locale.
 *
 * @param ptn Pattern
 * @param locale Format locale
 * @param arguments Arguments
 */
public FormattedText(
    final Text ptn,
    final Locale locale,
    final Object... arguments
) {
    this(ptn, locale, new ListOf<>(arguments));
}
 
Example #14
Source File: UncheckedBytesTest.java    From cactoos with MIT License 5 votes vote down vote up
@Test
public void worksNormallyWhenNoExceptionIsThrown() throws Exception {
    final Text source = new TextOf("hello, cactoos!");
    new Assertion<>(
        "Must works normally when no exception is thrown",
        new UncheckedBytes(
            new BytesOf(source)
        ).asBytes(),
        Matchers.equalTo(
            new BytesOf(source).asBytes()
        )
    ).affirm();
}
 
Example #15
Source File: Normalized.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param text A Text
 */
public Normalized(final Text text) {
    super(
        (Scalar<String>) () -> new Replaced(
            new Trimmed(text),
            "\\s+",
            " "
        ).asString()
    );
}
 
Example #16
Source File: RsXsltTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * RsXSLT closes decorated Response body's InputStream when XML conversion
 * is done.
 * @throws Exception If some problem inside
 */
@Test
public void closesDecoratedResponseInputStream() throws Exception {
    final Text xml = new Joined(
        " ",
        "<?xml-stylesheet href='/b.xsl' type='text/xsl'?>",
        "<subject>World</subject>"
    );
    final Text xsl =
        new Joined(
            " ",
            "<stylesheet xmlns='http://www.w3.org/1999/XSL/Transform'  ",
            " xmlns:x='http://www.w3.org/1999/xhtml' version='2.0'  >",
            "<output method='text'/><template match='/'> ",
            "Hello, <value-of select='/subject'/>!</template></stylesheet>"
        );
    final StateAwareInputStream stream = new StateAwareInputStream(
        new InputStreamOf(xml)
    );
    MatcherAssert.assertThat(
        new RsPrint(
            new RsXslt(
                new RsText(stream),
                (href, base) -> new StreamSource(new InputStreamOf(xsl))
            )
        ),
        new EndsWith("Hello, World!")
    );
    MatcherAssert.assertThat(
        stream.isClosed(),
        Matchers.is(true)
    );
}
 
Example #17
Source File: MappedTest.java    From cactoos with MIT License 5 votes vote down vote up
@Test
public void transformsEmptyList() {
    MatcherAssert.assertThat(
        "Can't transform an empty iterable",
        new Mapped<String, Text>(
            input -> new Upper(new TextOf(input)),
            Collections.emptyList()
        ),
        Matchers.emptyIterable()
    );
}
 
Example #18
Source File: TempFile.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * 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 Text prefix,
    final Text suffix) {
    this(
        new Sticky<>(
            () -> Files.createTempFile(
                dir.value(),
                prefix.asString(),
                suffix.asString()
            )
        )
    );
}
 
Example #19
Source File: ComparableTextTest.java    From cactoos with MIT License 5 votes vote down vote up
@Test
public void equalsToItself() {
    final Text text = new TextOf("text");
    new Assertion<>(
        "Does not equal to itself",
        text,
        new TextIs(text)
    ).affirm();
}
 
Example #20
Source File: Reversed.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Ctor.
 *
 * @param text The text
 */
public Reversed(final Text text) {
    super((Scalar<String>) () -> new StringBuilder(
        text.asString()
        ).reverse().toString()
    );
}
 
Example #21
Source File: Strict.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param predicate The Func as a predicate
 * @param origin The Text
 */
public Strict(final Func<String, Boolean> predicate, final Text origin) {
    super((Scalar<String>) () -> {
        final String str = origin.asString();
        if (!predicate.apply(str)) {
            throw new IllegalArgumentException(
                new FormattedText(
                    "String '%s' does not match a given predicate",
                    str
                ).asString()
            );
        }
        return str;
    });
}
 
Example #22
Source File: ExpectedStatus.java    From verano-http with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param statuses Statuses
 * @param message Error message
 */
public ExpectedStatus(
    final Iterable<Integer> statuses, final Text message
) {
    this.statuses = statuses;
    this.message = new UncheckedText(message);
}
 
Example #23
Source File: Repeated.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param text The Text
 * @param count How many times repeat the Text
 */
public Repeated(final Text text, final int count) {
    super((Scalar<String>) () -> {
        final StringBuilder out = new StringBuilder();
        for (int cnt = 0; cnt < count; ++cnt) {
            out.append(text.asString());
        }
        return out.toString();
    });
}
 
Example #24
Source File: Base64Decoded.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Ctor.
 *
 * @param origin Origin text
 */
public Base64Decoded(final Text origin) {
    super(new TextOf(
        new Base64Bytes(
            new BytesOf(origin)
        )
    ));
}
 
Example #25
Source File: SplitTest.java    From cactoos with MIT License 5 votes vote down vote up
@Test
public void splitTextWithStringRegexAndLimit() throws Exception {
    final Text txt = new TextOf("Cact!4Primitives");
    new Assertion<>(
        "Must split text with string regex and limit",
        new Split(txt, "4", 1),
        new IsEqual<>(new IterableOf<>(txt))
    ).affirm();
}
 
Example #26
Source File: MediaType.java    From takes with MIT License 5 votes vote down vote up
/**
 * Returns the low part of the media type.
 * @param text The media type text.
 * @return The low part of the media type.
 */
private static String lowPart(final String text) {
    final String[] sectors = MediaType.sectors(text);
    final Text sector;
    if (sectors.length > 1) {
        sector = new Trimmed(new TextOf(sectors[1]));
    } else {
        sector = new TextOf("");
    }
    return new UncheckedText(sector).asString();
}
 
Example #27
Source File: Split.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param text The text
 * @param rgx The regex
 * @param lmt The limit
 * @see String#split(String, int)
 */
public Split(final UncheckedText text, final UncheckedText rgx, final int lmt) {
    super(
        new Mapped<String, Text>(
            TextOf::new,
            new IterableOf<>(
                text.asString().split(rgx.asString(), lmt)
            )
        )
    );
}
 
Example #28
Source File: PaddedStart.java    From cactoos with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param text The text
 * @param length The minimum length of the resulting string
 * @param symbol The padding symbol
 */
public PaddedStart(
    final Text text, final int length, final char symbol) {
    super((Scalar<String>) () -> {
        final String original = text.asString();
        return new Joined(
            new TextOf(""),
            new Repeated(
                new TextOf(symbol), length - original.length()
            ),
            text
        ).asString();
    });
}
 
Example #29
Source File: BytesOfTest.java    From cactoos with MIT License 5 votes vote down vote up
@Test
public void asBytes() throws Exception {
    final Text text = new TextOf("Hello!");
    new Assertion<>(
        "Can't convert text into bytes",
        new BytesOf(
            new InputOf(text)
        ).asBytes(),
        new IsEqual<>(
            new BytesOf(text.asString()).asBytes()
        )
    ).affirm();
}
 
Example #30
Source File: RqHref.java    From takes with MIT License 5 votes vote down vote up
@Override
public Href href() throws IOException {
    final String uri = new RqRequestLine.Base(this).uri();
    final Iterator<String> hosts = new RqHeaders.Base(this)
        .header("host").iterator();
    final Iterator<String> protos = new RqHeaders.Base(this)
        .header("x-forwarded-proto").iterator();
    final Text host;
    if (hosts.hasNext()) {
        host = new Trimmed(new TextOf(hosts.next()));
    } else {
        host = new TextOf("localhost");
    }
    final Text proto;
    if (protos.hasNext()) {
        proto = new Trimmed(new TextOf(protos.next()));
    } else {
        proto = new TextOf("http");
    }
    return new Href(
        String.format(
            "%s://%s%s",
            new UncheckedText(proto).asString(),
            new UncheckedText(host).asString(),
            uri
        )
    );
}