org.takes.rs.RsText Java Examples

The following examples show how to use org.takes.rs.RsText. 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: FbStatusTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FbStatus can react to Condition.
 * @throws Exception If some problem inside
 */
@Test
public void reactsToCondition() throws Exception {
    final RqFallback req = new RqFallback.Fake(
        HttpURLConnection.HTTP_MOVED_PERM
    );
    MatcherAssert.assertThat(
        new RsPrint(
            new FbStatus(
                new Filtered<>(
                    status -> {
                        return status == HttpURLConnection.HTTP_MOVED_PERM
                            || status == HttpURLConnection.HTTP_MOVED_TEMP;
                    },
                    new ListOf<>(
                        HttpURLConnection.HTTP_MOVED_PERM,
                        HttpURLConnection.HTTP_MOVED_TEMP
                    )
                ),
                new FbFixed(new RsText("response text"))
            ).route(req).get()
        ).printBody(),
        Matchers.startsWith("response")
    );
}
 
Example #2
Source File: TakesApp.java    From tutorials with MIT License 6 votes vote down vote up
public static void main(final String... args) throws IOException, SQLException {
    new FtBasic(
        new TkFallback(
            new TkFork(
                new FkRegex("/", new TakesHelloWorld()),
                new FkRegex("/index", new TakesIndex()),
                new FkRegex("/contact", new TakesContact())
                ),
            new FbChain(
                new FbStatus(404, new RsText("Page Not Found")),
                new FbStatus(405, new RsText("Method Not Allowed")),
                new Fallback() {
                    @Override
                    public Opt<Response> route(final RqFallback req) {
                        return new Opt.Single<Response>(new RsText(req.throwable().getMessage()));
                    }
                })
            ), 6060
        ).start(Exit.NEVER);
}
 
Example #3
Source File: TkCorsTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkCors can't handle connections with wrong domain on origin.
 * @throws Exception If some problem inside
 */
@Test
public void cantHandleConnectionsWithWrongDomainOnOrigin()
    throws Exception {
    MatcherAssert.assertThat(
        "Wrong value on header.",
        new RsPrint(
            new TkCors(
                new TkFixed(new RsText()),
                "http://www.teamed.io",
                "http://sample.com"
            ).act(
                new RqWithHeaders(
                    new RqFake(),
                    "Origin: http://wrong.teamed.io"
                )
            )
        ).printHead(),
        Matchers.allOf(
            Matchers.containsString("HTTP/1.1 403"),
            Matchers.containsString(
                "Access-Control-Allow-Credentials: false"
            )
        )
    );
}
 
Example #4
Source File: TkCorsTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkCORS can handle connections with correct domain on origin.
 * @throws Exception If some problem inside
 */
@Test
public void handleConnectionsWithCorrectDomainOnOrigin() throws Exception {
    MatcherAssert.assertThat(
        "Invalid HTTP status for a request with correct domain.",
        new TkCors(
            new TkFixed(new RsText()),
            "http://teamed.io",
            "http://example.com"
        ).act(
            new RqWithHeaders(
                new RqFake(),
                "Origin: http://teamed.io"
            )
        ),
        new HmRsStatus(HttpURLConnection.HTTP_OK)
    );
}
 
Example #5
Source File: TkRetryTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkRetry can retry when initial take fails with IOException,
 * till get successful result.
 *
 * @throws Exception if something is wrong
 */
@Test
public void retriesOnExceptionTillSuccess() throws Exception {
    final int count = Tv.THREE;
    final int delay = Tv.THOUSAND;
    final String data = "data";
    final Take take = Mockito.mock(Take.class);
    Mockito
        .when(take.act(Mockito.any(Request.class)))
        .thenThrow(new IOException())
        .thenReturn(new RsText(data));
    final long start = System.nanoTime();
    final RsPrint response = new RsPrint(
        new TkRetry(count, delay, take).act(new RqFake(RqMethod.GET))
    );
    final long spent = System.nanoTime() - start;
    MatcherAssert.assertThat(
        Long.valueOf(delay - Tv.HUNDRED) * Tv.MILLION,
        Matchers.lessThanOrEqualTo(spent)
    );
    MatcherAssert.assertThat(
        response,
        new TextHasString(data)
    );
}
 
