Example usage for io.netty.buffer Unpooled EMPTY_BUFFER

List of usage examples for io.netty.buffer Unpooled EMPTY_BUFFER

Introduction

In this page you can find the example usage for io.netty.buffer Unpooled EMPTY_BUFFER.

Prototype

ByteBuf EMPTY_BUFFER

To view the source code for io.netty.buffer Unpooled EMPTY_BUFFER.

Click Source Link

Document

A buffer whose capacity is 0 .

Usage

From source file:code.google.nfs.rpc.netty.serialize.NettyProtocolDecoder.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    RecyclableArrayList out = RecyclableArrayList.newInstance();
    try {/*from ww w.  j av  a2 s .  c o m*/
        if (cumulation != null) {
            callDecode(ctx, cumulation, out);
            decodeLast(ctx, cumulation, out);
        } else {
            decodeLast(ctx, Unpooled.EMPTY_BUFFER, out);
        }
    } catch (DecoderException e) {
        throw e;
    } catch (Exception e) {
        throw new DecoderException(e);
    } finally {
        if (cumulation != null) {
            cumulation.release();
            cumulation = null;
        }

        for (int i = 0; i < out.size(); i++) {
            ctx.fireChannelRead(out.get(i));
        }
        ctx.fireChannelInactive();
    }
}

From source file:com.bala.learning.learning.netty.HttpServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);//  ww w .ja  va  2  s  .c om
        }

        buf.setLength(0);
        buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        buf.append("===================================\r\n");

        buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(HttpHeaders.getHost(request, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n");

        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Map.Entry<String, String> h : headers) {
                String key = h.getKey();
                String value = h.getValue();
                buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
            }
            buf.append("\r\n");
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n");
                }
            }
            buf.append("\r\n");
        }

        appendDecoderResult(buf, request);
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            buf.append("CONTENT: ");
            buf.append(content.toString(CharsetUtil.UTF_8));
            buf.append("\r\n");
            appendDecoderResult(buf, request);
        }

        if (msg instanceof LastHttpContent) {
            buf.append("END OF CONTENT\r\n");

            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                buf.append("\r\n");
                for (String name : trailer.trailingHeaders().names()) {
                    for (String value : trailer.trailingHeaders().getAll(name)) {
                        buf.append("TRAILING HEADER: ");
                        buf.append(name).append(" = ").append(value).append("\r\n");
                    }
                }
                buf.append("\r\n");
            }

            if (!writeResponse(trailer, ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}

From source file:com.chenyang.proxy.http.HttpRelayHandler.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    if (relayChannel != null && relayChannel.isActive()) {
        relayChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }//from w  w w .  j a  v a 2s  . c om
    ctx.fireChannelInactive();
}

From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception {

    final Channel uaChannel = uaChannelCtx.channel();

    final HttpRemote apnProxyRemote = uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        if (remoteChannel != null && remoteChannel.isActive()) {
            HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote);
            remoteChannel.writeAndFlush(request);
        } else {/* w  w  w . j av a  2  s  .  c o  m*/

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.AUTO_READ, false)
                    .handler(new HttpRemoteForwardChannelInitializer(uaChannel, this));

            ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getInetSocketAddress(),
                    new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0));
            remoteChannel = remoteConnectFuture.channel();
            remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel);

            remoteConnectFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote));

                        for (HttpContent hc : httpContentBuffer) {
                            future.channel().writeAndFlush(hc);

                            if (hc instanceof LastHttpContent) {
                                future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future)
                                                    throws Exception {
                                                if (future.isSuccess()) {
                                                    future.channel().read();
                                                }

                                            }
                                        });
                            }
                        }
                        httpContentBuffer.clear();
                    } else {
                        HttpErrorUtil.writeAndFlush(uaChannel, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                        httpContentBuffer.clear();
                        future.channel().close();
                    }
                }
            });

        }
        ReferenceCountUtil.release(msg);
    } else {
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());
        HttpContent hc = ((HttpContent) msg);
        if (remoteChannel != null && remoteChannel.isActive()) {
            remoteChannel.writeAndFlush(hc);

            if (hc instanceof LastHttpContent) {
                remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            future.channel().read();
                        }

                    }
                });
            }
        } else {
            httpContentBuffer.add(hc);
        }
    }

}

