org.cactoos.io.InputOf Java Examples

The following examples show how to use org.cactoos.io.InputOf. 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: HtStatusTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void takesStatusOutOfHttpResponse() throws IOException {
    MatcherAssert.assertThat(
        new HtStatus(
            new HtHead(
                new InputOf(
                    new Joined(
                        "\r\n",
                        "HTTP/1.1 200 OK",
                        "Content-type: text/plain",
                        "",
                        "Hello, dude!",
                        "How are you?"
                    )
                )
            )
        ).intValue(),
        Matchers.equalTo(HttpURLConnection.HTTP_OK)
    );
}
 
Example #2
Source File: PropertiesOfTest.java    From cactoos with MIT License 6 votes vote down vote up
@Test
public void readsInputContent() {
    new Assertion<>(
        "Must read properties from an input",
        new PropertiesOf(
            new InputOf("greet=Hello, inner world!\nask=works fine?\n")
        ),
        new ScalarHasValue<>(
            new MatcherOf<Properties>(
                props -> {
                    return "Hello, inner world!".equals(
                        props.getProperty("greet")
                    );
                }
            )
        )
    ).affirm();
}
 
Example #3
Source File: TextOfTest.java    From cactoos with MIT License 6 votes vote down vote up
@Test
public void readsInputIntoText() throws Exception {
    new Assertion<>(
        "Can't read text from Input",
        new Synced(
            new TextOf(
                new InputOf("привет, друг!"),
                StandardCharsets.UTF_8
            )
        ).asString(),
        Matchers.allOf(
            Matchers.startsWith("привет, "),
            Matchers.endsWith("друг!")
        )
    ).affirm();
}
 
Example #4
Source File: Reports.java    From jpeek with MIT License 6 votes vote down vote up
/**
 * Extract classes from passed Jar file.
 * @param path Jar file path
 * @throws IOException If fails
 */
private static void extractClasses(final Path path) throws IOException {
    try (JarFile jar = new JarFile(path.toFile())) {
        final Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            final JarEntry entry = entries.nextElement();
            final Path item = path.getParent().resolve(entry.getName());
            if (entry.isDirectory()) {
                item.toFile().mkdir();
                continue;
            }
            final Path parent = item.getParent();
            if (!parent.toFile().exists()) {
                parent.toFile().mkdirs();
            }
            new LengthOf(
                new TeeInput(
                    new InputOf(jar.getInputStream(entry)),
                    item
                )
            ).intValue();
        }
    }
}
 
Example #5
Source File: JavaInterface.java    From eo with MIT License 6 votes vote down vote up
@Override
public Input code() {
    return new InputOf(
        new FormattedText(
            "%s\n\npublic interface %s {\n  %s\n}\n",
            "package eo;",
            this.name,
            new UncheckedText(
                new JoinedText(
                    "\n    ",
                    new Mapped<>(
                        mtd -> new UncheckedText(
                            new FormattedText("%s;", mtd.java())
                        ).asString(),
                        this.methods
                    )
                )
            ).asString().replace("\n", "\n  ")
        )
    );
}
 
Example #6
Source File: SkipInputTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void skipsEverythingWhenEndingWithDelimiter() throws Exception {
    final String delimiter = "\r\n";
    MatcherAssert.assertThat(
        new TextOf(
            new SkipInput(
                new InputOf(
                    new Joined(
                        "",
                        "Hello dude! How are you?",
                        delimiter
                    )
                ),
                new BytesOf(delimiter)
            )
        ),
        new TextHasString("")
    );
}
 
Example #7
Source File: SkipInputTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void skipsSomeBytes() throws Exception {
    final String prefix = "Hello dude!";
    final String suffix = "How are you?";
    final String delimiter = "\r";
    MatcherAssert.assertThat(
        new TextOf(
            new SkipInput(
                new InputOf(
                    new Joined(
                        delimiter,
                        prefix,
                        suffix
                    )
                ),
                new BytesOf(delimiter)
            )
        ),
        new TextHasString(suffix)
    );
}
 
