org.takes.Request Java Examples
The following examples show how to use
org.takes.Request.
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: TkAuthTest.java From takes with MIT License | 6 votes |
/** * 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 #2
Source File: PsByFlag.java From takes with MIT License | 6 votes |
@Override public Opt<Identity> enter(final Request req) throws Exception { final Iterator<String> flg = new RqHref.Base(req).href() .param(this.flag).iterator(); Opt<Identity> user = new Opt.Empty<>(); if (flg.hasNext()) { final String value = flg.next(); for (final Map.Entry<Pattern, Pass> ent : this.passes.entrySet()) { if (ent.getKey().matcher(value).matches()) { user = ent.getValue().enter(req); break; } } } return user; }
Example #3
Source File: FkHitRefreshTest.java From takes with MIT License | 6 votes |
/** * FkHitRefresh can refresh on demand. * @throws Exception If some problem inside */ @Test public void refreshesOnDemand() throws Exception { final Request req = new RqWithHeader( new RqFake(), "X-Takes-HitRefresh: yes" ); final AtomicBoolean done = new AtomicBoolean(false); final Fork fork = new FkHitRefresh( this.temp.getRoot(), new Runnable() { @Override public void run() { done.set(true); } }, new TkEmpty() ); TimeUnit.SECONDS.sleep(2L); FileUtils.touch(this.temp.newFile("hey.txt")); MatcherAssert.assertThat( fork.route(req).has(), Matchers.is(true) ); MatcherAssert.assertThat(done.get(), Matchers.is(true)); }
Example #4
Source File: RqSocketTest.java From takes with MIT License | 6 votes |
@Test public void hashCodeMustEqualToSameTypeRequest() throws Exception { final Request request = new RqWithHeader( new RqFake(), "X-Takes-LocalPort: 55555" ); new Assertion<>( "RqSocket must equal to other RqSocket", new RqSocket( request ).hashCode(), new IsEqual<>( new RqSocket( request ).hashCode() ) ).affirm(); }
Example #5
Source File: TkAdd.java From jare with MIT License | 6 votes |
@Override public Response act(final Request req) throws IOException { final String name = new RqFormBase(req).param("name") .iterator().next().trim(); try { new SafeUser(this.base.user(new RqUser(req).name())).add(name); } catch (final SafeUser.InvalidNameException ex) { throw TkAdd.forward(new RsFlash(ex)); } return TkAdd.forward( new RsFlash( String.format( "domain \"%s\" added", name ) ) ); }
Example #6
Source File: RqOnceTest.java From takes with MIT License | 6 votes |
/** * RqOnce can make request read-only-once. * @throws IOException If some problem inside */ @Test(expected = IllegalStateException.class) public void makesRequestReadOnlyOnce() throws IOException { final Request req = new RqOnce( new RqLive( new InputStreamOf( new Joined( "\r\n", "GET /test HTTP/1.1", "Host: localhost", "", "... the body ..." ) ) ) ); new RqPrint(req).printBody(); new RqPrint(req).printBody(); }
Example #7
Source File: TkDomains.java From jare with MIT License | 6 votes |
@Override public Response act(final Request req) throws IOException { return new RsPage( "/xsl/domains.xsl", req, new XeAppend( "domains", new XeTransform<>( this.base.user(new RqUser(req).name()).mine(), TkDomains::source ) ), new XeLink("add", "/add"), new XeLink("invalidate", "/invalidate") ); }
Example #8
Source File: TkVerbose.java From takes with MIT License | 6 votes |
/** * 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 #9
Source File: TkClasspath.java From takes with MIT License | 6 votes |
/** * 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 #10
Source File: TkRelayTest.java From jare with MIT License | 6 votes |
/** * Fake request. * @param home Base URI * @param path Path * @return Request * @throws UnsupportedEncodingException If fails */ private static Request fake(final URI home, final String path) throws UnsupportedEncodingException { return new RqFake( Arrays.asList( String.format( "GET /?u=%s", URLEncoder.encode( home.resolve(path).toString(), "UTF-8" ) ), "Host: localhost" ), "" ); }
Example #11
Source File: RqLiveTest.java From takes with MIT License | 6 votes |
/** * RqLive can support multi-line headers. * @throws IOException If some problem inside */ @Test public void supportMultiLineHeaders() throws IOException { final Request req = new RqLive( new InputStreamOf( new Joined( RqLiveTest.CRLF, "GET /multiline HTTP/1.1", "X-Foo: this is a test", " header for you", "", "hello multi part" ) ) ); MatcherAssert.assertThat( new RqHeaders.Base(req).header("X-Foo"), Matchers.hasItem("this is a test header for you") ); }
Example #12
Source File: RqMtBase.java From takes with MIT License | 6 votes |
/** * Make a request. * Scans the origin request until the boundary reached. Caches * the content into a temporary file and returns it as a new request. * @param boundary Boundary * @param body Origin request body * @return Request * @throws IOException If fails */ private Request make(final byte[] boundary, final ReadableByteChannel body) throws IOException { final File file = File.createTempFile( RqMultipart.class.getName(), ".tmp" ); try (WritableByteChannel channel = Files.newByteChannel( file.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE ) ) { channel.write( ByteBuffer.wrap( this.head().iterator().next().getBytes(RqMtBase.ENCODING) ) ); channel.write( ByteBuffer.wrap(RqMtBase.CRLF.getBytes(RqMtBase.ENCODING)) ); this.copy(channel, boundary, body); } return new RqTemp(file); }
Example #13
Source File: TkRetryTest.java From takes with MIT License | 6 votes |
/** * TkRetry can retry when initial take fails with IOException, * till get successful result. * * @throws Exception if something is wrong */ @Test public void retriesOnExceptionTillSuccess() throws Exception { final int count = Tv.THREE; final int delay = Tv.THOUSAND; final String data = "data"; final Take take = Mockito.mock(Take.class); Mockito .when(take.act(Mockito.any(Request.class))) .thenThrow(new IOException()) .thenReturn(new RsText(data)); final long start = System.nanoTime(); final RsPrint response = new RsPrint( new TkRetry(count, delay, take).act(new RqFake(RqMethod.GET)) ); final long spent = System.nanoTime() - start; MatcherAssert.assertThat( Long.valueOf(delay - Tv.HUNDRED) * Tv.MILLION, Matchers.lessThanOrEqualTo(spent) ); MatcherAssert.assertThat( response, new TextHasString(data) ); }
Example #14
Source File: TkForwardTest.java From takes with MIT License | 6 votes |
/** * TkForward can catch RsForward. * @throws Exception If some problem inside */ @Test public void catchesExceptionCorrectly() throws Exception { final Take take = new Take() { @Override public Response act(final Request request) throws RsForward { throw new RsForward("/"); } }; MatcherAssert.assertThat( new RsPrint( new TkForward(take).act(new RqFake()) ), new StartsWith("HTTP/1.1 303 See Other") ); }
Example #15
Source File: TkReturn.java From takes with MIT License | 6 votes |
@Override public Response act(final Request request) throws Exception { final RqCookies cookies = new RqCookies.Base(request); final Iterator<String> values = cookies.cookie(this.cookie).iterator(); final Response response; if (values.hasNext()) { response = new RsWithCookie( new RsRedirect( URLDecoder.decode( values.next(), Charset.defaultCharset().name() ) ), this.cookie, "" ); } else { response = this.origin.act(request); } return response; }
Example #16
Source File: RsForkTest.java From takes with MIT License | 6 votes |
/** * RsFork can route by the Accept header. * @throws IOException If some problem inside */ @Test public void negotiatesContentWithComplexHeader() throws IOException { final Request req = new RqFake( Arrays.asList( "GET /hell-1o.html", "Accept: text/xml" ), "" ); MatcherAssert.assertThat( new RsPrint( new RsFork( req, new FkTypes( "application/xml,text/xml", new RsText("how are you?") ) ) ).printBody(), Matchers.endsWith("you?") ); }
Example #17
Source File: RqLiveTest.java From takes with MIT License | 6 votes |
/** * RqLive can support multi-line headers with colon in second line. * Yegor counterexample. * @throws IOException If some problem inside */ @Test public void supportMultiLineHeadersWithColon() throws IOException { final Request req = new RqLive( new InputStreamOf( new Joined( RqLiveTest.CRLF, "GET /multilinecolon HTTP/1.1", "Foo: first line", " second: line", "" ) ) ); MatcherAssert.assertThat( new RqHeaders.Base(req).header("Foo"), Matchers.hasItem("first line second: line") ); }
Example #18
Source File: RqWithHeaders.java From takes with MIT License | 6 votes |
/** * Ctor. * @param req Original request * @param headers Headers to add */ public RqWithHeaders(final Request req, final Iterable<? extends CharSequence> headers) { super( new RequestOf( () -> { final List<String> head = new LinkedList<>(); for (final String hdr : req.head()) { head.add(hdr); } for (final CharSequence header : headers) { head.add( new UncheckedText( new Trimmed(new TextOf(header)) ).asString() ); } return head; }, req::body ) ); }
Example #19
Source File: TkWithHeaders.java From takes with MIT License | 5 votes |
/** * Ctor. * @param take Original * @param headers Headers */ public TkWithHeaders(final Take take, final Collection<String> headers) { super( new Take() { @Override public Response act(final Request req) throws Exception { return new RsWithHeaders(take.act(req), headers); } } ); }
Example #20
Source File: RqOnce.java From takes with MIT License | 5 votes |
/** * Wrap the request. * @param req Request * @return New request */ private static Request wrap(final Request req) { final AtomicBoolean seen = new AtomicBoolean(false); return new RequestOf( req::head, () -> { if (!seen.getAndSet(true)) { throw new IllegalStateException( "It's not allowed to call body() more than once" ); } return req.body(); } ); }
Example #21
Source File: TkWithType.java From takes with MIT License | 5 votes |
/** * 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); } } ); }
Example #22
Source File: RqFakeTest.java From takes with MIT License | 5 votes |
/** * RqFake can print body only once. * @throws IOException If some problem inside */ @Test public void printsBodyOnlyOnce() throws IOException { final String body = "the body text"; final Request req = new RqFake("", "", body); MatcherAssert.assertThat( new RqPrint(req).print(), Matchers.containsString(body) ); MatcherAssert.assertThat( new RqPrint(req).print(), Matchers.not(Matchers.containsString(body)) ); }
Example #23
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 #24
Source File: TkFixed.java From takes with MIT License | 5 votes |
/** * Ctor. * @param res Response * @since 1.4 */ public TkFixed(final Scalar<Response> res) { super( new Take() { @Override public Response act(final Request req) throws IOException { return res.get(); } } ); }
Example #25
Source File: TakesIndex.java From tutorials with MIT License | 5 votes |
@Override public Response act(final Request req) throws IOException { RqFormSmart form = new RqFormSmart(req); String username = form.single("username"); return new RsHtml( new RsVelocity(this.getClass().getResource("/templates/index.vm"), new RsVelocity.Pair("username", username)) ); }
Example #26
Source File: TkText.java From takes with MIT License | 5 votes |
/** * Ctor. * @param body Text * @since 1.4 */ public TkText(final Scalar<String> body) { super( new Take() { @Override public Response act(final Request req) throws IOException { return new RsText(body.get()); } } ); }
Example #27
Source File: PsChain.java From takes with MIT License | 5 votes |
@Override public Opt<Identity> enter(final Request req) throws Exception { Opt<Identity> user = new Opt.Empty<>(); for (final Pass pass : this.passes) { user = pass.enter(req); if (user.has()) { break; } } return user; }
Example #28
Source File: RqChunk.java From takes with MIT License | 5 votes |
/** * Cap the steam. * @param req Request * @return Stream with a cap * @throws IOException If fails */ private static InputStream cap(final Request req) throws IOException { final Iterator<String> hdr = new RqHeaders.Base(req) .header("Transfer-Encoding").iterator(); final InputStream result; if (hdr.hasNext() && "chunked".equalsIgnoreCase(hdr.next())) { result = new ChunkedInputStream(req.body()); } else { result = req.body(); } return result; }
Example #29
Source File: XeGithubLink.java From takes with MIT License | 5 votes |
/** * Ctor. * @param req Request * @param app Github application ID * @param rel Related * @param flag Flag to add * @return Source * @throws IOException If fails * @checkstyle ParameterNumberCheck (4 lines) */ private static XeSource make(final Request req, final CharSequence app, final CharSequence rel, final CharSequence flag) throws IOException { return new XeLink( rel, new Href("https://github.com/login/oauth/authorize") .with("client_id", app) .with( "redirect_uri", new RqHref.Base(req).href() .with(flag, PsGithub.class.getSimpleName()) ) ); }
Example #30
Source File: TkFallback.java From takes with MIT License | 5 votes |
/** * 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); } } ); }