Example #6
Source File: FtRemoteTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FtRemote can work.
 * @throws Exception If some problem inside
 */
@Test
public void simplyWorks() throws Exception {
    new FtRemote(new TkFixed(new RsText("simple answer"))).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .assertBody(Matchers.startsWith("simple"));
            }
        }
    );
}
 
Example #7
Source File: TkFallbackTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkFallback can fall back.
 * @throws Exception If some problem inside
 */
@Test
public void fallsBack() throws Exception {
    final String err = "message";
    MatcherAssert.assertThat(
        new RsPrint(
            new TkFallback(
                new TkFailure(err),
                new Fallback() {
                    @Override
                    public Opt<Response> route(final RqFallback req) {
                        return new Opt.Single<Response>(
                            new RsText(req.throwable().getMessage())
                        );
                    }
                }
            ).act(new RqFake())
        ).printBody(),
        Matchers.endsWith(err)
    );
}
 
Example #8
Source File: FbChainTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FbChain can chain fallbacks.
 * @throws Exception If some problem inside
 */
@Test
public void chainsFallbacks() throws Exception {
    final RqFallback req = new RqFallback.Fake(
        HttpURLConnection.HTTP_NOT_FOUND
    );
    MatcherAssert.assertThat(
        new RsPrint(
            new FbChain(
                new FbEmpty(),
                new FbFixed(new RsText("first rs")),
                new FbFixed(new RsText("second rs"))
            ).route(req).get()
        ).printBody(),
        Matchers.startsWith("first")
    );
}
 
Example #9
Source File: TkJoinedCookiesTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkJoinedCookies can join cookies.
 * @throws Exception If some problem inside
 */
@Test
public void joinsCookies() throws Exception {
    new Assertion<>(
        "Response with joined cookies",
        new RsPrint(
            new TkJoinedCookies(
                new TkFixed(
                    new RsWithHeaders(
                        new RsText(),
                        "Set-Cookie: a=1",
                        "Set-cookie: b=1; Path=/"
                    )
                )
            ).act(new RqFake())
        ),
        new TextHasString("Set-Cookie: a=1, b=1; Path=/")
    ).affirm();
}
 
Example #10
Source File: TkAuthTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkAuth can logout a user.
 * @throws Exception If some problem inside
 */
@Test
public void logsUserOut() throws Exception {
    final Pass pass = new PsLogout();
    final Take take = Mockito.mock(Take.class);
    Mockito.doReturn(new RsText()).when(take)
        .act(Mockito.any(Request.class));
    new TkAuth(take, pass).act(
        new RqWithHeader(
            new RqFake(),
            TkAuth.class.getSimpleName(),
            "urn%3Atest%3A2"
        )
    );
    final ArgumentCaptor<Request> captor =
        ArgumentCaptor.forClass(Request.class);
    Mockito.verify(take).act(captor.capture());
    MatcherAssert.assertThat(
        new RqHeaders.Base(captor.getValue()).header(
            TkAuth.class.getSimpleName()
        ),
        Matchers.emptyIterable()
    );
}
 
Example #11
Source File: TkAuthTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkAuth can login a user.
 * @throws Exception If some problem inside
 */
@Test
public void logsUserIn() throws Exception {
    final Pass pass = new PsFixed(new Identity.Simple("urn:test:1"));
    final Take take = Mockito.mock(Take.class);
    Mockito.doReturn(new RsText()).when(take)
        .act(Mockito.any(Request.class));
    new TkAuth(take, pass).act(new RqFake());
    final ArgumentCaptor<Request> captor =
        ArgumentCaptor.forClass(Request.class);
    Mockito.verify(take).act(captor.capture());
    MatcherAssert.assertThat(
        new RqHeaders.Base(captor.getValue()).header(
            TkAuth.class.getSimpleName()
        ),
        Matchers.hasItem("urn%3Atest%3A1")
    );
}
 
