Java Code Examples for org.takes.Response

The following examples show how to use org.takes.Response. 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: RsReturn.java    License: MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param res Response to decorate
 * @param loc Location to be set as return location
 * @param cookie Cookie name
 * @throws IOException If fails
 */
public RsReturn(final Response res, final String loc, final String cookie)
    throws IOException {
    // @checkstyle IndentationCheck (18 lines)
    super(
        new RsWithCookie(
            res,
            cookie,
            URLEncoder.encode(
                RsReturn.validLocation(loc), Charset.defaultCharset().name()
            ),
            "Path=/",
            new Expires.Date(
                System.currentTimeMillis()
                    + TimeUnit.HOURS.toMillis(1L)
            ).print()
        )
    );
}
 
Example 2
Source Project: takes   Source File: TkSslOnly.java    License: MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
public Response act(final Request req) throws Exception {
    final String href = new RqHref.Base(req).href().toString();
    final String proto = new RqHeaders.Smart(
        new RqHeaders.Base(req)
    ).single("x-forwarded-proto", "https");
    final Response answer;
    if ("https".equalsIgnoreCase(proto)) {
        answer = this.origin.act(req);
    } else {
        answer = new RsRedirect(
            href.replaceAll("^http", "https")
        );
    }
    return answer;
}
 
Example 3
Source Project: jpeek   Source File: StickyFutures.java    License: MIT License 6 votes vote down vote up
@Override
public Future<Func<String, Response>> apply(
    final String group, final String artifact)
    throws Exception {
    synchronized (this.cache) {
        if (this.cache.size() > this.max) {
            this.cache.clear();
        }
        final String target = String.format("%s:%s", group, artifact);
        if (!this.cache.containsKey(target)
            || this.cache.get(target).isCancelled()) {
            this.cache.put(target, this.origin.apply(group, artifact));
        }
        return this.cache.get(target);
    }
}
 
Example 4
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 5
Source Project: takes   Source File: FbStatus.java    License: MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param check HTTP status code predicate
 * @since 0.16.10
 */
public FbStatus(final Iterable<Integer> check) {
    this(check, new Fallback() {
        @Override
        public Opt<Response> route(final RqFallback req)
            throws Exception {
            final Response res = new RsWithStatus(req.code());
            return new Opt.Single<>(
                new RsWithType(
                    new RsWithBody(
                        res,
                        String.format(
                            "%s: %s", FbStatus.WHITESPACE.split(
                                res.head().iterator().next(),
                                2
                            )[1], req.throwable().getLocalizedMessage()
                        )
                    ), "text/plain"
                )
            );
        }
    });
}
 
Example 6
Source Project: takes   Source File: FbStatus.java    License: MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param check Check
 * @param fallback Fallback
 */
@SuppressWarnings
    (
        {
            "PMD.CallSuperInConstructor",
            "PMD.ConstructorOnlyInitializesOrCallOtherConstructors"
        }
    )
public FbStatus(final Iterable<Integer> check,
    final Scalar<Fallback> fallback) {
    super(
        new Fallback() {
            @Override
            public Opt<Response> route(final RqFallback req)
                throws Exception {
                Opt<Response> rsp = new Opt.Empty<>();
                if (new ListOf<>(check).contains(req.code())) {
                    rsp = fallback.get().route(req);
                }
                return rsp;
            }
        }
    );
}
 
Example 7
Source Project: takes   Source File: RsPrint.java    License: MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param res Original response
 */
public RsPrint(final Response res) {
    super(res);
    this.text = new IoChecked<>(
        new Sticky<>(
            new Scalar<String>() {
                private final ByteArrayOutputStream baos =
                    new ByteArrayOutputStream();

                @Override
                public String value() throws Exception {
                    RsPrint.this.printHead(this.baos);
                    RsPrint.this.printBody(this.baos);
                    return new TextOf(
                        this.baos.toByteArray()
                    ).asString();
                }
            }
        )
    );
}
 
Example 8
Source Project: takes   Source File: RsWithType.java    License: MIT License 6 votes vote down vote up
/**
 * Factory allowing to create {@code Response} with the corresponding
 * content type and character set.
 * @param res Original response
 * @param type Content type
 * @param charset The character set to add to the content type header. If
 *  absent no character set will be added to the content type header
 * @return Response
 */
private static Response make(final Response res, final CharSequence type,
    final Opt<Charset> charset) {
    final Response response;
    if (charset.has()) {
        response = new RsWithHeader(
            new RsWithoutHeader(res, RsWithType.HEADER),
            RsWithType.HEADER,
            String.format(
                "%s; %s=%s",
                type,
                RsWithType.CHARSET,
                charset.get().name()
            )
        );
    } else {
        response = new RsWithHeader(
            new RsWithoutHeader(res, RsWithType.HEADER),
            RsWithType.HEADER,
            type
        );
    }
    return response;
}
 
