Java Code Examples for org.takes.Take

The following examples show how to use org.takes.Take. These examples are extracted from open source projects. 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 Project: takes   Source File: TkSecureTest.java    License: 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 2
Source Project: takes   Source File: TkGzip.java    License: 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 3
Source Project: jpeek   Source File: TkAppTest.java    License: 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 4
Source Project: takes   Source File: TkConsumesTest.java    License: 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 5
Source Project: takes   Source File: TkAuthTest.java    License: 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 6
Source Project: jare   Source File: TkIndexTest.java    License: 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 7
Source Project: takes   Source File: TkFiles.java    License: 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 8
Source Project: jare   Source File: TkAppTest.java    License: 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 9
Source Project: takes   Source File: PsBasicTest.java    License: 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 10
Source Project: takes   Source File: TkReturnTest.java    License: 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 11
Source Project: takes   Source File: TkFlashTest.java    License: 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 12
Source Project: takes   Source File: TkVerboseTest.java    License: 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 13
Source Project: takes   Source File: TkVerbose.java    License: 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 14
Source Project: takes   Source File: TkForwardTest.java    License: 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 15
Source Project: takes   Source File: TkSmartRedirect.java    License: 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 16
Source Project: takes   Source File: TkAuthTest.java    License: 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 17
Source Project: takes   Source File: TkClasspath.java    License: 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 18
Source Project: cactoos-http   Source File: HtSecureWireTest.java    License: MIT License 5 votes vote down vote up
/**
 * Creates an instance of secure Front.
 * @param take Take
 * @return FtRemote Front
 * @throws Exception If fails
 */
private static FtRemote secure(final Take take, final int port)
    throws Exception {
    final ServerSocket skt = SSLServerSocketFactory.getDefault()
        .createServerSocket(port);
    return new FtRemote(new BkBasic(take), skt);
}
 
Example 19
Source Project: jare   Source File: TkAppFallback.java    License: 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 20
Source Project: jare   Source File: TkIndexTest.java    License: MIT License 5 votes vote down vote up
/**
 * TkHome can render home page.
 * @throws Exception If some problem inside
 */
@Test
public void rendersHomePage() throws Exception {
    final Take take = new TkAppAuth(new TkIndex(new FkBase()));
    MatcherAssert.assertThat(
        XhtmlMatchers.xhtml(
            new RsPrint(
                take.act(
                    new RqWithHeader(
                        new RqFake("GET", "/"),
                        "Accept",
                        "text/xml"
                    )
                )
            ).printBody()
        ),
        XhtmlMatchers.hasXPaths(
            "/page/millis",
            "/page/identity/urn",
            "/page/version",
            "/page/links/link[@rel='home']",
            "/page/links/link[@rel='self']",
            "/page/links/link[@rel='takes:logout']",
            "/page/domains/domain[name and owner and usage]"
        )
    );
}
 
Example 21
Source Project: jare   Source File: PingingTest.java    License: MIT License 5 votes vote down vote up
/**
 * App can render the URL.
 * @throws Exception If some problem inside
 */
@Test
public void rendersAllPossibleUrls() throws Exception {
    final Take take = new TkApp(new FkBase());
    MatcherAssert.assertThat(
        this.url,
        take.act(new RqFake("INFO", this.url)),
        Matchers.not(
            new HmRsStatus(
                HttpURLConnection.HTTP_NOT_FOUND
            )
        )
    );
}
 
Example 22
Source Project: jare   Source File: TkRelayTest.java    License: 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 23
Source Project: jare   Source File: TkRelayTest.java    License: MIT License 5 votes vote down vote up
/**
 * TkRelay can set cache headers to "forever".
 * @throws Exception If some problem inside
 */
@Test
public void setsCachingHeaders() throws Exception {
    final Take target = new TkWithHeaders(
        new TkText("cacheable forever"),
        "age: 600",
        "cache-control: max-age=600",
        "expires: Thu, 08 Dec 2016 22:51:37 GMT"
    );
    new FtRemote(target).exec(
        home -> MatcherAssert.assertThat(
            new RsPrint(
                new TkRelay(new FkBase()).act(
                    TkRelayTest.fake(home, "/&whatever")
                )
            ),
            Matchers.allOf(
                new HmRsHeader("Age", "31536000"),
                new HmRsHeader("Cache-control", "max-age=31536000"),
                new HmRsHeader("Expires", "Sun, 19 Jul 2020 18:06:32 GMT"),
                Matchers.not(
                    new HmRsHeader("Cache-Control", "max-age=600")
                )
            )
        )
    );
}
 
Example 24
Source Project: jare   Source File: TkAppTest.java    License: MIT License 5 votes vote down vote up
/**
 * App can render not found.
 * @throws Exception If some problem inside
 */
@Test
public void rendersNotFoundPage() throws Exception {
    final Take take = new TkApp(new FkBase());
    MatcherAssert.assertThat(
        new RsPrint(
            take.act(new RqFake("HEAD", "/not-found"))
        ).printBody(),
        Matchers.equalTo("Page not found")
    );
}
 
Example 25
Source Project: takes   Source File: FkTypes.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param list List of types
 * @param resp Response to return
 * @param tke The take to use to build the response to return
 */
private FkTypes(final String list, final Opt<Response> resp,
    final Opt<Take> tke) {
    this.types = new MediaTypes(list);
    this.response = resp;
    this.take = tke;
}
 
Example 26
Source Project: takes   Source File: FkRegex.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param ptn Pattern
 * @param tke Take
 */
public FkRegex(final String ptn, final Take tke) {
    this(
        Pattern.compile(ptn, Pattern.CASE_INSENSITIVE | Pattern.DOTALL),
        tke
    );
}
 
Example 27
Source Project: takes   Source File: FkContentTypeTest.java    License: MIT License 5 votes vote down vote up
/**
 * Create a Take instance with empty response.
 * @return Take
 */
private static Take emptyResponse() {
    return new Take() {
        @Override
        public Response act(final Request req) throws IOException {
            return new RsEmpty();
        }
    };
}
 
Example 28
Source Project: takes   Source File: TkHtml.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param body Text
 * @since 1.4
 */
public TkHtml(final Scalar<String> body) {
    super(
        new Take() {
            @Override
            public Response act(final Request req) throws IOException {
                return new RsHtml(body.get());
            }
        }
    );
}
 
Example 29
Source Project: takes   Source File: TkFailure.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param err Error to throw
 * @since 0.27
 */
public TkFailure(final IOException err) {
    super(
        new Take() {
            @Override
            public Response act(final Request request) throws IOException {
                throw err;
            }
        }
    );
}
 
Example 30
Source Project: takes   Source File: TkMethods.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 *
 * @param take Original take
 * @param methods Methods the take should act
 */
public TkMethods(final Take take, final String... methods) {
    super(
        new TkFork(
            new FkMethods(Arrays.asList(methods), take),
            new FkFixed(
                new TkFailure(
                    () -> new HttpException(
                        HttpURLConnection.HTTP_BAD_METHOD
                    )
                )
            )
        )
    );
}