Example #8
Source File: HtContentTypeTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void takesDefaultContentType() {
    MatcherAssert.assertThat(
        new HtContentType(
            new HtHead(
                new InputOf(
                    new Joined(
                        "\r\n",
                        "HTTP/1.1 200 OK",
                        "",
                        "Hello, dude!"
                    )
                )
            )
        ).value(),
        new IsEqual<>(new ListOf<>("application/octet-stream"))
    );
}
 
Example #9
Source File: HtContentTypeTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void takesContentTypeOutOfHttpResponse() {
    MatcherAssert.assertThat(
        new HtContentType(
            new HtHead(
                new InputOf(
                    new Joined(
                        "\r\n",
                        "HTTP/1.1 200 OK",
                        "Content-type: text/plain",
                        "",
                        "Hello, dude!"
                    )
                )
            )
        ).value(),
        new IsEqual<>(new ListOf<>("text/plain"))
    );
}
 
Example #10
Source File: HtRetryWireTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void failsAfterMaxRetries() throws Exception {
    final String msg = "retry";
    final int max = 3;
    final AtomicInteger tries = new AtomicInteger(0);
    try {
        this.expected.expect(IllegalArgumentException.class);
        this.expected.expectMessage(msg);
        new HtRetryWire(
            input -> {
                if (tries.incrementAndGet() <= max) {
                    throw new IllegalArgumentException(msg);
                }
                return new InputOf("ignored");
            },
            max
        ).send(new InputOf("ignored"));
    } finally {
        MatcherAssert.assertThat(tries.get(), new IsEqual<>(max));
    }
}
 
Example #11
Source File: HtRetryWireTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void eventuallySucceeds() throws Exception {
    final Text txt = new TextOf("out");
    final int max = 3;
    final AtomicInteger tries = new AtomicInteger(0);
    MatcherAssert.assertThat(
        new HtRetryWire(
            input -> {
                if (tries.incrementAndGet() < max) {
                    throw new IllegalArgumentException("retry");
                }
                return new InputOf(txt);
            },
            max
        ).send(new InputOf("ignored")),
        new InputHasContent(txt.asString())
    );
}
 
Example #12
Source File: HtRetryWireTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void retriesMultipleTimesButNotMaxAttempts() {
    final int times = 3;
    final int max = times + 2;
    MatcherAssert.assertThat(
        t -> {
            final AtomicInteger tries = new AtomicInteger(0);
            new HtRetryWire(
                input -> {
                    if (tries.incrementAndGet() < t) {
                        throw new IllegalArgumentException("retry");
                    }
                    return new InputOf("ignored");
                },
                max
            ).send(new InputOf("ignored"));
            return tries.get();
        },
        new FuncApplies<>(times, times)
    );
}
 
Example #13
Source File: HtSecureWireTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Override
public InputStream stream() throws Exception {
    final String delimiter = "\r\n";
    return new InputOf(
        new Joined(
            delimiter,
            "GET / HTTP/1.1",
            new FormattedText(
                "Host: %s",
                this.host
            ).asString(),
            "Connection: close",
            delimiter
        )
    ).stream();
}
 
Example #14
Source File: HtBodyTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void takesBodyOutOfHttpResponse() {
    MatcherAssert.assertThat(
        new TextOf(
            new HtBody(
                new InputOf(
                    new Joined(
                        "\r\n",
                        "HTTP/1.1 200 OK",
                        "Content-type: text/plain",
                        "",
                        "Hello, dude!",
                        "How are you?"
                    )
                )
            )
        ),
        new TextHasString("Hello, dude!\r\nHow are you?")
    );
}
 
