Search in sources :

Example 11 with HttpRequest

use of org.eclipse.jetty.client.HttpRequest in project airlift by airlift.

the class JettyHttpClient method execute.

@Override
public <T, E extends Exception> T execute(Request request, ResponseHandler<T, E> responseHandler) throws E {
    long requestStart = System.nanoTime();
    // apply filters
    request = applyRequestFilters(request);
    // create jetty request and response listener
    JettyRequestListener requestListener = new JettyRequestListener(request.getUri());
    HttpRequest jettyRequest = buildJettyRequest(request, requestListener);
    InputStreamResponseListener listener = new InputStreamResponseListener() {

        @Override
        public void onContent(Response response, ByteBuffer content) {
            // ignore empty blocks
            if (content.remaining() == 0) {
                return;
            }
            super.onContent(response, content);
        }
    };
    long requestTimestamp = System.currentTimeMillis();
    RequestInfo requestInfo = RequestInfo.from(jettyRequest, requestTimestamp);
    if (logEnabled) {
        addLoggingListener(jettyRequest, requestTimestamp);
    }
    // fire the request
    jettyRequest.send(listener);
    // wait for response to begin
    Response response;
    try {
        response = listener.get(httpClient.getIdleTimeout(), MILLISECONDS);
    } catch (InterruptedException e) {
        stats.recordRequestFailed();
        requestLogger.log(requestInfo, ResponseInfo.failed(Optional.empty(), Optional.of(e)));
        jettyRequest.abort(e);
        Thread.currentThread().interrupt();
        return responseHandler.handleException(request, e);
    } catch (TimeoutException e) {
        stats.recordRequestFailed();
        requestLogger.log(requestInfo, ResponseInfo.failed(Optional.empty(), Optional.of(e)));
        jettyRequest.abort(e);
        return responseHandler.handleException(request, e);
    } catch (ExecutionException e) {
        stats.recordRequestFailed();
        requestLogger.log(requestInfo, ResponseInfo.failed(Optional.empty(), Optional.of(e)));
        Throwable cause = e.getCause();
        if (cause instanceof Exception) {
            return responseHandler.handleException(request, (Exception) cause);
        } else if ((cause instanceof NoClassDefFoundError) && cause.getMessage().endsWith("ALPNClientConnection")) {
            return responseHandler.handleException(request, new RuntimeException("HTTPS cannot be used when HTTP/2 is enabled", cause));
        } else {
            return responseHandler.handleException(request, new RuntimeException(cause));
        }
    }
    // process response
    long responseStart = System.nanoTime();
    JettyResponse jettyResponse = null;
    T value;
    try {
        jettyResponse = new JettyResponse(response, listener.getInputStream());
        value = responseHandler.handle(request, jettyResponse);
    } finally {
        if (jettyResponse != null) {
            try {
                jettyResponse.getInputStream().close();
            } catch (IOException ignored) {
            // ignore errors closing the stream
            }
        }
        if (recordRequestComplete) {
            recordRequestComplete(stats, request, requestStart, jettyResponse, responseStart);
        }
    }
    return value;
}
Also used : HttpRequest(org.eclipse.jetty.client.HttpRequest) InputStreamResponseListener(org.eclipse.jetty.client.util.InputStreamResponseListener) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) RequestInfo(io.airlift.http.client.jetty.HttpClientLogger.RequestInfo) ByteBuffer(java.nio.ByteBuffer) GeneralSecurityException(java.security.GeneralSecurityException) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) Response(org.eclipse.jetty.client.api.Response) ExecutionException(java.util.concurrent.ExecutionException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 12 with HttpRequest

use of org.eclipse.jetty.client.HttpRequest in project airlift by airlift.

the class JettyHttpClient method buildJettyRequest.

private HttpRequest buildJettyRequest(Request finalRequest, JettyRequestListener listener) {
    HttpRequest jettyRequest = (HttpRequest) httpClient.newRequest(finalRequest.getUri());
    jettyRequest.onRequestBegin(request -> listener.onRequestBegin());
    jettyRequest.onRequestSuccess(request -> listener.onRequestEnd());
    jettyRequest.onResponseBegin(response -> listener.onResponseBegin());
    jettyRequest.onComplete(result -> listener.onFinish());
    jettyRequest.onComplete(result -> {
        if (result.isFailed() && result.getFailure() instanceof TimeoutException) {
            clientDiagnostics.logDiagnosticsInfo(httpClient);
        }
    });
    jettyRequest.attribute(STATS_KEY, listener);
    jettyRequest.method(finalRequest.getMethod());
    for (Entry<String, String> entry : finalRequest.getHeaders().entries()) {
        jettyRequest.header(entry.getKey(), entry.getValue());
    }
    BodyGenerator bodyGenerator = finalRequest.getBodyGenerator();
    if (bodyGenerator != null) {
        if (bodyGenerator instanceof StaticBodyGenerator) {
            StaticBodyGenerator staticBodyGenerator = (StaticBodyGenerator) bodyGenerator;
            jettyRequest.content(new BytesContentProvider(staticBodyGenerator.getBody()));
        } else if (bodyGenerator instanceof FileBodyGenerator) {
            Path path = ((FileBodyGenerator) bodyGenerator).getPath();
            jettyRequest.content(fileContentProvider(path));
        } else {
            jettyRequest.content(new BodyGeneratorContentProvider(bodyGenerator, httpClient.getExecutor()));
        }
    }
    jettyRequest.followRedirects(finalRequest.isFollowRedirects());
    setPreserveAuthorization(jettyRequest, finalRequest.isPreserveAuthorizationOnRedirect());
    // timeouts
    jettyRequest.timeout(requestTimeoutMillis, MILLISECONDS);
    jettyRequest.idleTimeout(idleTimeoutMillis, MILLISECONDS);
    return jettyRequest;
}
Also used : HttpRequest(org.eclipse.jetty.client.HttpRequest) Path(java.nio.file.Path) BodyGenerator(io.airlift.http.client.BodyGenerator) StaticBodyGenerator(io.airlift.http.client.StaticBodyGenerator) FileBodyGenerator(io.airlift.http.client.FileBodyGenerator) FileBodyGenerator(io.airlift.http.client.FileBodyGenerator) StaticBodyGenerator(io.airlift.http.client.StaticBodyGenerator) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) TimeoutException(java.util.concurrent.TimeoutException)

