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.whizzosoftware.hobson.davisvantage.api.codec.VantageSerialFrameEncoderTest.java

License:Open Source License

@Test
public void testLoopRequest() throws Exception {
    VantageSerialFrameEncoder encoder = new VantageSerialFrameEncoder();

    com.whizzosoftware.hobson.davisvantage.api.command.LoopRequest ver = new com.whizzosoftware.hobson.davisvantage.api.command.LoopRequest(
            5);/*from  w  w w. j av  a 2  s.  c o m*/
    ByteBuf buf = Unpooled.buffer();
    encoder.encode(null, ver, buf);
    assertEquals("LOOP 5\n", buf.toString(Charset.forName("UTF8")));
}

From source file:com.whizzosoftware.hobson.dsc.api.codec.DSCFrameDecoder.java

License:Open Source License

@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    logger.trace("decode: {}", buffer.toString(CharsetUtil.UTF_8));

    ByteBuf frame = (ByteBuf) super.decode(ctx, buffer);

    if (frame != null) {
        try {/* www.  j  a v  a  2s. c o m*/
            if (frame.readableBytes() >= 3) {
                String cmdId = new String(new byte[] { frame.getByte(0), frame.getByte(1), frame.getByte(2) });
                switch (cmdId) {
                case CodeRequired.ID:
                    return new CodeRequired();
                case CommandAcknowledge.ID:
                    return new CommandAcknowledge();
                case CommandError.ID:
                    return new CommandError();
                case LCDUpdate.ID:
                    int lineNumber = frame.getByte(3) - '0';
                    int columnNumber = Integer
                            .parseInt(new String(new byte[] { frame.getByte(4), frame.getByte(5) }));
                    int length = Integer
                            .parseInt(new String(new byte[] { frame.getByte(6), frame.getByte(7) }));
                    return new LCDUpdate(lineNumber, columnNumber,
                            frame.slice(8, length).toString(CharsetUtil.UTF_8));
                case LEDStatus.ID:
                    return new LEDStatus(LEDStatus.LEDType.forOrdinal(frame.getByte(3) - '0'),
                            LEDStatus.Status.forOrdinal(frame.getByte(4) - '0'));
                case SoftwareVersion.ID:
                    return new SoftwareVersion(frame.slice(3, 4).toString(CharsetUtil.UTF_8));
                case PartitionBusy.ID:
                    return new PartitionBusy(frame.getByte(3) - '0');
                case PartitionNotReady.ID:
                    return new PartitionNotReady(frame.getByte(3) - '0');
                case PartitionReady.ID:
                    return new PartitionReady(frame.getByte(3) - '0');
                case TroubleLEDOff.ID:
                    return new TroubleLEDOff(frame.getByte(3) - '0');
                case ZoneOpen.ID:
                    return new ZoneOpen(Integer.parseInt(
                            new String(new byte[] { frame.getByte(3), frame.getByte(4), frame.getByte(5) })));
                case ZoneRestored.ID:
                    return new ZoneRestored(Integer.parseInt(
                            new String(new byte[] { frame.getByte(3), frame.getByte(4), frame.getByte(5) })));
                case TimeDateBroadcast.ID:
                    return new TimeDateBroadcast(frame.slice(3, 10).toString(CharsetUtil.UTF_8));
                default:
                    logger.debug("Ignoring unknown command frame: {}", buffer.toString(CharsetUtil.UTF_8));
                    return null;
                }
            } else {
                throw new CorruptedFrameException("Frame should not be less than 3 bytes");
            }
        } finally {
            frame.release();
        }
    } else {
        return null;
    }
}

From source file:com.whizzosoftware.hobson.radiora.api.codec.RadioRaFrameDecoder.java

License:Open Source License

@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    logger.trace("decode: {}", buffer.toString(CharsetUtil.UTF_8));

    ByteBuf frame = (ByteBuf) super.decode(ctx, buffer);

    if (frame != null) {
        // if we receive a single byte frame, it should be a '!'
        if (frame.readableBytes() == 1) {
            byte b = frame.readByte();
            if (b == '!') {
                return null;
            } else {
                throw new CorruptedFrameException("Unexpected single byte frame");
            }//from   w  ww .  j a va  2 s  . com
            // otherwise, we assume it's a command frame
        } else {
            int ix = frame.indexOf(frame.readerIndex(), frame.writerIndex(), (byte) ',');
            if (ix > 0) {
                String cmdName = frame.slice(0, ix).toString(CharsetUtil.UTF_8);

                switch (cmdName) {
                case ZoneMap.TYPE:
                    if (frame.readableBytes() >= ix + 33) {
                        return new ZoneMap(frame.slice(ix + 1, 32).toString(CharsetUtil.UTF_8));
                    } else {
                        throw new CorruptedFrameException("Received invalid zone map size");
                    }

                case LocalZoneChange.TYPE:
                    if (frame.readableBytes() >= ix + 3) {
                        String sZoneNum = frame.slice(ix + 1, 2).toString(CharsetUtil.UTF_8);
                        if (frame.readableBytes() >= ix + 7) {
                            String state = frame.slice(ix + 4, 3).toString(CharsetUtil.UTF_8).trim();
                            try {
                                return new LocalZoneChange(Integer.parseInt(sZoneNum),
                                        LocalZoneChange.State.valueOf(state));
                            } catch (IllegalArgumentException iae) {
                                throw new CorruptedFrameException("Invalid LZC state string");
                            }
                        } else {
                            throw new CorruptedFrameException("Invalid LZC size (state)");
                        }
                    } else {
                        throw new CorruptedFrameException("Invalid LZC size (zoneNum)");
                    }

                case LEDMap.TYPE:
                    if (frame.readableBytes() >= ix + 16) {
                        return new LEDMap(frame.slice(ix + 1, 15).toString(CharsetUtil.UTF_8));
                    } else {
                        throw new CorruptedFrameException("Invalid LED map size");
                    }

                default:
                    throw new DecoderException("Unrecognized command: " + cmdName);
                }
            } else {
                throw new CorruptedFrameException("Invalid frame format (no comma)");
            }
        }
    } else {
        return null;
    }
}