Example 9
Source Project: takes   Source File: RsWithStatus.java    License: MIT License 6 votes vote down vote up
/**
 * Make head.
 * @param origin Original response
 * @param status Status
 * @param reason Reason
 * @return Head
 * @throws IOException If fails
 */
private static Iterable<String> head(final Response origin,
    final int status, final CharSequence reason) throws IOException {
    // @checkstyle MagicNumber (1 line)
    if (status < 100 || status > 999) {
        throw new IllegalArgumentException(
            String.format(
                // @checkstyle LineLength (1 line)
                "according to RFC 7230 HTTP status code must have three digits: %d",
                status
            )
        );
    }
    return new Joined<>(
        new FormattedText(
            "HTTP/1.1 %d %s", status, reason
        ).asString(),
        new Filtered<>(
            item -> new Not(
                new StartsWith(item, "HTTP/")
            ).value(),
            origin.head()
        )
    );
}
 
Example 10
Source Project: takes   Source File: RsGzip.java    License: MIT License 6 votes vote down vote up
/**
 * Make a response.
 * @return Response just made
 * @throws IOException If fails
 */
private Response make() throws IOException {
    if (this.zipped.isEmpty()) {
        this.zipped.add(
            new RsWithHeader(
                new RsWithBody(
                    this.origin,
                    RsGzip.gzip(this.origin.body())
                ),
                "Content-Encoding",
                "gzip"
            )
        );
    }
    return this.zipped.get(0);
}
 
Example 11
Source Project: takes   Source File: RsGzipTest.java    License: MIT License 6 votes vote down vote up
/**
 * RsGzip can build a compressed response.
 * @throws IOException If some problem inside
 */
@Test
public void makesCompressedResponse() throws IOException {
    final String text = "some unicode text: \u20ac\n\t";
    final Response response = new RsGzip(new RsText(text));
    MatcherAssert.assertThat(
        new RsPrint(response).printHead(),
        Matchers.containsString("Content-Encoding: gzip")
    );
    MatcherAssert.assertThat(
        IOUtils.toString(
            new GZIPInputStream(response.body()),
            StandardCharsets.UTF_8
        ),
        Matchers.equalTo(text)
    );
}
 
Example 12
Source Project: takes   Source File: TkForward.java    License: MIT License 6 votes vote down vote up
/**
 * Load it.
 * @return Response
 * @throws IOException If fails
 */
private Response load() throws IOException {
    if (this.saved.isEmpty()) {
        Iterable<String> head;
        InputStream body;
        try {
            head = this.origin.head();
            body = this.origin.body();
        } catch (final RsForward ex) {
            head = ex.head();
            body = ex.body();
        }
        this.saved.add(new RsSimple(head, body));
    }
    return this.saved.get(0);
}
 
Example 13
Source Project: takes   Source File: RsWithBody.java    License: MIT License 6 votes vote down vote up
/**
 * Constructs a {@code RsWithBody} with the specified response and body
 * content.
 * @param res Original response
 * @param body The content of the body
 */
RsWithBody(final Response res, final Body body) {
    super(
        new ResponseOf(
            () -> {
                final String header = "Content-Length";
                return new RsWithHeader(
                    new RsWithoutHeader(res, header),
                    header,
                    Integer.toString(body.length())
                ).head();
            },
            body::stream
        )
    );
}
 
Example 14
Source Project: tutorials   Source File: TakesApp.java    License: 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 15
Source Project: takes   Source File: PsCookie.java    License: MIT License 6 votes vote down vote up
@Override
public Response exit(final Response res,
    final Identity idt) throws IOException {
    final String text;
    if (idt.equals(Identity.ANONYMOUS)) {
        text = "";
    } else {
        text = new TextOf(this.codec.encode(idt)).asString();
    }
    return new RsWithCookie(
        res, this.cookie, text,
        "Path=/",
        "HttpOnly",
        new Expires.Date(
            System.currentTimeMillis()
                + TimeUnit.DAYS.toMillis(this.age)
        ).print()
    );
}
 