Example #15
Source File: HtHeadersTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void takesHeadersOutOfHttpResponse() throws IOException {
    MatcherAssert.assertThat(
        new HtHeaders(
            new HtHead(
                new InputOf(
                    new Joined(
                        "\r\n",
                        "HTTP/1.1 200 OK",
                        "Content-type: text/plain",
                        "",
                        "Hello, dude!",
                        "How are you?"
                    )
                )
            )
        ),
        new IsMapContaining<>(
            new IsEqual<>("content-type"),
            new IsEqual<>(new ListOf<>("text/plain"))
        )
    );
}
 
Example #16
Source File: HtHeadTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void takesHeadOutOfHttpResponse() {
    new Assertion<>(
        "Header does not have 'text/plain'",
        new TextOf(
            new HtHead(
                new InputOf(
                    new Joined(
                        "\r\n",
                        "HTTP/1.1 200 OK",
                        "Content-type: text/plain",
                        "",
                        "Hello, dude!"
                    )
                )
            )
        ),
        new EndsWith("text/plain")
    ).affirm();
}
 
Example #17
Source File: HtWire.java    From cactoos-http with MIT License 6 votes vote down vote up
@Override
public Input send(final Input input) throws Exception {
    final Socket socket = this.supplier.value();
    final InputStream source = input.stream();
    final InputStream ins = socket.getInputStream();
    final OutputStream ous = socket.getOutputStream();
    final byte[] buf = new byte[HtWire.LENGTH];
    while (true) {
        final int len = source.read(buf);
        if (len < 0) {
            break;
        }
        ous.write(buf, 0, len);
    }
    return new InputOf(ins);
}
 
Example #18
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 #19
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 #20
Source File: HtHeadTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void emptyHeadOfHttpResponse()  {
    new Assertion<>(
        "Text does not have an empty string",
        new TextOf(
            new HtHead(
                new InputOf(
                    new Joined(
                        "\r\n",
                        "",
                        "",
                        "Body"
                    )
                )
            )
        ),
        new TextHasString("")
    ).affirm();
}
 
Example #21
Source File: HtHeadTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void largeText() throws Exception {
    //@checkstyle MagicNumberCheck (1 lines)
    final byte[] bytes = new byte[18000];
    new Random().nextBytes(bytes);
    new Assertion<>(
        "Header does not have text/plain header",
        new TextOf(
            new HtHead(
                new InputOf(
                    new Joined(
                        "\r\n",
                        "HTTP/1.1 200 OK",
                        "Content-type: text/plain",
                        "",
                        new TextOf(new BytesOf(bytes)).asString()
                    )
                )
            )
        ),
        new EndsWith("text/plain")
    ).affirm();
}
 
Example #22
Source File: HtCookiesTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void takesCookiesOfHttpResponse() {
    MatcherAssert.assertThat(
        new HtCookies(
            new HtHead(
                new InputOf(
                    new Joined(
                        "\r\n",
                        "HTTP/1.1 200 OK",
                        "Content-type: text/plain",
                        "Set-Cookie: path=/; domain=.google.com",
                        "",
                        "Hello, dude!",
                        "How are you?"
                    )
                )
            )
        ),
        new IsMapContaining<>(
            new IsEqual<>("domain"),
            new IsEqual<>(new ListOf<>(".google.com"))
        )
    );
}
 
Example #23
Source File: CompileMojoTest.java    From eo with MIT License 6 votes vote down vote up
/**
 * Main can print a simple text.
 * @throws Exception If some problem inside
 */
public void testSimpleCompilation() throws Exception {
    final CompileMojo mojo = new CompileMojo();
    this.temp.create();
    final File src = this.temp.newFolder();
    this.setVariableValueToObject(mojo, "sourceDirectory", src);
    new LengthOf(
        new TeeInput(
            new InputOf(
                "type Pixel:\n  Pixel moveTo(Integer x, Integer y)"
            ),
            new OutputTo(new File(src, "main.eo"))
        )
    ).value();
    final File target = this.temp.newFolder();
    this.setVariableValueToObject(mojo, "targetDirectory", target);
    this.setVariableValueToObject(mojo, "project", new MavenProjectStub());
    mojo.execute();
    MatcherAssert.assertThat(
        new File(target, "Pixel.java").exists(),
        Matchers.is(true)
    );
}
 
