Java Code Examples for io.vertx.core.http.HttpClientRequest#exceptionHandler()
The following examples show how to use
io.vertx.core.http.HttpClientRequest#exceptionHandler() .
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: VertxNonceRequestTransmitter.java From ethsigner with Apache License 2.0 | 6 votes |
private CompletableFuture<BigInteger> getNonceFromWeb3Provider( final JsonRpcRequest requestBody, final MultiMap headers) { requestBody.setId(new JsonRpcRequestId(nextId.getAndIncrement())); final CompletableFuture<BigInteger> result = new CompletableFuture<>(); final HttpClientRequest request = client.request( HttpMethod.POST, downstreamPathCalculator.calculateDownstreamPath("/"), response -> response.bodyHandler(responseBody -> handleResponse(responseBody, result))); request.setTimeout(requestTimeout.toMillis()); request.headers().setAll(headers); request.exceptionHandler(result::completeExceptionally); request.headers().remove("Content-Length"); // created during 'end'. request.setChunked(false); request.end(Json.encode(requestBody)); LOG.info("Transmitted {}", Json.encode(requestBody)); return result; }
Example 2
Source File: OkapiClientTest.java From okapi with Apache License 2.0 | 6 votes |
@Test public void testHttpClientLegacy1(TestContext context) { Async async = context.async(); StringBuilder b = new StringBuilder(); context.assertTrue(server != null); HttpClient client = vertx.createHttpClient(); HttpClientRequest requestAbs = HttpClientLegacy.requestAbs(client, HttpMethod.GET, URL + "/test1", res -> { b.append("response"); context.assertEquals(200, res.statusCode()); async.complete(); }); requestAbs.exceptionHandler(res -> { b.append("exception"); async.complete(); }); requestAbs.end(); async.await(); context.assertEquals("response", b.toString()); }
Example 3
Source File: OkapiClientTest.java From okapi with Apache License 2.0 | 6 votes |
@Test public void testHttpClientLegacy2(TestContext context) { Async async = context.async(); StringBuilder b = new StringBuilder(); context.assertTrue(server != null); HttpClient client = vertx.createHttpClient(); HttpClientRequest requestAbs = HttpClientLegacy.requestAbs(client, HttpMethod.GET, BAD_URL + "/test1", res -> { b.append("response"); async.complete(); }); requestAbs.exceptionHandler(res -> { b.append("exception"); async.complete(); }); requestAbs.end(); async.await(); context.assertEquals("exception", b.toString()); }
Example 4
Source File: DockerModuleHandle.java From okapi with Apache License 2.0 | 6 votes |
void postUrlJson(String url, String msg, String doc, Handler<AsyncResult<Void>> future) { HttpClientRequest req = request(HttpMethod.POST, url, res -> { Buffer body = Buffer.buffer(); res.exceptionHandler(d -> future.handle(Future.failedFuture(d.getCause()))); res.handler(body::appendBuffer); res.endHandler(d -> { if (res.statusCode() >= 200 && res.statusCode() <= 201) { containerId = body.toJsonObject().getString("Id"); future.handle(Future.succeededFuture()); } else { String m = msg + " HTTP error " + res.statusCode() + "\n" + body.toString(); logger.error(m); future.handle(Future.failedFuture(m)); } }); }); req.exceptionHandler(d -> future.handle(Future.failedFuture(d.getCause()))); req.putHeader("Content-Type", "application/json"); req.end(doc); }
Example 5
Source File: OkapiClientTest.java From okapi with Apache License 2.0 | 6 votes |
@Test public void testHttpClientLegacy4(TestContext context) { Async async = context.async(); StringBuilder b = new StringBuilder(); context.assertTrue(server != null); HttpClient client = vertx.createHttpClient(); SocketAddress sa = SocketAddress.inetSocketAddress(PORT + 1, LOCALHOST); HttpClientRequest requestAbs = HttpClientLegacy.requestAbs(client, HttpMethod.GET, sa, URL + "/test1", res -> { b.append("response"); async.complete(); }); requestAbs.exceptionHandler(res -> { b.append("exception"); async.complete(); }); requestAbs.end(); async.await(); context.assertEquals("exception", b.toString()); }
Example 6
Source File: OkapiClientTest.java From okapi with Apache License 2.0 | 6 votes |
@Test public void testHttpClientLegacy5(TestContext context) { Async async = context.async(); StringBuilder b = new StringBuilder(); context.assertTrue(server != null); HttpClient client = vertx.createHttpClient(); HttpClientRequest requestAbs = HttpClientLegacy.get(client, PORT, LOCALHOST, URL + "/test1", res -> { b.append("response"); async.complete(); }); requestAbs.exceptionHandler(res -> { b.append("exception"); async.complete(); }); requestAbs.end(); async.await(); context.assertEquals("response", b.toString()); }
Example 7
Source File: OkapiClientTest.java From okapi with Apache License 2.0 | 6 votes |
@Test public void testHttpClientLegacy6(TestContext context) { Async async = context.async(); StringBuilder b = new StringBuilder(); context.assertTrue(server != null); HttpClient client = vertx.createHttpClient(); HttpClientRequest requestAbs = HttpClientLegacy.delete(client, PORT, LOCALHOST, URL + "/test1", res -> { b.append("response"); async.complete(); }); requestAbs.exceptionHandler(res -> { b.append("exception"); async.complete(); }); requestAbs.end(); async.await(); context.assertEquals("response", b.toString()); }
Example 8
Source File: PauseResumeTest.java From okapi with Apache License 2.0 | 6 votes |
private void myStreamHandle2(RoutingContext ctx) { ctx.request().pause(); HttpClient cli = vertx.createHttpClient(); HttpClientRequest req = cli.post(PORT, "localhost", "/test1", res -> { if (ctx.request().isEnded()) { ctx.response().end("OK2"); // Vert.x 3.6 series } else { ctx.request().endHandler(x -> { ctx.response().end("OK2"); }); } ctx.request().resume(); }); req.exceptionHandler(x -> { ctx.response().setStatusCode(500); ctx.response().end(x.getLocalizedMessage()); }); req.end(); }
Example 9
Source File: DockerModuleHandle.java From okapi with Apache License 2.0 | 6 votes |
private void getContainerLog(Handler<AsyncResult<Void>> future) { final String url = "/containers/" + containerId + "/logs?stderr=1&stdout=1&follow=1"; HttpClientRequest req = request(HttpMethod.GET, url, res -> { if (res.statusCode() == 200) { // stream OK. Continue other work but keep fetching! // remove 8 bytes of binary data and final newline res.handler(this::logHandler); tcpPortWaiting.waitReady(null, future); } else { String m = "getContainerLog HTTP error " + res.statusCode(); logger.error(m); future.handle(Future.failedFuture(m)); } }); req.exceptionHandler(d -> future.handle(Future.failedFuture(d.getCause()))); req.end(); }
Example 10
Source File: DemoRamlRestTest.java From raml-module-builder with Apache License 2.0 | 5 votes |
public Buffer checkURLs(TestContext context, String url, int codeExpected, String accept) { Buffer res = Buffer.buffer(); try { Async async = context.async(); HttpClient client = vertx.createHttpClient(); HttpClientRequest request = client.getAbs(url, httpClientResponse -> { httpClientResponse.handler(res::appendBuffer); httpClientResponse.endHandler(x -> { log.info(httpClientResponse.statusCode() + ", " + codeExpected + " status expected: " + url); context.assertEquals(codeExpected, httpClientResponse.statusCode(), url); log.info(res.toString()); async.complete(); }); }); request.exceptionHandler(error -> { context.fail(url + " - " + error.getMessage()); async.complete(); }); request.headers().add("x-okapi-tenant", TENANT); request.headers().add("Accept", accept); request.setChunked(true); request.end(); async.await(); } catch (Throwable e) { log.error(e.getMessage(), e); context.fail(e); } return res; }
Example 11
Source File: DockerTest.java From okapi with Apache License 2.0 | 5 votes |
private void checkDocker(Handler<AsyncResult<JsonArray>> future) { final SocketAddress socketAddress = SocketAddress.domainSocketAddress("/var/run/docker.sock"); final String url = "http://localhost/images/json?all=1"; HttpClientRequest req = HttpClientLegacy.requestAbs(client, HttpMethod.GET, socketAddress, url, res -> { Buffer body = Buffer.buffer(); res.handler(d -> { body.appendBuffer(d); }); res.endHandler(d -> { if (res.statusCode() == 200) { boolean gotIt = false; try { JsonArray ar = body.toJsonArray(); future.handle(Future.succeededFuture(ar)); } catch (Exception ex) { logger.warn(ex); future.handle(Future.failedFuture(ex)); } } else { String m = "checkDocker HTTP error " + res.statusCode() + "\n" + body.toString(); logger.error(m); future.handle(Future.failedFuture(m)); } }); res.exceptionHandler(d -> { logger.warn("exceptionHandler 2 " + d, d); future.handle(Future.failedFuture(d)); }); }); req.exceptionHandler(d -> { logger.warn("exceptionHandler 1 " + d, d); future.handle(Future.failedFuture(d)); }); req.end(); }
Example 12
Source File: DockerModuleHandle.java From okapi with Apache License 2.0 | 5 votes |
void getUrl(String url, Handler<AsyncResult<JsonObject>> future) { HttpClientRequest req = request(HttpMethod.GET, url, res -> { Buffer body = Buffer.buffer(); res.exceptionHandler(d -> { logger.warn("{}: {}", url, d.getMessage()); future.handle(Future.failedFuture(url + ": " + d.getMessage())); }); res.handler(body::appendBuffer); res.endHandler(d -> { if (res.statusCode() == 200) { JsonObject b = body.toJsonObject(); logger.info(b.encodePrettily()); future.handle(Future.succeededFuture(b)); } else { String m = url + " HTTP error " + res.statusCode() + "\n" + body.toString(); logger.error(m); future.handle(Future.failedFuture(m)); } }); }); req.exceptionHandler(e -> { Throwable cause = e.getCause() == null ? e : e.getCause(); String msg = url + ": " + e.getMessage() + " - " + cause.getClass().getName(); logger.warn(msg); future.handle(Future.failedFuture(msg)); }); req.end(); }
Example 13
Source File: DockerModuleHandle.java From okapi with Apache License 2.0 | 5 votes |
void deleteUrl(String url, String msg, Handler<AsyncResult<Void>> future) { HttpClientRequest req = request(HttpMethod.DELETE, url, res -> handle204(res, msg, future)); req.exceptionHandler(d -> future.handle(Future.failedFuture(d.getCause()))); req.end(); }
Example 14
Source File: DockerModuleHandle.java From okapi with Apache License 2.0 | 5 votes |
void postUrl(String url, String msg, Handler<AsyncResult<Void>> future) { HttpClientRequest req = request(HttpMethod.POST, url, res -> handle204(res, msg, future)); req.exceptionHandler(d -> future.handle(Future.failedFuture(d.getCause()))); req.end(); }
Example 15
Source File: PauseResumeTest.java From okapi with Apache License 2.0 | 5 votes |
@Test public void test4(TestContext context) { Async async = context.async(); HttpClient cli = vertx.createHttpClient(); HttpClientRequest req = HttpClientLegacy.post(cli, PORT, "localhostxxx", "/test2", res -> { context.assertTrue(false); async.complete(); }); req.exceptionHandler(res -> { context.assertTrue(res.getMessage().contains("localhostxxx"), res.getMessage()); async.complete(); }); req.end(); async.await(); }
Example 16
Source File: TypeScriptVerticleTest.java From vertx-lang-typescript with Apache License 2.0 | 5 votes |
private void makeRequest(HttpClient client, int port, int retries, int delay, Handler<AsyncResult<Buffer>> handler) { Vertx vertx = runTestOnContext.vertx(); HttpClientRequest request = client.get(port, "localhost", "/", response -> response.bodyHandler(buffer -> handler.handle(Future.succeededFuture(buffer)))); request.exceptionHandler(t -> { if (retries > 0 && t instanceof ConnectException) { vertx.setTimer(delay, l -> makeRequest(client, port, retries - 1, delay, handler)); } else { handler.handle(Future.failedFuture(t)); } }); request.end(); }
Example 17
Source File: ProxyVerticle.java From quarantyne with Apache License 2.0 | 4 votes |
private void proxiedRequestHandler(HttpServerRequest frontReq, @Nullable Buffer frontReqBody) { HttpServerResponse frontRep = frontReq.response(); CaseInsensitiveStringKV frontReqHeaders = new CaseInsensitiveStringKV(frontReq.headers().entries()); // inject quarantyne headers, if any HttpRequest qReq = new HttpRequest( HttpRequestMethod.valueOf(frontReq.method().toString().toUpperCase()), frontReqHeaders, RemoteIpAddressesParser.parse(frontReqHeaders, frontReq.remoteAddress().host()), frontReq.path() ); @Nullable final HttpRequestBody qBody = getBody(qReq.getMethod(), frontReqBody, frontReq.getHeader(HttpHeaders.CONTENT_TYPE)); Set<Label> quarantyneLabels = quarantyneClassifier.classify(qReq, qBody); if (configSupplier.get().isBlocked(quarantyneLabels)) { log.info("blocking request {} because we are blocking {}", qReq.getFingerprint(), quarantyneLabels); bouncer.bounce(frontRep); } else { HttpClientRequest backReq = httpClient.request( frontReq.method(), frontReq.uri() ); backReq.headers().setAll(frontReq.headers()); backReq.headers().set(HttpHeaders.HOST, configArgs.getEgress().getHost()); backReq.headers().addAll(quarantyneCheck(quarantyneLabels)); // -------------------------------- backReq.handler(backRep -> { Buffer body = Buffer.buffer(); backRep.handler(body::appendBuffer); backRep.endHandler(h -> { // callback quarantyne with data to record, if needed quarantyneClassifier.record(new HttpResponse(backRep.statusCode()), qReq, qBody); // -------------------------------- frontRep.setStatusCode(backRep.statusCode()); frontRep.headers().setAll(backRep.headers()); frontRep.end(body); }); }); backReq.exceptionHandler(ex -> { log.error("error while querying downstream service", ex); frontRep.setStatusCode(500); frontRep.end("Internal Server Error. This request cannot be satisfied."); }); if (frontReqBody != null) { backReq.end(frontReqBody); } else { backReq.end(); } } }
Example 18
Source File: VertxHttpClient.java From feign-vertx with Apache License 2.0 | 4 votes |
/** * Executes HTTP request and returns {@link Future} with response. * * @param request request * @return future of HTTP response */ public Future<Response> execute(final Request request) { checkNotNull(request, "Argument request must be not null"); final HttpClientRequest httpClientRequest; try { httpClientRequest = makeHttpClientRequest(request); } catch (final MalformedURLException unexpectedException) { return Future.failedFuture(unexpectedException); } final Future<Response> responseFuture = Future.future(); httpClientRequest.exceptionHandler(responseFuture::fail); httpClientRequest.handler(response -> { final Map<String, Collection<String>> responseHeaders = StreamSupport .stream(response.headers().spliterator(), false) .collect(Collectors.groupingBy( Map.Entry::getKey, Collectors.mapping( Map.Entry::getValue, Collectors.toCollection(ArrayList::new)))); response.exceptionHandler(responseFuture::fail); response.bodyHandler(body -> { final Response feignResponse = Response.create( response.statusCode(), response.statusMessage(), responseHeaders, body.getBytes()); responseFuture.complete(feignResponse); }); }); /* Write body if exists */ if (request.body() != null) { httpClientRequest.write(Buffer.buffer(request.body())); } httpClientRequest.end(); return responseFuture; }
Example 19
Source File: HttpProvider.java From gravitee-management-rest-api with Apache License 2.0 | 4 votes |
@Override public CompletableFuture<Collection<DynamicProperty>> get() { CompletableFuture<Buffer> future = new VertxCompletableFuture<>(vertx); URI requestUri = URI.create(configuration.getUrl()); boolean ssl = HTTPS_SCHEME.equalsIgnoreCase(requestUri.getScheme()); final HttpClientOptions options = new HttpClientOptions() .setSsl(ssl) .setTrustAll(true) .setMaxPoolSize(1) .setKeepAlive(false) .setTcpKeepAlive(false) .setConnectTimeout(2000); final HttpClient httpClient = vertx.createHttpClient(options); final int port = requestUri.getPort() != -1 ? requestUri.getPort() : (HTTPS_SCHEME.equals(requestUri.getScheme()) ? 443 : 80); try { HttpClientRequest request = httpClient.request( HttpMethod.GET, port, requestUri.getHost(), requestUri.toString() ); request.putHeader(HttpHeaders.USER_AGENT, NodeUtils.userAgent(node)); request.putHeader("X-Gravitee-Request-Id", RandomString.generate()); if (configuration.getHeaders() != null) { configuration.getHeaders().forEach(httpHeader -> request.putHeader(httpHeader.getName(), httpHeader.getValue())); } request.handler(response -> { if (response.statusCode() == HttpStatusCode.OK_200) { response.bodyHandler(buffer -> { future.complete(buffer); // Close client httpClient.close(); }); } else { future.complete(null); } }); request.exceptionHandler(event -> { try { future.completeExceptionally(event); // Close client httpClient.close(); } catch (IllegalStateException ise) { // Do not take care about exception when closing client } }); request.end(); } catch (Exception ex) { logger.error("Unable to look for dynamic properties", ex); future.completeExceptionally(ex); } return future.thenApply(buffer -> { if (buffer == null) { return null; } return mapper.map(buffer.toString()); }); }
Example 20
Source File: HttpProvider.java From gravitee-management-rest-api with Apache License 2.0 | 4 votes |
@Override public CompletableFuture<Collection<DynamicProperty>> get() { CompletableFuture<Buffer> future = new VertxCompletableFuture<>(vertx); URI requestUri = URI.create(dpConfiguration.getUrl()); boolean ssl = HTTPS_SCHEME.equalsIgnoreCase(requestUri.getScheme()); final HttpClientOptions options = new HttpClientOptions() .setSsl(ssl) .setTrustAll(true) .setMaxPoolSize(1) .setKeepAlive(false) .setTcpKeepAlive(false) .setConnectTimeout(2000); final HttpClient httpClient = vertx.createHttpClient(options); final int port = requestUri.getPort() != -1 ? requestUri.getPort() : (HTTPS_SCHEME.equals(requestUri.getScheme()) ? 443 : 80); try { HttpClientRequest request = httpClient.request( HttpMethod.GET, port, requestUri.getHost(), requestUri.toString() ); request.putHeader(HttpHeaders.USER_AGENT, NodeUtils.userAgent(node)); request.putHeader("X-Gravitee-Request-Id", RandomString.generate()); request.handler(response -> { if (response.statusCode() == HttpStatusCode.OK_200) { response.bodyHandler(buffer -> { future.complete(buffer); // Close client httpClient.close(); }); } else { future.complete(null); } }); request.exceptionHandler(event -> { try { future.completeExceptionally(event); // Close client httpClient.close(); } catch (IllegalStateException ise) { // Do not take care about exception when closing client } }); request.end(); } catch (Exception ex) { logger.error("Unable to look for dynamic properties", ex); future.completeExceptionally(ex); } return future.thenApply(buffer -> { if (buffer == null) { return null; } return mapper.map(buffer.toString()); }); }