use of io.netty.handler.codec.http.DefaultHttpRequest in project elasticsearch by elastic.
the class Netty4HttpPipeliningHandlerTests method testThatPipeliningWorksWithChunkedRequests.
public void testThatPipeliningWorksWithChunkedRequests() throws InterruptedException {
final int numberOfRequests = randomIntBetween(2, 128);
final EmbeddedChannel embeddedChannel = new EmbeddedChannel(new AggregateUrisAndHeadersHandler(), new HttpPipeliningHandler(numberOfRequests), new WorkEmulatorHandler());
for (int i = 0; i < numberOfRequests; i++) {
final DefaultHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/" + i);
embeddedChannel.writeInbound(request);
embeddedChannel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
}
final List<CountDownLatch> latches = new ArrayList<>();
for (int i = numberOfRequests - 1; i >= 0; i--) {
latches.add(finishRequest(Integer.toString(i)));
}
for (final CountDownLatch latch : latches) {
latch.await();
}
embeddedChannel.flush();
for (int i = 0; i < numberOfRequests; i++) {
assertReadHttpMessageHasContent(embeddedChannel, Integer.toString(i));
}
assertTrue(embeddedChannel.isOpen());
}
use of io.netty.handler.codec.http.DefaultHttpRequest 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.DefaultHttpRequest in project jocean-http by isdom.
the class DefaultHttpClientTestCase method testInitiatorInteractionSendPartRequestThenFailedAsHttp.
@Test(timeout = 5000)
public void testInitiatorInteractionSendPartRequestThenFailedAsHttp() throws Exception {
// 配置 池化分配器 为 取消缓存,使用 Heap
configDefaultAllocator();
final PooledByteBufAllocator allocator = defaultAllocator();
final BlockingQueue<HttpTrade> trades = new ArrayBlockingQueue<>(1);
final String addr = UUID.randomUUID().toString();
final Subscription server = TestHttpUtil.createTestServerWith(addr, trades, Feature.ENABLE_LOGGING);
final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), Feature.ENABLE_LOGGING);
assertEquals(0, allActiveAllocationsCount(allocator));
try {
final HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
req.headers().set(HttpHeaderNames.CONTENT_LENGTH, 100);
final ConnectableObservable<HttpObject> errorOfEnd = Observable.<HttpObject>error(new RuntimeException("test error")).publish();
final Channel ch1 = (Channel) startInteraction(client.initiator().remoteAddress(new LocalAddress(addr)), Observable.concat(Observable.<HttpObject>just(req), errorOfEnd), new Interaction() {
@Override
public void interact(final HttpInitiator initiator, final Observable<DisposableWrapper<FullHttpResponse>> getresp) throws Exception {
final TestSubscriber<DisposableWrapper<FullHttpResponse>> subscriber = new TestSubscriber<>();
getresp.subscribe(subscriber);
// server side recv req
final HttpTrade trade = trades.take();
assertTrue(trade.isActive());
// fire error
errorOfEnd.connect();
subscriber.awaitTerminalEvent();
subscriber.assertError(RuntimeException.class);
subscriber.assertNoValues();
TerminateAware.Util.awaitTerminated(trade);
assertTrue(!trade.isActive());
}
}, new Action1<WriteCtrl>() {
@Override
public void call(final WriteCtrl writeCtrl) {
writeCtrl.setFlushPerWrite(true);
}
}).transport();
assertEquals(0, allActiveAllocationsCount(allocator));
final Channel ch2 = (Channel) startInteraction(client.initiator().remoteAddress(new LocalAddress(addr)), Observable.just(fullHttpRequest()), standardInteraction(allocator, trades)).transport();
assertEquals(0, allActiveAllocationsCount(allocator));
assertNotSame(ch1, ch2);
} finally {
client.close();
server.unsubscribe();
}
}
use of io.netty.handler.codec.http.DefaultHttpRequest in project jocean-http by isdom.
the class DefaultHttpTradeTestCase method testTradeForMultiSubscribeRequestOnlyOneToSource.
@Test
public final void testTradeForMultiSubscribeRequestOnlyOneToSource() {
final DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
final HttpContent[] req_contents = Nettys4Test.buildContentArray(REQ_CONTENT.getBytes(Charsets.UTF_8), 1);
final EmbeddedChannel channel = new EmbeddedChannel();
final HttpTrade trade = new DefaultHttpTrade(channel);
// trade.inboundHolder().setMaxBlockSize(-1);
final TestSubscriber<DisposableWrapper<HttpObject>> reqSubscriber1 = new TestSubscriber<>();
trade.inbound().subscribe(reqSubscriber1);
final TestSubscriber<DisposableWrapper<HttpObject>> reqSubscriber2 = new TestSubscriber<>();
trade.inbound().subscribe(reqSubscriber2);
final TestSubscriber<DisposableWrapper<HttpObject>> reqSubscriber3 = new TestSubscriber<>();
trade.inbound().subscribe(reqSubscriber3);
writeToInboundAndFlush(channel, request);
writeToInboundAndFlush(channel, req_contents[0]);
reqSubscriber1.assertValueCount(2);
reqSubscriber1.assertValues(RxNettys.<HttpObject>wrap4release(request), RxNettys.<HttpObject>wrap4release(req_contents[0]));
reqSubscriber2.assertValueCount(2);
reqSubscriber2.assertValues(RxNettys.<HttpObject>wrap4release(request), RxNettys.<HttpObject>wrap4release(req_contents[0]));
reqSubscriber3.assertValueCount(2);
reqSubscriber3.assertValues(RxNettys.<HttpObject>wrap4release(request), RxNettys.<HttpObject>wrap4release(req_contents[0]));
}
use of io.netty.handler.codec.http.DefaultHttpRequest in project jocean-http by isdom.
the class DefaultHttpTradeTestCase method testTradeForReadyOutboundResponseAfterResponseOnNext.
@Test
public final void testTradeForReadyOutboundResponseAfterResponseOnNext() {
final HttpTrade trade = new DefaultHttpTrade(new EmbeddedChannel());
assertTrue(trade.isActive());
final SubscriberHolder<HttpObject> subsholder1 = new SubscriberHolder<>();
final Subscription subscription1 = trade.outbound(Observable.unsafeCreate(subsholder1));
assertNotNull(subscription1);
final DefaultHttpRequest req1 = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
Nettys4Test.emitHttpObjects(subsholder1.getAt(0), req1);
}
Aggregations