List of usage examples for io.vertx.core.http HttpClientRequest exceptionHandler
@Override HttpClientRequest exceptionHandler(Handler<Throwable> handler);
From source file:examples.HTTP2Examples.java
License:Open Source License
public void example12(HttpClientRequest request) { request.exceptionHandler(err -> { if (err instanceof StreamResetException) { StreamResetException reset = (StreamResetException) err; System.out.println("Stream reset " + reset.getCode()); }/*from w ww . j av a 2s. c om*/ }); }
From source file:examples.HTTPExamples.java
License:Open Source License
public void example42(HttpClient client) { HttpClientRequest request = client.post("some-uri", response -> { System.out.println("Received response with status code " + response.statusCode()); });// www.ja va 2 s .co m request.exceptionHandler(e -> { System.out.println("Received exception: " + e.getMessage()); e.printStackTrace(); }); }
From source file:io.advantageous.qbit.vertx.http.client.HttpVertxClient.java
License:Apache License
@Override public void sendHttpRequest(final HttpRequest request) { checkClosed();//from w w w . j av a2 s.co m if (trace) { logger.debug(sputs("HTTP CLIENT: sendHttpRequest:: \n{}\n", request, "\nparams\n", request.params())); } final String uri = getURICreateParamsIfNeeded(request); final HttpMethod httpMethod = HttpMethod.valueOf(request.getMethod()); final HttpClientRequest httpClientRequest = httpClient.request(httpMethod, uri, httpClientResponse -> handleResponse(request, httpClientResponse)); final MultiMap<String, String> headers = request.getHeaders(); httpClientRequest.exceptionHandler(error -> { if (error instanceof ConnectException) { closed.set(true); try { stop(); } catch (Exception ex) { errorHandler.accept(ex); logger.warn("Unable to stop client " + "after failed connection", ex); } request.getReceiver().errorWithCode("\"Client connection was closed\"", HttpStatus.SERVICE_UNAVAILABLE); logger.warn("Connection error", error); } else { logger.error("Unable to connect to " + host + " port " + port, error); } errorHandler.accept(error); }); if (headers != null) { for (String key : headers.keySet()) { httpClientRequest.putHeader(key, headers.getAll(key)); } } final byte[] body = request.getBody(); if (keepAlive) { httpClientRequest.putHeader(HttpHeaders.CONNECTION, HttpHeaders.KEEP_ALIVE); } if (body != null && body.length > 0) { httpClientRequest.putHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(body.length)); if (request.getContentType() != null) { httpClientRequest.putHeader("Content-Type", request.getContentType()); } httpClientRequest.end(Buffer.buffer(request.getBody())); } else { httpClientRequest.end(); } if (trace) logger.trace("HttpClientVertx::SENT \n{}", request); }
From source file:io.apiman.gateway.platforms.vertx3.components.HttpClientComponentImpl.java
License:Apache License
@Override public IHttpClientRequest request(String endpoint, HttpMethod method, IAsyncResultHandler<IHttpClientResponse> responseHandler) { URL pEndpoint = parseEndpoint(endpoint); int port = pEndpoint.getPort(); String proto = pEndpoint.getProtocol(); HttpClient client;/*from w w w . ja v a 2s. c o m*/ // If protocol provided if (port != -1 || proto != null) { if (port == 443 || "https".equals(proto)) { //$NON-NLS-1$ client = sslClient; port = (port == -1) ? 443 : port; } else { client = plainClient; port = (port == -1) ? 80 : port; } } else { client = plainClient; port = 80; } HttpClientRequest request = client.request(convertMethod(method), pEndpoint.getPort(), pEndpoint.getHost(), pEndpoint.getFile(), new HttpClientResponseImpl(responseHandler)); request.setChunked(true); request.exceptionHandler(exception -> { logger.error("Exception in HttpClientRequestImpl: {0}", exception.getMessage()); //$NON-NLS-1$ responseHandler.handle(AsyncResultImpl.create(exception)); }); return new HttpClientRequestImpl(request); }
From source file:io.apiman.gateway.platforms.vertx3.engine.VertxPluginRegistry.java
License:Apache License
/** * @see io.apiman.gateway.engine.impl.DefaultPluginRegistry#downloadArtifactTo(java.net.URL, java.io.File, * io.apiman.gateway.engine.async.IAsyncResultHandler) *///from ww w. j av a 2 s . c om @Override protected void downloadArtifactTo(final URL artifactUrl, final File pluginFile, final IAsyncResultHandler<File> handler) { int port = artifactUrl.getPort(); if (port == -1) { port = 80; } final HttpClientRequest request = client.get(port, artifactUrl.getHost(), artifactUrl.getPath(), (Handler<HttpClientResponse>) response -> { response.exceptionHandler((Handler<Throwable>) error -> { handler.handle(AsyncResultImpl.create(error, File.class)); }); // Body Handler response.handler((Handler<Buffer>) buffer -> { try { Files.write(pluginFile.toPath(), buffer.getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE, StandardOpenOption.WRITE); } catch (IOException e) { handler.handle(AsyncResultImpl.create(e, File.class)); } }); response.endHandler((Handler<Void>) event -> { handler.handle(AsyncResultImpl.create(pluginFile)); }); }); request.exceptionHandler((Handler<Throwable>) error -> { handler.handle(AsyncResultImpl.create(error, File.class)); }); request.end(); }
From source file:io.gravitee.fetcher.http.HttpFetcher.java
License:Apache License
private CompletableFuture<Buffer> fetchContent() { CompletableFuture<Buffer> future = new VertxCompletableFuture<>(vertx); URI requestUri = URI.create(httpFetcherConfiguration.getUrl()); boolean ssl = HTTPS_SCHEME.equalsIgnoreCase(requestUri.getScheme()); final HttpClientOptions options = new HttpClientOptions().setSsl(ssl).setTrustAll(true).setMaxPoolSize(1) .setKeepAlive(false).setTcpKeepAlive(false).setConnectTimeout(httpClientTimeout); if (httpFetcherConfiguration.isUseSystemProxy()) { ProxyOptions proxyOptions = new ProxyOptions(); proxyOptions.setType(ProxyType.valueOf(httpClientProxyType)); if (HTTPS_SCHEME.equals(requestUri.getScheme())) { proxyOptions.setHost(httpClientProxyHttpsHost); proxyOptions.setPort(httpClientProxyHttpsPort); proxyOptions.setUsername(httpClientProxyHttpsUsername); proxyOptions.setPassword(httpClientProxyHttpsPassword); } else {//from w ww.ja va 2s . co m proxyOptions.setHost(httpClientProxyHttpHost); proxyOptions.setPort(httpClientProxyHttpPort); proxyOptions.setUsername(httpClientProxyHttpUsername); proxyOptions.setPassword(httpClientProxyHttpPassword); } options.setProxyOptions(proxyOptions); } 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.setTimeout(httpClientTimeout); 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 fetch content using HTTP", ex); future.completeExceptionally(ex); } return future; }
From source file:io.gravitee.gateway.http.connector.VertxHttpClient.java
License:Apache License
@Override public ProxyConnection request(ProxyRequest proxyRequest) { HttpClient httpClient = httpClients.computeIfAbsent(Vertx.currentContext(), createHttpClient()); // Remove hop-by-hop headers. if (!proxyRequest.isWebSocket()) { for (CharSequence header : HOP_HEADERS) { proxyRequest.headers().remove(header); }//from ww w. ja v a2 s . co m } else { for (CharSequence header : WS_HOP_HEADERS) { proxyRequest.headers().remove(header); } } final URI uri = proxyRequest.uri(); final int port = uri.getPort() != -1 ? uri.getPort() : (HTTPS_SCHEME.equals(uri.getScheme()) ? 443 : 80); final String host = (port == DEFAULT_HTTP_PORT || port == DEFAULT_HTTPS_PORT) ? uri.getHost() : uri.getHost() + ':' + port; proxyRequest.headers().set(HttpHeaders.HOST, host); // Apply headers from endpoint if (endpoint.getHeaders() != null && !endpoint.getHeaders().isEmpty()) { endpoint.getHeaders().forEach(proxyRequest.headers()::set); } String relativeUri = (uri.getRawQuery() == null) ? uri.getRawPath() : uri.getRawPath() + '?' + uri.getRawQuery(); if (proxyRequest.isWebSocket()) { VertxWebSocketProxyConnection webSocketProxyConnection = new VertxWebSocketProxyConnection(); WebSocketProxyRequest wsProxyRequest = (WebSocketProxyRequest) proxyRequest; httpClient.websocket(port, uri.getHost(), relativeUri, new Handler<WebSocket>() { @Override public void handle(WebSocket event) { // The client -> gateway connection must be upgraded now that the one between gateway -> upstream // has been accepted wsProxyRequest.upgrade(); // From server to client wsProxyRequest.frameHandler(frame -> { if (frame.type() == io.gravitee.gateway.api.ws.WebSocketFrame.Type.BINARY) { event.writeBinaryMessage(io.vertx.core.buffer.Buffer.buffer(frame.data().getBytes())); } else if (frame.type() == io.gravitee.gateway.api.ws.WebSocketFrame.Type.TEXT) { event.writeTextMessage(frame.data().toString()); } }); wsProxyRequest.closeHandler(result -> event.close()); // From client to server event.frameHandler(frame -> wsProxyRequest.write(new VertxWebSocketFrame(frame))); event.closeHandler(event1 -> wsProxyRequest.close()); event.exceptionHandler(new Handler<Throwable>() { @Override public void handle(Throwable throwable) { wsProxyRequest.reject(HttpStatusCode.BAD_REQUEST_400); ProxyResponse clientResponse = new EmptyProxyResponse(HttpStatusCode.BAD_REQUEST_400); clientResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE); webSocketProxyConnection.handleResponse(clientResponse); } }); // Tell the reactor that the request has been handled by the HTTP client webSocketProxyConnection.handleResponse(new SwitchProtocolProxyResponse()); } }, throwable -> { if (throwable instanceof WebsocketRejectedException) { wsProxyRequest.reject(((WebsocketRejectedException) throwable).getStatus()); ProxyResponse clientResponse = new EmptyProxyResponse( ((WebsocketRejectedException) throwable).getStatus()); clientResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE); webSocketProxyConnection.handleResponse(clientResponse); } else { wsProxyRequest.reject(HttpStatusCode.BAD_GATEWAY_502); ProxyResponse clientResponse = new EmptyProxyResponse(HttpStatusCode.BAD_GATEWAY_502); clientResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE); webSocketProxyConnection.handleResponse(clientResponse); } }); return webSocketProxyConnection; } else { // Prepare HTTP request HttpClientRequest clientRequest = httpClient.request(HttpMethod.valueOf(proxyRequest.method().name()), port, uri.getHost(), relativeUri); clientRequest.setTimeout(endpoint.getHttpClientOptions().getReadTimeout()); clientRequest.setFollowRedirects(endpoint.getHttpClientOptions().isFollowRedirects()); if (proxyRequest.method() == io.gravitee.common.http.HttpMethod.OTHER) { clientRequest.setRawMethod(proxyRequest.rawMethod()); } VertxProxyConnection proxyConnection = new VertxProxyConnection(proxyRequest, clientRequest); clientRequest.handler( clientResponse -> handleClientResponse(proxyConnection, clientResponse, clientRequest)); clientRequest.connectionHandler(connection -> { connection.exceptionHandler(ex -> { // I don't want to fill my logs with error }); }); clientRequest.exceptionHandler(event -> { if (!proxyConnection.isCanceled() && !proxyConnection.isTransmitted()) { proxyRequest.metrics().setMessage(event.getMessage()); if (proxyConnection.timeoutHandler() != null && (event instanceof ConnectException || event instanceof TimeoutException || event instanceof NoRouteToHostException || event instanceof UnknownHostException)) { proxyConnection.handleConnectTimeout(event); } else { ProxyResponse clientResponse = new EmptyProxyResponse( ((event instanceof ConnectTimeoutException) || (event instanceof TimeoutException)) ? HttpStatusCode.GATEWAY_TIMEOUT_504 : HttpStatusCode.BAD_GATEWAY_502); clientResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE); proxyConnection.handleResponse(clientResponse); } } }); return proxyConnection; } }
From source file:io.gravitee.gateway.http.vertx.VertxHttpClient.java
License:Apache License
@Override public ClientRequest request(io.gravitee.common.http.HttpMethod method, URI uri, HttpHeaders headers, Handler<ClientResponse> responseHandler) { HttpClient httpClient = httpClients.computeIfAbsent(Vertx.currentContext(), createHttpClient()); final int port = uri.getPort() != -1 ? uri.getPort() : (HTTPS_SCHEME.equals(uri.getScheme()) ? 443 : 80); String relativeUri = (uri.getRawQuery() == null) ? uri.getRawPath() : uri.getRawPath() + '?' + uri.getRawQuery(); HttpClientRequest clientRequest = httpClient.request(convert(method), port, uri.getHost(), relativeUri, clientResponse -> handleClientResponse(clientResponse, responseHandler)); clientRequest.setTimeout(endpoint.getHttpClientOptions().getReadTimeout()); VertxClientRequest invokerRequest = new VertxClientRequest(clientRequest); clientRequest.exceptionHandler(event -> { LOGGER.error("Server proxying failed: {}", event.getMessage()); if (invokerRequest.connectTimeoutHandler() != null && event instanceof ConnectTimeoutException) { invokerRequest.connectTimeoutHandler().handle(event); } else {//from w ww.j a va 2 s. c o m VertxClientResponse clientResponse = new VertxClientResponse( ((event instanceof ConnectTimeoutException) || (event instanceof TimeoutException)) ? HttpStatusCode.GATEWAY_TIMEOUT_504 : HttpStatusCode.BAD_GATEWAY_502); clientResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE); Buffer buffer = null; if (event.getMessage() != null) { // Create body content with error message buffer = Buffer.buffer(event.getMessage()); clientResponse.headers().set(HttpHeaders.CONTENT_LENGTH, Integer.toString(buffer.length())); } responseHandler.handle(clientResponse); if (buffer != null) { clientResponse.bodyHandler().handle(buffer); } clientResponse.endHandler().handle(null); } }); // Copy headers to final API copyRequestHeaders(headers, clientRequest, (port == 80 || port == 443) ? uri.getHost() : uri.getHost() + ':' + port); // Check chunk flag on the request if there are some content to push and if transfer_encoding is set // with chunk value if (hasContent(headers)) { String transferEncoding = headers.getFirst(HttpHeaders.TRANSFER_ENCODING); if (HttpHeadersValues.TRANSFER_ENCODING_CHUNKED.equalsIgnoreCase(transferEncoding)) { clientRequest.setChunked(true); } } // Send HTTP head as soon as possible clientRequest.sendHead(); return invokerRequest; }
From source file:io.gravitee.gateway.services.healthcheck.http.HttpEndpointRuleHandler.java
License:Apache License
@Override public void handle(Long timer) { HttpEndpoint endpoint = (HttpEndpoint) rule.endpoint(); logger.debug("Running health-check for endpoint: {} [{}]", endpoint.getName(), endpoint.getTarget()); // Run request for each step for (io.gravitee.definition.model.services.healthcheck.Step step : rule.steps()) { try {//from w w w. ja va 2 s . c o m URI hcRequestUri = create(endpoint.getTarget(), step.getRequest()); // Prepare HTTP client HttpClientOptions httpClientOptions = new HttpClientOptions().setMaxPoolSize(1).setKeepAlive(false) .setTcpKeepAlive(false); if (endpoint.getHttpClientOptions() != null) { httpClientOptions .setIdleTimeout((int) (endpoint.getHttpClientOptions().getIdleTimeout() / 1000)) .setConnectTimeout((int) endpoint.getHttpClientOptions().getConnectTimeout()) .setTryUseCompression(endpoint.getHttpClientOptions().isUseCompression()); } // Configure HTTP proxy HttpProxy proxy = endpoint.getHttpProxy(); if (proxy != null && proxy.isEnabled()) { ProxyOptions proxyOptions = new ProxyOptions().setHost(proxy.getHost()).setPort(proxy.getPort()) .setUsername(proxy.getUsername()).setPassword(proxy.getPassword()) .setType(ProxyType.valueOf(proxy.getType().name())); httpClientOptions.setProxyOptions(proxyOptions); } HttpClientSslOptions sslOptions = endpoint.getHttpClientSslOptions(); if (HTTPS_SCHEME.equalsIgnoreCase(hcRequestUri.getScheme())) { // Configure SSL httpClientOptions.setSsl(true); if (sslOptions != null) { httpClientOptions.setVerifyHost(sslOptions.isHostnameVerifier()) .setTrustAll(sslOptions.isTrustAll()); // Client trust configuration if (!sslOptions.isTrustAll() && sslOptions.getTrustStore() != null) { switch (sslOptions.getTrustStore().getType()) { case PEM: PEMTrustStore pemTrustStore = (PEMTrustStore) sslOptions.getTrustStore(); PemTrustOptions pemTrustOptions = new PemTrustOptions(); if (pemTrustStore.getPath() != null && !pemTrustStore.getPath().isEmpty()) { pemTrustOptions.addCertPath(pemTrustStore.getPath()); } else if (pemTrustStore.getContent() != null && !pemTrustStore.getContent().isEmpty()) { pemTrustOptions.addCertValue( io.vertx.core.buffer.Buffer.buffer(pemTrustStore.getContent())); } else { throw new EndpointException( "Missing PEM certificate value for endpoint " + endpoint.getName()); } httpClientOptions.setPemTrustOptions(pemTrustOptions); break; case PKCS12: PKCS12TrustStore pkcs12TrustStore = (PKCS12TrustStore) sslOptions.getTrustStore(); PfxOptions pfxOptions = new PfxOptions(); pfxOptions.setPassword(pkcs12TrustStore.getPassword()); if (pkcs12TrustStore.getPath() != null && !pkcs12TrustStore.getPath().isEmpty()) { pfxOptions.setPath(pkcs12TrustStore.getPath()); } else if (pkcs12TrustStore.getContent() != null && !pkcs12TrustStore.getContent().isEmpty()) { pfxOptions.setValue( io.vertx.core.buffer.Buffer.buffer(pkcs12TrustStore.getContent())); } else { throw new EndpointException( "Missing PKCS12 value for endpoint " + endpoint.getName()); } httpClientOptions.setPfxTrustOptions(pfxOptions); break; case JKS: JKSTrustStore jksTrustStore = (JKSTrustStore) sslOptions.getTrustStore(); JksOptions jksOptions = new JksOptions(); jksOptions.setPassword(jksTrustStore.getPassword()); if (jksTrustStore.getPath() != null && !jksTrustStore.getPath().isEmpty()) { jksOptions.setPath(jksTrustStore.getPath()); } else if (jksTrustStore.getContent() != null && !jksTrustStore.getContent().isEmpty()) { jksOptions.setValue( io.vertx.core.buffer.Buffer.buffer(jksTrustStore.getContent())); } else { throw new EndpointException( "Missing JKS value for endpoint " + endpoint.getName()); } httpClientOptions.setTrustStoreOptions(jksOptions); break; } } // Client authentication configuration if (sslOptions.getKeyStore() != null) { switch (sslOptions.getKeyStore().getType()) { case PEM: PEMKeyStore pemKeyStore = (PEMKeyStore) sslOptions.getKeyStore(); PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions(); if (pemKeyStore.getCertPath() != null && !pemKeyStore.getCertPath().isEmpty()) { pemKeyCertOptions.setCertPath(pemKeyStore.getCertPath()); } else if (pemKeyStore.getCertContent() != null && !pemKeyStore.getCertContent().isEmpty()) { pemKeyCertOptions.setCertValue( io.vertx.core.buffer.Buffer.buffer(pemKeyStore.getCertContent())); } if (pemKeyStore.getKeyPath() != null && !pemKeyStore.getKeyPath().isEmpty()) { pemKeyCertOptions.setKeyPath(pemKeyStore.getKeyPath()); } else if (pemKeyStore.getKeyContent() != null && !pemKeyStore.getKeyContent().isEmpty()) { pemKeyCertOptions.setKeyValue( io.vertx.core.buffer.Buffer.buffer(pemKeyStore.getKeyContent())); } httpClientOptions.setPemKeyCertOptions(pemKeyCertOptions); break; case PKCS12: PKCS12KeyStore pkcs12KeyStore = (PKCS12KeyStore) sslOptions.getKeyStore(); PfxOptions pfxOptions = new PfxOptions(); pfxOptions.setPassword(pkcs12KeyStore.getPassword()); if (pkcs12KeyStore.getPath() != null && !pkcs12KeyStore.getPath().isEmpty()) { pfxOptions.setPath(pkcs12KeyStore.getPath()); } else if (pkcs12KeyStore.getContent() != null && !pkcs12KeyStore.getContent().isEmpty()) { pfxOptions.setValue( io.vertx.core.buffer.Buffer.buffer(pkcs12KeyStore.getContent())); } httpClientOptions.setPfxKeyCertOptions(pfxOptions); break; case JKS: JKSKeyStore jksKeyStore = (JKSKeyStore) sslOptions.getKeyStore(); JksOptions jksOptions = new JksOptions(); jksOptions.setPassword(jksKeyStore.getPassword()); if (jksKeyStore.getPath() != null && !jksKeyStore.getPath().isEmpty()) { jksOptions.setPath(jksKeyStore.getPath()); } else if (jksKeyStore.getContent() != null && !jksKeyStore.getContent().isEmpty()) { jksOptions .setValue(io.vertx.core.buffer.Buffer.buffer(jksKeyStore.getContent())); } httpClientOptions.setKeyStoreOptions(jksOptions); break; } } } } HttpClient httpClient = vertx.createHttpClient(httpClientOptions); final int port = hcRequestUri.getPort() != -1 ? hcRequestUri.getPort() : (HTTPS_SCHEME.equals(hcRequestUri.getScheme()) ? 443 : 80); String relativeUri = (hcRequestUri.getRawQuery() == null) ? hcRequestUri.getRawPath() : hcRequestUri.getRawPath() + '?' + hcRequestUri.getRawQuery(); // Run health-check HttpClientRequest healthRequest = httpClient.request( HttpMethod.valueOf(step.getRequest().getMethod().name().toUpperCase()), port, hcRequestUri.getHost(), relativeUri); // Set timeout on request if (endpoint.getHttpClientOptions() != null) { healthRequest.setTimeout(endpoint.getHttpClientOptions().getReadTimeout()); } // Prepare request if (step.getRequest().getHeaders() != null) { step.getRequest().getHeaders().forEach( httpHeader -> healthRequest.headers().set(httpHeader.getName(), httpHeader.getValue())); } final EndpointStatus.Builder healthBuilder = EndpointStatus .forEndpoint(rule.api(), endpoint.getName()).on(currentTimeMillis()); long startTime = currentTimeMillis(); Request request = new Request(); request.setMethod(step.getRequest().getMethod()); request.setUri(hcRequestUri.toString()); healthRequest.handler(response -> response.bodyHandler(buffer -> { long endTime = currentTimeMillis(); logger.debug("Health-check endpoint returns a response with a {} status code", response.statusCode()); String body = buffer.toString(); EndpointStatus.StepBuilder stepBuilder = validateAssertions(step, new EvaluableHttpResponse(response, body)); stepBuilder.request(request); stepBuilder.responseTime(endTime - startTime); Response healthResponse = new Response(); healthResponse.setStatus(response.statusCode()); // If validation fail, store request and response data if (!stepBuilder.isSuccess()) { request.setBody(step.getRequest().getBody()); if (step.getRequest().getHeaders() != null) { HttpHeaders reqHeaders = new HttpHeaders(); step.getRequest().getHeaders().forEach(httpHeader -> reqHeaders .put(httpHeader.getName(), Collections.singletonList(httpHeader.getValue()))); request.setHeaders(reqHeaders); } // Extract headers HttpHeaders headers = new HttpHeaders(); response.headers().names().forEach( headerName -> headers.put(headerName, response.headers().getAll(headerName))); healthResponse.setHeaders(headers); // Store body healthResponse.setBody(body); } stepBuilder.response(healthResponse); // Append step stepBuilder healthBuilder.step(stepBuilder.build()); report(healthBuilder.build()); // Close client httpClient.close(); })); healthRequest.exceptionHandler(event -> { long endTime = currentTimeMillis(); EndpointStatus.StepBuilder stepBuilder = EndpointStatus.forStep(step.getName()); stepBuilder.fail(event.getMessage()); Response healthResponse = new Response(); // Extract request information request.setBody(step.getRequest().getBody()); if (step.getRequest().getHeaders() != null) { HttpHeaders reqHeaders = new HttpHeaders(); step.getRequest().getHeaders().forEach(httpHeader -> reqHeaders.put(httpHeader.getName(), Collections.singletonList(httpHeader.getValue()))); request.setHeaders(reqHeaders); } if (event instanceof ConnectTimeoutException) { stepBuilder.fail(event.getMessage()); healthResponse.setStatus(HttpStatusCode.REQUEST_TIMEOUT_408); } else { healthResponse.setStatus(HttpStatusCode.SERVICE_UNAVAILABLE_503); } Step result = stepBuilder.build(); result.setResponse(healthResponse); result.setRequest(request); result.setResponseTime(endTime - startTime); // Append step result healthBuilder.step(result); report(healthBuilder.build()); try { // Close client httpClient.close(); } catch (IllegalStateException ise) { // Do not take care about exception when closing client } }); // Send request logger.debug("Execute health-check request: {}", healthRequest); if (step.getRequest().getBody() != null && !step.getRequest().getBody().isEmpty()) { healthRequest.end(step.getRequest().getBody()); } else { healthRequest.end(); } } catch (EndpointException ee) { logger.error("An error occurs while configuring the endpoint " + endpoint.getName() + ". Healthcheck is skipped for this endpoint.", ee); } catch (Exception ex) { logger.error("An unexpected error occurs", ex); } } }
From source file:io.gravitee.resource.oauth2.am.OAuth2AMResource.java
License:Apache License
@Override public void introspect(String accessToken, Handler<OAuth2Response> responseHandler) { HttpClient httpClient = httpClients.computeIfAbsent(Vertx.currentContext(), context -> vertx.createHttpClient(httpClientOptions)); logger.debug("Introspect access token by requesting {}", introspectionEndpointURI); HttpClientRequest request = httpClient.post(introspectionEndpointURI); request.headers().add(HttpHeaders.AUTHORIZATION, introspectionEndpointAuthorization); request.headers().add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); request.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); request.handler(response -> response.bodyHandler(buffer -> { logger.debug("AM Introspection endpoint returns a response with a {} status code", response.statusCode());// w w w. ja v a 2s. c o m if (response.statusCode() == HttpStatusCode.OK_200) { // Introspection Response for AM v2 always returns HTTP 200 // with an "active" boolean indicator of whether or not the presented token is currently active. if (configuration().getVersion() == OAuth2ResourceConfiguration.Version.V2_X) { // retrieve active indicator JsonObject jsonObject = buffer.toJsonObject(); boolean active = jsonObject.getBoolean(INTROSPECTION_ACTIVE_INDICATOR, false); responseHandler.handle(new OAuth2Response(active, (active) ? buffer.toString() : "{\"error\": \"Invalid Access Token\"}")); } else { responseHandler.handle(new OAuth2Response(true, buffer.toString())); } } else { responseHandler.handle(new OAuth2Response(false, buffer.toString())); } })); request.exceptionHandler(event -> { logger.error("An error occurs while checking access_token", event); responseHandler.handle(new OAuth2Response(false, event.getMessage())); }); request.end("token=" + accessToken); }