Example usage for io.netty.buffer Unpooled buffer

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

Introduction

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

Prototype

public static ByteBuf buffer() 

Source Link

Document

Creates a new big-endian Java heap buffer with reasonably small initial capacity, which expands its capacity boundlessly on demand.

Usage

From source file:cc.agentx.client.net.nio.XConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    boolean proxyMode = isAgentXNeeded(request.host());
    log.info("\tClient -> Proxy           \tTarget {}:{} [{}]", request.host(), request.port(),
            proxyMode ? "AGENTX" : "DIRECT");
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new FutureListener<Channel>() {
        @Override// ww  w . j  av  a2  s  .c  o  m
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .addListener(channelFuture -> {
                            ByteBuf byteBuf = Unpooled.buffer();
                            request.encodeAsByteBuf(byteBuf);
                            if (byteBuf.hasArray()) {
                                byte[] xRequestBytes = new byte[byteBuf.readableBytes()];
                                byteBuf.getBytes(0, xRequestBytes);

                                if (proxyMode) {
                                    // handshaking to remote proxy
                                    xRequestBytes = requestWrapper.wrap(xRequestBytes);
                                    outboundChannel.writeAndFlush(Unpooled.wrappedBuffer(
                                            exposeRequest ? xRequestBytes : wrapper.wrap(xRequestBytes)));
                                }

                                // task handover
                                ReferenceCountUtil.retain(request); // auto-release? a trap?
                                ctx.pipeline().remove(XConnectHandler.this);
                                outboundChannel.pipeline().addLast(new XRelayHandler(ctx.channel(),
                                        proxyMode ? wrapper : rawWrapper, false));
                                ctx.pipeline().addLast(new XRelayHandler(outboundChannel,
                                        proxyMode ? wrapper : rawWrapper, true));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));

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

    String host = request.host();
    int port = request.port();
    if (host.equals(config.getConsoleDomain())) {
        host = "localhost";
        port = config.getConsolePort();
    } else if (proxyMode) {
        host = config.getServerHost();
        port = config.getServerPort();
    }

    // ping target
    bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port)
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.channel().writeAndFlush(
                                new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                        if (ctx.channel().isActive()) {
                            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        }
                    }
                }
            });
}

From source file:chapter01.EchoClientHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    String sendMessage = "Hello netty";

    ByteBuf messageBuffer = Unpooled.buffer();
    messageBuffer.writeBytes(sendMessage.getBytes());

    StringBuilder builder = new StringBuilder();
    builder.append(" ? [");
    builder.append(sendMessage);/*from ww  w  . j  av  a 2 s.  c o m*/
    builder.append("]");

    //System.out.println(builder.toString());
    log.info(String.valueOf(builder));
    ctx.writeAndFlush(messageBuffer);
}

From source file:cn.liutils.api.player.ControlData.java

License:Open Source License

@Override
public void saveNBTData(NBTTagCompound tag) {
    ByteBuf buf = Unpooled.buffer();
    toBytes(buf);
    tag.setByteArray(IDENTIFIER, buf.array());
}

From source file:co.rsk.rpc.netty.JsonRpcWeb3ServerHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBufHolder request) throws Exception {
    ByteBuf responseContent = Unpooled.buffer();
    int responseCode;
    try (ByteBufOutputStream os = new ByteBufOutputStream(responseContent);
            ByteBufInputStream is = new ByteBufInputStream(request.content().retain())) {

        responseCode = jsonRpcServer.handleRequest(is, os);
    } catch (Exception e) {
        String unexpectedErrorMsg = "Unexpected error";
        LOGGER.error(unexpectedErrorMsg, e);
        int errorCode = ErrorResolver.JsonError.CUSTOM_SERVER_ERROR_LOWER;
        responseContent = buildErrorContent(errorCode, unexpectedErrorMsg);
        responseCode = errorCode;/*from w  w  w. j av a 2s .  c om*/
    }

    ctx.fireChannelRead(new Web3Result(responseContent, responseCode));
}

From source file:com.addthis.hydra.store.db.DBKey.java

License:Apache License

@Override
public byte[] deltaEncode(@Nonnull IPageDB.Key baseKey) {
    long offset = id - baseKey.id();
    ByteBuf buffer = Unpooled.buffer();
    Varint.writeSignedVarLong(offset, buffer);
    if (key != null) {
        buffer.writeBytes(key.toBytes());
    }//from ww w.  j av  a2s . com
    return Arrays.copyOf(buffer.array(), buffer.readableBytes());
}

