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 int readBytes(FileChannel out, long position, int length) throws IOException;

Source Link

Document

Transfers this buffer's data starting at the current readerIndex to the specified channel starting at the given file position.

Usage

From source file:com.quavo.osrs.network.protocol.codec.game.GamePacketDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!in.isReadable() || !player.getChannel().isRegistered()) {
        return;//from   ww w. j av  a  2s .com
    }
    int opcode = in.readUnsignedByte();
    Optional<PacketDecoderIdentifier> data = PacketDecoderIdentifier.getPacket(opcode);
    if (data.isPresent()) {
        PacketDecoderIdentifier packet = data.get();

        int size = packet.getSize();
        if (packet.getType() == PacketType.VARIABLE_BYTE) {
            if (in.readableBytes() < 1) {
                return;
            }
            size = in.readUnsignedByte();
        } else if (packet.getType() == PacketType.VARIABLE_SHORT) {
            if (in.readableBytes() < 2) {
                return;
            }
            size = in.readUnsignedShort();
        }

        if (in.readableBytes() >= size) {
            if (size < 0) {
                return;
            }

            byte[] bytes = new byte[size];
            in.readBytes(bytes, 0, size);
            out.add(new GamePacketRequest(this, player, packet.getId(),
                    new GamePacketReader(Unpooled.wrappedBuffer(bytes))));
        }

    } else {
        System.out.println("No data present for incoming packet: " + opcode + ".");
        in.readBytes(new byte[in.readableBytes()]);
    }
}

From source file:com.spotify.folsom.client.ascii.AsciiMemcacheDecoder.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf buf, final List<Object> out)
        throws Exception {
    while (true) {
        //      String tmp = new String(buf.copy().array());
        int readableBytes = buf.readableBytes();
        if (readableBytes == 0) {
            return;
        }/*from  w  ww .  ja va  2 s .c o  m*/

        if (key != null) {
            final int toCopy = Math.min(value.length - valueOffset, readableBytes);
            if (toCopy > 0) {
                buf.readBytes(value, valueOffset, toCopy);
                readableBytes -= toCopy;
                valueOffset += toCopy;
                if (valueOffset < value.length) {
                    return;
                }
            }
            final StringBuilder line = readLine(buf, readableBytes);
            if (line == null) {
                return;
            }
            if (line.length() > 0) {
                throw new IOException(String.format("Unexpected end of data block: %s", line));
            }
            valueResponse.addGetResult(key, value, cas);
            key = null;
            value = null;
            cas = 0;
        } else {
            final StringBuilder line = readLine(buf, readableBytes);
            if (line == null) {
                return;
            }

            final int firstEnd = endIndex(line, 0);
            if (firstEnd < 1) {
                throw new IOException("Unexpected line: " + line);
            }

            final char firstChar = line.charAt(0);

            if (Character.isDigit(firstChar)) {
                try {
                    long numeric = Long.valueOf(line.toString());
                    out.add(new NumericAsciiResponse(numeric));
                } catch (NumberFormatException e) {
                    throw new IOException("Unexpected line: " + line, e);
                }
            } else if (firstEnd == 2) {
                if (firstChar == 'O') {
                    expect(line, "OK");
                    out.add(AsciiResponse.OK);
                    return;
                }
            } else if (firstEnd == 3) {
                expect(line, "END");
                out.add(valueResponse);
                valueResponse = new ValueAsciiResponse();
                valueMode = false;
                return;
            } else if (firstEnd == 5) {
                expect(line, "VALUE");
                valueMode = true;
                // VALUE <key> <flags> <bytes> [<cas unique>]\r\n
                final int keyStart = firstEnd + 1;
                final int keyEnd = endIndex(line, keyStart);
                final String key = line.substring(keyStart, keyEnd);
                if (key.isEmpty()) {
                    throw new IOException("Unexpected line: " + line);
                }

                final int flagsStart = keyEnd + 1;
                final int flagsEnd = endIndex(line, flagsStart);
                if (flagsEnd <= flagsStart) {
                    throw new IOException("Unexpected line: " + line);
                }

                final int sizeStart = flagsEnd + 1;
                final int sizeEnd = endIndex(line, sizeStart);
                if (sizeEnd <= sizeStart) {
                    throw new IOException("Unexpected line: " + line);
                }
                final int size = (int) parseLong(line, sizeStart, sizeEnd);

                final int casStart = sizeEnd + 1;
                final int casEnd = endIndex(line, casStart);
                long cas = 0;
                if (casStart < casEnd) {
                    cas = parseLong(line, casStart, casEnd);
                }
                this.key = key;
                this.value = new byte[size];
                this.valueOffset = 0;
                this.cas = cas;
            } else if (valueMode) {
                // when in valueMode, the only valid responses are "END" and "VALUE"
                throw new IOException("Unexpected line: " + line);
            } else if (firstEnd == 2) {
                if (firstChar == 'O') {
                    expect(line, "OK");
                    out.add(AsciiResponse.OK);
                    return;
                }
            } else if (firstEnd == 6) {
                if (firstChar == 'S') {
                    expect(line, "STORED");
                    out.add(AsciiResponse.STORED);
                    return;
                } else {
                    expect(line, "EXISTS");
                    out.add(AsciiResponse.EXISTS);
                    return;
                }
            } else if (firstEnd == 7) {
                if (firstChar == 'T') {
                    expect(line, "TOUCHED");
                    out.add(AsciiResponse.TOUCHED);
                    return;
                } else {
                    expect(line, "DELETED");
                    out.add(AsciiResponse.DELETED);
                    return;
                }
            } else if (firstEnd == 9) {
                expect(line, "NOT_FOUND");
                out.add(AsciiResponse.NOT_FOUND);
                return;
            } else if (firstEnd == 10) {
                expect(line, "NOT_STORED");
                out.add(AsciiResponse.NOT_STORED);
                return;
            } else {
                throw new IOException("Unexpected line: " + line);
            }
        }
    }
}

