org.takes.rs.RsWithStatus Java Examples

The following examples show how to use org.takes.rs.RsWithStatus. 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: TkAppFallback.java    From jare with MIT License 6 votes vote down vote up
/**
 * Make fatal error page.
 * @param req Request
 * @return Response
 * @throws IOException If fails
 */
private static Response fatal(final RqFallback req) throws IOException {
    return new RsWithStatus(
        new RsWithType(
            new RsVelocity(
                TkAppFallback.class.getResource("error.html.vm"),
                new RsVelocity.Pair(
                    "err",
                    ExceptionUtils.getStackTrace(req.throwable())
                ),
                new RsVelocity.Pair("rev", TkAppFallback.REV)
            ),
            "text/html"
        ),
        HttpURLConnection.HTTP_INTERNAL_ERROR
    );
}
 
Example #2
Source File: FbStatus.java    From takes with 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 #3
Source File: PsByFlagTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * PsByFlag wraps response with authenticated user.
 * @throws IOException If some problem inside
 */
@Test
public void exitTest() throws IOException {
    final Response response = new RsWithStatus(
        new RsWithType(
            new RsWithBody("<html>This is test response</html>"),
            "text/html"
        ),
        HttpURLConnection.HTTP_OK
    );
    MatcherAssert.assertThat(
        new PsByFlag(
            ImmutableMap.<Pattern, Pass>of(
                Pattern.compile("key"), new PsFake(true)
            )
        ).exit(response, Mockito.mock(Identity.class)),
        Matchers.is(response)
    );
}
 
Example #4
Source File: HtUpgradeWireTest.java    From cactoos-http with MIT License 5 votes vote down vote up
@Override
public Response act(final Request req) throws IOException {
    return new RsWithStatus(
        this.origin.act(req),
        // @checkstyle MagicNumber (1 line)
        101,
        "Switching Protocols"
    );
}
 
Example #5
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 #6
Source File: RsForward.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param res Original
 * @param code HTTP status code
 * @param loc Location
 */
public RsForward(final Response res, final int code,
    final CharSequence loc) {
    super(code, String.format("[%3d] %s %s", code, loc, res.toString()));
    this.origin = new RsWithHeader(
        new RsWithoutHeader(
            new RsWithStatus(res, code),
            "Location"
        ),
        new FormattedText(
            "Location: %s", loc
        ).toString()
    );
}
 
Example #7
Source File: HttpServletResponseFake.java    From takes with MIT License 5 votes vote down vote up
@Override
public void setStatus(final int code) {
    this.response.set(
        new RsWithStatus(
            this.response.get(),
            code
        )
    );
}
 
Example #8
Source File: HttpServletResponseFake.java    From takes with MIT License 5 votes vote down vote up
@Override
public void sendError(
    final int code,
    final String reason
) throws IOException {
    this.response.set(
        new RsWithStatus(
            this.response.get(),
            code,
            reason
        )
    );
}
 
Example #9
Source File: BkBasic.java    From takes with MIT License 5 votes vote down vote up
/**
 * Make a failure response.
 * @param err Error
 * @param code HTTP error code
 * @return Response
 */
private static Response failure(final Throwable err, final int code) {
    return new RsWithStatus(
        new RsText(
            new InputStreamOf(
                new BytesOf(err)
            )
        ),
        code
    );
}
 
Example #10
Source File: TkCors.java    From takes with MIT License 5 votes vote down vote up
@Override
public Response act(final Request req) throws Exception {
    final Response response;
    final String domain = new RqHeaders.Smart(
        new RqHeaders.Base(req)
    ).single("origin", "");
    if (this.allowed.contains(domain)) {
        response = new RsWithHeaders(
            this.origin.act(req),
            "Access-Control-Allow-Credentials: true",
            // @checkstyle LineLengthCheck (1 line)
            "Access-Control-Allow-Methods: OPTIONS, GET, PUT, POST, DELETE, HEAD",
            String.format(
                "Access-Control-Allow-Origin: %s",
                domain
            )
        );
    } else {
        response = new RsWithHeaders(
            new RsWithStatus(
                HttpURLConnection.HTTP_FORBIDDEN
            ),
            "Access-Control-Allow-Credentials: false"
        );
    }
    return response;
}
 
Example #11
Source File: TkProxy.java    From takes with MIT License 5 votes vote down vote up
/**
 * Creates the response received from the target host.
 *
 * @param home Home host
 * @param dest Destination URL
 * @param rsp Response received from the target host
 * @return Response
 */
private Response response(final String home, final URI dest,
    final com.jcabi.http.Response rsp) {
    final Collection<String> hdrs = new LinkedList<>();
    hdrs.add(
        String.format(
            "X-Takes-TkProxy: from %s to %s by %s",
            home, dest, this.label
        )
    );
    for (final Map.Entry<String, List<String>> entry
        : rsp.headers().entrySet()) {
        for (final String value : entry.getValue()) {
            final String val;
            if (TkProxy.isHost(entry.getKey())) {
                val = this.target.toString();
            } else {
                val = value;
            }
            hdrs.add(String.format("%s: %s", entry.getKey(), val));
        }
    }
    return new RsWithStatus(
        new RsWithBody(
            new RsWithHeaders(hdrs),
            rsp.binary()
        ),
        rsp.status(),
        rsp.reason()
    );
}
 
