io.vertx.reactivex.ext.web.client.HttpResponse Java Examples
The following examples show how to use
io.vertx.reactivex.ext.web.client.HttpResponse.
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: WebClientTest.java From vertx-rx with Apache License 2.0 | 6 votes |
@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(); } }
Example #2
Source File: Code10.java From rxjava2-lab with Apache License 2.0 | 6 votes |
public static void main(String[] args) { SuperHeroesService.run(); Single<JsonObject> request1 = client() .get("/heroes") .rxSend() .map(HttpResponse::bodyAsJsonObject); request1 // Transform the response to retrieve a stream of ids. .flatMapObservable(j -> Observable.fromIterable(j.fieldNames())) // Take the first one .take(1) // this is an observable of 1 element // Second request .flatMapSingle(Code10::getHero) // Print the result .subscribe(json -> System.out.println(json.encodePrettily())); }
Example #3
Source File: CongratsTest.java From vertx-in-action with MIT License | 6 votes |
@Test @DisplayName("No email must be sent below 10k steps") void checkNothingBelow10k(Vertx vertx, VertxTestContext testContext) { producer .rxSend(record("123", 5000)) .ignoreElement() .delay(3, TimeUnit.SECONDS, RxHelper.scheduler(vertx)) .andThen(webClient .get(8025, "localhost", "/api/v2/search?kind=to&[email protected]") .as(BodyCodec.jsonObject()).rxSend()) .map(HttpResponse::body) .subscribe( json -> { testContext.verify(() -> assertThat(json.getInteger("total")).isEqualTo(0)); testContext.completeNow(); }, testContext::failNow); }
Example #4
Source File: Code13_Solution.java From rxjava2-lab with Apache License 2.0 | 6 votes |
public static void main(String[] args) { SuperHeroesService.run(); Single<Character> random_heroes = client() .get("/heroes/random") .as(BodyCodec.json(Character.class)) .rxSend() .map(HttpResponse::body); Single<Character> random_villains = client() .get("/villains/random") .as(BodyCodec.json(Character.class)) .rxSend() .map(HttpResponse::body); random_heroes.zipWith(random_villains, (h, v) -> fight(h, v)) .subscribe(j -> System.out.println(j.encodePrettily())); }
Example #5
Source File: Code13.java From rxjava2-lab with Apache License 2.0 | 6 votes |
public static void main(String[] args) { SuperHeroesService.run(); Single<Character> random_heroes = client() .get("/heroes/random") .as(BodyCodec.json(Character.class)) .rxSend() .map(HttpResponse::body); Single<Character> random_villains = client() .get("/villains/random") .as(BodyCodec.json(Character.class)) .rxSend() .map(HttpResponse::body); // Associate the items emitted by both single and call the fight method. // In the subscribe print the returned json object (using encodePrettily). }
Example #6
Source File: Code5_Solution.java From rxjava2-lab with Apache License 2.0 | 6 votes |
public static void main(String[] args) { SuperHeroesService.run(); String name1 = "Yoda"; String name2 = "clement"; client().get("/heroes").rxSend() .map(HttpResponse::bodyAsJsonObject) .filter(json -> contains(name1, json)) .subscribe( x -> System.out.println("Yes, " + name1 + " is a super hero"), Throwable::printStackTrace, () -> System.out.println("No, " + name1 + " is not a super hero") ); client().get("/heroes").rxSend() .map(HttpResponse::bodyAsJsonObject) .filter(json -> contains(name2, json)) .subscribe( x -> System.out.println("Yes, " + name2 + " is a super hero"), Throwable::printStackTrace, () -> System.out.println("No, " + name2 + " is not a super hero") ); }
Example #7
Source File: Code5.java From rxjava2-lab with Apache License 2.0 | 6 votes |
public static void main(String[] args) { SuperHeroesService.run(); String name1 = "Yoda"; String name2 = "clement"; client().get("/heroes").rxSend() .map(HttpResponse::bodyAsJsonObject) // Use the filter operator and contains to check if the is a hero named `name1` // Don't forget to subscribe ; client().get("/heroes").rxSend() .map(HttpResponse::bodyAsJsonObject) // Use the filter operator and contains to check if the is a hero named `name2` // Don't forget to subscribe ; }
Example #8
Source File: MyResource.java From redpipe with Apache License 2.0 | 6 votes |
@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"); }
Example #9
Source File: DashboardWebAppVerticle.java From vertx-in-action with MIT License | 6 votes |
private void hydrate() { WebClient webClient = WebClient.create(vertx); webClient .get(3001, "localhost", "/ranking-last-24-hours") .as(BodyCodec.jsonArray()) .rxSend() .delay(5, TimeUnit.SECONDS, RxHelper.scheduler(vertx)) .retry(5) .map(HttpResponse::body) .flattenAsFlowable(Functions.identity()) .cast(JsonObject.class) .flatMapSingle(json -> whoOwnsDevice(webClient, json)) .flatMapSingle(json -> fillWithUserProfile(webClient, json)) .subscribe( this::hydrateEntryIfPublic, err -> logger.error("Hydratation error", err), () -> logger.info("Hydratation completed")); }
Example #10
Source File: MyResource.java From redpipe with Apache License 2.0 | 6 votes |
@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; }
Example #11
Source File: MyResource.java From redpipe with Apache License 2.0 | 6 votes |
@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()); }
Example #12
Source File: MyResource.java From redpipe with Apache License 2.0 | 6 votes |
@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()); }
Example #13
Source File: MyResource.java From redpipe with Apache License 2.0 | 6 votes |
@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(); }); }
Example #14
Source File: PortfolioServiceImpl.java From vertx-kubernetes-workshop with Apache License 2.0 | 6 votes |
private Single<Double> getValueForCompany(WebClient client, String company, int numberOfShares) { //TODO //---- return client.get("/?name=" + encode(company)) .as(BodyCodec.jsonObject()) .rxSend() .map(HttpResponse::body) .map(json -> json.getDouble("bid")) .map(val -> val * numberOfShares); // return Single.just(0.0); // --- }
Example #15
Source File: MyResource.java From redpipe with Apache License 2.0 | 6 votes |
@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; }
Example #16
Source File: WebClientTest.java From vertx-rx with Apache License 2.0 | 6 votes |
@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(); } }
Example #17
Source File: WebClientTest.java From vertx-rx with Apache License 2.0 | 6 votes |
@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(); } }
Example #18
Source File: WebClientTest.java From vertx-rx with Apache License 2.0 | 6 votes |
@Test public void testPost() { int times = 5; waitFor(times); HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080)); server.requestStream().handler(req -> req.bodyHandler(buff -> { assertEquals("onetwothree", buff.toString()); req.response().end(); })); try { server.listen(ar -> { client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions())); Observable<Buffer> stream = Observable.just(Buffer.buffer("one"), Buffer.buffer("two"), Buffer.buffer("three")); Single<HttpResponse<Buffer>> single = client .post(8080, "localhost", "/the_uri") .rxSendStream(stream); for (int i = 0; i < times; i++) { single.subscribe(resp -> complete(), this::fail); } }); await(); } finally { server.close(); } }
Example #19
Source File: WebClientTest.java From vertx-rx with Apache License 2.0 | 6 votes |
@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(); } }
Example #20
Source File: DynamicClientRegistrationServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void create_sectorIdentifierUri_validRedirectUri() { final String redirectUri = "https://graviee.io/callback"; final String sectorUri = "https://sector/uri"; DynamicClientRegistrationRequest request = new DynamicClientRegistrationRequest(); request.setRedirectUris(Optional.of(Arrays.asList(redirectUri))); request.setSectorIdentifierUri(Optional.of(sectorUri)); HttpRequest<Buffer> httpRequest = Mockito.mock(HttpRequest.class); HttpResponse httpResponse = Mockito.mock(HttpResponse.class); when(webClient.getAbs(sectorUri)).thenReturn(httpRequest); when(httpRequest.rxSend()).thenReturn(Single.just(httpResponse)); when(httpResponse.bodyAsString()).thenReturn("[\""+redirectUri+"\"]"); TestObserver<Client> testObserver = dcrService.create(request, BASE_PATH).test(); testObserver.assertNoErrors(); testObserver.assertComplete(); }
Example #21
Source File: DynamicClientRegistrationServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void create_sectorIdentifierUri_invalidRedirectUri() { final String sectorUri = "https://sector/uri"; DynamicClientRegistrationRequest request = new DynamicClientRegistrationRequest(); request.setRedirectUris(Optional.of(Arrays.asList("https://graviee.io/callback"))); request.setSectorIdentifierUri(Optional.of(sectorUri));//fail due to invalid url HttpRequest<Buffer> httpRequest = Mockito.mock(HttpRequest.class); HttpResponse httpResponse = Mockito.mock(HttpResponse.class); when(webClient.getAbs(sectorUri)).thenReturn(httpRequest); when(httpRequest.rxSend()).thenReturn(Single.just(httpResponse)); when(httpResponse.bodyAsString()).thenReturn("[\"https://not/same/redirect/uri\"]"); TestObserver<Client> testObserver = dcrService.create(request, BASE_PATH).test(); testObserver.assertError(InvalidRedirectUriException.class); testObserver.assertNotComplete(); }
Example #22
Source File: DynamicClientRegistrationServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void create_sectorIdentifierUriBadRequest() { final String sectorUri = "https://sector/uri"; DynamicClientRegistrationRequest request = new DynamicClientRegistrationRequest(); request.setRedirectUris(Optional.empty()); request.setSectorIdentifierUri(Optional.of(sectorUri));//fail due to invalid url HttpRequest<Buffer> httpRequest = Mockito.mock(HttpRequest.class); HttpResponse httpResponse = Mockito.mock(HttpResponse.class); when(webClient.getAbs(sectorUri)).thenReturn(httpRequest); when(httpRequest.rxSend()).thenReturn(Single.just(httpResponse)); TestObserver<Client> testObserver = dcrService.create(request, BASE_PATH).test(); testObserver.assertError(InvalidClientMetadataException.class); testObserver.assertNotComplete(); assertTrue("Should have only one exception", testObserver.errorCount()==1); assertTrue("Unexpected start of error message", testObserver.errors().get(0).getMessage().startsWith("Unable to parse sector_identifier_uri")); }
Example #23
Source File: JWKServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void testGetClientKeys_fromJksUriProperty() { Client client = new Client(); client.setJwksUri(JWKS_URI); HttpRequest<Buffer> request = Mockito.mock(HttpRequest.class); HttpResponse<Buffer> response = Mockito.mock(HttpResponse.class); String bodyAsString = "{\"keys\":[{\"kty\": \"RSA\",\"use\": \"enc\",\"kid\": \"KID\",\"n\": \"modulus\",\"e\": \"exponent\"}]}"; when(webClient.getAbs(any())).thenReturn(request); when(request.rxSend()).thenReturn(Single.just(response)); when(response.bodyAsString()).thenReturn(bodyAsString); TestObserver testObserver = jwkService.getKeys(client).test(); testObserver.assertNoErrors(); testObserver.assertComplete(); testObserver.assertValue(jwkSet -> ((JWKSet)jwkSet).getKeys().get(0).getKid().equals("KID")); }
Example #24
Source File: JWKServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void testGetKeys() { HttpRequest<Buffer> request = Mockito.mock(HttpRequest.class); HttpResponse<Buffer> response = Mockito.mock(HttpResponse.class); String bodyAsString = "{\"keys\":[{\"kty\": \"RSA\",\"use\": \"enc\",\"kid\": \"KID\",\"n\": \"modulus\",\"e\": \"exponent\"}]}"; when(webClient.getAbs(any())).thenReturn(request); when(request.rxSend()).thenReturn(Single.just(response)); when(response.bodyAsString()).thenReturn(bodyAsString); TestObserver testObserver = jwkService.getKeys(JWKS_URI).test(); testObserver.assertNoErrors(); testObserver.assertComplete(); testObserver.assertValue(jwkSet -> ((JWKSet)jwkSet).getKeys().get(0).getKid().equals("KID")); }
Example #25
Source File: MyResource.java From redpipe with Apache License 2.0 | 6 votes |
@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(); }); }
Example #26
Source File: EventStatsVerticle.java From vertx-in-action with MIT License | 5 votes |
private Single<JsonObject> addOwnerData(JsonObject data) { String username = data.getString("username"); return webClient .get(3000, "localhost", "/" + username) .as(BodyCodec.jsonObject()) .rxSend() .map(HttpResponse::body) .map(data::mergeIn); }
Example #27
Source File: CurrencyServiceProxy.java From vertx-kubernetes-workshop with Apache License 2.0 | 5 votes |
/** * Example of method not using a circuit breaker. * * @param rc the routing context */ private void delegate(RoutingContext rc) { HttpEndpoint.rxGetWebClient(discovery, svc -> svc.getName().equals("currency-3rdparty-service")) .flatMap(client -> client.post("/").rxSendJsonObject(rc.getBodyAsJson())) .map(HttpResponse::bodyAsBuffer) .subscribe(toObserver(rc)); }
Example #28
Source File: PublicApiVerticle.java From vertx-in-action with MIT License | 5 votes |
private Single<HttpResponse<JsonObject>> fetchUserDetails(String username) { return webClient .get(3000, "localhost", "/" + username) .expect(ResponsePredicate.SC_OK) .as(BodyCodec.jsonObject()) .rxSend(); }
Example #29
Source File: EventStatsVerticle.java From vertx-in-action with MIT License | 5 votes |
private Single<JsonObject> addDeviceOwner(KafkaConsumerRecord<String, JsonObject> record) { JsonObject data = record.value(); return webClient .get(3000, "localhost", "/owns/" + data.getString("deviceId")) .as(BodyCodec.jsonObject()) .rxSend() .map(HttpResponse::body) .map(data::mergeIn); }
Example #30
Source File: RequestObjectServiceImpl.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Override public Single<JWT> readRequestObjectFromURI(String requestUri, Client client) { try { if (requestUri.startsWith(RESOURCE_OBJECT_URN_PREFIX)) { // Extract the identifier String identifier = requestUri.substring(RESOURCE_OBJECT_URN_PREFIX.length()); return requestObjectRepository.findById(identifier) .switchIfEmpty(Single.error(new InvalidRequestObjectException())) .flatMap((Function<RequestObject, Single<JWT>>) req -> { if (req.getExpireAt().after(new Date())) { return readRequestObject(req.getPayload(), client); } return Single.error(new InvalidRequestObjectException()); }); } else { return webClient.getAbs(UriBuilder.fromHttpUrl(requestUri).build().toString()) .rxSend() .map(HttpResponse::bodyAsString) .flatMap((Function<String, Single<JWT>>) s -> readRequestObject(s, client)); } } catch (IllegalArgumentException | URISyntaxException ex) { return Single.error(new InvalidRequestObjectException(requestUri+" is not valid.")); } }