com.jcabi.http.request.JdkRequest Java Examples

The following examples show how to use com.jcabi.http.request.JdkRequest. 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: TkAppTest.java    From jpeek with 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 #2
Source File: TkSlf4jRemoteTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkSlf4j can return an empty response body for {@link TkEmpty}.
 * @throws Exception if some I/O problem occurred.
 */
@Ignore
@Test
public void returnsAnEmptyResponseBody() throws Exception {
    new FtRemote(
        new TkSlf4j(new TkEmpty())
    ).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .method("POST")
                    .body().set("returnsAnEmptyResponseBody").back()
                    .fetch()
                    .as(RestResponse.class)
                    .assertBody(new IsEqual<>(""))
                    .assertStatus(HttpURLConnection.HTTP_NO_CONTENT);
            }
        }
    );
}
 
Example #3
Source File: FtSecureTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FtSecure can gracefully work with a broken back.
 * @throws Exception If some problem inside
 */
@Test
public void gracefullyHandlesBrokenBack() throws Exception {
    FtSecureTest.secure(new TkFailure("Jeffrey Lebowski")).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_INTERNAL_ERROR)
                    .assertBody(Matchers.containsString("Lebowski"));
            }
        }
    );
}
 
Example #4
Source File: FtSecureTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FtSecure can work.
 * @throws Exception If some problem inside
 */
@Test
public void justWorks() throws Exception {
    FtSecureTest.secure(new TkFixed("hello, world")).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .assertBody(Matchers.startsWith("hello"));
            }
        }
    );
}
 
Example #5
Source File: BkBasicTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * BkBasic can return HTTP status 404 when accessing invalid URL.
 *
 * @throws Exception if any I/O error occurs.
 */
@Test
public void returnsProperResponseCodeOnInvalidUrl() throws Exception {
    new FtRemote(
        new TkFork(
            new FkRegex("/path/a", new TkText("a")),
            new FkRegex("/path/b", new TkText("b"))
        )
    ).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(String.format("%s/path/c", home))
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_NOT_FOUND);
            }
        }
    );
}
 
Example #6
Source File: FtBasicTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FtBasic can work with a broken back.
 * @throws Exception If some problem inside
 */
@Test
public void gracefullyHandlesBrokenBack() throws Exception {
    new FtRemote(new TkFailure("Jeffrey Lebowski")).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_INTERNAL_ERROR)
                    .assertBody(Matchers.containsString("Lebowski"));
            }
        }
    );
}
 
Example #7
Source File: FtBasicTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FtBasic can work.
 * @throws Exception If some problem inside
 */
@Test
public void justWorks() throws Exception {
    new FtRemote(
        new TkFork(new FkRegex(FtBasicTest.ROOT_PATH, "hello, world!"))
    ).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .assertBody(Matchers.startsWith("hello"));
            }
        }
    );
}
 
Example #8
Source File: FtRemoteTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FtRemote can return empty response body for {@link TkEmpty}.
 * @throws Exception If some problems inside
 */
@Test
public void returnsAnEmptyResponseBody() throws Exception {
    new FtRemote(
        new TkEmpty()
    ).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .method("POST")
                    .body().set("returnsAnEmptyResponseBody").back()
                    .fetch()
                    .as(RestResponse.class)
                    .assertBody(new IsEqual<>(""))
                    .assertStatus(HttpURLConnection.HTTP_NO_CONTENT);
            }
        }
    );
}
 
Example #9
Source File: FtRemoteTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * FtRemote can work.
 * @throws Exception If some problem inside
 */
@Test
public void simplyWorks() throws Exception {
    new FtRemote(new TkFixed(new RsText("simple answer"))).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .assertBody(Matchers.startsWith("simple"));
            }
        }
    );
}
 
Example #10
Source File: MainRemoteTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * MainRemote passes additional arguments.
 * @throws Exception If some problem inside
 */
@Test
public void passesArgumentsToApp() throws Exception {
    final String[] args = {"works well!"};
    new MainRemote(MainRemoteTest.DemoAppArgs.class, args).exec(
        new MainRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .assertBody(Matchers.startsWith("works well"));
            }
        }
    );
}
 
Example #11
Source File: MainRemoteTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * MainRemote can work.
 * @throws Exception If some problem inside
 */