Example #12
Source File: RsForkTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * RsFork can route by the Accept header.
 * @throws IOException If some problem inside
 */
@Test
public void negotiatesContentWithComplexHeader() throws IOException {
    final Request req = new RqFake(
        Arrays.asList(
            "GET /hell-1o.html",
            "Accept: text/xml"
        ),
        ""
    );
    MatcherAssert.assertThat(
        new RsPrint(
            new RsFork(
                req,
                new FkTypes(
                    "application/xml,text/xml",
                    new RsText("how are you?")
                )
            )
        ).printBody(),
        Matchers.endsWith("you?")
    );
}
 
Example #13
Source File: RsForkTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * RsFork can route by the Accept header.
 * @throws IOException If some problem inside
 */
@Test
public void negotiatesContent() throws IOException {
    final Request req = new RqFake(
        Arrays.asList(
            "GET /hello.html",
            "Accept: text/xml; q=0.3, text/plain; q=0.1",
            "Accept: */*; q=0.05"
        ),
        ""
    );
    MatcherAssert.assertThat(
        new RsPrint(
            new RsFork(
                req,
                new FkTypes("text/plain", new RsText("it's a text")),
                new FkTypes("image/*", new RsText("it's an image"))
            )
        ).printBody(),
        Matchers.endsWith("a text")
    );
}
 
Example #14
Source File: RsForkTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * RsFork can route without Accept header.
 * @throws IOException If some problem inside
 */
@Test
public void negotiatesContentWithoutAccept() throws IOException {
    MatcherAssert.assertThat(
        new RsPrint(
            new RsFork(
                new RqFake(),
                new FkTypes("image/png,*/*", new RsText("a png"))
            )
        ).printBody(),
        Matchers.endsWith("png")
    );
}
 
Example #15
Source File: TkQueue.java    From jpeek with MIT License 5 votes vote down vote up
@SuppressWarnings("PMD.AvoidCatchingGenericException")
@Override
public Response act(final Request req) throws IOException {
    try {
        return new RsText(
            this.futures.asString()
        );
    } catch (final Exception exception) {
        throw new IOException(exception);
    }
}
 
Example #16
Source File: AsyncReportsTest.java    From jpeek with MIT License 5 votes vote down vote up
@Test
public void rendersOneReport() throws Exception {
    final ExecutorService service = Executors.newSingleThreadExecutor();
    final BiFunc<String, String, Func<String, Response>> bifunc = new AsyncReports(
        new SolidBiFunc<>(
            (first, second) -> service.submit(
                () -> input -> {
                    TimeUnit.DAYS.sleep(1L);
                    return new RsText("done!");
                }
            )
        )
    );
    final Response response = bifunc.apply("org.jpeek", "jpeek").apply(
        "index.html"
    );
    new Assertion<>(
        "Must return HTTP NOT FOUND status",
        response,
        new HmRsStatus(HttpURLConnection.HTTP_NOT_FOUND)
    ).affirm();
    new Assertion<>(
        "Must have body in response",
        XhtmlMatchers.xhtml(new RsPrint(response).printBody()),
        XhtmlMatchers.hasXPath("//xhtml:body")
    ).affirm();
    service.shutdownNow();
}
 
Example #17
Source File: TkCorsTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * TkCORS can handle connections without origin in the request.
 * @throws Exception If some problem inside
 */
@Test
public void handleConnectionsWithoutOriginInTheRequest() throws Exception {
    MatcherAssert.assertThat(
        "It was expected to receive a 403 error.",
        new TkCors(
            new TkFixed(new RsText()),
            "http://www.netbout.io",
            "http://www.example.com"
        ).act(new RqFake()),
        new HmRsStatus(HttpURLConnection.HTTP_FORBIDDEN)
    );
}
 
Example #18
Source File: TkAppFallback.java    From jare with MIT License 5 votes vote down vote up
/**
 * Authenticated.
 * @param take Takes
 * @return Authenticated takes
 */
