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;
}
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;
}
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);
}
Aggregations