org.takes.Take Java Examples

The following examples show how to use org.takes.Take. 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: TkFlashTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkFlash can remove a flash cookie.
 * @throws Exception If some problem inside
 */
@Test
public void removesFlashCookie() throws Exception {
    final Take take = new TkFlash(new TkEmpty());
    MatcherAssert.assertThat(
        take.act(
            new RqWithHeader(
                new RqFake(),
                "Cookie: RsFlash=Hello!"
            )
        ).head(),
        Matchers.hasItem(
            Matchers.allOf(
                Matchers.startsWith("Set-Cookie: RsFlash=deleted;"),
                Matchers.containsString("Path=/;"),
                Matchers.containsString(
                    "Expires=Thu, 01 Jan 1970 00:00:00 GMT"
                )
            )
        )
    );
}
 
Example #2
Source File: TkForwardTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkForward can catch RsForward throws by Response.
 * @throws Exception If some problem inside
 */
@Test
public void catchesExceptionThrownByResponse() throws Exception {
    final Take take =
        request -> new ResponseOf(
            () -> new RsEmpty().head(),
            () -> {
                throw new RsForward("/b");
            }
        );
    MatcherAssert.assertThat(
        new RsPrint(
            new TkForward(take).act(new RqFake())
        ),
        new StartsWith("HTTP/1.1 303")
    );
}
 
Example #3
Source File: TkVerbose.java    From takes with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param take Original take
 */
public TkVerbose(final Take take) {
    super(
        new Take() {
            @Override
            public Response act(final Request request) throws Exception {
                try {
                    return take.act(request);
                } catch (final HttpException ex) {
                    throw new HttpException(
                        ex.code(),
                        String.format(
                            "%s %s",
                            new RqMethod.Base(request).method(),
                            new RqHref.Base(request).href()
                        ),
                        ex
                    );
                }
            }
        }
    );
}
 
Example #4
Source File: TkReturnTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkReturn can redirect to return location
 * and remove a return cookie.
 * @throws Exception If some problem inside
 */
@Test
public void redirectsAndRemovesCookie() throws Exception {
    final Take take = new TkReturn(new TkEmpty());
    final String destination = "/return/to";
    MatcherAssert.assertThat(
        take.act(
            new RqWithHeader(
                new RqFake(),
                String.format(
                    "Cookie: RsReturn=%s;",
                    URLEncoder.encode(
                        destination,
                        Charset.defaultCharset().name()
                    )
                )
            )
        ).head(),
        Matchers.contains(
            "HTTP/1.1 303 See Other",
            String.format("Location: %s", destination),
            "Set-Cookie: RsReturn=;"
        )
    );
}
 
Example #5
Source File: TkSmartRedirect.java    From takes with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param location Location to redirect to
 * @param code Redirection status code
 */
public TkSmartRedirect(final String location, final int code) {
    super(
        new Take() {
            @Override
            public Response act(final Request req) throws IOException {
                return new RsRedirect(
                    new TkSmartRedirect.RedirectParams(
                        req, location
                    ).location(),
                    code
                );
            }
        }
    );
}
 
Example #6
Source File: PsBasicTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * PsBasic can authenticate a user.
 * @throws Exception If some problem inside
 */
@Test
public void authenticatesUser() throws Exception {
    final Take take = new TkAuth(
        new TkSecure(
            new TkText("secured")
        ),
        new PsBasic(
            "myrealm",
            new PsBasic.Default("mike secret11 urn:users:michael")
        )
    );
    new Assertion<>(
        "PsBasic should authenticate mike",
        new RsPrint(
            take.act(
                new RqWithHeader(
                    new RqFake(),
                    PsBasicTest.header("mike", "secret11")
                )
            )
        ),
        new TextHasString("HTTP/1.1 200 OK")
    ).affirm();
}
 
Example #7
Source File: TkAppTest.java    From jare with MIT License 6 votes vote down vote up
/**
 * App can render front page.
 * @throws Exception If some problem inside
 */
@Test
public void rendersHomePageViaHttp() throws Exception {
    final Take app = new TkApp(new FkBase());
    new FtRemote(app).exec(
        home -> {
            new JdkRequest(home)
                .fetch()
                .as(RestResponse.class)
                .assertStatus(HttpURLConnection.HTTP_OK)
                .as(XmlResponse.class)
                .assertXPath("/xhtml:html");
            new JdkRequest(home)
                .through(VerboseWire.class)
                .header("Accept", "application/xml")
                .fetch()
                .as(RestResponse.class)
                .assertStatus(HttpURLConnection.HTTP_OK)
                .as(XmlResponse.class)
                .assertXPath("/page/version");
        }
    );
}
 