From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext uaChannelCtx) throws Exception {

    for (Map.Entry<String, Channel> entry : remoteChannelMap.entrySet()) {
        final Channel remoteChannel = entry.getValue();
        remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {
            @Override/*w ww . j  a  va 2 s.  co  m*/
            public void operationComplete(ChannelFuture future) throws Exception {
                remoteChannel.close();
            }
        });
    }
}

From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java

License:Apache License

@Override
public void remoteChannelInactive(final Channel uaChannel, String inactiveRemoteAddr) throws Exception {

    remoteChannelMap.remove(inactiveRemoteAddr);

    if (uaChannel.isActive()) {
        uaChannel.writeAndFlush(Unpooled.EMPTY_BUFFER);
    }//from ww w .  java  2 s .c  o m

}

From source file:com.chenyang.proxy.http.HttpUserAgentTunnelHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception {

    if (msg instanceof HttpRequest) {
        // Channel uaChannel = uaChannelCtx.channel();

        // connect remote
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.AUTO_READ, false)
                .handler(new HttpTunnelChannelInitializer(uaChannelCtx.channel()));

        final HttpRemote apnProxyRemote = uaChannelCtx.channel().attr(HttpConnectionAttribute.ATTRIBUTE_KEY)
                .get().getRemote();// w  ww  .  ja v a 2s.c  o m

        bootstrap
                .connect(apnProxyRemote.getInetSocketAddress(),
                        new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0))
                .addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(final ChannelFuture future1) throws Exception {
                        if (future1.isSuccess()) {
                            HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse(
                                    HttpVersion.HTTP_1_1,
                                    new HttpResponseStatus(200, "Connection established"));
                            uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse)
                                    .addListener(new ChannelFutureListener() {
                                        @Override
                                        public void operationComplete(ChannelFuture future2) throws Exception {
                                            // remove handlers
                                            uaChannelCtx.pipeline().remove("codec");
                                            uaChannelCtx.pipeline().remove(HttpPreHandler.HANDLER_NAME);
                                            uaChannelCtx.pipeline()
                                                    .remove(HttpUserAgentTunnelHandler.HANDLER_NAME);

                                            uaChannelCtx.pipeline()
                                                    .addLast(new HttpRelayHandler(
                                                            "UA --> " + apnProxyRemote.getRemoteAddr(),
                                                            future1.channel()));
                                        }

                                    });

                        } else {
                            if (uaChannelCtx.channel().isActive()) {
                                uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(ChannelFutureListener.CLOSE);
                            }
                        }
                    }
                });

    }
    ReferenceCountUtil.release(msg);
}