@Test
public void startsAndStopsApp() throws Exception {
    new MainRemote(MainRemoteTest.DemoApp.class).exec(
        new MainRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .assertBody(Matchers.startsWith("works"));
            }
        }
    );
}
 
Example #12
Source File: AppTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * App can work.
 * @throws Exception If some problem inside
 */
@Test
public void justWorks() throws Exception {
    final File dir = this.temp.newFolder();
    FileUtils.write(new File(dir, "hello.txt"), "hello, world!");
    new FtRemote(new App(dir)).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .uri().path("/f").back()
                    .through(VerboseWire.class)
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .as(XmlResponse.class)
                    .assertXPath("//xhtml:li[.='hello.txt: 13']");
            }
        }
    );
}
 
Example #13
Source File: TkAppTest.java    From jare with 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 #14
Source File: PsGoogle.java    From takes with MIT License 6 votes vote down vote up
/**
 * Retrieve Google access token.
 * @param code Google "authorization code"
 * @return The token
 * @throws IOException If failed
 */
private String token(final String code) throws IOException {
    return new JdkRequest(
        new Href(this.gauth).path("o").path("oauth2").path("token")
            .toString()
    ).body()
        .formParam("client_id", this.app)
        .formParam("redirect_uri", this.redir)
        .formParam("client_secret", this.key)
        .formParam("grant_type", "authorization_code")
        .formParam(PsGoogle.CODE, code)
        .back()
        .header("Content-Type", "application/x-www-form-urlencoded")
        .method(com.jcabi.http.Request.POST)
        .fetch().as(RestResponse.class)
        .assertStatus(HttpURLConnection.HTTP_OK)
        .as(JsonResponse.class).json()
        .readObject()
        .getString(PsGoogle.ACCESS_TOKEN);
}
 
Example #15
Source File: PsGoogle.java    From takes with MIT License 6 votes vote down vote up
/**
 * Get user name from Google, with the token provided.
 * @param token Google access token
 * @return The user found in Google
 * @throws IOException If fails
 */
private Identity fetch(final String token) throws IOException {
    // @checkstyle LineLength (1 line)
    final String uri = new Href(this.gapi).path("plus").path("v1")
        .path("people")
        .path("me")
        .with(PsGoogle.ACCESS_TOKEN, token)
        .toString();
    final JsonObject json = new JdkRequest(uri).fetch()
        .as(JsonResponse.class).json()
        .readObject();
    if (json.containsKey(PsGoogle.ERROR)) {
        throw new HttpException(
            HttpURLConnection.HTTP_BAD_REQUEST,
            String.format(
                "could not retrieve id from Google, possible cause: %s.",
                json.getJsonObject(PsGoogle.ERROR).get("message")
            )
        );
    }
    return PsGoogle.parse(json);
}
 
Example #16
Source File: PsGithub.java    From takes with MIT License 6 votes vote down vote up
/**
 * Retrieve Github access token.
 * @param home Home of this page
 * @param code Github "authorization code"
 * @return The token
 * @throws IOException If failed
 */
private String token(final String home, final String code)
    throws IOException {
    final String uri = new Href(this.github)
        .path(PsGithub.LOGIN).path("oauth").path(PsGithub.ACCESS_TOKEN)
        .toString();
    return new JdkRequest(uri)
        .method("POST")
        .header("Accept", "application/xml")
        .body()
        .formParam("client_id", this.app)
        .formParam("redirect_uri", home)
        .formParam("client_secret", this.key)
        .formParam(PsGithub.CODE, code)
        .back()
        .fetch().as(RestResponse.class)
        .assertStatus(HttpURLConnection.HTTP_OK)
        .as(XmlResponse.class)
        .assertXPath("/OAuth/access_token")
        .xml()
        .xpath("/OAuth/access_token/text()")
        .get(0);
}
 
Example #17
Source File: PsLinkedin.java    From takes with MIT License 6 votes vote down vote up
/**
 * Retrieve PsLinkedin access token.
 * @param home Home of this page
 * @param code PsLinkedin "authorization code"
 * @return The token
 * @throws IOException If failed
 */