Example #8
Source File: TkFiles.java    From takes with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param base Base directory
 */
public TkFiles(final File base) {
    super(
        new Take() {
            @Override
            public Response act(final Request request) throws IOException {
                final File file = new File(
                    base, new RqHref.Base(request).href().path()
                );
                if (!file.exists()) {
                    throw new HttpException(
                        HttpURLConnection.HTTP_NOT_FOUND,
                        String.format(
                            "%s not found", file.getAbsolutePath()
                        )
                    );
                }
                return new RsWithBody(Files.newInputStream(file.toPath()));
            }
        }
    );
}
 
Example #9
Source File: TkSecureTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkSecure can pass on registered user.
 * @throws Exception If some problem inside
 */
@Test
public void passesOnRegisteredUser() throws Exception {
    MatcherAssert.assertThat(
        new TkSecure(
            new Take() {
                @Override
                public Response act(final Request request) {
                    return new RsEmpty();
                }
            }
        ).act(
            new RqWithHeader(
                new RqFake(),
                TkAuth.class.getSimpleName(),
                new String(
                    new CcPlain().encode(new Identity.Simple("urn:test:2"))
                )
            )
        ),
        Matchers.instanceOf(RsEmpty.class)
    );
}
 
Example #10
Source File: TkIndexTest.java    From jare with MIT License 6 votes vote down vote up
/**
 * TkIndex can render home page in HTML.
 * @throws Exception If some problem inside
 */
@Test
public void rendersHomePageInHtml() throws Exception {
    final Take take = new TkAppAuth(new TkIndex(new FkBase()));
    MatcherAssert.assertThat(
        XhtmlMatchers.xhtml(
            new RsPrint(
                take.act(new RqFake("GET", "/"))
            ).printBody()
        ),
        XhtmlMatchers.hasXPaths(
            "/xhtml:html",
            "/xhtml:html/xhtml:body"
        )
    );
}
 
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: TkGzip.java    From takes with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param take Original take
 */
public TkGzip(final Take take) {
    super(
        new Take() {
            @Override
            public Response act(final Request req) throws Exception {
                final Response response = take.act(req);
                return new RsFork(
                    req,
                    new FkEncoding("gzip", new RsGzip(response)),
                    new FkEncoding("", response)
                );
            }
        }
    );
}
 
Example #13
Source File: TkAppTest.java    From jpeek with MIT License 6 votes vote down vote up
@Test
public void rendersOneReport(@TempDir final Path temp) throws Exception {
    final Take app = new TkApp(temp);
    new FtRemote(app).exec(
        home -> {
            new JdkRequest(home)
                .uri().path("org.jpeek")
                .path("jpeek")
                .path("index.html").back()
                .fetch()
                .as(RestResponse.class)
                .assertStatus(HttpURLConnection.HTTP_NOT_FOUND);
            new JdkRequest(String.format("%s/org.jpeek/jpeek/", home))
                .fetch()
                .as(RestResponse.class)
                .assertStatus(HttpURLConnection.HTTP_SEE_OTHER);
            new JdkRequest(String.format("%s/org.jpeek/jpeek", home))
                .fetch()
                .as(RestResponse.class)
                .assertStatus(HttpURLConnection.HTTP_SEE_OTHER);
        }
    );
}
 
Example #14
Source File: TkVerboseTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkVerbose can extend not-found exception.
 * @throws Exception If some problem inside
 */
@Test
public void extendsNotFoundException() throws Exception {
    final Take take = new Take() {
        @Override
        public Response act(final Request request) throws IOException {
            throw new HttpException(HttpURLConnection.HTTP_NOT_FOUND);
        }
    };
    try {
        new TkVerbose(take).act(new RqFake());
    } catch (final HttpException ex) {
        MatcherAssert.assertThat(
            ex.getLocalizedMessage(),
            Matchers.endsWith("GET http://www.example.com/")
        );
    }
}
 
Example #15
Source File: TkConsumesTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkConsumes can fail on unsupported Content-Type header.
 * @throws Exception If some problem inside
 */
@Test(expected = HttpException.class)
public void failsOnUnsupportedAcceptHeader() throws Exception {
    final Take consumes = new TkConsumes(
        new TkFixed(new RsJson(new RsEmpty())),
        TkConsumesTest.APPLICATION_JSON
    );
    consumes.act(
        new RqFake(
            Arrays.asList(
                "GET /?TkConsumes error",
                "Content-Type: application/xml"
            ),
            ""
        )
    ).head();
}
 
