Example usage for io.netty.buffer ByteBuf readerIndex

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

Introduction

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

Prototype

public abstract int readerIndex();

Source Link

Document

Returns the readerIndex of this buffer.

Usage

From source file:com.vethrfolnir.game.network.mu.crypt.MuDecoder.java

License:Open Source License

public static ByteBuf DecodeXor32(ByteBuf buff) {

    if (buff.readerIndex() != 0) {
        log.warn("Buffer must be at index 0!");
        buff.readerIndex(0);// ww  w  . j a v  a 2s  .co  m
    }

    int header = GetHeaderSize(buff);
    int decodedSize = GetDecodedSize(buff);

    buff.readerIndex(header);
    DecXor32(buff, header, decodedSize - header);
    buff.readerIndex(0);
    return buff;
}

From source file:com.vethrfolnir.game.network.mu.crypt.MuDecoder.java

License:Open Source License

/**
 * C3 C4/*from  www .jav a  2s  . co m*/
 * @param buff
 * @return 
 */
public static ByteBuf DecodePacket(ByteBuf buff) {
    if (buff.writerIndex() <= 2) {
        log.fatal("Ambiguous buffer! " + ByteBufUtil.hexDump(buff));
        return null;
    }
    if (buff.readerIndex() != 0) {
        log.warn("Buffer must be at index 0!");
        buff.readerIndex(0);
    }

    int header = GetHeaderSize(buff);
    int packetSize = GetPacketSize(buff);
    int decodedSize = GetDecodedSize(buff);

    int contentSize = packetSize - header;

    //System.out.println("Header[0x"+PrintData.fillHex(buff.getUnsignedByte(0), 2)+"] size: "+GetHeaderSize(buff)+" Packet Size: "+GetPacketSize(buff) +" Content Size: "+contentSize +" Decoded: "+ GetDecodedSize(buff));

    ByteBuf out = alloc.heapBuffer(decodedSize, decodedSize);

    int originalHead = buff.getUnsignedByte(0);

    buff.readerIndex(header);
    int size = DecodeBlock(buff, out, header, contentSize);
    //buff.clear();

    size += header - 1;

    out.writerIndex(0);
    out.writeByte(originalHead);

    switch (originalHead) {
    case 0xc3:
        out.writeByte(size);
        break;
    case 0xC4:
        out.writeByte(size >> 8);
        out.writeByte(size & 0xFF);
        break;
    }

    out.writerIndex(size);
    out.readerIndex(header);

    DecXor32(out, header, size);

    out.readerIndex(0);
    return out;
}

From source file:com.vethrfolnir.game.network.mu.crypt.MuDecoder.java

License:Open Source License

private static void DecXor32(ByteBuf buff, int SizeOfHeader, int Len) {

    for (int i = Len - 1; i > 0; i--) {
        int Buff = buff.getUnsignedByte(buff.readerIndex() + i);
        Buff ^= (Xor32Keys[(i + SizeOfHeader) & 31] ^ buff.getUnsignedByte((buff.readerIndex() + i) - 1));
        buff.setByte(buff.readerIndex() + i, Buff);
    }/*w  w w . j av  a  2  s . c  om*/
}

From source file:com.vethrfolnir.game.network.mu.received.MovedToLocation.java

License:Open Source License