Example 13 with HttpRequest

use of org.eclipse.jetty.client.HttpRequest in project instrumentation-java by census-instrumentation.

the class HelloWorldClient method main.

/**
 * HelloWorldClient sends http request periodically to {@link HelloWorldServer}. These requests
 * are instrumented using opencensus jetty client library to enable tracing and monitoring stats.
 */
public static void main(String[] args) throws Exception {
    BasicConfigurator.configure();
    initTracing();
    initStatsExporter();
    // Create http client that will trace requests. By default trace context is propagated using
    // w3c TraceContext propagator.
    // To use B3 propagation use following
    // OcJettyHttpClient httpClient =
    // new OcJettyHttpClient(
    // new HttpClientTransportOverHTTP(),
    // new SslContextFactory(),
    // null,
    // Tracing.getPropagationComponent().getB3Format());
    OcJettyHttpClient httpClient = new OcJettyHttpClient(new HttpClientTransportOverHTTP(), new SslContextFactory(), null, null);
    httpClient.start();
    do {
        HttpRequest request = (HttpRequest) httpClient.newRequest("http://localhost:8080/helloworld/request").method(HttpMethod.GET);
        HttpRequest asyncRequest = (HttpRequest) httpClient.newRequest("http://localhost:8080/helloworld/request/async").method(HttpMethod.GET);
        HttpRequest postRequest = (HttpRequest) httpClient.newRequest("http://localhost:8080/helloworld/request").method(HttpMethod.POST);
        postRequest.content(new StringContentProvider("{\"hello\": \"world\"}"), "application/json");
        if (request == null) {
            logger.info("Request is null");
            break;
        }
        request.send();
        asyncRequest.send();
        postRequest.send();
        try {
            Thread.sleep(15000);
        } catch (Exception e) {
            logger.error("Error while sleeping");
        }
    } while (true);
}
Also used : HttpRequest(org.eclipse.jetty.client.HttpRequest) OcJettyHttpClient(io.opencensus.contrib.http.jetty.client.OcJettyHttpClient) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) HttpClientTransportOverHTTP(org.eclipse.jetty.client.http.HttpClientTransportOverHTTP) IOException(java.io.IOException)

Aggregations

HttpRequest (org.eclipse.jetty.client.HttpRequest)13 IOException (java.io.IOException)4 CountDownLatch (java.util.concurrent.CountDownLatch)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)3 Response (org.eclipse.jetty.client.api.Response)3 Result (org.eclipse.jetty.client.api.Result)3 BufferingResponseListener (org.eclipse.jetty.client.util.BufferingResponseListener)3 HttpFields (org.eclipse.jetty.http.HttpFields)3 Request (org.eclipse.jetty.server.Request)3 Test (org.junit.Test)3 BodyGenerator (io.airlift.http.client.BodyGenerator)2 FileBodyGenerator (io.airlift.http.client.FileBodyGenerator)2 StaticBodyGenerator (io.airlift.http.client.StaticBodyGenerator)2 Path (java.nio.file.Path)2 Random (java.util.Random)2 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)2 TimeoutException (java.util.concurrent.TimeoutException)2 ServletException (javax.servlet.ServletException)2