Example #16
Source File: TkClasspath.java    From takes with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param prefix Prefix
 */
public TkClasspath(final String prefix) {
    super(
        new Take() {
            @Override
            public Response act(final Request request) throws IOException {
                final String name = String.format(
                    "%s%s", prefix, new RqHref.Base(request).href().path()
                );
                final InputStream input = this.getClass()
                    .getResourceAsStream(name);
                if (input == null) {
                    throw new HttpException(
                        HttpURLConnection.HTTP_NOT_FOUND,
                        String.format("%s not found in classpath", name)
                    );
                }
                return new RsWithBody(input);
            }
        }
    );
}
 
Example #17
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 #18
Source File: TkJoinedCookies.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param take The take to wrap
 * @checkstyle AnonInnerLengthCheck (100 lines)
 */
public TkJoinedCookies(final Take take) {
    super(
        new Take() {
            @Override
            public Response act(final Request req) throws Exception {
                return TkJoinedCookies.join(take.act(req));
            }
        }
    );
}
 
Example #19
Source File: TkFallback.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param take Original take
 * @param fbk Fallback
 */
public TkFallback(final Take take, final Fallback fbk) {
    super(
        new Take() {
            @Override
            public Response act(final Request req) throws Exception {
                return TkFallback.route(take, fbk, req);
            }
        }
    );
}
 
Example #20
Source File: FtSecureTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * Creates an instance of secure Front.
 *
 * @param take Take
 * @return Secure Front
 * @throws IOException If some problem inside
 */
private static FtRemote secure(final Take take) throws IOException {
    final ServerSocket skt = SSLServerSocketFactory.getDefault()
        .createServerSocket(0);
    return new FtRemote(
        new FtSecure(new BkBasic(take), skt),
        skt,
        true
    );
}
 
Example #21
Source File: TkTextTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * TkText can print multiple times.
 * @throws Exception If some problem inside
 */
@Test
public void printsResourceMultipleTimes() throws Exception {
    final String body = "hello, dude!";
    final Take take = new TkText(body);
    MatcherAssert.assertThat(
        new RsPrint(take.act(new RqFake())),
        new TextHasString(body)
    );
    MatcherAssert.assertThat(
        new RsPrint(take.act(new RqFake())),
        new TextHasString(body)
    );
}
 
Example #22
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 #23
Source File: FkContentTypeTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * Checks FkContentType equals method.
 * @throws Exception If some problem inside
 */
@Test
public void mustEvaluateEqualsTest() throws Exception {
    final Take take = req -> new RsEmpty();
    final String type = "text/xml";
    new Assertion<>(
        "Must evaluate true equality",
        new FkContentType(type, take),
        new IsEqual<>(new FkContentType(type, take))
    ).affirm();
}
 
Example #24
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 #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: TkFallbackTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * TkFallback can fall back.
 * @throws Exception If some problem inside
 */
@Test
public void fallsBackInsideResponse() throws Exception {
    MatcherAssert.assertThat(
        new RsPrint(
            new TkFallback(
                new Take() {
                    @Override
                    public Response act(final Request req) {
                        return new ResponseOf(
                            () -> {
                                throw new UnsupportedOperationException("");
                            },
                            () -> {
                                throw new IllegalArgumentException(
                                    "here we fail"
                                );
                            }
                        );
                    }
                },
                new FbFixed(new RsText("caught here!"))
            ).act(new RqFake())
        ).printBody(),
        Matchers.startsWith("caught")
    );
}
 
Example #27
Source File: TkText.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param body Text
 */
public TkText(final String body) {
    super(
        new Take() {
            @Override
            public Response act(final Request req) {
                return new RsText(body);
            }
        }
    );
}
 
Example #28
Source File: TkText.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param body Body with HTML
 */
public TkText(final byte[] body) {
    super(
        new Take() {
            @Override
            public Response act(final Request req) {
                return new RsText(body);
            }
        }
    );
}
 
Example #29
Source File: TkWithCookie.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param take Original
 * @param key Cookie name
 * @param value Cookie value
 */
public TkWithCookie(final Take take, final String key, final String value) {
    super(
        new TkWithHeaders(
            take,
            String.format("Set-Cookie: %s=%s", key, value)
    )
    );
}
 
Example #30
Source File: TkWithType.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param take Original take
 * @param type Content type
 */
public TkWithType(final Take take, final String type) {
    super(
        new Take() {
            @Override
            public Response act(final Request req) throws Exception {
                return new RsWithType(take.act(req), type);
            }
        }
    );
}