use of io.netty.handler.codec.http.HttpObject in project vert.x by eclipse.
the class ClientHandler method doMessageReceived.
@Override
protected void doMessageReceived(ClientConnection conn, ChannelHandlerContext ctx, Object msg) {
if (conn == null) {
return;
}
if (msg instanceof HttpObject) {
HttpObject obj = (HttpObject) msg;
DecoderResult result = obj.decoderResult();
if (result.isFailure()) {
// Close the connection as Netty's HttpResponseDecoder will not try further processing
// see https://github.com/netty/netty/issues/3362
conn.handleException(result.cause());
conn.close();
return;
}
if (msg instanceof HttpResponse) {
HttpResponse response = (HttpResponse) obj;
conn.handleResponse(response);
return;
}
if (msg instanceof HttpContent) {
HttpContent chunk = (HttpContent) obj;
if (chunk.content().isReadable()) {
Buffer buff = Buffer.buffer(chunk.content().slice());
conn.handleResponseChunk(buff);
}
if (chunk instanceof LastHttpContent) {
conn.handleResponseEnd((LastHttpContent) chunk);
}
return;
}
} else if (msg instanceof WebSocketFrameInternal) {
WebSocketFrameInternal frame = (WebSocketFrameInternal) msg;
switch(frame.type()) {
case BINARY:
case CONTINUATION:
case TEXT:
conn.handleWsFrame(frame);
break;
case PING:
// Echo back the content of the PING frame as PONG frame as specified in RFC 6455 Section 5.5.2
ctx.writeAndFlush(new WebSocketFrameImpl(FrameType.PONG, frame.getBinaryData()));
break;
case PONG:
// Just ignore it
break;
case CLOSE:
if (!closeFrameSent) {
// Echo back close frame and close the connection once it was written.
// This is specified in the WebSockets RFC 6455 Section 5.4.1
ctx.writeAndFlush(frame).addListener(ChannelFutureListener.CLOSE);
closeFrameSent = true;
}
break;
default:
throw new IllegalStateException("Invalid type: " + frame.type());
}
return;
}
throw new IllegalStateException("Invalid object " + msg);
}
use of io.netty.handler.codec.http.HttpObject in project riposte by Nike-Inc.
the class ComponentTestUtils method executeRequest.
public static Pair<Integer, String> executeRequest(HttpRequest request, int port, int incompleteCallTimeoutMillis) throws Exception {
Bootstrap bootstrap = new Bootstrap();
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
CompletableFuture<Pair<Integer, String>> responseFromServer = new CompletableFuture<>();
bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpClientCodec());
p.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
p.addLast(new SimpleChannelInboundHandler<HttpObject>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof FullHttpResponse) {
// Store the proxyServer response for asserting on later.
FullHttpResponse responseMsg = (FullHttpResponse) msg;
responseFromServer.complete(Pair.of(responseMsg.getStatus().code(), responseMsg.content().toString(UTF_8)));
} else {
// Should never happen.
throw new RuntimeException("Received unexpected message type: " + msg.getClass());
}
}
});
}
});
// Connect to the proxyServer.
Channel ch = bootstrap.connect("localhost", port).sync().channel();
// Send the request.
ch.writeAndFlush(request);
// Wait for the response to be received
try {
responseFromServer.get(incompleteCallTimeoutMillis, TimeUnit.MILLISECONDS);
} catch (TimeoutException ex) {
fail("The call took much longer than expected without receiving a response. " + "Cancelling this test - it's not working properly", ex);
} finally {
ch.close();
}
// If we reach here then the call should be complete.
return responseFromServer.get();
} finally {
eventLoopGroup.shutdownGracefully();
}
}
use of io.netty.handler.codec.http.HttpObject in project ambry by linkedin.
the class FrontendIntegrationTest method assertNoContent.
/**
* Verifies that no content has been sent as part of the response or readable bytes is equivalent to 0
* @param contents the content of the response.
*/
private void assertNoContent(Queue<HttpObject> contents) {
boolean endMarkerFound = false;
for (HttpObject object : contents) {
assertFalse("There should have been no more data after the end marker was found", endMarkerFound);
HttpContent content = (HttpContent) object;
assertEquals("No content expected ", 0, content.content().readableBytes());
endMarkerFound = object instanceof LastHttpContent;
ReferenceCountUtil.release(content);
}
assertTrue("There should have been an end marker", endMarkerFound);
}
use of io.netty.handler.codec.http.HttpObject in project jocean-http by isdom.
the class DefaultHttpClientTestCase method testInitiatorInteractionSendPartRequestThenFailedAsHttps.
@Test(timeout = 5000)
public void testInitiatorInteractionSendPartRequestThenFailedAsHttps() 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, enableSSL4ServerWithSelfSigned(), Feature.ENABLE_LOGGING_OVER_SSL);
final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), enableSSL4Client(), Feature.ENABLE_LOGGING_OVER_SSL);
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.HttpObject in project jocean-http by isdom.
the class DefaultHttpTradeTestCase method testTradeForFullRequestSourceAndMultiInboundThenDumpFullRequestContent.
@Test
public final void testTradeForFullRequestSourceAndMultiInboundThenDumpFullRequestContent() throws IOException {
final DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", Nettys4Test.buildByteBuf(REQ_CONTENT));
final EmbeddedChannel channel = new EmbeddedChannel();
final HttpTrade trade = new DefaultHttpTrade(channel);
final AtomicReference<DefaultFullHttpRequest> ref1 = new AtomicReference<DefaultFullHttpRequest>();
trade.inbound().subscribe(new Action1<DisposableWrapper<HttpObject>>() {
@Override
public void call(DisposableWrapper<HttpObject> dwh) {
ref1.set((DefaultFullHttpRequest) dwh.unwrap());
}
});
final AtomicReference<DefaultFullHttpRequest> ref2 = new AtomicReference<DefaultFullHttpRequest>();
trade.inbound().subscribe(new Action1<DisposableWrapper<HttpObject>>() {
@Override
public void call(DisposableWrapper<HttpObject> dwh) {
ref2.set((DefaultFullHttpRequest) dwh.unwrap());
}
});
writeToInboundAndFlush(channel, request);
final byte[] firstReadBytes = Nettys.dumpByteBufAsBytes(ref1.get().content());
assertTrue(Arrays.equals(REQ_CONTENT.getBytes(Charsets.UTF_8), firstReadBytes));
final byte[] secondReadBytes = Nettys.dumpByteBufAsBytes(ref2.get().content());
assertTrue(Arrays.equals(REQ_CONTENT.getBytes(Charsets.UTF_8), secondReadBytes));
}
Aggregations