Example #24
Source File: HtCookiesTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void incorrectHttpResponseCookie() {
    MatcherAssert.assertThat(
        new HtCookies(
            new HtHead(
                new InputOf(
                    new Joined(
                        "\r\n",
                        "HTTP/1.1 200 OK",
                        "Content-type: text/plain",
                        "Set-Cookie: path=/; 123; domain=.google.com",
                        "",
                        "Hello, dude!",
                        "How are you?"
                    )
                )
            )
        ),
        new IsMapContaining<>(
            new IsEqual<>("domain"),
            new IsEqual<>(".google.com")
        )
    );
}
 
Example #25
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 #26
Source File: CompileMojo.java    From eo with MIT License 6 votes vote down vote up
/**
 * Compile one EO file.
 * @param file EO file
 */
private void compile(final Path file) {
    try {
        new Program(
            new InputOf(file),
            this.targetDirectory.toPath()
        ).compile();
    } catch (final IOException ex) {
        throw new IllegalStateException(
            new UncheckedText(
                new FormattedText(
                    "Can't compile %s into %s",
                    file, this.targetDirectory
                )
            ).asString(),
            ex
        );
    }
    Logger.info(this, "%s compiled to %s", file, this.targetDirectory);
}
 
Example #27
Source File: HttpServletResponseFake.java    From takes with MIT License 5 votes vote down vote up
@Override
public ServletOutputStream getOutputStream() throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new LengthOf(
        new TeeInput(
            new InputOf(this.response.get().body()),
            new OutputTo(baos)
        )
    ).intValue();
    return new ServletOutputStreamTo(baos);
}
 
Example #28
Source File: ProgramTest.java    From eo with MIT License 5 votes vote down vote up
/**
 * Creates Java code that really works.
 * @throws Exception If some problem inside
 */
@Test
public void compilesExecutableJava() throws Exception {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final Program program = new Program(
        new InputOf(
            new JoinedText(
                "\n",
                "object car as Serializable:",
                "  Integer @vin",
                "  String name():",
                "    \"Mercedes-Benz\""
            ).asString()
        ),
        s -> new OutputTo(baos)
    );
    program.compile();
    try (final GroovyClassLoader loader = new GroovyClassLoader()) {
        final Class<?> type = loader.parseClass(
            new GroovyCodeSource(
                new TextOf(baos.toByteArray()).asString(),
                "car", GroovyShell.DEFAULT_CODE_BASE
            )
        );
        MatcherAssert.assertThat(
            type.getMethod("name").invoke(
                type.getConstructor(Integer.class).newInstance(0)
            ),
            Matchers.equalTo("Mercedes-Benz")
        );
    }
}
 
Example #29
Source File: ProgramTest.java    From eo with MIT License 5 votes vote down vote up
/**
 * Program can parse a type with multiple methods.
 * @throws Exception If some problem inside
 */
@Test(expected = CompileException.class)
public void failsOnBrokenSyntax() throws Exception {
    final Program program = new Program(
        new InputOf("this code is definitely wrong"),
        Files.createTempDirectory("")
    );
    program.compile();
}
 
Example #30
Source File: BodyStreamTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * Body.Stream can provide the expected input.
 * @throws Exception If there is some problem inside.
 */
@Test
public void returnsCorrectInputWithStream() throws Exception {
    final byte[] bytes =
        new BytesOf("Stream returnsCorrectInput!").asBytes();
    MatcherAssert.assertThat(
        "Body content of Body.Stream doesn't provide the correct bytes",
        new BytesOf(
            new Body.Stream(new InputOf(bytes).stream())
        ).asBytes(),
        new IsEqual<>(bytes)
    );
}