use of io.netty.handler.codec.http.HttpRequest in project jersey by jersey.
the class NettyConnector method apply.
@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) {
final CompletableFuture<Object> settableFuture = new CompletableFuture<>();
final URI requestUri = jerseyRequest.getUri();
String host = requestUri.getHost();
int port = requestUri.getPort() != -1 ? requestUri.getPort() : "https".equals(requestUri.getScheme()) ? 443 : 80;
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
// Enable HTTPS if necessary.
if ("https".equals(requestUri.getScheme())) {
// making client authentication optional for now; it could be extracted to configurable property
JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true, ClientAuth.NONE);
p.addLast(jdkSslContext.newHandler(ch.alloc()));
}
// http proxy
Configuration config = jerseyRequest.getConfiguration();
final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
if (proxyUri != null) {
final URI u = getProxyUri(proxyUri);
final String userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME, String.class);
final String password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD, String.class);
p.addLast(new HttpProxyHandler(new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()), userName, password));
}
p.addLast(new HttpClientCodec());
p.addLast(new ChunkedWriteHandler());
p.addLast(new HttpContentDecompressor());
p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback, settableFuture));
}
});
// connect timeout
Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(), ClientProperties.CONNECT_TIMEOUT, 0);
if (connectTimeout > 0) {
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
}
// Make the connection attempt.
final Channel ch = b.connect(host, port).sync().channel();
// guard against prematurely closed channel
final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
@Override
public void operationComplete(io.netty.util.concurrent.Future<? super Void> future) throws Exception {
if (!settableFuture.isDone()) {
settableFuture.completeExceptionally(new IOException("Channel closed."));
}
}
};
ch.closeFuture().addListener(closeListener);
HttpRequest nettyRequest;
if (jerseyRequest.hasEntity()) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
} else {
nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
}
// headers
for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) {
nettyRequest.headers().add(e.getKey(), e.getValue());
}
// host header - http 1.1
nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());
if (jerseyRequest.hasEntity()) {
if (jerseyRequest.getLengthLong() == -1) {
HttpUtil.setTransferEncodingChunked(nettyRequest, true);
} else {
nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());
}
}
if (jerseyRequest.hasEntity()) {
// Send the HTTP request.
ch.writeAndFlush(nettyRequest);
final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch);
jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {
@Override
public OutputStream getOutputStream(int contentLength) throws IOException {
return jerseyChunkedInput;
}
});
if (HttpUtil.isTransferEncodingChunked(nettyRequest)) {
ch.write(new HttpChunkedInput(jerseyChunkedInput));
} else {
ch.write(jerseyChunkedInput);
}
executorService.execute(new Runnable() {
@Override
public void run() {
// close listener is not needed any more.
ch.closeFuture().removeListener(closeListener);
try {
jerseyRequest.writeEntity();
} catch (IOException e) {
jerseyCallback.failure(e);
settableFuture.completeExceptionally(e);
}
}
});
ch.flush();
} else {
// close listener is not needed any more.
ch.closeFuture().removeListener(closeListener);
// Send the HTTP request.
ch.writeAndFlush(nettyRequest);
}
} catch (InterruptedException e) {
settableFuture.completeExceptionally(e);
return settableFuture;
}
return settableFuture;
}
use of io.netty.handler.codec.http.HttpRequest in project pinpoint by naver.
the class HttpClientStreamInterceptor method before.
@Override
public void before(Object target, Object[] args) {
if (isDebug) {
logger.beforeInterceptor(target, args);
}
final Trace trace = traceContext.currentTraceObject();
if (trace == null) {
return;
}
try {
final SpanEventRecorder recorder = trace.traceBlockBegin();
if (!validate(args)) {
return;
}
final HttpRequest request = (HttpRequest) args[0];
final HttpHeaders headers = request.headers();
if (headers == null) {
// defense code.
return;
}
final String uri = request.uri();
final String host = (String) args[1];
// generate next trace id.
final TraceId nextId = trace.getTraceId().getNextTraceId();
recorder.recordNextSpanId(nextId.getSpanId());
headers.add(Header.HTTP_TRACE_ID.toString(), nextId.getTransactionId());
headers.add(Header.HTTP_SPAN_ID.toString(), String.valueOf(nextId.getSpanId()));
headers.add(Header.HTTP_PARENT_SPAN_ID.toString(), String.valueOf(nextId.getParentSpanId()));
headers.add(Header.HTTP_FLAGS.toString(), String.valueOf(nextId.getFlags()));
headers.add(Header.HTTP_PARENT_APPLICATION_NAME.toString(), traceContext.getApplicationName());
headers.add(Header.HTTP_PARENT_APPLICATION_TYPE.toString(), Short.toString(traceContext.getServerTypeCode()));
if (host != null) {
headers.add(Header.HTTP_HOST.toString(), host);
recorder.recordDestinationId(host);
} else {
recorder.recordDestinationId("unknown");
}
if (uri != null) {
final String httpUrl = InterceptorUtils.getHttpUrl(uri, param);
recorder.recordAttribute(AnnotationKey.HTTP_URL, httpUrl);
}
} catch (Throwable t) {
if (logger.isWarnEnabled()) {
logger.warn("BEFORE. Caused:{}", t.getMessage(), t);
}
}
}
use of io.netty.handler.codec.http.HttpRequest in project pinpoint by naver.
the class HttpClientStreamInterceptor method after.
@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
if (isDebug) {
logger.afterInterceptor(target, args, result, throwable);
}
final Trace trace = traceContext.currentTraceObject();
if (trace == null) {
return;
}
try {
final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
recorder.recordApi(descriptor);
recorder.recordException(throwable);
recorder.recordServiceType(VertxConstants.VERTX_HTTP_CLIENT);
if (!validate(args)) {
return;
}
final HttpRequest request = (HttpRequest) args[0];
final HttpHeaders headers = request.headers();
if (headers == null) {
return;
}
final boolean isException = InterceptorUtils.isThrowable(throwable);
if (cookie) {
if (DumpType.ALWAYS == cookieDumpType) {
recordCookie(headers, trace);
} else if (DumpType.EXCEPTION == cookieDumpType && isException) {
recordCookie(headers, trace);
}
}
} catch (Throwable t) {
if (logger.isWarnEnabled()) {
logger.warn("AFTER. Caused:{}", t.getMessage(), t);
}
} finally {
trace.traceBlockEnd();
}
}
use of io.netty.handler.codec.http.HttpRequest in project netty by netty.
the class WebSocketServerCompressionHandlerTest method testServerWindowSizeDisable.
@Test
public void testServerWindowSizeDisable() {
EmbeddedChannel ch = new EmbeddedChannel(new WebSocketServerExtensionHandler(new PerMessageDeflateServerExtensionHandshaker(6, false, 15, false, false)));
HttpRequest req = newUpgradeRequest(PERMESSAGE_DEFLATE_EXTENSION + "; " + SERVER_MAX_WINDOW + "=10");
ch.writeInbound(req);
HttpResponse res = newUpgradeResponse(null);
ch.writeOutbound(res);
HttpResponse res2 = ch.readOutbound();
Assert.assertFalse(res2.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateDecoder.class) == null);
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateEncoder.class) == null);
}
use of io.netty.handler.codec.http.HttpRequest in project netty by netty.
the class WebSocketServerCompressionHandlerTest method testClientNoContext.
@Test
public void testClientNoContext() {
EmbeddedChannel ch = new EmbeddedChannel(new WebSocketServerCompressionHandler());
HttpRequest req = newUpgradeRequest(PERMESSAGE_DEFLATE_EXTENSION + "; " + CLIENT_NO_CONTEXT);
ch.writeInbound(req);
HttpResponse res = newUpgradeResponse(null);
ch.writeOutbound(res);
HttpResponse res2 = ch.readOutbound();
List<WebSocketExtensionData> exts = WebSocketExtensionUtil.extractExtensions(res2.headers().get(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
Assert.assertEquals(PERMESSAGE_DEFLATE_EXTENSION, exts.get(0).name());
Assert.assertTrue(exts.get(0).parameters().isEmpty());
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateDecoder.class) != null);
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateEncoder.class) != null);
}
Aggregations