Example usage for io.vertx.core.http HttpClientResponse exceptionHandler

List of usage examples for io.vertx.core.http HttpClientResponse exceptionHandler

Introduction

In this page you can find the example usage for io.vertx.core.http HttpClientResponse exceptionHandler.

Prototype

@Override
    HttpClientResponse exceptionHandler(Handler<Throwable> handler);

Source Link

Usage

From source file:com.hubrick.vertx.rest.impl.DefaultRestClientRequest.java

License:Apache License

private void handleResponse(HttpClientResponse httpClientResponse, Class clazz) {
    final Integer firstStatusDigit = httpClientResponse.statusCode() / 100;
    if (firstStatusDigit == 4 || firstStatusDigit == 5) {
        httpClientResponse.bodyHandler((buffer) -> {
            httpClientResponse.exceptionHandler(null);
            if (log.isWarnEnabled()) {
                final String body = new String(buffer.getBytes(), Charsets.UTF_8);
                log.warn("Http request to {} FAILED. Return status: {}, message: {}, body: {}", new Object[] {
                        uri, httpClientResponse.statusCode(), httpClientResponse.statusMessage(), body });
            }//from w w w  .j  a v  a2 s  . com

            RuntimeException exception = null;
            switch (firstStatusDigit) {
            case 4:
                exception = new HttpClientErrorException(httpClientResponse, httpMessageConverters,
                        buffer.getBytes());
                break;
            case 5:
                exception = new HttpServerErrorException(httpClientResponse, httpMessageConverters,
                        buffer.getBytes());
                break;
            }
            handleException(exception);
        });
    } else {
        httpClientResponse.bodyHandler((buffer) -> {
            httpClientResponse.exceptionHandler(null);
            if (log.isDebugEnabled()) {
                final String body = new String(buffer.getBytes(), Charsets.UTF_8);
                log.debug("Http request to {} {} SUCCESSFUL. Return status: {}, message: {}, body: {}",
                        new Object[] { method, uri, httpClientResponse.statusCode(),
                                httpClientResponse.statusMessage(), body });
            }

            final RestClientResponse<T> restClientResponse = new DefaultRestClientResponse(
                    httpMessageConverters, clazz, buffer.getBytes(), httpClientResponse, exceptionHandler);

            handleResponse(restClientResponse);
        });
    }
}

From source file:io.apiman.gateway.platforms.vertx3.connector.HttpConnector.java

License:Apache License

private void doConnection() {
    String endpoint = ApimanPathUtils.join(apiPath, destination + queryParams(apiRequest.getQueryParams()));
    logger.debug(String.format("Connecting to %s | port: %d verb: %s path: %s", apiHost, apiPort,
            HttpMethod.valueOf(apiRequest.getType()), endpoint));

    clientRequest = client.request(HttpMethod.valueOf(apiRequest.getType()), apiPort, apiHost, endpoint,
            (HttpClientResponse vxClientResponse) -> {
                clientResponse = vxClientResponse;

                // Pause until we're given permission to xfer the response.
                vxClientResponse.pause();

                apiResponse = HttpApiFactory.buildResponse(vxClientResponse, SUPPRESSED_HEADERS);

                vxClientResponse.handler((Handler<Buffer>) chunk -> {
                    bodyHandler.handle(new VertxApimanBuffer(chunk));
                });//w  ww  .  j av  a 2  s. c  om

                vxClientResponse.endHandler((Handler<Void>) v -> {
                    endHandler.handle((Void) null);
                });

                vxClientResponse.exceptionHandler(exceptionHandler);

                // The response is only ever returned when vxClientResponse is valid.
                resultHandler.handle(AsyncResultImpl.create((IApiConnectionResponse) HttpConnector.this));
            });

    clientRequest.exceptionHandler(exceptionHandler);

    if (options.hasDataPolicy()) {
        clientRequest.headers().remove("Content-Length");
        clientRequest.setChunked(true);
    }

    apiRequest.getHeaders().forEach(e -> clientRequest.headers().add(e.getKey(), e.getValue()));

    addMandatoryRequestHeaders(clientRequest.headers());

    if (options.getRequiredAuthType() == RequiredAuthType.BASIC) {
        clientRequest.putHeader("Authorization",
                Basic.encode(basicOptions.getUsername(), basicOptions.getPassword()));
    }
}

From source file:io.gravitee.gateway.http.connector.VertxHttpClient.java

License:Apache License

private void handleClientResponse(final VertxProxyConnection proxyConnection,
        final HttpClientResponse clientResponse, final HttpClientRequest clientRequest) {
    VertxProxyResponse proxyClientResponse = new VertxProxyResponse(clientResponse);
    proxyConnection.setProxyResponse(proxyClientResponse);

    // Copy HTTP headers
    clientResponse.headers().names().forEach(headerName -> proxyClientResponse.headers().put(headerName,
            clientResponse.headers().getAll(headerName)));

    proxyClientResponse.pause();/*from   w  w w.  jav a2  s  . co m*/

    // Copy body content
    clientResponse.handler(event -> proxyClientResponse.bodyHandler().handle(Buffer.buffer(event.getBytes())));

    // Signal end of the response
    clientResponse.endHandler(v -> proxyClientResponse.endHandler().handle(null));

    clientResponse.exceptionHandler(throwable -> {
        LOGGER.error("Unexpected error while handling backend response for request {} {} - {}",
                clientRequest.method(), clientRequest.absoluteURI(), throwable.getMessage());
        ProxyResponse clientResponse1 = new EmptyProxyResponse(HttpStatusCode.BAD_GATEWAY_502);

        proxyConnection.handleResponse(clientResponse1);
    });

    proxyConnection.handleResponse(proxyClientResponse);
}