private String token(final String home, final String code)
    throws IOException {
    final String uri = this.tkhref.toString();
    return new JdkRequest(uri)
        .method("POST")
        .header("Accept", "application/xml")
        .body()
        .formParam("grant_type", "authorization_code")
        .formParam("client_id", this.app)
        .formParam("redirect_uri", home)
        .formParam("client_secret", this.key)
        .formParam(PsLinkedin.CODE, code)
        .back()
        .fetch().as(RestResponse.class)
        .assertStatus(HttpURLConnection.HTTP_OK)
        .as(JsonResponse.class)
        .json().readObject().getString("access_token");
}
 
Example #18
Source File: AppITCase.java    From takes with MIT License 5 votes vote down vote up
/**
 * App can work.
 * @throws Exception If some problem inside
 * @checkstyle NonStaticMethodCheck (2 lines)
 */
@Test
public void justWorks() throws Exception {
    Assume.assumeNotNull(AppITCase.HOME);
    new JdkRequest(String.format("%s/f", AppITCase.HOME))
        .through(VerboseWire.class)
        .fetch()
        .as(RestResponse.class)
        .assertStatus(HttpURLConnection.HTTP_OK)
        .as(XmlResponse.class)
        .assertXPath("//xhtml:html");
}
 
Example #19
Source File: TkReadAlwaysTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * 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 #20
Source File: FtSecureTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * FtSecure can properly parse incoming HTTP request.
 * @throws Exception If some problem inside
 */
@Test
public void parsesIncomingHttpRequest() throws Exception {
    final Take take = new Take() {
        @Override
        public Response act(final Request request) throws IOException {
            MatcherAssert.assertThat(
                new RqPrint(request).printBody(),
                Matchers.containsString("Jeff")
            );
            return new RsText("works!");
        }
    };
    FtSecureTest.secure(take).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .method("PUT")
                    .body().set("Jeff, how are you?").back()
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK);
            }
        }
    );
}
 
Example #21
Source File: PsLinkedin.java    From takes with MIT License 5 votes vote down vote up
/**
 * Get user name from Linkedin, with the token provided.
 * @param token PsLinkedin access token
 * @return The user found in PsLinkedin
 * @throws IOException If fails
 */
private Identity fetch(final String token) throws IOException {
    // @checkstyle LineLength (1 line)
    final String uri = this.apihref
        .with("oauth2_access_token", token)
        .with("format", "json")
        .toString();
    return PsLinkedin.parse(
        new JdkRequest(uri)
            .header("accept", "application/json")
            .fetch().as(RestResponse.class)
            .assertStatus(HttpURLConnection.HTTP_OK)
            .as(JsonResponse.class).json().readObject()
    );
}
 
Example #22
Source File: FtBasicTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * FtBasic can consume twice the input stream in case of a RsHTML.
 * @throws Exception If some problem inside
 */
@Test
public void consumesTwiceInputStreamWithRsHtml() throws Exception {
    final String result = "Hello RsHTML!";
    new FtRemote(
        new TkFork(
            new FkRegex(
                FtBasicTest.ROOT_PATH,
                new RsHtml(
                    new InputStreamOf(result)
                )
            )
        )
    ).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .assertBody(Matchers.equalTo(result));
                new JdkRequest(home)
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .assertBody(Matchers.equalTo(result));
            }
        }
    );
}
 
Example #23
Source File: FtBasicTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * FtBasic can consume twice the input stream in case of a RsText.
 * @throws Exception If some problem inside
 */
@Test
public void consumesTwiceInputStreamWithRsText() throws Exception {
    final String result = "Hello RsText!";
    new FtRemote(
        new TkFork(
            new FkRegex(
                FtBasicTest.ROOT_PATH,
                new RsText(
                    new InputStreamOf(result)
                )
            )
        )
    ).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .assertBody(Matchers.equalTo(result));
                new JdkRequest(home)
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .assertBody(Matchers.equalTo(result));
            }
        }
    );
}
 
Example #24
Source File: FtBasicTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * FtBasic can work with a stuck back.
 * @throws Exception If some problem inside
 */
