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:com.uber.tchannel.handlers.TestPingResponse.java

License:Open Source License

@Test
public void shouldInterceptPing() throws Exception {

    EmbeddedChannel channel = new EmbeddedChannel(new PingHandler());

    TFrame frame = new TFrame(0, FrameType.PingRequest.byteValue(), Integer.MAX_VALUE, Unpooled.EMPTY_BUFFER);

    channel.writeInbound(MessageCodec.decode(frame));
    TFrame newFrame = channel.readOutbound();

    assertNotNull(newFrame);/*from w ww.j  av  a  2 s  .com*/
    assertEquals(frame.size, newFrame.size);
    assertEquals(FrameType.PingResponse.byteValue(), newFrame.type);
    assertEquals(frame.id, newFrame.id);

}

From source file:com.uber.tchannel.messages.JSONSerializerTest.java

License:Open Source License

@Test
public void testDecodeEmptyHeaders() throws Exception {
    Map<String, String> emptyHeaders = new HashMap<>();
    Map<String, String> decodedHeaders = serializer.decodeHeaders(Unpooled.EMPTY_BUFFER);
    assertEquals(emptyHeaders, decodedHeaders);
}

From source file:com.vmware.dcp.common.http.netty.NettyHttpClientRequestHandler.java

License:Open Source License

private void writeResponse(ChannelHandlerContext ctx, Operation request, FullHttpResponse response) {
    boolean isClose = !request.isKeepAlive() || response == null;
    Object rsp = Unpooled.EMPTY_BUFFER;
    if (response != null) {
        AsciiString v = isClose ? HttpHeaderValues.CLOSE : HttpHeaderValues.KEEP_ALIVE;
        response.headers().set(HttpHeaderNames.CONNECTION, v);
        rsp = response;//from  ww w.  j  a va  2s . co m
    }

    ctx.channel().attr(NettyChannelContext.OPERATION_KEY).remove();

    ChannelFuture future = ctx.writeAndFlush(rsp);
    if (isClose) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.xx_dev.apn.proxy.ApnProxyRelayHandler.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    LoggerUtil.debug(logger, ctx.channel().attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), tag,
            "channel inactive");
    if (relayChannel != null && relayChannel.isActive()) {
        relayChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }/*from ww w .  ja  v a2  s.c  o m*/
    ctx.fireChannelInactive();
}

From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentForwardHandler.java

License:Apache License

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

    final Channel uaChannel = uaChannelCtx.channel();

    final ApnProxyRemote apnProxyRemote = uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get()
            .getRemote();//w  w  w .j  av  a  2  s .  c  om

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

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

        if (remoteChannel != null && remoteChannel.isActive()) {
            LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                    "Use old remote channel");
            HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote);
            remoteChannel.writeAndFlush(request);
        } else {
            LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                    "Create new remote channel");

            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 ApnProxyRemoteForwardChannelInitializer(uaChannel, this));

            // set local address
            if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) {
                bootstrap.localAddress(new InetSocketAddress(
                        (ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0));
            }

            ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getRemoteHost(),
                    apnProxyRemote.getRemotePort());

            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 {
                        LoggerUtil.error(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                                "Remote channel create fail");

                        // send error response
                        String errorMsg = "remote connect to "
                                + uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote()
                                        .getRemoteAddr()
                                + " fail";
                        HttpMessage errorResponseMsg = HttpErrorUtil
                                .buildHttpErrorMessage(HttpResponseStatus.INTERNAL_SERVER_ERROR, errorMsg);
                        uaChannel.writeAndFlush(errorResponseMsg);
                        httpContentBuffer.clear();

                        future.channel().close();
                    }
                }
            });

        }
        ReferenceCountUtil.release(msg);
    } else {
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        HttpContent hc = ((HttpContent) msg);
        //hc.retain();

        //HttpContent _hc = hc.copy();

        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.xx_dev.apn.proxy.ApnProxyUserAgentForwardHandler.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext uaChannelCtx) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("UA channel: inactive" + uaChannelCtx.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY));
    }//from www.  j  av  a 2s.  co m
    LoggerUtil.debug(logger, uaChannelCtx.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
            "UA channel inactive");

    for (Map.Entry<String, Channel> entry : remoteChannelMap.entrySet()) {
        final Channel remoteChannel = entry.getValue();
        remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                remoteChannel.close();
            }
        });
    }
}

