Example usage for io.netty.buffer ByteBuf readBytes

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

Introduction

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

Prototype

public abstract ByteBuf readBytes(ByteBuffer dst);

Source Link

Document

Transfers this buffer's data to the specified destination starting at the current readerIndex until the destination's position reaches its limit, and increases the readerIndex by the number of the transferred bytes.

Usage

From source file:com.vethrfolnir.network.ReadPacket.java

License:Open Source License

protected byte[] readByteArray(ByteBuf buff) {
    byte[] arr = new byte[buff.readableBytes()];
    buff.readBytes(arr);
    return arr;//from  www .j a  va2s . c o m
}

From source file:com.vethrfolnir.network.ReadPacket.java

License:Open Source License

/**
 * Don't forget to release the buffer/*from   w  ww. j a  va  2  s.c o  m*/
 * @param buff
 * @param len
 * @return
 */
protected ByteBuf readArray(ByteBuf buff, int len) {
    return buff.readBytes(len);
}

From source file:com.weibo.api.motan.transport.netty.NettyDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

    if (in.readableBytes() <= MotanConstants.NETTY_HEADER) {
        return;//from  www .j  a  v  a 2  s.c  o m
    }

    in.markReaderIndex();

    short type = in.readShort();

    if (type != MotanConstants.NETTY_MAGIC_TYPE) {
        in.resetReaderIndex();
        throw new MotanFrameworkException("NettyDecoder transport header not support, type: " + type);
    }

    byte messageType = (byte) in.readShort();
    long requestId = in.readLong();

    int dataLength = in.readInt();

    // FIXME dataLength?
    if (in.readableBytes() < dataLength) {
        in.resetReaderIndex();
        return;
    }

    if (maxContentLength > 0 && dataLength > maxContentLength) {
        LoggerUtil.warn(
                "NettyDecoder transport data content length over of limit, size: {}  > {}. remote={} local={}",
                dataLength, maxContentLength, ctx.channel().remoteAddress(), ctx.channel().localAddress());
        Exception e = new MotanServiceException(
                "NettyDecoder transport data content length over of limit, size: " + dataLength + " > "
                        + maxContentLength);

        if (messageType == MotanConstants.FLAG_REQUEST) {
            Response response = buildExceptionResponse(requestId, e);
            ctx.channel().writeAndFlush(response);
            throw e;
        } else {
            throw e;
        }
    }

    byte[] data = new byte[dataLength];

    in.readBytes(data);

    try {
        String remoteIp = getRemoteIp(ctx.channel());
        out.add(codec.decode(client, remoteIp, data));
    } catch (Exception e) {
        //????
        if (messageType == MotanConstants.FLAG_REQUEST) {
            Response response = buildExceptionResponse(requestId, e);
            ctx.channel().writeAndFlush(response);
            return;
        } else {
            out.add(buildExceptionResponse(requestId, e));
            return;
        }
    }
}