From source file:com.cmz.http.snoop.HttpSnoopServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpUtil.is100ContinueExpected(request)) {
            send100Continue(ctx);/* w w w.j  a  v  a2s.com*/
        }

        buf.setLength(0);
        buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        buf.append("===================================\r\n");

        buf.append("VERSION: ").append(request.protocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(request.headers().get(HttpHeaderNames.HOST, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.uri()).append("\r\n\r\n");

        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Map.Entry<String, String> h : headers) {
                CharSequence key = h.getKey();
                CharSequence value = h.getValue();
                buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
            }
            buf.append("\r\n");
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n");
                }
            }
            buf.append("\r\n");
        }

        appendDecoderResult(buf, request);
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            buf.append("CONTENT: ");
            buf.append(content.toString(CharsetUtil.UTF_8));
            buf.append("\r\n");
            appendDecoderResult(buf, request);
        }

        if (msg instanceof LastHttpContent) {
            buf.append("END OF CONTENT\r\n");

            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                buf.append("\r\n");
                for (CharSequence name : trailer.trailingHeaders().names()) {
                    for (CharSequence value : trailer.trailingHeaders().getAll(name)) {
                        buf.append("TRAILING HEADER: ");
                        buf.append(name).append(" = ").append(value).append("\r\n");
                    }
                }
                buf.append("\r\n");
            }

            if (!writeResponse(trailer, ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}

From source file:com.couchbase.client.core.cluster.SubdocumentMessageTest.java

License:Apache License

@Test
public void shouldThrowIllegalArgumentExceptionOnOperationsNotPermittingEmptyPath() {
    String path = "";
    ByteBuf fragment = Unpooled.EMPTY_BUFFER;
    String operation;//from  w w  w .java 2s  . c om

    operation = "GET";
    try {
        new SubGetRequest(testSubKey, path, bucket());
        fail("Expected IllegalArgumentException for " + operation);
    } catch (IllegalArgumentException e) {
        assertSame("Expected emtpy path IllegalArgumentException for " + operation,
                AbstractSubdocRequest.EXCEPTION_EMPTY_PATH, e);
    }

    operation = "EXIST";
    try {
        new SubExistRequest(testSubKey, path, bucket());
        fail("Expected IllegalArgumentException for " + operation);
    } catch (IllegalArgumentException e) {
        assertSame("Expected emtpy path IllegalArgumentException for " + operation,
                AbstractSubdocRequest.EXCEPTION_EMPTY_PATH, e);
    }

    operation = "DELETE";
    try {
        new SubDeleteRequest(testSubKey, path, bucket());
        fail("Expected IllegalArgumentException for " + operation);
    } catch (IllegalArgumentException e) {
        assertSame("Expected emtpy path IllegalArgumentException for " + operation,
                AbstractSubdocRequest.EXCEPTION_EMPTY_PATH, e);
    }

    operation = "ARRAY INSERT";
    try {
        new SubArrayRequest(testSubKey, path, SubArrayRequest.ArrayOperation.INSERT, fragment, bucket());
        fail("Expected IllegalArgumentException for " + operation);
    } catch (IllegalArgumentException e) {
        assertSame("Expected emtpy path IllegalArgumentException for " + operation,
                AbstractSubdocRequest.EXCEPTION_EMPTY_PATH, e);
    }

    operation = "COUNTER";
    try {
        new SubCounterRequest(testSubKey, path, 21L, bucket());
        fail("Expected IllegalArgumentException for " + operation);
    } catch (IllegalArgumentException e) {
        assertSame("Expected emtpy path IllegalArgumentException for " + operation,
                AbstractSubdocRequest.EXCEPTION_EMPTY_PATH, e);
    }

    operation = "DICT_ADD";
    try {
        new SubDictAddRequest(testSubKey, path, fragment, bucket());
        fail("Expected IllegalArgumentException for " + operation);
    } catch (IllegalArgumentException e) {
        assertSame("Expected emtpy path IllegalArgumentException for " + operation,
                AbstractSubdocRequest.EXCEPTION_EMPTY_PATH, e);
    }

    operation = "DICT_UPSERT";
    try {
        new SubDictUpsertRequest(testSubKey, path, fragment, bucket());
        fail("Expected IllegalArgumentException for " + operation);
    } catch (IllegalArgumentException e) {
        assertSame("Expected emtpy path IllegalArgumentException for " + operation,
                AbstractSubdocRequest.EXCEPTION_EMPTY_PATH, e);
    }

    operation = "REPLACE";
    try {
        new SubReplaceRequest(testSubKey, path, fragment, bucket());
        fail("Expected IllegalArgumentException for " + operation);
    } catch (IllegalArgumentException e) {
        assertSame("Expected emtpy path IllegalArgumentException for " + operation,
                AbstractSubdocRequest.EXCEPTION_EMPTY_PATH, e);
    }
}

From source file:com.couchbase.client.core.cluster.SubdocumentMessageTest.java

License:Apache License

@Test
public void shouldHaveIndividualResultsOnSparseMultiLookup() {
    String expected = "EXIST(sub): SUCCESS\n" + "EXIST(sub2): SUBDOC_PATH_NOT_FOUND\n"
            + "GET(sub): SUCCESS = {\"value\": \"subStringValue\",\"array\": [\"array1\", 2, true]}\n"
            + "GET(sub.array[1]): SUCCESS = 2\n" + "GET(sub2): SUBDOC_PATH_NOT_FOUND\n";

    SubMultiLookupRequest request = new SubMultiLookupRequest(testSubKey, bucket(),
            new LookupCommand(Lookup.EXIST, "sub"), new LookupCommand(Lookup.EXIST, "sub2"),
            new LookupCommand(Lookup.GET, "sub"), new LookupCommand(Lookup.GET, "sub.array[1]"),
            new LookupCommand(Lookup.GET, "sub2"));

    MultiLookupResponse response = cluster().<MultiLookupResponse>send(request).toBlocking().single();
    assertEquals(Unpooled.EMPTY_BUFFER, response.content());
    StringBuilder body = new StringBuilder();
    for (MultiResult r : response.responses()) {
        body.append(r.toString()).append('\n');
        ReferenceCountUtil.release(r.value());
    }//  w ww.j  av  a2s .  co  m

    assertTrue(response.cas() != 0);
    assertEquals(ResponseStatus.SUBDOC_MULTI_PATH_FAILURE, response.status());
    assertEquals(expected, body.toString());
}