Search in sources :

Example 21 with DefaultFullHttpRequest

use of io.netty.handler.codec.http.DefaultFullHttpRequest in project jocean-http by isdom.

the class HttpServerDemo method main.

public static void main(final String[] args) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final // SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    // create for LocalChannel
    @SuppressWarnings("resource") final HttpServerBuilder server = new DefaultHttpServerBuilder(new AbstractBootstrapCreator(new DefaultEventLoopGroup(1), new DefaultEventLoopGroup()) {

        @Override
        protected void initializeBootstrap(final ServerBootstrap bootstrap) {
            bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            bootstrap.channel(LocalServerChannel.class);
        }
    }, Feature.ENABLE_LOGGING, new Feature.ENABLE_SSL(sslCtx));
    @SuppressWarnings("unused") final Subscription subscription = server.defineServer(new LocalAddress("test")).subscribe(new Action1<HttpTrade>() {

        @Override
        public void call(final HttpTrade trade) {
            trade.outbound(trade.inbound().compose(RxNettys.message2fullreq(trade)).map(DisposableWrapperUtil.<FullHttpRequest>unwrap()).map(new Func1<FullHttpRequest, HttpObject>() {

                @Override
                public HttpObject call(final FullHttpRequest fullreq) {
                    try {
                        final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(Nettys.dumpByteBufAsBytes(fullreq.content())));
                        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
                        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
                        return response;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }));
        }
    });
    @SuppressWarnings("resource") final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), Feature.ENABLE_LOGGING, new Feature.ENABLE_SSL(SslContextBuilder.forClient().build()));
    while (true) {
        final ByteBuf content = Unpooled.buffer(0);
        content.writeBytes("test content".getBytes("UTF-8"));
        final DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", content);
        HttpUtil.setContentLength(request, content.readableBytes());
        /* // TODO using initiator
            final Iterator<HttpObject> itr =
                client.defineInteraction(
                new LocalAddress("test"), 
                Observable.just(request))
                .map(RxNettys.<HttpObject>retainer())
                .toBlocking().toIterable().iterator();
            
            final byte[] bytes = RxNettys.httpObjectsAsBytes(itr);
            LOG.info("recv Response: {}", new String(bytes, "UTF-8"));
            */
        Thread.sleep(1000);
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpServerBuilder(org.jocean.http.server.HttpServerBuilder) ByteBuf(io.netty.buffer.ByteBuf) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) Feature(org.jocean.http.Feature) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) LocalServerChannel(io.netty.channel.local.LocalServerChannel) HttpObject(io.netty.handler.codec.http.HttpObject) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Subscription(rx.Subscription) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) LocalAddress(io.netty.channel.local.LocalAddress) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) TestChannelCreator(org.jocean.http.client.impl.TestChannelCreator)

Example 22 with DefaultFullHttpRequest

use of io.netty.handler.codec.http.DefaultFullHttpRequest in project jocean-http by isdom.

the class DefaultHttpTradeTestCase method testTradeForFullRequestSourceAndDumpFullRequests.

@Test
public final void testTradeForFullRequestSourceAndDumpFullRequests() 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);
    writeToInboundAndFlush(channel, request);
    // expected refCnt, request -- 1 + HttpMessageHolder -- 1, total refcnt is 2
    // TODO, why 4 & 5 refCnt ?
    callByteBufHolderBuilderOnceAndAssertDumpContentAndRefCnt(trade.inbound().compose(RxNettys.message2fullreq(trade)).toBlocking().single().unwrap(), REQ_CONTENT.getBytes(Charsets.UTF_8), 4);
    callByteBufHolderBuilderOnceAndAssertDumpContentAndRefCnt(trade.inbound().compose(RxNettys.message2fullreq(trade)).toBlocking().single().unwrap(), REQ_CONTENT.getBytes(Charsets.UTF_8), 5);
}
Also used : HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Nettys4Test(org.jocean.http.util.Nettys4Test) Test(org.junit.Test)

Example 23 with DefaultFullHttpRequest

use of io.netty.handler.codec.http.DefaultFullHttpRequest in project jocean-http by isdom.

the class SslDemo method main.