From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentForwardHandler.java

License:Apache License

@Override
public void remoteChannelInactive(final Channel uaChannel, String inactiveRemoteAddr) throws Exception {
    LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
            "Remote channel inactive, and flush end");

    remoteChannelMap.remove(inactiveRemoteAddr);

    if (uaChannel.isActive()) {
        uaChannel.writeAndFlush(Unpooled.EMPTY_BUFFER);
    }/*w  ww . ja  v  a 2 s  . c om*/

}

From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentTunnelHandler.java

License:Apache License

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

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

        //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 ApnProxyTunnelChannelInitializer(uaChannelCtx.channel()));

        final ApnProxyRemote apnProxyRemote = uaChannelCtx.channel()
                .attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

        // set local address
        if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) {
            bootstrap.localAddress(new InetSocketAddress(
                    (ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0));
        }//  w  ww .j  av a  2s.c  o m

        bootstrap.connect(apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort())
                .addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(final ChannelFuture future1) throws Exception {
                        if (future1.isSuccess()) {
                            if (apnProxyRemote.isAppleyRemoteRule()) {
                                uaChannelCtx.pipeline().remove("codec");
                                uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME);
                                uaChannelCtx.pipeline().remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME);

                                // add relay handler
                                uaChannelCtx.pipeline()
                                        .addLast(new ApnProxyRelayHandler("UA --> Remote", future1.channel()));

                                future1.channel()
                                        .writeAndFlush(Unpooled.copiedBuffer(
                                                constructConnectRequestForProxy(httpRequest, apnProxyRemote),
                                                CharsetUtil.UTF_8))
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future2)
                                                    throws Exception {
                                                if (!future2.channel().config()
                                                        .getOption(ChannelOption.AUTO_READ)) {
                                                    future2.channel().read();
                                                }
                                            }
                                        });

                            } else {
                                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(ApnProxyPreHandler.HANDLER_NAME);
                                                uaChannelCtx.pipeline()
                                                        .remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME);

                                                // add relay handler
                                                uaChannelCtx.pipeline()
                                                        .addLast(new ApnProxyRelayHandler(
                                                                "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.yahoo.pulsar.common.compression.CompressorCodecTest.java

License:Apache License

@Test(dataProvider = "codec")
void testEmptyInput(CompressionType type) throws IOException {
    CompressionCodec codec = CompressionCodecProvider.getCompressionCodec(type);

    ByteBuf compressed = codec.encode(Unpooled.EMPTY_BUFFER);
    ByteBuf uncompressed = codec.decode(compressed, 0);

    assertEquals(uncompressed, Unpooled.EMPTY_BUFFER);
}

From source file:de.dfki.kiara.http.HttpHandler.java

License:Open Source License

@Override
public ListenableFuture<Void> send(TransportMessage message) {
    if (message == null) {
        throw new NullPointerException("msg");
    }//  www. jav a2 s  .  co  m
    if (state != State.CONNECTED || channel == null) {
        throw new IllegalStateException("state=" + state.toString() + " channel=" + channel);
    }

    HttpMessage httpMsg;

    boolean keepAlive = true;

    if (message instanceof HttpRequestMessage) {
        HttpRequestMessage msg = (HttpRequestMessage) message;

        httpMsg = msg.finalizeRequest();

        if (logger.isDebugEnabled()) {
            logger.debug("SEND CONTENT: {}", msg.getContent().content().toString(StandardCharsets.UTF_8));
        }
    } else if (message instanceof HttpResponseMessage) {
        HttpResponseMessage msg = (HttpResponseMessage) message;

        httpMsg = msg.finalizeResponse();

        keepAlive = HttpHeaders.isKeepAlive(httpMsg);

        if (logger.isDebugEnabled()) {
            logger.debug("SEND CONTENT: {}", msg.getContent().content().toString(StandardCharsets.UTF_8));
        }
    } else {
        throw new IllegalArgumentException("msg is neither of type HttpRequestMessage nor HttpResponseMessage");
    }

    ChannelFuture result = channel.writeAndFlush(httpMsg);

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

    return new ListenableConstantFutureAdapter<>(result, null);
}