@Override
public void read(MuClient client, ByteBuf buff, Object... params) {
    GameObject entity = client.getEntity();
    Positioning positioning = entity.get(PlayerMapping.Positioning);

    int origianlX = readC(buff);
    int origianlY = readC(buff);

    int offset = buff.readerIndex();
    byte[] data = buff.array();

    int pack = data[offset];
    int stepCount = (pack & 0x0F) + 1; // ... seriously now ...
    int heading = (pack & 0xF0) >> 4;

    int x = origianlX, y = origianlY;

    int TableIndex = 0;
    for (int i = 1; i < stepCount; i++) {
        if ((i % 2) == 1)
            TableIndex = data[offset + (i + 1) / 2] >> 4;
        else//from   w  ww.j av a 2  s  . c  o m
            TableIndex = data[offset + (i + 1) / 2] & 0x0F;

        x += stepDirections[TableIndex * 2];
        y += stepDirections[TableIndex * 2 + 1];
    }

    PlayerState state = entity.get(PlayerMapping.PlayerState);

    // Cheap yet effective, for now
    int distance = (int) MuUtils.distanceSquared(positioning.getX(), positioning.getY(), x, y);

    if (!state.isGM() && (distance > 10 && !positioning.moveFlag())) {
        client.close();
    }

    positioning.moveTo(x, y, heading);
    //System.out.println(getClass().getSimpleName()+": player "+entity.getName()+" "+x+" X "+y+" Y from[x "+origianlX+" y "+origianlY+"]  Heading: "+(heading)+". Step Count: "+stepCount);
}

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);//from w w  w  .j  av  a  2  s  .com
            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();
        } 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.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 w w.  j ava2 s  .  c om*/
            // 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.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));
    }/*  www. ja  v a2s. c om*/

    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.codec.ZWaveFrameDecoder.java

License:Open Source License

private int scanForFrame(ByteBuf data, int startIndex) {
    int readableBytes = data.readableBytes();
    if (data.getByte(startIndex) == DataFrame.START_OF_FRAME
            && startIndex + 1 < data.readerIndex() + readableBytes) {
        byte frameLen = data.getByte(startIndex + 1);
        int checksumIx = startIndex + frameLen + 1;
        if (frameLen > 0 && checksumIx < data.readerIndex() + readableBytes) {
            byte frameChecksum = data.getByte(checksumIx);
            byte checksum = 0;
            for (int i = startIndex + 1; i < checksumIx; i++) {
                checksum ^= data.getByte(i);
            }//from  w w  w . ja  v a2 s .c  o  m
            checksum = (byte) (~checksum);
            if (frameChecksum == checksum) {
                return checksumIx;
            }
        }
    }
    return -1;
}

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

License:Open Source License

/**
 * Creates a Z-Wave DataFrame from a ByteBuf.
 *
 * @param buf the buffer to process//from www.  ja v  a 2 s . com
 *
 * @return a DataFrame instance (or null if a valid one wasn't found)
 */
private DataFrame createDataFrame(ByteBuf buf) {
    if (buf.readableBytes() > 3) {
        byte messageType = buf.getByte(buf.readerIndex() + 3);

        switch (messageType) {
        case Version.ID:
            return new Version(buf);
        case MemoryGetId.ID:
            return new MemoryGetId(buf);
        case InitData.ID:
            return new InitData(buf);
        case NodeProtocolInfo.ID:
            return new NodeProtocolInfo(buf);
        case SendData.ID:
            return new SendData(buf);
        case ApplicationCommand.ID:
            return new ApplicationCommand(buf);
        case ApplicationUpdate.ID:
            return new ApplicationUpdate(buf);
        case RequestNodeInfo.ID:
            return new RequestNodeInfo(buf);
        case GetRoutingInfo.ID:
            return new GetRoutingInfo(buf);
        case GetSUCNodeId.ID:
            return new GetSUCNodeId(buf);
        case AddNodeToNetwork.ID:
            return new AddNodeToNetwork(buf);
        case RemoveNodeFromNetwork.ID:
            return new RemoveNodeFromNetwork(buf);
        case SetDefault.ID:
            return new SetDefault(buf);
        }
    }
    return null;
}

From source file:com.whizzosoftware.wzwave.util.ByteUtil.java

License:Open Source License

static public String createString(ByteBuf buf) {
    int length = buf.readableBytes();
    char[] hexChars = new char[length * 5];
    int v;//from w ww. j  av  a2 s  . c  o m
    int i = 0;
    for (int j = buf.readerIndex(); j < buf.readerIndex() + length; j++) {
        v = buf.getByte(j) & 0xFF;
        hexChars[i * 5] = '0';
        hexChars[i * 5 + 1] = 'x';
        hexChars[i * 5 + 2] = hexArray[v >>> 4];
        hexChars[i * 5 + 3] = hexArray[v & 0x0F];
        hexChars[i * 5 + 4] = ' ';
        i++;
    }
    return new String(hexChars);
}