Search in sources :

Example 26 with HttpObject

use of io.netty.handler.codec.http.HttpObject 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 27 with HttpObject

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

the class TestHttpUtil method buildBytesResponse.

public static Observable<HttpObject> buildBytesResponse(final String contentType, final byte[] content) {
    final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, Unpooled.wrappedBuffer(content));
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType);
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    return Observable.<HttpObject>just(response);
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpObject(io.netty.handler.codec.http.HttpObject) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse)

Example 28 with HttpObject

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

the class RxNettys method response404NOTFOUND.

public static Observable<HttpObject> response404NOTFOUND(final HttpVersion version) {
    final HttpResponse response = new DefaultFullHttpResponse(version, HttpResponseStatus.NOT_FOUND);
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
    return Observable.<HttpObject>just(response);
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpObject(io.netty.handler.codec.http.HttpObject) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse)

Example 29 with HttpObject

use of io.netty.handler.codec.http.HttpObject in project netty by netty.

the class WebSocketServerProtocolHandshakeHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    final HttpObject httpObject = (HttpObject) msg;
    if (httpObject instanceof HttpRequest) {
        final HttpRequest req = (HttpRequest) httpObject;
        isWebSocketPath = isWebSocketPath(req);
        if (!isWebSocketPath) {
            ctx.fireChannelRead(msg);
            return;
        }
        try {
            if (!GET.equals(req.method())) {
                sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN, ctx.alloc().buffer(0)));
                return;
            }
            final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(ctx.pipeline(), req, serverConfig.websocketPath()), serverConfig.subprotocols(), serverConfig.decoderConfig());
            final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
            final ChannelPromise localHandshakePromise = handshakePromise;
            if (handshaker == null) {
                WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
            } else {
                // Ensure we set the handshaker and replace this handler before we
                // trigger the actual handshake. Otherwise we may receive websocket bytes in this handler
                // before we had a chance to replace it.
                // 
                // See https://github.com/netty/netty/issues/9471.
                WebSocketServerProtocolHandler.setHandshaker(ctx.channel(), handshaker);
                ctx.pipeline().remove(this);
                final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req);
                handshakeFuture.addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) {
                        if (!future.isSuccess()) {
                            localHandshakePromise.tryFailure(future.cause());
                            ctx.fireExceptionCaught(future.cause());
                        } else {
                            localHandshakePromise.trySuccess();
                            // Kept for compatibility
                            ctx.fireUserEventTriggered(WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
                            ctx.fireUserEventTriggered(new WebSocketServerProtocolHandler.HandshakeComplete(req.uri(), req.headers(), handshaker.selectedSubprotocol()));
                        }
                    }
                });
                applyHandshakeTimeout();
            }
        } finally {
            ReferenceCountUtil.release(req);
        }
    } else if (!isWebSocketPath) {
        ctx.fireChannelRead(msg);
    } else {
        ReferenceCountUtil.release(msg);
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelFuture(io.netty.channel.ChannelFuture) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpObject(io.netty.handler.codec.http.HttpObject) ChannelPromise(io.netty.channel.ChannelPromise) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 30 with HttpObject

use of io.netty.handler.codec.http.HttpObject in project vert.x by eclipse.

the class Http1xServerResponse method end.

private void end(Buffer chunk, PromiseInternal<Void> listener) {
    synchronized (conn) {
        if (written) {
            throw new IllegalStateException(RESPONSE_WRITTEN);
        }
        ByteBuf data = chunk.getByteBuf();
        bytesWritten += data.readableBytes();
        HttpObject msg;
        if (!headWritten) {
            // if the head was not written yet we can write out everything in one go
            // which is cheaper.
            prepareHeaders(bytesWritten);
            msg = new AssembledFullHttpResponse(head, version, status, headers, data, trailingHeaders);
        } else {
            msg = new AssembledLastHttpContent(data, trailingHeaders);
        }
        conn.writeToChannel(msg, listener);
        written = true;
        conn.responseComplete();
        if (bodyEndHandler != null) {
            bodyEndHandler.handle(null);
        }
        if (!closed && endHandler != null) {
            endHandler.handle(null);
        }
        if (!keepAlive) {
            closeConnAfterWrite();
            closed = true;
        }
    }
}
Also used : HttpObject(io.netty.handler.codec.http.HttpObject) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

HttpObject (io.netty.handler.codec.http.HttpObject)66 Test (org.junit.Test)38 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)31 HttpContent (io.netty.handler.codec.http.HttpContent)29 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)27 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)25 ArrayList (java.util.ArrayList)19 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)16 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)14 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)14 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)14 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)9 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)9 HttpResponse (io.netty.handler.codec.http.HttpResponse)9 Subscription (rx.Subscription)9 Nettys4Test (org.jocean.http.util.Nettys4Test)8 TestSubscriber (rx.observers.TestSubscriber)8 HttpRequest (io.netty.handler.codec.http.HttpRequest)7 DisposableWrapper (org.jocean.idiom.DisposableWrapper)7 Channel (io.netty.channel.Channel)6