From source file:com.streamsets.pipeline.lib.parser.net.netflow.v9.NetflowV9Decoder.java

License:Apache License

private byte[] readBytesAndCheckpoint(ByteBuf buf, int size) {
    if (currentRawBytesIndex == null) {
        currentRawBytesIndex = 0;//  w  ww . j av a  2s. c o  m
        currentRawBytes = new byte[size];
    }
    while (currentRawBytesIndex < size) {
        buf.readBytes(currentRawBytes, currentRawBytesIndex, 1);
        parentDecoder.doCheckpoint();
        currentRawBytesIndex++;
    }
    currentRawBytesIndex = null;
    return currentRawBytes;
}

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

License:Open Source License

/**
 * Pops two bytes from the buffer and returns them as a little-endian integer.
 *
 * @param buf the buffer to read//from   w  ww .  java 2 s  .  c  om
 *
 * @return an Integer (or null if there aren't at least two bytes available in the buffer)
 */
private Integer popINT16(ByteBuf buf) {
    if (buf.readableBytes() >= 2) {
        byte b[] = new byte[2];
        buf.readBytes(b, 0, 2);
        return (int) java.nio.ByteBuffer.wrap(b).order(java.nio.ByteOrder.LITTLE_ENDIAN).getShort();
    } else {
        return null;
    }
}

From source file:com.xiovr.unibot.bot.network.impl.ConnectionDecoderImpl.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // System.out.println("Run decoder bytes="+ in.readableBytes());

    for (;;) {//  w ww.  j a  v  a2 s  .  c o m
        if (in.readableBytes() < 2)
            return;

        // System.out.println("Decoder size=" + in.readableBytes());
        in.markReaderIndex();

        // int dataLen = in.readUnsignedShort() - 2;
        byte b1 = in.readByte();
        byte b2 = in.readByte();
        int dataLen = (b1 & 0xFF) | ((b2 << 8) & 0xFF00);

        // System.out.println("packet len =" + dataLen);

        // System.out.println("readable bytes =" + in.readableBytes());
        if (in.readableBytes() < dataLen - 2) {
            in.resetReaderIndex();
            return;
        }
        Packet pck = PacketPool.obtain();
        pck.clear();

        byte[] pckArr = pck.getBuf().array();
        // byte[] inArr = in.array();
        in.readBytes(pckArr, 2, dataLen - 2);
        pck.putHeader(dataLen);
        pck.setPosition(dataLen);
        // int rIndex = in.readerIndex();
        // System.arraycopy(inArr, rIndex-2, pckArr, 0, dataLen+2);
        // in.readerIndex(rIndex+dataLen);
        out.add(pck);
        // System.out.println("DECODER END");
    }
}