private static Take make(final Take take) {
    return new TkFallback(
        take,
        new FbChain(
            new FbStatus(
                HttpURLConnection.HTTP_NOT_FOUND,
                new RsWithStatus(
                    new RsText("Page not found"),
                    HttpURLConnection.HTTP_NOT_FOUND
                )
            ),
            new FbStatus(
                HttpURLConnection.HTTP_BAD_REQUEST,
                new RsWithStatus(
                    new RsText("Bad request"),
                    HttpURLConnection.HTTP_BAD_REQUEST
                )
            ),
            req -> {
                Sentry.capture(req.throwable());
                return new Opt.Empty<>();
            },
            req -> new Opt.Single<>(TkAppFallback.fatal(req))
        )
    );
}
 
Example #19
Source File: TkReadAlwaysTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * Send a request with body which is ignored.
 * @throws Exception If there are problems
 */
@Test
public void requestBodyIsIgnored() throws Exception {
    final String expected = "response ok";
    final Take take = new Take() {
        @Override
        public Response act(final Request req) throws IOException {
            return new RsText(expected);
        }
    };
    new FtRemote(new TkReadAlways(take)).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .method("POST").header(
                        "Content-Type", "application/x-www-form-urlencoded"
                    ).body()
                    .formParam("name", "Jeff Warraby")
                    .formParam("age", "4")
                    .back()
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .assertBody(Matchers.equalTo(expected));
            }
        }
    );
}
 
Example #20
Source File: TkSslOnlyTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * Redirects when it's HTTP instead of HTTPS.
 * @throws Exception If fails
 */
@Test
public void redirects() throws Exception {
    final Request req = new RqFake(
        Arrays.asList(
            "GET /one/two?a=1",
            "Host: www.0crat.com",
            "X-Forwarded-Proto: http"
        ),
        ""
    );
    MatcherAssert.assertThat(
        new RsPrint(
            new TkSslOnly(
                new Take() {
                    @Override
                    public Response act(final Request request)
                        throws IOException {
                        return new RsText(
                            new RqPrint(request).print()
                        );
                    }
                }
            ).act(req)
        ),
        new TextHasString("https://www.0crat.com/one/two?a=1")
    );
}
 
Example #21
Source File: TkProxyTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * TkProxy can correctly maps path string.
 * @throws Exception If some problem inside
 * @checkstyle AnonInnerLengthCheck (100 lines)
 */
@Test
public void correctlyMapsPathString() throws Exception {
    final Take take = new Take() {
        @Override
        public Response act(final Request req) throws IOException {
            return new RsText(new RqHref.Base(req).href().toString());
        }
    };
    new FtRemote(
        new TkFork(
            new FkMethods(this.method, take)
        )
    ).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws Exception {
                MatcherAssert.assertThat(
                    new RsPrint(
                        new TkProxy(home).act(
                            new RqFake(
                                TkProxyTest.this.method,
                                "/a/%D0%B0/c?%D0%B0=1#%D0%B0"
                            )
                        )
                    ).printBody(),
                    Matchers.equalTo(
                        String.format(
                            "http://%s:%d/a/%%D0%%B0/c?%%D0%%B0=1",
                            home.getHost(), home.getPort()
                        )
                    )
                );
            }
        }
    );
}
 
Example #22
Source File: FtSecureTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * FtSecure can properly parse incoming HTTP request.
 * @throws Exception If some problem inside
 */
@Test
public void parsesIncomingHttpRequest() throws Exception {
    final Take take = new Take() {
        @Override
        public Response act(final Request request) throws IOException {
            MatcherAssert.assertThat(
                new RqPrint(request).printBody(),
                Matchers.containsString("Jeff")
            );
            return new RsText("works!");
        }
    };
    FtSecureTest.secure(take).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .method("PUT")
                    .body().set("Jeff, how are you?").back()
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK);
            }
        }
    );
}
 
Example #23
Source File: FtBasicTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * FtBasic can consume twice the input stream in case of a RsText.
 * @throws Exception If some problem inside
 */
