use of io.netty.handler.codec.http.HttpResponseEncoder in project activemq-artemis by apache.
the class NettyConnectorWithHTTPUpgradeTest method startWebServer.
private void startWebServer(int port) throws Exception {
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
final SSLContext context;
if (useSSL) {
context = SSLSupport.createContext("JKS", SERVER_SIDE_KEYSTORE, PASSWORD, null, null, null);
} else {
context = null;
}
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// create a HTTP server
ChannelPipeline p = ch.pipeline();
if (useSSL) {
SSLEngine engine = context.createSSLEngine();
engine.setUseClientMode(false);
SslHandler handler = new SslHandler(engine);
p.addLast("ssl", handler);
}
p.addLast("decoder", new HttpRequestDecoder());
p.addLast("encoder", new HttpResponseEncoder());
p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler<Object>() {
// handle HTTP GET + Upgrade with a handshake specific to ActiveMQ Artemis remoting.
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpRequest) {
HttpRequest request = (HttpRequest) msg;
for (Map.Entry<String, String> entry : request.headers()) {
System.out.println(entry);
}
String upgrade = request.headers().get(UPGRADE);
String secretKey = request.headers().get(SEC_ACTIVEMQ_REMOTING_KEY);
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS);
response.headers().set(UPGRADE, upgrade);
response.headers().set(SEC_ACTIVEMQ_REMOTING_ACCEPT, createExpectedResponse(MAGIC_NUMBER, secretKey));
ctx.writeAndFlush(response);
// when the handshake is successful, the HTTP handlers are removed
ctx.pipeline().remove("decoder");
ctx.pipeline().remove("encoder");
ctx.pipeline().remove(this);
System.out.println("HTTP handshake sent, transferring channel");
// transfer the control of the channel to the Netty Acceptor
NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService().getAcceptor(acceptorName);
acceptor.transfer(ctx.channel());
// at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones.
}
}
});
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
});
b.bind(port).sync();
}
use of io.netty.handler.codec.http.HttpResponseEncoder in project reactor-netty by reactor.
the class HttpClientTest method prematureCancel.
@Test
public void prematureCancel() throws Exception {
DirectProcessor<Void> signal = DirectProcessor.create();
NettyContext x = TcpServer.create("localhost", 0).newHandler((in, out) -> {
signal.onComplete();
return out.context(c -> c.addHandlerFirst(new HttpResponseEncoder())).sendObject(Mono.delay(Duration.ofSeconds(2)).map(t -> new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.PROCESSING))).neverComplete();
}).block(Duration.ofSeconds(30));
StepVerifier.create(createHttpClientForContext(x).get("/").timeout(signal)).verifyError(TimeoutException.class);
// Thread.sleep(1000000);
}
use of io.netty.handler.codec.http.HttpResponseEncoder in project reactor-netty by reactor.
the class HttpClientTest method abort.
@Test
public void abort() throws Exception {
NettyContext x = TcpServer.create("localhost", 0).newHandler((in, out) -> in.receive().take(1).thenMany(Flux.defer(() -> out.context(c -> c.addHandlerFirst(new HttpResponseEncoder())).sendObject(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED)).then(Mono.delay(Duration.ofSeconds(2)).then())))).block(Duration.ofSeconds(30));
PoolResources pool = PoolResources.fixed("test", 1);
HttpClient.create(opts -> opts.host("localhost").port(x.address().getPort()).poolResources(pool)).get("/").flatMap(r -> {
r.dispose();
return Mono.just(r.status().code());
}).log().block(Duration.ofSeconds(30));
HttpClientResponse resp = HttpClient.create(opts -> opts.host("localhost").port(x.address().getPort()).poolResources(pool)).get("/").log().block(Duration.ofSeconds(30));
resp.dispose();
resp = HttpClient.create(opts -> opts.host("localhost").port(x.address().getPort()).poolResources(pool)).get("/").log().block(Duration.ofSeconds(30));
resp.dispose();
x.dispose();
pool.dispose();
}
use of io.netty.handler.codec.http.HttpResponseEncoder in project java by wavefrontHQ.
the class PlainTextOrHttpFrameDecoder method decode.
/**
* Dynamically adds the appropriate encoder/decoder(s) to the pipeline based on the detected
* protocol.
*/
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf buffer, List<Object> out) throws Exception {
// read the first 2 bytes to use for protocol detection
if (buffer.readableBytes() < 2) {
logger.warning("buffer has less that 2 readable bytes");
return;
}
final int firstByte = buffer.getUnsignedByte(buffer.readerIndex());
final int secondByte = buffer.getUnsignedByte(buffer.readerIndex() + 1);
// determine the protocol and add the encoder/decoder
final ChannelPipeline pipeline = ctx.pipeline();
if (isHttp(firstByte, secondByte)) {
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("aggregator", new HttpObjectAggregator(16 * 1024 * 1024));
pipeline.addLast("deflate", new HttpContentCompressor());
pipeline.addLast("handler", this.handler);
} else {
pipeline.addLast("line", new LineBasedFrameDecoder(4096));
pipeline.addLast("decoder", STRING_DECODER);
pipeline.addLast("encoder", STRING_ENCODER);
pipeline.addLast("handler", this.handler);
}
pipeline.remove(this);
}
use of io.netty.handler.codec.http.HttpResponseEncoder in project vert.x by eclipse.
the class HttpServerHandlerBenchmark method setup.
@Setup
public void setup() {
vertx = (VertxInternal) Vertx.vertx();
HttpServerOptions options = new HttpServerOptions();
vertxChannel = new EmbeddedChannel(new VertxHttpRequestDecoder(options), // We don't use the VertxHttpResponseDecoder because it will use the PartialPooledByteBufAllocator
new HttpResponseEncoder() {
@Override
protected void encodeHeaders(HttpHeaders headers, ByteBuf buf) {
((HeadersMultiMap) headers).encode(buf);
}
});
vertxChannel.config().setAllocator(new Alloc());
ContextInternal context = vertx.createEventLoopContext(vertxChannel.eventLoop(), null, Thread.currentThread().getContextClassLoader());
Handler<HttpServerRequest> app = request -> {
HttpServerResponse response = request.response();
MultiMap headers = response.headers();
headers.add(HEADER_CONTENT_TYPE, RESPONSE_TYPE_PLAIN).add(HEADER_SERVER, SERVER).add(HEADER_DATE, DATE_STRING).add(HEADER_CONTENT_LENGTH, HELLO_WORLD_LENGTH);
response.end(HELLO_WORLD_BUFFER);
};
VertxHandler<Http1xServerConnection> handler = VertxHandler.create(chctx -> {
Http1xServerConnection conn = new Http1xServerConnection(() -> context, null, new HttpServerOptions(), chctx, context, "localhost", null);
conn.handler(app);
return conn;
});
vertxChannel.pipeline().addLast("handler", handler);
nettyChannel = new EmbeddedChannel(new HttpRequestDecoder(options.getMaxInitialLineLength(), options.getMaxHeaderSize(), options.getMaxChunkSize(), false, options.getDecoderInitialBufferSize()), new HttpResponseEncoder(), new SimpleChannelInboundHandler<HttpRequest>() {
private final byte[] STATIC_PLAINTEXT = "Hello, World!".getBytes(CharsetUtil.UTF_8);
private final int STATIC_PLAINTEXT_LEN = STATIC_PLAINTEXT.length;
private final ByteBuf PLAINTEXT_CONTENT_BUFFER = Unpooled.unreleasableBuffer(Unpooled.directBuffer().writeBytes(STATIC_PLAINTEXT));
private final CharSequence PLAINTEXT_CLHEADER_VALUE = new AsciiString(String.valueOf(STATIC_PLAINTEXT_LEN));
private final CharSequence TYPE_PLAIN = new AsciiString("text/plain");
private final CharSequence SERVER_NAME = new AsciiString("Netty");
private final CharSequence CONTENT_TYPE_ENTITY = HttpHeaderNames.CONTENT_TYPE;
private final CharSequence DATE_ENTITY = HttpHeaderNames.DATE;
private final CharSequence CONTENT_LENGTH_ENTITY = HttpHeaderNames.CONTENT_LENGTH;
private final CharSequence SERVER_ENTITY = HttpHeaderNames.SERVER;
private final DateFormat FORMAT = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
private final CharSequence date = new AsciiString(FORMAT.format(new Date()));
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
writeResponse(ctx, msg, PLAINTEXT_CONTENT_BUFFER.duplicate(), TYPE_PLAIN, PLAINTEXT_CLHEADER_VALUE);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
private void writeResponse(ChannelHandlerContext ctx, HttpRequest request, ByteBuf buf, CharSequence contentType, CharSequence contentLength) {
// Build the response object.
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf, false);
HttpHeaders headers = response.headers();
headers.set(CONTENT_TYPE_ENTITY, contentType);
headers.set(SERVER_ENTITY, SERVER_NAME);
headers.set(DATE_ENTITY, date);
headers.set(CONTENT_LENGTH_ENTITY, contentLength);
// Close the non-keep-alive connection after the write operation is done.
ctx.write(response, ctx.voidPromise());
}
});
nettyChannel.config().setAllocator(new Alloc());
GET = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(("GET / HTTP/1.1\r\n" + "\r\n").getBytes()));
readerIndex = GET.readerIndex();
writeIndex = GET.writerIndex();
}
Aggregations