From source file:com.barchart.http.server.HttpRequestChannelHandler.java

License:BSD License

private void sendServerError(final ChannelHandlerContext ctx, final ServerException cause) throws Exception {

    if (ctx.channel().isActive()) {

        final ByteBuf content = Unpooled.buffer();

        content.writeBytes(//from   w ww.ja v  a2s.  c o  m
                (cause.getStatus().code() + " " + cause.getStatus().reasonPhrase() + " - " + cause.getMessage())
                        .getBytes());

        final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, cause.getStatus());

        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());

        response.content().writeBytes(content);

        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

    }

}

From source file:com.basho.riak.client.core.netty.RiakHttpMessageHandlerTest.java

License:Apache License

@Test
public void notifiesListenerOnComplete() throws Exception {
    HttpResponse response = mock(HttpResponse.class);
    HttpResponseStatus status = mock(HttpResponseStatus.class);
    doReturn(status).when(response).getStatus();
    doReturn(200).when(status).code();/*from  w  ww .jav  a  2  s. c  o m*/
    LastHttpContent lastContent = mock(LastHttpContent.class);
    ByteBuf bb = Unpooled.buffer();
    bb.writeByte((byte) 1);
    doReturn(bb).when(lastContent).data();
    handler.messageReceived(mockContext, response);
    handler.messageReceived(mockContext, lastContent);

    verify(mockListener).onSuccess(Matchers.any(Channel.class), Matchers.any(RiakHttpMessage.class));
}

From source file:com.basho.riak.client.core.netty.RiakHttpMessageHandlerTest.java

License:Apache License

@Test
public void removesSelfFromPipelineOnCompletion() throws Exception {
    HttpResponse response = mock(HttpResponse.class);
    HttpResponseStatus status = mock(HttpResponseStatus.class);
    doReturn(status).when(response).getStatus();
    doReturn(200).when(status).code();/*from  ww w  .  ja v  a2 s  . c  o m*/
    LastHttpContent lastContent = mock(LastHttpContent.class);
    ByteBuf bb = Unpooled.buffer();
    bb.writeByte((byte) 1);
    doReturn(bb).when(lastContent).data();
    handler.messageReceived(mockContext, response);
    handler.messageReceived(mockContext, lastContent);

    verify(mockPipeline).remove(handler);
}

From source file:com.basho.riak.client.core.netty.RiakHttpMessageHandlerTest.java

License:Apache License

@Test
public void producesCorrectResponse() throws Exception {
    HttpResponse response = mock(HttpResponse.class);
    HttpResponseStatus status = mock(HttpResponseStatus.class);
    doReturn(status).when(response).getStatus();
    doReturn(200).when(status).code();/* w  w  w.  java  2  s. c o m*/
    HttpContent content = mock(HttpContent.class);
    LastHttpContent lastContent = mock(LastHttpContent.class);

    ByteBuf bb = Unpooled.buffer();
    bb.writeByte((byte) 1);
    doReturn(bb).when(content).data();
    doReturn(bb.copy()).when(lastContent).data();

    handler.messageReceived(mockContext, response);
    handler.messageReceived(mockContext, content);
    handler.messageReceived(mockContext, lastContent);

    RiakHttpMessage message = Whitebox.getInternalState(handler, "message");

    verify(mockListener).onSuccess(mockChannel, message);
    assertEquals(message.getResponse(), response);
    byte[] bytes = new byte[] { 1, 1 };
    assertArrayEquals(message.getContent(), bytes);
}

From source file:com.basho.riak.client.core.netty.RiakMessageCodecTest.java

License:Apache License

@Before
public void setUp() throws Exception {
    code = 1;//from w w  w  .j  a v  a2  s .  c o  m
    data = new byte[SIZE_DATA];
    Arrays.fill(data, (byte) 1);

    RiakMessage pbMessage = new RiakMessage(code, data);
    RiakMessageCodec codec = new RiakMessageCodec();

    mockContext = mock(ChannelHandlerContext.class);
    buffer = Unpooled.buffer();
    Whitebox.invokeMethod(codec, "encode", mockContext, pbMessage, buffer);
}