From source file:com.whizzosoftware.foscam.camera.protocol.OrderDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> list) throws Exception {
    Byte b;/*from  w ww  . ja v a  2  s.c  o  m*/
    if (buf.isReadable()) {
        do {
            b = buf.readByte();
        } while (b != 'M' && buf.isReadable());

        if (buf.readableBytes() > 0) {
            logger.trace("Found possible start of order");
            b = buf.readByte();
            if (b == 'O' && buf.isReadable()) {
                b = buf.readByte();
                if (b == '_' && buf.isReadable()) {
                    b = buf.readByte();
                    if (b == 'I' && buf.isReadable()) {
                        Integer operationCode = popINT16(buf);
                        if (operationCode != null) {
                            if (popBytes(buf, 9)) {
                                Integer length = popINT32(buf);
                                if (length != null && popBytes(buf, 4)) {
                                    if (buf.readableBytes() >= length) {
                                        byte[] text = new byte[length];
                                        buf.readBytes(text);
                                        switch (operationCode) {
                                        case 1:
                                            try {
                                                list.add(new SearchResponse(text, 0, length));
                                            } catch (UnknownHostException e) {
                                                logger.error("Error processing search response", e);
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:com.whizzosoftware.foscam.camera.protocol.OrderDecoder.java

License:Open Source License

/**
 * Pop a specified number of bytes from the buffer
 *
 * @param buf the byte buffer to read from
 * @param num the number of bytes to pop (read & discard)
 *
 * @return whether the bytes were successfully popped
 *///from   www  .j  a  v  a 2s. c  o  m
private boolean popBytes(ByteBuf buf, int num) {
    if (buf.readableBytes() > num) {
        buf.readBytes(num);
        return true;
    } else {
        return false;
    }
}

From source file:com.whizzosoftware.hobson.davisvantage.api.codec.VantageSerialFrameDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf buffer, List<Object> list)
        throws Exception {
    int ix = buffer.readerIndex();
    int readableBytes = buffer.readableBytes();
    logger.trace("Readable bytes remaining to read: {}", readableBytes);
    if (readableBytes > 0) {
        if (buffer.readableBytes() >= 6 && buffer.getByte(ix) == 'T' && buffer.getByte(ix + 1) == 'E'
                && buffer.getByte(ix + 2) == 'S' && buffer.getByte(ix + 3) == 'T'
                && buffer.getByte(ix + 4) == '\n' && buffer.getByte(ix + 5) == '\r') {
            buffer.readBytes(6);
            logger.trace("Got TEST");
            list.add(new Test());
        } else if (buffer.getByte(ix) == '\r' || buffer.getByte(ix) == '\n') {
            logger.trace("Discarding whitespace: {}", (int) buffer.getByte(ix));
            buffer.readByte();/*from  w ww  .  j a va 2  s. c  om*/
        } else if (buffer.getByte(ix) == 0x06) {
            buffer.readByte();
            list.add(new ACK());
        } else if (buffer.readableBytes() >= 4 && buffer.getByte(ix) == 'O' && buffer.getByte(ix + 1) == 'K'
                && buffer.getByte(ix + 2) == '\n' && buffer.getByte(ix + 3) == '\r') {
            logger.trace("Got OK");
            buffer.readBytes(4);
            list.add(new OK());
        } else if (buffer.getByte(ix) == 'L' && buffer.getByte(ix + 1) == 'O'
                && buffer.getByte(ix + 2) == 'O') {
            if (buffer.readableBytes() >= 99) {
                logger.trace("Got LOOP");
                byte[] bytes = new byte[99];
                buffer.readBytes(bytes, 0, 99);
                list.add(new LoopResponse(bytes));
            }
        } else if ((buffer.getByte(ix) == 'A' && buffer.getByte(ix + 1) == 'p' && buffer.getByte(ix + 2) == 'r')
                || (buffer.getByte(ix) == 'A' && buffer.getByte(ix + 1) == 'u' && buffer.getByte(ix + 2) == 'g')
                || (buffer.getByte(ix) == 'D' && buffer.getByte(ix + 1) == 'e' && buffer.getByte(ix + 2) == 'c')
                || (buffer.getByte(ix) == 'F' && buffer.getByte(ix + 1) == 'e' && buffer.getByte(ix + 2) == 'b')
                || (buffer.getByte(ix) == 'J' && buffer.getByte(ix + 1) == 'a' && buffer.getByte(ix + 2) == 'n')
                || (buffer.getByte(ix) == 'J' && buffer.getByte(ix + 1) == 'u' && buffer.getByte(ix + 2) == 'l')
                || (buffer.getByte(ix) == 'J' && buffer.getByte(ix + 1) == 'u' && buffer.getByte(ix + 2) == 'n')
                || (buffer.getByte(ix) == 'M' && buffer.getByte(ix + 1) == 'a' && buffer.getByte(ix + 2) == 'r')
                || (buffer.getByte(ix) == 'M' && buffer.getByte(ix + 1) == 'a' && buffer.getByte(ix + 2) == 'y')
                || (buffer.getByte(ix) == 'N' && buffer.getByte(ix + 1) == 'o' && buffer.getByte(ix + 2) == 'v')
                || (buffer.getByte(ix) == 'O' && buffer.getByte(ix + 1) == 'c' && buffer.getByte(ix + 2) == 't')
                || (buffer.getByte(ix) == 'D' && buffer.getByte(ix + 1) == 'e'
                        && buffer.getByte(ix + 2) == 'c')) {
            if (buffer.readableBytes() >= 13) {
                byte[] bytes = new byte[13];
                buffer.readBytes(bytes, 0, 13);
                list.add(new VersionResponse(new String(bytes, 0, 11)));
            }
        } else {
            byte b = buffer.readByte();
            logger.trace("Discarding unknown byte: {}", Hex.encodeHexString(new byte[] { b }));
        }
    }
}

From source file:com.whizzosoftware.hobson.mysensors.protocol.MySensorsDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf buf, List<Object> out)
        throws Exception {
    if (buf.readableBytes() > 0) {
        byte[] b = new byte[buf.readableBytes()];
        buf.readBytes(b);
        String s = new String(b);
        logger.trace("Read: {}", s);

        String[] tokens = s.split(";");

        if (tokens.length >= 5) {
            try {
                out.add(new MySensorsMessage(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]),
                        Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]) == 1,
                        Integer.parseInt(tokens[4]), tokens.length >= 6 ? tokens[5] : null));
            } catch (NumberFormatException e) {
                logger.error("Received invalid message: {}", s);
            }/*  ww  w  . ja va  2 s. com*/
        } else {
            logger.error("Received invalid message: {}", s);
        }
    }
}

From source file:com.whizzosoftware.hobson.ssdp.SSDPInboundHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
    final DatagramPacket p = (io.netty.channel.socket.DatagramPacket) o;
    ByteBuf buf = p.content();
    byte[] b = new byte[buf.readableBytes()];
    buf.readBytes(b);
    final String data = new String(b, 0, b.length, "UTF8");
    buf.release();/* w  w w.  j av a  2s  .  c o m*/
    logger.trace("Received data from {}: {}", p.sender().getHostString(), data);

    // publish the advertisement
    try {
        final SSDPPacket packet = SSDPPacket.createWithData(data);
        // ignore packets that originated from Hobson
        if (!p.sender().getAddress().equals(InetAddress.getLocalHost())) {
            if ("M-SEARCH".equals(packet.getMethod())) {
                context.executeInEventLoop(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            context.processDiscoveryRequest(p.sender(), packet);
                        } catch (Throwable e) {
                            logger.error("Error processing discovery packet", e);
                        }
                    }
                });
            } else if (packet.getUSN() != null && packet.getLocation() != null) {
                // execute this in the event loop so we can get on with processing UDP packets as
                // quickly as possible
                context.executeInEventLoop(new Runnable() {
                    @Override
                    public void run() {
                        context.publishDeviceAdvertisement(
                                new DeviceAdvertisement.Builder(packet.getUSN(), SSDPPacket.PROTOCOL_ID)
                                        .rawData(data).object(packet).build(),
                                false);
                    }
                });
            } else {
                logger.trace("Ignoring SSDP packet with USN {} and location: {}", packet.getUSN(),
                        packet.getLocation());
            }
        }
    } catch (Throwable e) {
        logger.error("Error creating SSDP packet", e);
    }
}

From source file:com.whizzosoftware.wzwave.codec.ZWaveFrameDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("RCVD: {}", ByteUtil.createString(in));
    }/*from   ww w .  j  av  a 2 s  . c  o  m*/

    ByteBuf data;

    // if there was data left from the last decode call, create a composite ByteBuf that contains both
    // previous and new data
    if (previousBuf != null) {
        CompositeByteBuf cbuf = Unpooled.compositeBuffer(2);
        cbuf.addComponent(previousBuf.copy());
        cbuf.addComponent(in);
        cbuf.writerIndex(previousBuf.readableBytes() + in.readableBytes());
        data = cbuf;
        // release the data from the previous decode call
        previousBuf.release();
        previousBuf = null;
    } else {
        data = in;
    }

    while (data.isReadable()) {
        // check for single ACK/NAK/CAN
        if (data.readableBytes() == 1 && isSingleByteFrame(data, data.readerIndex())) {
            out.add(createSingleByteFrame(data));
        } else {
            boolean foundFrame = false;
            // search for a valid frame in the data
            for (int searchStartIx = data.readerIndex(); searchStartIx < data.readerIndex()
                    + data.readableBytes(); searchStartIx++) {
                if (data.getByte(searchStartIx) == DataFrame.START_OF_FRAME) {
                    int frameEndIx = scanForFrame(data, searchStartIx);
                    if (frameEndIx > 0) {
                        if (searchStartIx > data.readerIndex() && isSingleByteFrame(data, searchStartIx - 1)) {
                            data.readerIndex(searchStartIx - 1);
                            out.add(createSingleByteFrame(data));
                        } else if (searchStartIx > data.readerIndex()) {
                            data.readerIndex(searchStartIx);
                        }
                        DataFrame df = createDataFrame(data);
                        if (df != null) {
                            out.add(df);
                            data.readByte(); // discard checksum
                            foundFrame = true;
                        } else {
                            logger.debug("Unable to determine frame type");
                        }
                    }
                }
            }
            if (!foundFrame) {
                previousBuf = data.copy();
                break;
            }
        }
    }

    // make sure we read from the input ByteBuf so Netty doesn't throw an exception
    in.readBytes(in.readableBytes());

    logger.trace("Done processing received data: {}", out);
}

From source file:com.whizzosoftware.wzwave.frame.ApplicationCommand.java

License:Open Source License

public ApplicationCommand(ByteBuf buffer) {
    super(buffer);

    this.status = buffer.readByte();
    this.nodeId = buffer.readByte();

    byte cmdLength = buffer.readByte();
    commandClassBytes = buffer.readBytes(cmdLength).array();
}