@Override public void start() throws Exception { WebClient client = WebClient.create(vertx); client.get(80, "perdu.com", "/") .rxSend() .map(HttpResponse::bodyAsString) .subscribe( s -> LOGGER.info("From web client: " + s), Throwable::printStackTrace ); } }
@Override public void start() throws Exception { WebClient client = WebClient.create(vertx); Single<HttpResponse<String>> request = client.get(8080, "localhost", "/") .as(BodyCodec.string()) .rxSend(); // Fire the request request.subscribe(resp -> System.out.println("Server content " + resp.body())); // Again request.subscribe(resp -> System.out.println("Server content " + resp.body())); // And again request.subscribe(resp -> System.out.println("Server content " + resp.body())); } }
@Override public void start() throws Exception { WebClient client = WebClient.create(vertx); Single<HttpResponse<Data>> request = client.get(8080, "localhost", "/") .as(BodyCodec.json(Data.class)) .rxSend(); // Fire the request request.subscribe(resp -> System.out.println("Server content " + resp.body().message)); // Again request.subscribe(resp -> System.out.println("Server content " + resp.body().message)); // And again request.subscribe(resp -> System.out.println("Server content " + resp.body().message)); } }
@Override public void start() throws Exception { // Create two requests WebClient client = WebClient.create(vertx); Single<JsonObject> request = client.get(8080, "localhost", "/") .as(BodyCodec.jsonObject()) .rxSend() .map(resp -> resp.body()); // Combine the responses with the zip into a single response request .zipWith(request, (b1, b2) -> new JsonObject().put("req1", b1).put("req2", b2)) .subscribe(json -> { System.out.println("Got combined result " + json); }, err -> { err.printStackTrace(); }); } }
@Override public Single<Integer> getVersion() throws ElasticsearchException { return httpClient .get(URL_ROOT) .rxSend() .doOnError(throwable -> logger.error("Unable to get a connection to Elasticsearch", throwable)) .map(response -> mapper.readTree(response.bodyAsString()).path("version").path("number").asText()) .map(sVersion -> { float result = Float.valueOf(sVersion.substring(0, 3)); int version = Integer.valueOf(sVersion.substring(0, 1)); if (result < 2) { logger.warn("Please upgrade to Elasticsearch 2 or later. version={}", version); } return version; }); }
/** * Get the cluster health * * @return the cluster health * @throws ElasticsearchException error occurs during ES call */ @Override public Single<Health> getClusterHealth() { return httpClient .get(URL_STATE_CLUSTER) .rxSend() .map(response -> mapper.readValue(response.bodyAsString(), Health.class)); }
private Single<String> get(Vertx vertx, URI uri){ WebClient client = WebClient.create(vertx); Single<HttpResponse<Buffer>> responseHandler = client.get(uri.getPort(), uri.getHost(), uri.getPath()).rxSend(); return responseHandler.map(response -> response.body().toString()) .doAfterTerminate(() -> client.close()); }
@Path("7error") @GET public CompletionStage<String> hello7Error(@Context Vertx vertx){ io.vertx.reactivex.core.Vertx rxVertx = io.vertx.reactivex.core.Vertx.newInstance(vertx); System.err.println("Creating client"); WebClientOptions options = new WebClientOptions(); options.setSsl(true); options.setTrustAll(true); options.setVerifyHost(false); WebClient client = WebClient.create(rxVertx, options); Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443, "www.google.com", "/robots.txt").rxSend(); CompletableFuture<String> ret = new CompletableFuture<>(); responseHandler .doAfterTerminate(() -> client.close()) .subscribe(body -> { System.err.println("Got body"); ret.completeExceptionally(new MyException()); }); System.err.println("Created client"); return ret; }
@Path("7") @GET public CompletionStage<String> hello7(@Context Vertx vertx){ io.vertx.reactivex.core.Vertx rxVertx = io.vertx.reactivex.core.Vertx.newInstance(vertx); System.err.println("Creating client"); WebClientOptions options = new WebClientOptions(); options.setSsl(true); options.setTrustAll(true); options.setVerifyHost(false); WebClient client = WebClient.create(rxVertx, options); Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443, "www.google.com", "/robots.txt").rxSend(); CompletableFuture<String> ret = new CompletableFuture<>(); responseHandler .doAfterTerminate(() -> client.close()) .subscribe(body -> { System.err.println("Got body"); ret.complete(body.body().toString()); }); System.err.println("Created client"); return ret; }
@Path("coroutines/1") @GET public Single<Response> helloAsync(@Context io.vertx.reactivex.core.Vertx rxVertx){ return Fibers.fiber(() -> { System.err.println("Creating client"); WebClientOptions options = new WebClientOptions(); options.setSsl(true); options.setTrustAll(true); options.setVerifyHost(false); WebClient client = WebClient.create(rxVertx, options); Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443, "www.google.com", "/robots.txt").rxSend(); System.err.println("Got response"); HttpResponse<io.vertx.reactivex.core.buffer.Buffer> httpResponse = Fibers.await(responseHandler); System.err.println("Got body"); client.close(); return Response.ok(httpResponse.body().toString()).build(); }); } }
@Path("8error") @GET public Single<String> hello8Error(@Context io.vertx.reactivex.core.Vertx rxVertx){ System.err.println("Creating client"); WebClientOptions options = new WebClientOptions(); options.setSsl(true); options.setTrustAll(true); options.setVerifyHost(false); WebClient client = WebClient.create(rxVertx, options); Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443, "www.google.com", "/robots.txt").rxSend(); System.err.println("Created client"); return responseHandler .doAfterTerminate(() -> client.close()) .map(body -> { System.err.println("Got body"); throw new MyException(); }); }
@Path("8") @GET public Single<String> hello8(@Context io.vertx.reactivex.core.Vertx rxVertx){ System.err.println("Creating client"); WebClientOptions options = new WebClientOptions(); options.setSsl(true); options.setTrustAll(true); options.setVerifyHost(false); WebClient client = WebClient.create(rxVertx, options); Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443, "www.google.com", "/robots.txt").rxSend(); System.err.println("Created client"); return responseHandler.map(body -> { System.err.println("Got body"); return body.body().toString(); }).doAfterTerminate(() -> client.close()); }
@Path("8user") @Produces("text/json") @GET public Single<DataClass> hello8User(@Context io.vertx.reactivex.core.Vertx rxVertx){ System.err.println("Creating client"); WebClientOptions options = new WebClientOptions(); options.setSsl(true); options.setTrustAll(true); options.setVerifyHost(false); WebClient client = WebClient.create(rxVertx, options); Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443, "www.google.com", "/robots.txt").rxSend(); System.err.println("Created client"); return responseHandler.map(body -> { System.err.println("Got body"); return new DataClass(body.body().toString()); }).doAfterTerminate(() -> client.close()); }
@Path("6") @GET public void hello6(@Suspended final AsyncResponse asyncResponse, // Inject the Vertx instance @Context Vertx vertx){ io.vertx.reactivex.core.Vertx rxVertx = io.vertx.reactivex.core.Vertx.newInstance(vertx); System.err.println("Creating client"); WebClientOptions options = new WebClientOptions(); options.setSsl(true); options.setTrustAll(true); options.setVerifyHost(false); WebClient client = WebClient.create(rxVertx, options); Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443, "www.google.com", "/robots.txt").rxSend(); responseHandler .doAfterTerminate(() -> client.close()) .subscribe(body -> { System.err.println("Got body"); asyncResponse.resume(Response.ok(body.body().toString()).build()); }); System.err.println("Created client"); }
@Test public void testErrorHandling() throws Exception { try { client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions())); Single<HttpResponse<WineAndCheese>> single = client .get(-1, "localhost", "/the_uri") .as(BodyCodec.json(WineAndCheese.class)) .rxSend(); single.subscribe(resp -> fail(), error -> { assertEquals(IllegalArgumentException.class, error.getClass()); testComplete(); }); await(); } catch (Throwable t) { fail(); } } }
@Test @KnotxApplyConfiguration("io/knotx/server/test-server-csrf.json") public void whenRequestingGetLocalPath_expectLocalAC( VertxTestContext context, Vertx vertx) { createPassThroughKnot(vertx, "test-splitter"); createPassThroughKnot(vertx, "test-assembler"); createSimpleKnot(vertx, "some-knot", "test", null); WebClient client = WebClient.create(vertx); Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> httpResponseSingle = client .get(KNOTX_SERVER_PORT, KNOTX_SERVER_ADDRESS, "/content/local/simple.html") .rxSend(); subscribeToResult_shouldSucceed(context, httpResponseSingle, response -> { assertEquals(HttpResponseStatus.OK.code(), response.statusCode()); assertTrue(response.getHeader(EXPECTED_RESPONSE_HEADER) != null); assertEquals(EXPECTED_XSERVER_HEADER_VALUE, response.getHeader(EXPECTED_RESPONSE_HEADER)); assertTrue(response.cookies().stream() .anyMatch(cookie -> cookie.contains(CSRFHandler.DEFAULT_COOKIE_NAME))); }); }
private void testGetRequest(VertxTestContext context, Vertx vertx, String url, String expectedResult) { WebClient client = WebClient.create(vertx); Single<HttpResponse<Buffer>> httpResponseSingle = client .get(KNOTX_SERVER_PORT, KNOTX_SERVER_ADDRESS, url).rxSend(); subscribeToResult_shouldSucceed(context, httpResponseSingle, resp -> { assertEquals(expectedResult, resp.body().toString(), "Wrong engines processed request, expected " + expectedResult); assertEquals(HttpResponseStatus.OK.code(), resp.statusCode()); assertNotNull(resp.getHeader(EXPECTED_RESPONSE_HEADER)); assertEquals(EXPECTED_XSERVER_HEADER_VALUE, resp.getHeader(EXPECTED_RESPONSE_HEADER)); }); }
@Test public void testResponseBodyAsAsJsonMapped() throws Exception { JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu"); HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080)); server.requestStream().handler(req -> req.response().end(expected.encode())); try { server.listen(ar -> { client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions())); Single<HttpResponse<WineAndCheese>> single = client .get(8080, "localhost", "/the_uri") .as(BodyCodec.json(WineAndCheese.class)) .rxSend(); single.subscribe(resp -> { assertEquals(200, resp.statusCode()); assertEquals(new WineAndCheese().setCheese("Goat Cheese").setWine("Condrieu"), resp.body()); testComplete(); }, this::fail); }); await(); } finally { server.close(); } }
@Test public void testResponseMissingBody() throws Exception { int times = 5; waitFor(times); HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080)); server.requestStream().handler(req -> req.response().setStatusCode(403).end()); try { server.listen(ar -> { client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions())); Single<HttpResponse<Buffer>> single = client .get(8080, "localhost", "/the_uri") .rxSend(); for (int i = 0; i < times; i++) { single.subscribe(resp -> { assertEquals(403, resp.statusCode()); assertNull(resp.body()); complete(); }, this::fail); } }); await(); } finally { server.close(); } }
@Test public void testGet() { int times = 5; waitFor(times); HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080)); server.requestStream().handler(req -> req.response().setChunked(true).end("some_content")); try { server.listen(ar -> { client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions())); Single<HttpResponse<Buffer>> single = client .get(8080, "localhost", "/the_uri") .as(BodyCodec.buffer()) .rxSend(); for (int i = 0; i < times; i++) { single.subscribe(resp -> { Buffer body = resp.body(); assertEquals("some_content", body.toString("UTF-8")); complete(); }, this::fail); } }); await(); } finally { server.close(); } }