From source file:com.xx_dev.apn.proxy.ApnProxyAESDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    switch (this.state()) {
    case READ_MAGIC_NUMBER: {
        int magicNumber = in.readInt();
        if (magicNumber != 0x34ed2b11) {
            throw new Exception("Wrong magic number!");
        }// w  w w .  java  2  s .  c  o  m
        this.checkpoint(STATE.READ_LENGTH);
    }
    case READ_LENGTH: {
        length = in.readInt();
        if (length > 1024 * 512 + 1000) {
            ctx.close();
        }
        this.checkpoint(STATE.READ_CONTENT);
    }
    case READ_CONTENT: {
        c1.init(Cipher.DECRYPT_MODE, securekey, iv);
        byte[] data = new byte[length];
        in.readBytes(data, 0, length);
        byte[] raw = c1.doFinal(data);
        ByteBuf outBuf = ctx.alloc().buffer();
        outBuf.writeBytes(raw);
        out.add(outBuf);
        this.checkpoint(STATE.READ_MAGIC_NUMBER);
        break;
    }
    default:
        throw new Error("Shouldn't reach here.");
    }

}

From source file:com.xx_dev.apn.proxy.ApnProxyAESEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
    try {//from  w  ww.ja  va2  s  .com

        while (msg.readableBytes() > 0) {
            c1.init(Cipher.ENCRYPT_MODE, securekey, iv);

            int readLength = msg.readableBytes();
            if (readLength > 1024 * 512) {
                readLength = 1024 * 512;
            }

            byte[] array = new byte[readLength];
            msg.readBytes(array, 0, readLength);

            byte[] raw = c1.doFinal(array);
            int length = raw.length;

            out.writeInt(0x34ed2b11);//magic number
            out.writeInt(length);
            out.writeBytes(raw);
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.xx_dev.apn.socks.local.FakeHttpClientDecoder.java

License:Apache License

protected void _decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    switch (this.state()) {
    case READ_FAKE_HTTP: {
        int fakeHttpHeadStartIndex = in.readerIndex();

        int fakeHttpHeadEndIndex = in.forEachByte(new ByteBufProcessor() {
            int c = 0;

            @Override/*from  w  ww . ja  va 2s  .c  o  m*/
            public boolean process(byte value) throws Exception {

                if (value == '\r' || value == '\n') {
                    c++;
                } else {
                    c = 0;
                }

                //logger.info("value=" + value + ", c=" + c);

                if (c >= 4) {
                    return false;
                } else {
                    return true;
                }
            }
        });

        logger.debug("s: " + fakeHttpHeadStartIndex);
        logger.debug("e: " + fakeHttpHeadEndIndex);

        if (fakeHttpHeadEndIndex == -1) {
            logger.warn("w: " + fakeHttpHeadStartIndex);
            break;
        }

        byte[] buf = new byte[fakeHttpHeadEndIndex - fakeHttpHeadStartIndex + 1];
        in.readBytes(buf, 0, fakeHttpHeadEndIndex - fakeHttpHeadStartIndex + 1);
        String s = TextUtil.fromUTF8Bytes(buf);

        //logger.info(s);

        String[] ss = StringUtils.split(s, "\r\n");

        //System.out.println(s + "" + this + " " + Thread.currentThread().getName());

        for (String line : ss) {
            if (StringUtils.startsWith(line, "X-C:")) {
                String lenStr = StringUtils.trim(StringUtils.split(line, ":")[1]);
                //System.out.println(lenStr + "" + this + " " + Thread.currentThread().getName());
                //System.out.println("*****************************************");
                try {
                    length = Integer.parseInt(lenStr, 16);
                    trafficLogger.info("D," + LocalConfig.ins().getUser() + "," + length);
                } catch (Throwable t) {
                    logger.error("--------------------------------------");
                    logger.error(s + "" + this + " " + Thread.currentThread().getName());
                    logger.error("--------------------------------------");
                }

            }
        }

        this.checkpoint(STATE.READ_CONTENT);
    }
    case READ_CONTENT: {
        if (length > 0) {
            byte[] buf = new byte[length];
            in.readBytes(buf, 0, length);

            byte[] res = new byte[length];

            for (int i = 0; i < length; i++) {
                res[i] = (byte) (buf[i] ^ (LocalConfig.ins().getEncryptKey() & 0xFF));
            }

            ByteBuf outBuf = ctx.alloc().buffer();

            outBuf.writeBytes(res);

            out.add(outBuf);
        }

        this.checkpoint(STATE.READ_FAKE_HTTP);
        break;
    }
    default:
        throw new Error("Shouldn't reach here.");
    }

}

From source file:com.xx_dev.apn.socks.local.FakeHttpClientEncoder.java

License:Apache License

@Override
protected void encode(final ChannelHandlerContext ctx, final ByteBuf msg, final ByteBuf out) throws Exception {
    int length = msg.readableBytes();

    out.writeBytes(TextUtil.toUTF8Bytes("POST /form.action HTTP/1.1\r\n"));
    out.writeBytes(TextUtil.toUTF8Bytes("HOST: www.baidu.com\r\n"));
    out.writeBytes(TextUtil.toUTF8Bytes("X-C: " + String.format("%1$08x", length) + "\r\n"));
    out.writeBytes(TextUtil.toUTF8Bytes("X-U: " + LocalConfig.ins().getUser() + "\r\n"));
    out.writeBytes(TextUtil.toUTF8Bytes("Content-Length: " + "1234" + "\r\n"));
    out.writeBytes(TextUtil.toUTF8Bytes("Connection: Keep-Alive\r\n"));
    out.writeBytes(TextUtil.toUTF8Bytes("\r\n"));

    if (length > 0) {
        byte[] buf = new byte[length];
        msg.readBytes(buf, 0, length);

        byte[] res = new byte[length];

        for (int i = 0; i < buf.length; i++) {
            //res[i] = (byte)(buf[i] ^ key);
            res[i] = (byte) (buf[i] ^ (LocalConfig.ins().getEncryptKey() & 0xFF));
        }//  w  ww. j a  v  a  2  s  . c o  m

        trafficLogger.info("U," + LocalConfig.ins().getUser() + "," + length);

        out.writeBytes(res);
    }

}

From source file:com.xx_dev.apn.socks.remote.FakeHttpServerDecoder.java

License:Apache License

protected void _decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    switch (this.state()) {
    case READ_FAKE_HTTP: {
        int fakeHttpHeadStartIndex = in.readerIndex();

        int fakeHttpHeadEndIndex = in.forEachByte(new ByteBufProcessor() {
            int c = 0;

            @Override/*ww  w  .j  a v  a  2  s.  c om*/
            public boolean process(byte value) throws Exception {

                if (value == '\r' || value == '\n') {
                    c++;
                } else {
                    c = 0;
                }

                //logger.info("value=" + value + ", c=" + c);

                if (c >= 4) {
                    return false;
                } else {
                    return true;
                }
            }
        });

        logger.debug("s: " + fakeHttpHeadStartIndex);
        logger.debug("e: " + fakeHttpHeadEndIndex);

        if (fakeHttpHeadEndIndex == -1) {
            logger.warn("w: " + fakeHttpHeadStartIndex);
            break;
        }

        byte[] buf = new byte[fakeHttpHeadEndIndex - fakeHttpHeadStartIndex + 1];
        in.readBytes(buf, 0, fakeHttpHeadEndIndex - fakeHttpHeadStartIndex + 1);
        String s = TextUtil.fromUTF8Bytes(buf);

        //logger.info(s);

        String[] ss = StringUtils.split(s, "\r\n");

        //System.out.println(s + "" + this + " " + Thread.currentThread().getName());

        for (String line : ss) {
            if (StringUtils.startsWith(line, "X-C:")) {
                String lenStr = StringUtils.trim(StringUtils.split(line, ":")[1]);
                //System.out.println(lenStr + "" + this + " " + Thread.currentThread().getName());
                //System.out.println("*****************************************");
                try {
                    length = Integer.parseInt(lenStr, 16);
                } catch (Throwable t) {
                    logger.error("--------------------------------------");
                    logger.error(s + "" + this + " " + Thread.currentThread().getName());
                    logger.error("--------------------------------------");
                }

            }

            if (StringUtils.startsWith(line, "X-U:")) {
                String user = StringUtils.trim(StringUtils.split(line, ":")[1]);
                ctx.channel().attr(NettyAttributeKey.LINK_USER).set(user);
                logger.info(user);
            }
        }

        this.checkpoint(STATE.READ_CONTENT);
    }
    case READ_CONTENT: {

        trafficLogger.info("U," + ctx.channel().attr(NettyAttributeKey.LINK_USER).get() + "," + length);

        if (length > 0) {

            byte[] buf = new byte[length];
            in.readBytes(buf, 0, length);

            byte[] res = new byte[length];

            for (int i = 0; i < length; i++) {
                res[i] = (byte) (buf[i] ^ (RemoteConfig.ins().getEncryptKey() & 0xFF));
            }

            ByteBuf outBuf = ctx.alloc().buffer();

            outBuf.writeBytes(res);

            out.add(outBuf);
        }

        this.checkpoint(STATE.READ_FAKE_HTTP);
        break;
    }
    default:
        throw new Error("Shouldn't reach here.");
    }

}