Example #12
Source File: RsXembly.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param dom DOM node to build upon
 * @param src Source
 */
public RsXembly(final Node dom, final XeSource src) {
    super(
        new ResponseOf(
            () -> new RsWithType(
                new RsWithStatus(
                    new RsEmpty(), HttpURLConnection.HTTP_OK
                ), "text/xml"
            ).head(),
            () -> RsXembly.render(dom, src)
        )
    );
}
 
Example #13
Source File: TakesContact.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public Response act(Request req) throws IOException {
    return new RsWithStatus(
        new RsWithType(
            new RsWithBody("Contact us at https://www.baeldung.com"), 
            "text/html"), 200);
}
 
Example #14
Source File: AsyncReports.java    From jpeek with MIT License 4 votes vote down vote up
@Override
public Func<String, Response> apply(final String group,
    final String artifact) throws IOException {
    final Future<Func<String, Response>> future = new IoCheckedBiFunc<>(
        this.cache
    ).apply(group, artifact);
    final Func<String, Response> output;
    if (future.isCancelled()) {
        output = input -> new RsPage(
            new RqFake(),
            "error",
            () -> new IterableOf<>(
                new XeAppend("group", group),
                new XeAppend("artifact", artifact),
                new XeAppend("future", future.toString())
            )
        );
    } else if (future.isDone()) {
        try {
            output = future.get();
        } catch (final InterruptedException | ExecutionException ex) {
            throw new IllegalStateException(ex);
        }
    } else {
        final long msec = System.currentTimeMillis()
            - this.starts.computeIfAbsent(
                String.format("%s:%s", group, artifact),
                s -> System.currentTimeMillis()
            );
        output = input -> new RsWithStatus(
            new RsPage(
                new RqFake(),
                "wait",
                () -> new IterableOf<>(
                    new XeAppend("group", group),
                    new XeAppend("artifact", artifact),
                    new XeAppend("future", future.toString()),
                    new XeAppend("msec", Long.toString(msec)),
                    new XeAppend(
                        "spent",
                        Logger.format("%[ms]s", msec)
                    )
                )
            ),
            HttpURLConnection.HTTP_NOT_FOUND
        );
    }
    return output;
}
 
Example #15
Source File: TkApp.java    From jpeek with MIT License 4 votes vote down vote up
/**
 * Ctor.
 * @param home Home directory
 * @return The take
 * @throws IOException If fails
 */
private static Take make(final Path home) throws IOException {
    final Futures futures = new Futures(
        new Reports(home)
    );
    final BiFunc<String, String, Func<String, Response>> reports =
        new AsyncReports(
            // @checkstyle MagicNumber (1 line)
            new StickyFutures(futures, 100)
        );
    return new TkSslOnly(
        new TkFallback(
            new TkForward(
                new TkFork(
                    new FkRegex("/", new TkIndex()),
                    new FkRegex("/robots.txt", new TkText("")),
                    new FkRegex("/mistakes", new TkMistakes()),
                    new FkRegex(
                        "/flush",
                        (Take) req -> new RsText(
                            String.format("%d flushed", new Results().flush())
                        )
                    ),
                    new FkRegex(
                        "/upload",
                        (Take) req -> new RsPage(req, "upload")
                    ),
                    new FkRegex("/do-upload", new TkUpload(reports)),
                    new FkRegex("/all", new TkAll()),
                    new FkRegex("/queue", new TkQueue(futures)),
                    new FkRegex(
                        ".+\\.xsl",
                        new TkWithType(
                            new TkClasspath(),
                            "text/xsl"
                        )
                    ),
                    new FkRegex(
                        "/jpeek\\.css",
                        new TkWithType(
                            new TkText(
                                new TextOf(
                                    new ResourceOf("org/jpeek/jpeek.css")
                                ).asString()
                            ),
                            "text/css"
                        )
                    ),
                    new FkRegex(
                        "/([^/]+)/([^/]+)(.*)",
                        new TkReport(reports, new Results())
                    )
                )
            ),
            new FbChain(
                new FbStatus(
                    HttpURLConnection.HTTP_NOT_FOUND,
                    (Fallback) req -> new Opt.Single<>(
                        new RsWithStatus(
                            new RsText(req.throwable().getMessage()),
                            req.code()
                        )
                    )
                ),
                req -> {
                    Sentry.capture(req.throwable());
                    return new Opt.Single<>(
                        new RsWithStatus(
                            new RsText(
                                new TextOf(req.throwable()).asString()
                            ),
                            HttpURLConnection.HTTP_INTERNAL_ERROR
                        )
                    );
                }
            )
        )
    );
}