Example 16
Source Project: takes   Source File: HmRsStatus.java    License: MIT License 5 votes vote down vote up
@Override
public Integer featureValueOf(final Response response) {
    try {
        final String head = response.head().iterator().next();
        final String[] parts = head.split(" ");
        return Integer.parseInt(parts[1]);
    } catch (final IOException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example 17
Source Project: takes   Source File: TkHtml.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param body Content
 */
public TkHtml(final InputStream body) {
    super(
        new Take() {
            @Override
            public Response act(final Request req) {
                return new RsHtml(body);
            }
        }
    );
}
 
Example 18
Source Project: takes   Source File: TkFallback.java    License: 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 19
Source Project: jpeek   Source File: StickyFutures.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param func Original bi-function
 * @param size Max size of cache before full clean up
 */
StickyFutures(final BiFunc<String, String,
    Future<Func<String, Response>>> func, final int size) {
    this.origin = func;
    this.cache = new ConcurrentHashMap<>(0);
    this.max = size;
}
 
Example 20
Source Project: takes   Source File: RsPrettyXml.java    License: MIT License 5 votes vote down vote up
/**
 * Make a response.
 * @return Response just made
 * @throws IOException If fails
 */
private Response make() throws IOException {
    synchronized (this.lock) {
        if (this.transformed.isEmpty()) {
            this.transformed.add(
                new RsWithBody(
                    this.origin,
                    RsPrettyXml.transform(this.origin.body())
                )
            );
        }
    }
    return this.transformed.get(0);
}
 
Example 21
Source Project: takes   Source File: TkFailure.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param err Error to throw
 * @since 1.4
 */
public TkFailure(final Scalar<IOException> err) {
    super(
        new Take() {
            @Override
            public Response act(final Request request) throws IOException {
                throw err.get();
            }
        }
    );
}
 
Example 22
Source Project: takes   Source File: TkGreedy.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param take Original take
 */
public TkGreedy(final Take take) {
    super(
        new Take() {
            @Override
            public Response act(final Request request) throws Exception {
                return take.act(new RqGreedy(request));
            }
        }
    );
}
 
Example 23
Source Project: jpeek   Source File: AsyncReportsTest.java    License: 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 24
Source Project: takes   Source File: TkHtml.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param url URL with content
 */
public TkHtml(final URL url) {
    super(
        new Take() {
            @Override
            public Response act(final Request req) {
                return new RsHtml(url);
            }
        }
    );
}
 
Example 25
Source Project: takes   Source File: TkOnce.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param take Original take
 */
public TkOnce(final Take take) {
    super(
        new Take() {
            @Override
            public Response act(final Request request) throws Exception {
                return take.act(new RqGreedy(request));
            }
        }
    );
}
 
Example 26
Source Project: jare   Source File: TkInvalidateITCase.java    License: MIT License 5 votes vote down vote up
/**
 * TkInvalidate can invalidate URL.
 * @throws Exception If some problem inside
 */
@Test
@Ignore
public void invalidatesUrl() throws Exception {
    final String url =
        "http://www.yegor256.com/images/yegor-bugayenko-192x192.png";
    final Response rsp = new TkInvalidate(
        "-key-", "-secret-"
    ).act(new RqFake("GET", String.format("/invalidate?url=%s", url)));
    MatcherAssert.assertThat(
        rsp.toString(),
        Matchers.containsString("InProgress")
    );
}
 
Example 27
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 28
Source Project: takes   Source File: TkFailure.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param err Error to throw
 */
public TkFailure(final RuntimeException err) {
    super(
        new Take() {
            @Override
            public Response act(final Request request) {
                throw err;
            }
        }
    );
}
 
Example 29
Source Project: takes   Source File: FkEncoding.java    License: MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param enc Encoding we accept
 * @param response Response to return
 */
public FkEncoding(final String enc, final Response response) {
    this.encoding = new UncheckedText(
        new Lowered(new Trimmed(new TextOf(enc)))
    ).asString();
    this.origin = response;
}
 
Example 30
Source Project: takes   Source File: FkEncoding.java    License: MIT License 5 votes vote down vote up
@Override
public Opt<Response> route(final Request req) throws IOException {
    final Iterator<String> headers =
        new RqHeaders.Base(req).header("Accept-Encoding").iterator();
    final Opt<Response> resp;
    if (this.encoding.isEmpty()) {
        resp = new Opt.Single<>(this.origin);
    } else if (headers.hasNext()) {
        final Collection<String> items = Arrays.asList(
            FkEncoding.ENCODING_SEP.split(
                new UncheckedText(
                    new Lowered(
                        new Trimmed(
                            new TextOf(headers.next())
                        )
                    )
                ).asString()
            )
        );
        if (items.contains(this.encoding)) {
            resp = new Opt.Single<>(this.origin);
        } else {
            resp = new Opt.Empty<>();
        }
    } else {
        resp = new Opt.Empty<>();
    }
    return resp;
}