From source file:com.whizzosoftware.hobson.radiora.api.codec.RadioRaFrameEncoderTest.java

License:Open Source License

@Test
public void testSetDimmerLevelEncode() throws Exception {
    RadioRaFrameEncoder encoder = new RadioRaFrameEncoder();

    // test with 3 digit level
    SetDimmerLevel sdl = new SetDimmerLevel(1, 100);
    ByteBuf buf = Unpooled.buffer();
    encoder.encode(null, sdl, buf);//from w  ww. j a  v a2s.  c  om
    assertEquals("SDL,1,100\r", buf.toString(Charset.forName("UTF8")));

    // test with 1 digit level
    sdl = new SetDimmerLevel(1, 1);
    buf = Unpooled.buffer();
    encoder.encode(null, sdl, buf);
    assertEquals("SDL,1,1\r", buf.toString(Charset.forName("UTF8")));

    // test with fade time
    sdl = new SetDimmerLevel(1, 1, 50);
    buf = Unpooled.buffer();
    encoder.encode(null, sdl, buf);
    assertEquals("SDL,1,1,50\r", buf.toString(Charset.forName("UTF8")));
}

From source file:com.whizzosoftware.hobson.radiora.api.codec.RadioRaFrameEncoderTest.java

License:Open Source License

@Test
public void testSetSwitchLevelEncode() throws Exception {
    RadioRaFrameEncoder encoder = new RadioRaFrameEncoder();

    // test with single digit zone number
    SetSwitchLevel ssl = new SetSwitchLevel(1, true);
    ByteBuf buf = Unpooled.buffer();
    encoder.encode(null, ssl, buf);// w  ww  .j a v  a2  s . c om
    assertEquals("SSL,1,ON\r", buf.toString(Charset.forName("UTF8")));

    // test with double digit zone number
    ssl = new SetSwitchLevel(10, true);
    buf = Unpooled.buffer();
    encoder.encode(null, ssl, buf);
    assertEquals("SSL,10,ON\r", buf.toString(Charset.forName("UTF8")));

    // test with delay time
    ssl = new SetSwitchLevel(10, true, 50);
    buf = Unpooled.buffer();
    encoder.encode(null, ssl, buf);
    assertEquals("SSL,10,ON,50\r", buf.toString(Charset.forName("UTF8")));
}

From source file:com.whizzosoftware.hobson.radiora.api.codec.RadioRaFrameEncoderTest.java

License:Open Source License

@Test
public void testZoneMapInquiryEncode() throws Exception {
    RadioRaFrameEncoder encoder = new RadioRaFrameEncoder();
    ZoneMapInquiry zmpi = new ZoneMapInquiry();
    ByteBuf buf = Unpooled.buffer();
    encoder.encode(null, zmpi, buf);/*from   ww w .  j  a v  a2 s  .c o m*/
    assertEquals("ZMPI\r", buf.toString(Charset.forName("UTF8")));
}

From source file:com.xxx.demo.netty.echo.EchoClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {

    ByteBuf in = (ByteBuf) msg;
    System.out.println(in.toString(CharsetUtil.US_ASCII));

    //ctx.write(msg);
}

From source file:com.xxx.util.io.client.netty.EchoClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {

    ByteBuf in = (ByteBuf) msg;
    System.out.println(in.toString(CharsetUtil.US_ASCII));

    //       ByteBuf in2 = ByteBufUtil.threadLocalDirectBuffer();
    //       System.out.println(in2.toString(CharsetUtil.US_ASCII));
    //ctx.write(msg);
}

From source file:com.zhang.client.NettyHttpResponse.java

License:Apache License

public String getResponseBody(Charset charset) {
    if (null == contents || 0 == contents.size()) {
        return null;
    }//from  w w w. ja v a 2 s.  com
    StringBuilder responseBody = new StringBuilder();
    for (ByteBuf content : contents) {
        responseBody.append(content.toString(charset));
    }

    return responseBody.toString();
}

From source file:com.zhuowenfeng.devtool.hs_server.handler.HttpServiceHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    HSServerContext hsContext = new HSServerContext();
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        hsContext.setRequest(request);//  w  w w.j av a  2 s .co  m

        String uri = request.getUri();
        hsContext.setRequestUri(uri);

        if (is100ContinueExpected(request)) {
            send100Continue(ctx);
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        JSONObject pathVariables = new JSONObject();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    pathVariables.put(key, val);
                }
            }
        }
        hsContext.setPathVariables(pathVariables);
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;
        ByteBuf content = httpContent.content();
        JSONObject requestContent = new JSONObject();
        if (content.isReadable()) {
            requestContent = JSONObject.fromObject(content.toString(CharsetUtil.UTF_8));
        }
        hsContext.setRequestContent(requestContent);
        if (msg instanceof LastHttpContent) {
            LastHttpContent trailer = (LastHttpContent) msg;
            JSONObject result = HttpServiceDispatcher.dispatch(hsContext);
            writeResponse(trailer, ctx, result);
        }
    }
}