Example usage for io.netty.buffer ByteBuf toString

List of usage examples for io.netty.buffer ByteBuf toString

Introduction

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

Prototype

public abstract String toString(Charset charset);

Source Link

Document

Decodes this buffer's readable bytes into a string with the specified character set name.

Usage

From source file:com.dwarf.netty.guide.http.snoop.HttpSnoopServerHandler.java

License:Apache License

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

        if (HttpHeaderUtil.is100ContinueExpected(request)) {
            send100Continue(ctx);//from  w ww . jav a2s  .  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.protocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(request.headers().get(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<CharSequence, CharSequence> 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.eightkdata.mongowp.bson.netty.pool.StringPool.java

License:Open Source License

protected static String getString(@Tight @ConservesIndexes ByteBuf stringBuf) {
    return stringBuf.toString(Charsets.UTF_8);
}

From source file:com.flysoloing.learning.network.netty.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  av a  2s  .  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 (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.github.liyp.netty.App.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();

    try {/*from w  w  w . j a va2s .c  o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(boss, worker).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ReplayingDecoder() {
                            @Override
                            protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
                                    throws Exception {
                                short magicHeader = in.readShort();
                                logger.debug("Receive magic header: {}.", magicHeader);
                                if (magicHeader != HEADER) {
                                    logger.error("Receive illegal magic header: {}, close channel: {}.",
                                            magicHeader, ctx.channel().remoteAddress());
                                    ctx.close();
                                }

                                short dataLen = in.readShort();
                                logger.debug("Receive message data length: {}.", dataLen);
                                if (dataLen < 0) {
                                    logger.error("Data length is negative, close channel: {}.",
                                            ctx.channel().remoteAddress());
                                    ctx.close();
                                }

                                ByteBuf payload = in.readBytes(dataLen);
                                String cloudMsg = payload.toString(CharsetUtil.UTF_8);
                                logger.debug("Receive data: {}.", cloudMsg);
                                out.add(cloudMsg);
                            }
                        }).addLast(new MessageToByteEncoder<String>() {
                            @Override
                            protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out)
                                    throws Exception {
                                out.writeBytes(msg.getBytes());
                            }
                        }).addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("start receive msg...");
                            }

                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                logger.info("receive msg: {}", msg);
                                logger.info("echo msg");
                                ctx.writeAndFlush(msg);
                            }
                        });
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(PORT).sync();
        logger.info("9999");
        f.channel().closeFuture().sync();
    } finally {
        worker.shutdownGracefully();
        boss.shutdownGracefully();
    }
}

From source file:com.github.nettybook.ch7.junit.Base64EncoderTest.java

License:Apache License

@Test
public void testEncoder() {
    String writeData = "";

    ByteBuf request = Unpooled.wrappedBuffer(writeData.getBytes());

    Base64Encoder encoder = new Base64Encoder();
    EmbeddedChannel embeddedChannel = new EmbeddedChannel(encoder);

    embeddedChannel.writeOutbound(request);
    ByteBuf response = (ByteBuf) embeddedChannel.readOutbound();

    String expect = "7JWI64WV7ZWY7IS47JqU";

    assertEquals(expect, response.toString(Charset.defaultCharset()));

    embeddedChannel.finish();//from w w w  .  j  av  a  2  s .  c o  m
}

From source file:com.github.nettybook.ch7.junit.DelimiterBasedFrameDecoderTest.java

License:Apache License

@Test
public void testDecoder() {
    String writeData = "\r\n\r\n";
    String firstResponse = "\r\n";
    String secondResponse = "\r\n";

    DelimiterBasedFrameDecoder decoder = new DelimiterBasedFrameDecoder(8192, false,
            Delimiters.lineDelimiter());
    EmbeddedChannel embeddedChannel = new EmbeddedChannel(decoder);

    ByteBuf request = Unpooled.wrappedBuffer(writeData.getBytes());
    boolean result = embeddedChannel.writeInbound(request);
    assertTrue(result);//  w w  w . j a va  2 s.com

    ByteBuf response = null;

    response = (ByteBuf) embeddedChannel.readInbound();
    assertEquals(firstResponse, response.toString(Charset.defaultCharset()));

    response = (ByteBuf) embeddedChannel.readInbound();
    assertEquals(secondResponse, response.toString(Charset.defaultCharset()));

    embeddedChannel.finish();
}

From source file:com.github.sinsinpub.pero.manual.proxyhandler.HttpProxyServer.java

License:Apache License

private boolean authenticate(ChannelHandlerContext ctx, FullHttpRequest req) {
    assertThat(req.method(), Matchers.is(HttpMethod.CONNECT));

    if (testMode != TestMode.INTERMEDIARY) {
        ctx.pipeline().addBefore(ctx.name(), "lineDecoder", new LineBasedFrameDecoder(64, false, true));
    }//  ww w  . j  a v a 2 s . co  m

    ctx.pipeline().remove(HttpObjectAggregator.class);
    ctx.pipeline().remove(HttpRequestDecoder.class);

    boolean authzSuccess = false;
    if (username != null) {
        CharSequence authz = req.headers().get(HttpHeaderNames.PROXY_AUTHORIZATION);
        if (authz != null) {
            String[] authzParts = StringUtil.split(authz.toString(), ' ', 2);
            ByteBuf authzBuf64 = Unpooled.copiedBuffer(authzParts[1], CharsetUtil.US_ASCII);
            ByteBuf authzBuf = Base64.decode(authzBuf64);

            String expectedAuthz = username + ':' + password;
            authzSuccess = "Basic".equals(authzParts[0])
                    && expectedAuthz.equals(authzBuf.toString(CharsetUtil.US_ASCII));

            authzBuf64.release();
            authzBuf.release();
        }
    } else {
        authzSuccess = true;
    }

    return authzSuccess;
}

From source file:com.gmail.ipshuvaev.server.CustomHttpHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof ByteBuf) {
        // ?  ?   

        ByteBuf buf = (ByteBuf) msg;
        String chunk = buf.toString(CharsetUtil.US_ASCII);
        requestData.append(chunk);/*from  w w w .ja v  a  2  s.  co m*/
    }
}

From source file:com.goide.dlv.DlvVm.java

License:Apache License

public DlvVm(@NotNull DebugEventListener tabListener, @NotNull Channel channel) {
    super(tabListener);

    commandProcessor = new DlvCommandProcessor() {
        @Override//from  ww  w. j a va 2  s  .  com
        public boolean write(@NotNull Request message) throws IOException {
            ByteBuf content = message.getBuffer();
            LOG.info("OUT: " + content.toString(CharsetToolkit.UTF8_CHARSET));
            return vmHelper.write(content);
        }
    };
    vmHelper = new StandaloneVmHelper(this, commandProcessor, channel);

    channel.pipeline().addLast(new JsonObjectDecoder(), new SimpleChannelInboundHandlerAdapter() {
        @Override
        protected void messageReceived(ChannelHandlerContext context, Object message) throws Exception {
            if (message instanceof ByteBuf) {
                LOG.info("IN: " + ((ByteBuf) message).toString(CharsetToolkit.UTF8_CHARSET));
                CharSequence string = ChannelBufferToString.readChars((ByteBuf) message);
                JsonReaderEx ex = new JsonReaderEx(string);
                getCommandProcessor().processIncomingJson(ex);
            }
        }
    });
}

From source file:com.hazelcast.simulator.protocol.handler.SimulatorProtocolDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    if (EMPTY_BUFFER.equals(buffer)) {
        return;//w  w w .ja  v  a  2 s .c om
    }
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(format("SimulatorProtocolDecoder.decode() %s %s", addressLevel, localAddress));
    }

    if (isSimulatorMessage(buffer)) {
        decodeSimulatorMessage(ctx, buffer, out);
        return;
    }
    if (isResponse(buffer)) {
        decodeResponse(ctx, buffer, out);
        return;
    }

    String msg = format("%s %s Invalid magic bytes %s", addressLevel, localAddress,
            buffer.toString(CharsetUtil.UTF_8));
    LOGGER.error(msg);
    throw new IllegalArgumentException(msg);
}