public static void main(String[] args) throws Exception {
    final SslContext sslCtx = SslContextBuilder.forClient().build();
    final Feature sslfeature = new Feature.ENABLE_SSL(sslCtx);
    try (final HttpClient client = new DefaultHttpClient()) {
        {
            final String host = "www.sina.com.cn";
            final DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
            // HttpUtil.setKeepAlive(request, true);
            request.headers().set(HttpHeaderNames.HOST, host);
            LOG.debug("send request:{}", request);
            final String content = sendRequestAndRecv(client, host, 443, request, sslfeature, Feature.ENABLE_LOGGING, Feature.ENABLE_COMPRESSOR);
        // LOG.info("recv:{}", content);
        }
    /*
            {
                final String host = "www.alipay.com";

                final DefaultFullHttpRequest request = new DefaultFullHttpRequest(
                        HttpVersion.HTTP_1_0, HttpMethod.GET, "/");
                HttpUtil.setKeepAlive(request, true);
                request.headers().set(HttpHeaderNames.HOST, host);

                LOG.debug("send request:{}", request);
              
                LOG.info("recv:{}", sendRequestAndRecv(client, request, host, sslfeature));
            }
            */
    /*
            {
                final String host = "github.com";

                final DefaultFullHttpRequest request = new DefaultFullHttpRequest(
                        HttpVersion.HTTP_1_0, HttpMethod.GET, "/isdom");
                HttpUtil.setKeepAlive(request, true);
                request.headers().set(HttpHeaderNames.HOST, host);

                LOG.debug("send request:{}", request);
              
                LOG.info("recv:{}", sendRequestAndRecv(client, request, host, sslfeature));
            }
            */
    }
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpClient(org.jocean.http.client.HttpClient) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) SslContext(io.netty.handler.ssl.SslContext)

Example 24 with DefaultFullHttpRequest

use of io.netty.handler.codec.http.DefaultFullHttpRequest in project cdap by caskdata.

the class NettyRouterPipelineTest method testHttpPipelining.

@Test
public void testHttpPipelining() throws Exception {
    final BlockingQueue<HttpResponseStatus> responseStatuses = new LinkedBlockingQueue<>();
    EventLoopGroup eventGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventGroup).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("codec", new HttpClientCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(1048576));
            pipeline.addLast("handler", new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (msg instanceof HttpResponse) {
                        responseStatuses.add(((HttpResponse) msg).status());
                    }
                    ReferenceCountUtil.release(msg);
                }
            });
        }
    });
    // Create a connection and make five consecutive HTTP call without waiting for the first to respond
    Channel channel = bootstrap.connect(HOSTNAME, ROUTER.getServiceMap().get(GATEWAY_NAME)).sync().channel();
    for (int i = 0; i < 5; i++) {
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/v1/sleep?sleepMillis=3000");
        request.headers().set(HttpHeaderNames.HOST, HOSTNAME);
        channel.writeAndFlush(request);
    }
    // Should get the first response as normal one
    HttpResponseStatus status = responseStatuses.poll(5, TimeUnit.SECONDS);
    Assert.assertEquals(HttpResponseStatus.OK, status);
    // The rest four should be failure responses
    for (int i = 0; i < 4; i++) {
        Assert.assertEquals(HttpResponseStatus.NOT_IMPLEMENTED, responseStatuses.poll(1, TimeUnit.SECONDS));
    }
    eventGroup.shutdownGracefully();
    channel.close();
    Assert.assertTrue(responseStatuses.isEmpty());
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) IOException(java.io.IOException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 25 with DefaultFullHttpRequest

use of io.netty.handler.codec.http.DefaultFullHttpRequest in project cdap by caskdata.

the class DefaultStreamManager method setStreamProperties.

@Override
public void setStreamProperties(StreamProperties properties) throws IOException {
    String path = String.format("/v3/namespaces/%s/streams/%s/properties", streamId.getNamespaceId(), streamId.getId());
    FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, path);
    httpRequest.content().writeCharSequence(GSON.toJson(properties), StandardCharsets.UTF_8);
    MockResponder responder = new MockResponder();
    try {
        streamHandler.setConfig(httpRequest, responder, streamId.getNamespaceId(), streamId.getId());
    } catch (Exception e) {
        Throwables.propagateIfPossible(e, IOException.class);
        throw Throwables.propagate(e);
    }
    if (responder.getStatus() != HttpResponseStatus.OK) {
        throw new IOException("Failed to set stream properties. Status = " + responder.getStatus());
    }
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) MockResponder(co.cask.cdap.internal.MockResponder) IOException(java.io.IOException) IOException(java.io.IOException)

Aggregations

DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)215 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)117 Test (org.junit.jupiter.api.Test)72 Test (org.junit.Test)61 ByteBuf (io.netty.buffer.ByteBuf)56 HttpRequest (io.netty.handler.codec.http.HttpRequest)47 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)43 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)40 AsciiString (io.netty.util.AsciiString)30 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)23 Channel (io.netty.channel.Channel)20 ChannelPromise (io.netty.channel.ChannelPromise)19 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)18 IOException (java.io.IOException)17 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)15 HttpResponse (io.netty.handler.codec.http.HttpResponse)15 URI (java.net.URI)15 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)14 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)13 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)12