@Test
public void consumesTwiceInputStreamWithRsText() throws Exception {
    final String result = "Hello RsText!";
    new FtRemote(
        new TkFork(
            new FkRegex(
                FtBasicTest.ROOT_PATH,
                new RsText(
                    new InputStreamOf(result)
                )
            )
        )
    ).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .assertBody(Matchers.equalTo(result));
                new JdkRequest(home)
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .assertBody(Matchers.equalTo(result));
            }
        }
    );
}
 
Example #24
Source File: FtBasicTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * FtBasic can work with a stuck back.
 * @throws Exception If some problem inside
 */
@Test
@Ignore
public void gracefullyHandlesStuckBack() throws Exception {
    final Take take = new Take() {
        @Override
        public Response act(final Request request) throws IOException {
            final Request req = new RqGreedy(request);
            return new RsText(
                String.format(
                    "first: %s, second: %s",
                    new RqPrint(req).printBody(),
                    new RqPrint(req).printBody()
                )
            );
        }
    };
    new FtRemote(take).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .method("POST")
                    .header("Content-Length", "4")
                    .fetch(new ByteArrayInputStream("ddgg".getBytes()))
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .assertBody(Matchers.containsString("second: dd"));
            }
        }
    );
}
 
Example #25
Source File: FtBasicTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * FtBasic can properly parse incoming HTTP request.
 * @throws Exception If some problem inside
 */
@Test
public void parsesIncomingHttpRequest() throws Exception {
    final Take take = new Take() {
        @Override
        public Response act(final Request request) throws IOException {
            MatcherAssert.assertThat(
                new RqPrint(request).printBody(),
                Matchers.containsString("Jeff")
            );
            return new RsText("works!");
        }
    };
    new FtRemote(take).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .method("PUT")
                    .body().set("Jeff, how are you?").back()
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK);
            }
        }
    );
}
 
Example #26
Source File: TkRelayTest.java    From jare with MIT License 5 votes vote down vote up
/**
 * TkRelay can send the request through.
 * @throws Exception If some problem inside
 */
@Test
public void sendsRequestThroughToHome() throws Exception {
    final Take target = new TkFork(
        new FkRegex(
            "/alpha/.*",
            (Take) req -> new RsText(
                new RqHref.Base(req).href().toString()
            )
        )
    );
    new FtRemote(target).exec(
        home -> MatcherAssert.assertThat(
            new RsPrint(
                new TkRelay(new FkBase()).act(
                    TkRelayTest.fake(
                        home, "/alpha/%D0%B4%D0%B0?abc=cde"
                    )
                )
            ).printBody(),
            Matchers.equalTo(
                String.format(
                    "%s/alpha/%%D0%%B4%%D0%%B0?abc=cde",
                    home
                )
            )
        )
    );
}
 
Example #27
Source File: SrvTakeTest.java    From takes with MIT License 5 votes vote down vote up
@Override
public Response act(final Request req) throws IOException {
    return new RsText(
        new UncheckedText(
            new FormattedText(
                SrvTakeTest.MSG,
                this.context.getServletContextName()
            )
        ).asString()
    );
}
 
Example #28
Source File: RsPreviousTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * RsPrevious can build a response.
 * @throws IOException If some problem inside
 */
@Test
public void buildsResponse() throws IOException {
    MatcherAssert.assertThat(
        new RsPrint(
            new RsPrevious(new RsText(""), "/home")
        ),
        new TextHasString(
            "Set-Cookie: TkPrevious=%2Fhome"
        )
    );
}
 
Example #29
Source File: TkText.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param body Content
 */
public TkText(final InputStream body) {
    super(
        new Take() {
            @Override
            public Response act(final Request req) {
                return new RsText(body);
            }
        }
    );
}
 
Example #30
Source File: TkText.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param url URL with content
 */
public TkText(final URL url) {
    super(
        new Take() {
            @Override
            public Response act(final Request req) {
                return new RsText(url);
            }
        }
    );
}