@Test
@Ignore
public void gracefullyHandlesStuckBack() throws Exception {
    final Take take = new Take() {
        @Override
        public Response act(final Request request) throws IOException {
            final Request req = new RqGreedy(request);
            return new RsText(
                String.format(
                    "first: %s, second: %s",
                    new RqPrint(req).printBody(),
                    new RqPrint(req).printBody()
                )
            );
        }
    };
    new FtRemote(take).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .method("POST")
                    .header("Content-Length", "4")
                    .fetch(new ByteArrayInputStream("ddgg".getBytes()))
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK)
                    .assertBody(Matchers.containsString("second: dd"));
            }
        }
    );
}
 
Example #25
Source File: FtBasicTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * FtBasic can properly parse incoming HTTP request.
 * @throws Exception If some problem inside
 */
@Test
public void parsesIncomingHttpRequest() throws Exception {
    final Take take = new Take() {
        @Override
        public Response act(final Request request) throws IOException {
            MatcherAssert.assertThat(
                new RqPrint(request).printBody(),
                Matchers.containsString("Jeff")
            );
            return new RsText("works!");
        }
    };
    new FtRemote(take).exec(
        new FtRemote.Script() {
            @Override
            public void exec(final URI home) throws IOException {
                new JdkRequest(home)
                    .method("PUT")
                    .body().set("Jeff, how are you?").back()
                    .fetch()
                    .as(RestResponse.class)
                    .assertStatus(HttpURLConnection.HTTP_OK);
            }
        }
    );
}
 
Example #26
Source File: PsTwitter.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param name Twitter app
 * @param keys Twitter key
 */
public PsTwitter(final String name, final String keys) {
    this(
        new JdkRequest(
            new Href("https://api.twitter.com/oauth2/token")
                .with("grant_type", "client_credentials")
                .toString()
        ),
        new JdkRequest(PsTwitter.VERIFY_URL), name, keys
    );
}
 
Example #27
Source File: PsFacebook.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param fapp Facebook app
 * @param fkey Facebook key
 */
public PsFacebook(final String fapp, final String fkey) {
    this(
        new JdkRequest(
            new Href(PsFacebook.ACCESS_TOKEN_URL)
                .with(PsFacebook.CLIENT_ID, fapp)
                .with(PsFacebook.CLIENT_SECRET, fkey)
                .toString()
        ),
        new DefaultWebRequestor(),
        fapp,
        fkey
    );
}
 
Example #28
Source File: PsGithub.java    From takes with MIT License 5 votes vote down vote up
/**
 * Get user name from Github, with the token provided.
 * @param token Github access token
 * @return The user found in Github
 * @throws IOException If fails
 */
private Identity fetch(final String token) throws IOException {
    final String uri = new Href(this.api).path("user")
        .with(PsGithub.ACCESS_TOKEN, token).toString();
    return PsGithub.parse(
        new JdkRequest(uri)
            .header("accept", "application/json")
            .fetch().as(RestResponse.class)
            .assertStatus(HttpURLConnection.HTTP_OK)
            .as(JsonResponse.class).json().readObject()
    );
}
 
Example #29
Source File: SrvTakeTest.java    From takes with MIT License 5 votes vote down vote up
@Test
public void executeATakesAsAServlet() throws Exception {
    final String name = "webapp";
    final HttpServer server = HttpServer.createSimpleServer("./", 18080);
    final WebappContext context = new WebappContext(name);
    final ServletRegistration servlet = context.addServlet(
        "takes",
        SrvTake.class
    );
    servlet.setInitParameter("take", TkApp.class.getName());
    servlet.addMapping("/test");
    context.deploy(server);
    server.start();
    new JdkRequest("http://localhost:18080/test")
        .fetch()
        .as(RestResponse.class)
        .assertStatus(HttpURLConnection.HTTP_OK)
        .assertBody(
            new StringContains(
                new FormattedText(
                    SrvTakeTest.MSG,
                    name
                ).asString()
            )
        );
    server.shutdownNow();
}
 
Example #30
Source File: TkMethodsTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * TkMethods can return 405 status when acting on unknown method.
 * @throws Exception If any I/O error occurs
 */
@Test
public void returnsMethodIsNotAllowedForUnsupportedMethods() throws
    Exception {
    new FtRemote(new TkMethods(new TkEmpty(), RqMethod.PUT)).exec(
        url -> new JdkRequest(url)
            .method(RqMethod.POST)
            .fetch().as(RestResponse.class)
            .assertStatus(HttpURLConnection.HTTP_BAD_METHOD)
    );
}