From source file:io.nitor.api.backend.msgraph.GraphQueryHandler.java

License:Apache License

private void mapResponse(HttpClientResponse cres, HttpServerResponse sres, String clientRequestId) {
    cres.exceptionHandler(t -> {
        logger.error("Error processing graph request [" + clientRequestId + "]", t);
        if (!sres.ended()) {
            sres.setStatusCode(BAD_GATEWAY.code());
            sres.end();//from w w w.j  a  v a  2 s .co m
        }
    });

    // TODO Together with the client-request-id always log the request-id, timestamp and x-ms-ags-diagnostic from the HTTP response headers

    sres.setStatusCode(cres.statusCode());
    sres.setStatusMessage(cres.statusMessage());

    MultiMap headers = sres.headers();
    cres.headers().forEach(entry -> {
        String key = entry.getKey();
        String lKey = key.toLowerCase();
        if ("server".equals(lKey) || "accept-ranges".equals(lKey) || "transfer-encoding".equals(lKey)
                || "date".equals(lKey) || "connection".equals(lKey)) {
            return;
        }
        headers.add(key, entry.getValue());
    });

    if (!headers.contains("content-length")) {
        sres.setChunked(true);
    }

    Pump resPump = Pump.pump(cres, sres);
    cres.endHandler(v -> {
        if (!sres.ended())
            sres.end();
    });
    resPump.start();
}

From source file:io.nitor.api.backend.msgraph.GraphSessionTokenService.java

License:Apache License

private void handleRefreshResponse(HttpClientResponse resp, Future<TokenData> future,
        String previousRefreshToken) {
    resp.exceptionHandler(future::fail);
    resp.bodyHandler(body -> {//from  w  w w .  ja v a2 s .c om
        if (resp.statusCode() != 200) {
            future.fail(body.toString());
            return;
        }
        JsonObject json = body.toJsonObject();
        TokenData d = new TokenData(json.getString("access_token"),
                currentTimeMillis() + 1_000 * (json.getLong("expires_in") - 10),
                json.getString("refresh_token"));
        cache.put(d.refreshToken, d);
        if (previousRefreshToken != null) {
            cache.put(previousRefreshToken, d);
        }
        future.complete(d);
    });
}

From source file:io.nitor.api.backend.s3.S3Handler.java

License:Apache License

private void mapResponse(HttpClientResponse cres, HttpServerResponse sres) {
    cres.exceptionHandler(t -> {
        logger.error("Error processing s3 request", t);
        if (!sres.ended()) {
            sres.setStatusCode(502);//  ww w.j  a  va  2 s.c o  m
            sres.end();
        }
    });

    sres.setStatusCode(cres.statusCode());
    sres.setStatusMessage(cres.statusMessage());
    if (cres.statusCode() != 200 && cres.statusCode() != 206) {
        sres.end();
        return;
    }

    MultiMap headers = sres.headers();
    cres.headers().forEach(entry -> {
        String key = entry.getKey();
        if (key.startsWith("x-amz-")) {
            return;
        }
        String lKey = key.toLowerCase();
        if ("server".equals(lKey) || "accept-ranges".equals(lKey) || "transfer-encoding".equals(lKey)
                || "date".equals(lKey) || "connection".equals(lKey)) {
            return;
        }
        headers.add(key, entry.getValue());
    });
    // TODO handle http 1.0 that requires connection header

    Pump resPump = Pump.pump(cres, sres);
    cres.endHandler(v -> sres.end());
    resPump.start();
}

From source file:org.apache.servicecomb.transport.rest.client.http.RestClientInvocation.java

License:Apache License

protected void handleResponse(HttpClientResponse httpClientResponse) {
    this.clientResponse = httpClientResponse;

    if (HttpStatus.isSuccess(clientResponse.statusCode())
            && Part.class.equals(invocation.getOperationMeta().getMethod().getReturnType())) {
        ReadStreamPart part = new ReadStreamPart(httpClientWithContext.context(), httpClientResponse);
        invocation.getHandlerContext().put(RestConst.READ_STREAM_PART, part);
        processResponseBody(null);/*from   w w  w .  ja  va2 s .  c  om*/
        return;
    }

    httpClientResponse.exceptionHandler(e -> {
        LOGGER.error("Failed to receive response from {}.", httpClientResponse.netSocket().remoteAddress(), e);
        fail(e);
    });

    clientResponse.bodyHandler(responseBuf -> {
        processResponseBody(responseBuf);
    });
}