org.takes.Response Java Examples
The following examples show how to use
org.takes.Response.
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: RsGzip.java From takes with MIT License | 6 votes |
/** * 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 #2
Source File: StickyFutures.java From jpeek with MIT License | 6 votes |
@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 #3
Source File: RsReturn.java From takes with MIT License | 6 votes |
/** * 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 #4
Source File: TkSslOnly.java From takes with MIT License | 6 votes |
@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 #5
Source File: PsCookie.java From takes with MIT License | 6 votes |
@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 #6
Source File: TakesApp.java From tutorials with MIT License | 6 votes |
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 #7
Source File: TkSecureTest.java From takes with MIT License | 6 votes |
/** * 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 #8
Source File: FbStatus.java From takes with MIT License | 6 votes |
/** * 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 #9
Source File: RsPrint.java From takes with MIT License | 6 votes |
/** * 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 #10
Source File: TkForward.java From takes with MIT License | 6 votes |
/** * 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 #11
Source File: FbStatus.java From takes with MIT License | 6 votes |
/** * 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 #12
Source File: RsWithType.java From takes with MIT License | 6 votes |
/** * 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 #13
Source File: RsWithStatus.java From takes with MIT License | 6 votes |
/** * 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 #14
Source File: RsGzipTest.java From takes with MIT License | 6 votes |
/** * 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 #15
Source File: RsWithBody.java From takes with MIT License | 6 votes |
/** * 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 #16
Source File: FkChain.java From takes with MIT License | 5 votes |
@Override public Opt<Response> route(final Request request) throws Exception { Opt<Response> response = new Opt.Empty<>(); for (final Fork fork : this.forks) { final Opt<Response> current = fork.route(request); if (current.has()) { response = current; break; } } return response; }
Example #17
Source File: RsPrettyJson.java From takes with MIT License | 5 votes |
/** * Make a response. * @return Response just made * @throws IOException If fails */ private Response make() throws IOException { if (this.transformed.isEmpty()) { this.transformed.add( new RsWithBody( this.origin, RsPrettyJson.transform(this.origin.body()) ) ); } return this.transformed.get(0); }
Example #18
Source File: FkMethods.java From takes with MIT License | 5 votes |
@Override public Opt<Response> route(final Request req) throws Exception { final String mtd = new RqMethod.Base(req).method(); final Opt<Response> resp; if (this.methods.contains(mtd)) { resp = new Opt.Single<>(this.take.act(req)); } else { resp = new Opt.Empty<>(); } return resp; }
Example #19
Source File: FkHost.java From takes with MIT License | 5 votes |
/** * Make fork. * @param host Host * @param take Take to use * @return Fork */ private static Fork fork(final String host, final Take take) { return req -> { final String hst = new RqHeaders.Smart( new RqHeaders.Base(req) ).single("host"); return new Ternary<Opt<Response>>( new EqualsNullable( new Lowered(host), new Lowered(hst) ), new Opt.Single<>(take.act(req)), new Opt.Empty<>() ).value(); }; }
Example #20
Source File: PsLinkedinTest.java From takes with MIT License | 5 votes |
@Override public Response act(final Request req) throws IOException { MatcherAssert.assertThat( new RqPrint(req).printBody(), Matchers.stringContainsInOrder( Arrays.asList( "grant_type=authorization_code", String.format("client_id=%s", this.lapp), "redirect_uri=", String.format("client_secret=%s", this.lkey), String.format("code=%s", this.code) ) ) ); MatcherAssert.assertThat( new RqHref.Base(req).href().toString(), Matchers.endsWith(this.tokenpath) ); return new RsJson( Json.createObjectBuilder() .add( "access_token", // @checkstyle MagicNumber (1 line) RandomStringUtils.randomAlphanumeric(10) ).build() ); }
Example #21
Source File: TkReadAlwaysTest.java From takes with MIT License | 5 votes |
/** * 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 #22
Source File: App.java From takes with MIT License | 5 votes |
@Override public Response act(final Request request) throws Exception { return new TkFork( new FkRegex("/", new TkRedirect("/f")), new FkRegex( "/about", new TkHtml(App.class.getResource("about.html")) ), new FkRegex("/robots.txt", ""), new FkRegex("/f(.*)", new TkDir(this.home)) ).act(request); }
Example #23
Source File: PsAll.java From takes with MIT License | 5 votes |
@Override public Response exit(final Response response, final Identity identity) throws Exception { if (this.index >= this.all.size()) { throw new IOException( "Index of identity is greater than Pass collection size" ); } return this.all.get(this.index).exit(response, identity); }
Example #24
Source File: TkAuth.java From takes with MIT License | 5 votes |
@Override public Response act(final Request request) throws Exception { final Opt<Identity> user = this.pass.enter(request); final Response response; if (user.has()) { response = this.act(request, user.get()); } else { response = this.origin.act(request); } return response; }
Example #25
Source File: TkFailure.java From takes with MIT License | 5 votes |
/** * Ctor. * @param err Error to throw */ public TkFailure(final RuntimeException err) { super( new Take() { @Override public Response act(final Request request) { throw err; } } ); }
Example #26
Source File: FkContentType.java From takes with MIT License | 5 votes |
@Override public Opt<Response> route(final Request req) throws Exception { final Opt<Response> resp; if (FkContentType.getType(req).contains(this.type)) { resp = new Opt.Single<>(this.take.act(req)); } else { resp = new Opt.Empty<>(); } return resp; }
Example #27
Source File: RsWithHeader.java From takes with MIT License | 5 votes |
/** * Ctor. * @param res Original response * @param header Header to add */ public RsWithHeader(final Response res, final CharSequence header) { super( new ResponseOf( () -> RsWithHeader.extend(res.head(), header.toString()), res::body ) ); }
Example #28
Source File: TkAuth.java From takes with MIT License | 5 votes |
/** * Make take. * @param req Request * @param identity Identity * @return Take * @throws Exception If fails */ private Response act(final Request req, final Identity identity) throws Exception { Request wrap = new RqWithoutHeader(req, this.header); if (!identity.equals(Identity.ANONYMOUS)) { wrap = new RqWithAuth(identity, this.header, wrap); } return this.pass.exit(this.origin.act(wrap), identity); }
Example #29
Source File: RsWithHeaders.java From takes with MIT License | 5 votes |
/** * Add to head additional headers. * @param res Original response * @param headers Values witch will be added to head * @return Head with additional headers * @throws IOException If fails */ @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") private static Iterable<String> extend(final Response res, final Iterable<? extends CharSequence> headers) throws IOException { Response resp = res; for (final CharSequence hdr : headers) { resp = new RsWithHeader(resp, hdr); } return resp.head(); }
Example #30
Source File: FkEncoding.java From takes with MIT License | 5 votes |
@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; }