Example usage for io.netty.buffer ByteBuf skipBytes

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

Introduction

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

Prototype

public abstract ByteBuf skipBytes(int length);

Source Link

Document

Increases the current readerIndex by the specified length in this buffer.

Usage

From source file:at.yawk.accordion.codec.unsafe.NamedObjectCodec.java

License:Mozilla Public License

private static String readClassName(ByteBuf buf) {
    int len = buf.bytesBefore((byte) 0);
    byte[] data = new byte[len];
    buf.readBytes(data);//from w  ww.j  a v  a 2  s .com
    buf.skipBytes(1); // \0
    return new String(data, StandardCharsets.UTF_8);
}

From source file:bftsmart.communication.client.netty.NettyTOMMessageDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> list) throws Exception {

    // Wait until the length prefix is available.
    if (buffer.readableBytes() < Integer.BYTES) {
        return;/*from w  ww . ja  v  a  2s .  c om*/
    }

    int dataLength = buffer.getInt(buffer.readerIndex());

    //Logger.println("Receiving message with "+dataLength+" bytes.");

    // Wait until the whole data is available.
    if (buffer.readableBytes() < dataLength + Integer.BYTES) {
        return;
    }

    // Skip the length field because we know it already.
    buffer.skipBytes(Integer.BYTES);

    int size = buffer.readInt();
    byte[] data = new byte[size];
    buffer.readBytes(data);

    byte[] signature = null;
    size = buffer.readInt();

    if (size > 0) {
        signature = new byte[size];
        buffer.readBytes(signature);
    }

    DataInputStream dis = null;
    TOMMessage sm = null;

    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        dis = new DataInputStream(bais);
        sm = new TOMMessage();
        sm.rExternal(dis);
        sm.serializedMessage = data;

        if (signature != null) {
            sm.serializedMessageSignature = signature;
            sm.signed = true;
        }

        if (!isClient) {
            rl.readLock().lock();
            if (!sessionTable.containsKey(sm.getSender())) {
                rl.readLock().unlock();

                NettyClientServerSession cs = new NettyClientServerSession(context.channel(), sm.getSender());

                rl.writeLock().lock();
                sessionTable.put(sm.getSender(), cs);
                logger.debug("Active clients: " + sessionTable.size());
                rl.writeLock().unlock();

            } else {
                rl.readLock().unlock();
            }
        }
        logger.debug("Decoded reply from " + sm.getSender() + " with sequence number " + sm.getSequence());
        list.add(sm);
    } catch (Exception ex) {

        logger.error("Failed to decode TOMMessage", ex);
    }
    return;
}

From source file:buildcraft.builders.TileBlueprintLibrary.java

License:Minecraft Mod Public

@Override
public void receiveCommand(String command, Side side, Object sender, ByteBuf stream) {
    if (side.isClient()) {
        if ("requestSelectedBlueprint".equals(command)) {
            if (isOutputConsistent()) {
                if (selected > -1 && selected < currentPage.size()) {
                    // Work around 32k max limit on client->server
                    final BlueprintBase bpt = BuildCraftBuilders.clientDB.load(currentPage.get(selected));
                    final byte[] bptData = bpt.getData();
                    final int chunks = (bptData.length + CHUNK_SIZE - 1) / CHUNK_SIZE;

                    BuildCraftCore.instance
                            .sendToServer(new PacketCommand(this, "uploadServerBegin", new CommandWriter() {
                                public void write(ByteBuf data) {
                                    bpt.id.writeData(data);
                                    data.writeShort(chunks);
                                }//w w  w. j  av  a 2 s . c o  m
                            }));

                    for (int i = 0; i < chunks; i++) {
                        final int chunk = i;
                        final int start = CHUNK_SIZE * chunk;
                        final int length = Math.min(CHUNK_SIZE, bptData.length - start);
                        BuildCraftCore.instance
                                .sendToServer(new PacketCommand(this, "uploadServerChunk", new CommandWriter() {
                                    public void write(ByteBuf data) {
                                        data.writeShort(chunk);
                                        data.writeShort(length);
                                        data.writeBytes(bptData, start, length);
                                    }
                                }));
                    }

                    BuildCraftCore.instance.sendToServer(new PacketCommand(this, "uploadServerEnd", null));
                } else {
                    BuildCraftCore.instance
                            .sendToServer(new PacketCommand(this, "uploadNothingToServer", null));
                }
            }
        } else if ("downloadBlueprintToClient".equals(command)) {
            BlueprintId id = new BlueprintId();
            id.readData(stream);
            byte[] data = Utils.readByteArray(stream);

            try {
                NBTTagCompound nbt = CompressedStreamTools.func_152457_a(data, NBTSizeTracker.field_152451_a);
                BlueprintBase bpt = BlueprintBase.loadBluePrint(nbt);
                bpt.setData(data);
                bpt.id = id;

                BuildCraftBuilders.clientDB.add(bpt);
                setCurrentPage(BuildCraftBuilders.clientDB.getPage(pageId));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } else if (side.isServer()) {
        if ("uploadNothingToServer".equals(command)) {
            setInventorySlotContents(3, getStackInSlot(2));
            setInventorySlotContents(2, null);

            downloadingPlayer = null;
        } else if ("uploadServerBegin".equals(command)) {
            blueprintDownloadId = new BlueprintId();
            blueprintDownloadId.readData(stream);
            blueprintDownload = new byte[CHUNK_SIZE * stream.readUnsignedShort()];
        } else if ("uploadServerChunk".equals(command)) {
            int start = stream.readUnsignedShort() * CHUNK_SIZE;
            int length = stream.readUnsignedShort();
            if (blueprintDownload != null) {
                stream.readBytes(blueprintDownload, start, length);
            } else {
                stream.skipBytes(length);
            }
        } else if ("uploadServerEnd".equals(command)) {
            try {
                NBTTagCompound nbt = CompressedStreamTools.func_152457_a(blueprintDownload,
                        NBTSizeTracker.field_152451_a);
                BlueprintBase bpt = BlueprintBase.loadBluePrint(nbt);
                bpt.setData(blueprintDownload);
                bpt.id = blueprintDownloadId;
                BuildCraftBuilders.serverDB.add(bpt);

                setInventorySlotContents(3, bpt.getStack());
                setInventorySlotContents(2, null);
            } catch (IOException e) {
                e.printStackTrace();
            }

            blueprintDownloadId = null;
            blueprintDownload = null;
            downloadingPlayer = null;
        }
    }
}

From source file:cloudeventbus.codec.Decoder.java

License:Open Source License

@Override
public Frame decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    in.markReaderIndex();//from  ww  w .java2s. c o m
    final int frameLength = indexOf(in, Codec.DELIMITER);
    // Frame hasn't been fully read yet.
    if (frameLength < 0) {
        if (in.readableBytes() > maxMessageSize) {
            throw new TooLongFrameException("Frame exceeds maximum size");
        }
        in.resetReaderIndex();
        return null;
    }
    // Empty frame, discard and continue decoding
    if (frameLength == 0) {
        in.skipBytes(Codec.DELIMITER.length);
        return decode(ctx, in);
    }
    if (frameLength > maxMessageSize) {
        throw new TooLongFrameException("Frame exceeds maximum size");
    }
    final String command = in.readBytes(frameLength).toString(CharsetUtil.UTF_8);
    in.skipBytes(Codec.DELIMITER.length);
    final String[] parts = command.split("\\s+");
    final char frameTypeChar = parts[0].charAt(0);
    final FrameType frameType = FrameType.getFrameType(frameTypeChar);
    if (frameType == null) {
        throw new DecodingException("Invalid frame type " + frameTypeChar);
    }
    LOGGER.debug("Decoding frame of type {}", frameType);
    final int argumentsLength = parts.length - 1;
    switch (frameType) {
    case AUTH_RESPONSE:
        assertArgumentsLength(3, argumentsLength, "authentication response");
        final CertificateChain certificates = new CertificateChain();
        final byte[] rawCertificates = Base64.decodeBase64(parts[1].getBytes());
        CertificateStoreLoader.load(new ByteArrayInputStream(rawCertificates), certificates);
        final byte[] salt = Base64.decodeBase64(parts[2]);
        final byte[] digitalSignature = Base64.decodeBase64(parts[3]);
        return new AuthenticationResponseFrame(certificates, salt, digitalSignature);
    case AUTHENTICATE:
        assertArgumentsLength(1, argumentsLength, "authentication request");
        final byte[] challenge = Base64.decodeBase64(parts[1]);
        return new AuthenticationRequestFrame(challenge);
    case ERROR:
        if (parts.length == 0) {
            throw new DecodingException("Error is missing error code");
        }
        final Integer errorNumber = Integer.valueOf(parts[1]);
        final ErrorFrame.Code errorCode = ErrorFrame.Code.lookupCode(errorNumber);
        int messageIndex = 1;
        messageIndex = skipWhiteSpace(messageIndex, command);
        while (messageIndex < command.length() && Character.isDigit(command.charAt(messageIndex))) {
            messageIndex++;
        }
        messageIndex = skipWhiteSpace(messageIndex, command);
        final String errorMessage = command.substring(messageIndex).trim();
        if (errorMessage.length() > 0) {
            return new ErrorFrame(errorCode, errorMessage);
        } else {
            return new ErrorFrame(errorCode);
        }
    case GREETING:
        assertArgumentsLength(3, argumentsLength, "greeting");
        final int version = Integer.valueOf(parts[1]);
        final String agent = parts[2];
        final long id = Long.valueOf(parts[3]);
        return new GreetingFrame(version, agent, id);
    case PING:
        return PingFrame.PING;
    case PONG:
        return PongFrame.PONG;
    case PUBLISH:
        if (argumentsLength < 2 || argumentsLength > 3) {
            throw new DecodingException(
                    "Expected message frame to have 2 or 3 arguments. It has " + argumentsLength + ".");
        }
        final String messageSubject = parts[1];
        final String replySubject;
        final Integer messageLength;
        if (parts.length == 3) {
            replySubject = null;
            messageLength = Integer.valueOf(parts[2]);
        } else {
            replySubject = parts[2];
            messageLength = Integer.valueOf(parts[3]);
        }
        if (in.readableBytes() < messageLength + Codec.DELIMITER.length) {
            // If we haven't received the entire message body (plus the CRLF), wait until it arrives.
            in.resetReaderIndex();
            return null;
        }
        final ByteBuf messageBytes = in.readBytes(messageLength);
        final String messageBody = new String(messageBytes.array(), CharsetUtil.UTF_8);
        in.skipBytes(Codec.DELIMITER.length); // Ignore the CRLF after the message body.
        return new PublishFrame(new Subject(messageSubject),
                replySubject == null ? null : new Subject(replySubject), messageBody);
    case SERVER_READY:
        return ServerReadyFrame.SERVER_READY;
    case SUBSCRIBE:
        assertArgumentsLength(1, argumentsLength, "subscribe");
        return new SubscribeFrame(new Subject(parts[1]));
    case UNSUBSCRIBE:
        assertArgumentsLength(1, argumentsLength, "unsubscribe");
        return new UnsubscribeFrame(new Subject(parts[1]));
    default:
        throw new DecodingException("Unknown frame type " + frameType);
    }
}

From source file:com.antsdb.saltedfish.server.mysql.packet.AuthPacket.java

License:Open Source License

@Override
public void read(MysqlServerHandler handler, ByteBuf in) {
    if (!checkResponseVer41(in)) {
        clientParam = BufferUtils.readInt(in);
        maxThreeBytes = BufferUtils.readLongInt(in);
        user = BufferUtils.readString(in);
        rawPwd = BufferUtils.readString(in);
        dbname = BufferUtils.readString(in);
    } else {//from ww w .  j  ava 2s .  c  om
        clientParam = BufferUtils.readLong(in);
        maxThreeBytes = BufferUtils.readLong(in);
        in.readByte(); // charset
        in.skipBytes(23); // reserved for future
        user = BufferUtils.readString(in);
        if ((clientParam & CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA) != 0) {
            int passwordLength = in.readByte();
            byte[] bytes = new byte[passwordLength];
            in.readBytes(bytes);
            rawPwd = new String(bytes, Charsets.ISO_8859_1);
        } else {
            if ((clientParam & CLIENT_SECURE_CONNECTION) != 0) {
                int passwordLength = in.readByte();
                byte[] bytes = new byte[passwordLength];
                in.readBytes(bytes);
                rawPwd = new String(bytes, Charsets.ISO_8859_1);
            } else {
                rawPwd = BufferUtils.readString(in);
            }
        }
        if ((clientParam & MysqlServerHandler.CLIENT_CONNECT_WITH_DB) != 0) {
            dbname = BufferUtils.readString(in);
        }
        if ((clientParam & MysqlServerHandler.CLIENT_PLUGIN_AUTH) != 0) {
            BufferUtils.readString(in);
        }
    }
}

From source file:com.antsdb.saltedfish.server.mysql.ReplicationPacketDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // do we have length field in buffer ?
    if (!in.isReadable(4)) {
        return;//from  w  w  w  .j  a v  a 2  s .com
    }

    // do we have entire packet in the buffer?

    in.markReaderIndex();
    int size = BufferUtils.readLongInt(in) + 1;
    if (size == (0x00ffffff + 1)) {
        return;
    }
    if (!in.isReadable(size)) {
        in.resetReaderIndex();
        return;
    }

    int pos = in.readerIndex();
    try {
        ReplicationPacket packet = readPacket(in, size);
        out.add(packet);
    } finally {
        int currentPos = in.readerIndex();
        in.skipBytes(size - (currentPos - pos));
    }
}

From source file:com.antsdb.saltedfish.server.mysql.util.BufferUtils.java

License:Open Source License

public static String readString(ByteBuf buf) {
    String s;//  ww w  . java 2 s. co m
    int bytes = buf.bytesBefore((byte) 0);
    if (bytes == -1) {
        // string might not be terminated by 0
        bytes = buf.readableBytes();
        s = buf.toString(buf.readerIndex(), bytes, Charset.defaultCharset());
        buf.skipBytes(bytes);
    } else {
        s = buf.toString(buf.readerIndex(), bytes, Charset.defaultCharset());
        buf.skipBytes(bytes + 1);
    }
    return s;
}

From source file:com.cc.nettytest.proxy.decoder.CCLengthFieldBasedFrameDecoder.java

License:Apache License

@Override
public Object decode(ChannelHandlerContext ctx, ByteBuf inBuffer) throws Exception {
    if (discardingTooLongFrame) {
        long bytesToDiscard = this.bytesToDiscard;
        int localBytesToDiscard = (int) Math.min(bytesToDiscard, inBuffer.readableBytes());
        inBuffer.skipBytes(localBytesToDiscard);
        bytesToDiscard -= localBytesToDiscard;
        this.bytesToDiscard = bytesToDiscard;
        failIfNecessary(ctx, false);//from   w  w w . j a  va  2  s  .com
        return null;
    }

    if (inBuffer.readableBytes() < lengthFieldEndOffset) {
        return null;
    }

    int actualLengthFieldOffset = inBuffer.readerIndex() + lengthFieldOffset;
    long frameLength;
    switch (lengthFieldLength) {
    case 1:
        frameLength = inBuffer.getUnsignedByte(actualLengthFieldOffset);
        break;
    case 2:
        frameLength = inBuffer.getUnsignedShort(actualLengthFieldOffset);
        break;
    case 3:
        frameLength = inBuffer.getUnsignedMedium(actualLengthFieldOffset);
        break;
    case 4:
        frameLength = ByteBufUtil.swapInt((int) inBuffer.getUnsignedInt(actualLengthFieldOffset)); //SWAP FOR UIMANAGER
        break;
    case 8:
        frameLength = inBuffer.getLong(actualLengthFieldOffset);
        break;
    default:
        throw new Error("should not reach here");
    }

    if (frameLength < 0) {
        inBuffer.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength);
    }

    frameLength += lengthAdjustment + lengthFieldEndOffset;

    if (frameLength < lengthFieldEndOffset) {
        inBuffer.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than lengthFieldEndOffset: " + lengthFieldEndOffset);
    }

    if (frameLength > maxFrameLength) {
        // Enter the discard mode and discard everything received so far.
        discardingTooLongFrame = true;
        tooLongFrameLength = frameLength;
        bytesToDiscard = frameLength - inBuffer.readableBytes();
        inBuffer.skipBytes(inBuffer.readableBytes());
        failIfNecessary(ctx, true);
        return null;
    }

    // never overflows because it's less than maxFrameLength
    int frameLengthInt = (int) frameLength;
    if (inBuffer.readableBytes() < frameLengthInt) {
        return null;
    }

    if (initialBytesToStrip > frameLengthInt) {
        inBuffer.skipBytes(frameLengthInt);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than initialBytesToStrip: " + initialBytesToStrip);
    }
    inBuffer.skipBytes(initialBytesToStrip);

    // extract frame
    int readerIndex = inBuffer.readerIndex();
    int actualFrameLength = frameLengthInt - initialBytesToStrip;
    ByteBuf frame = extractFrame(inBuffer, readerIndex, actualFrameLength);
    inBuffer.readerIndex(readerIndex + actualFrameLength);
    return frame;
}

From source file:com.chat.common.netty.handler.decode.LengthFieldBasedFrameDecoder.java

License:Apache License

/**
 * Create a frame out of the {@link ByteBuf} and return it.
 *
 * @param   ctx             the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
 * @param   in              the {@link ByteBuf} from which to read data
 * @return  frame           the {@link ByteBuf} which represent the frame or {@code null} if no frame could
 *                          be created.//from  www  . ja v a 2 s  .co m
 */
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    if (discardingTooLongFrame) {
        long bytesToDiscard = this.bytesToDiscard;
        int localBytesToDiscard = (int) Math.min(bytesToDiscard, in.readableBytes());
        in.skipBytes(localBytesToDiscard);
        bytesToDiscard -= localBytesToDiscard;
        this.bytesToDiscard = bytesToDiscard;

        failIfNecessary(false);
    }

    if (in.readableBytes() < lengthFieldEndOffset) {
        return null;
    }

    int actualLengthFieldOffset = in.readerIndex() + lengthFieldOffset;
    long frameLength = getUnadjustedFrameLength(in, actualLengthFieldOffset, lengthFieldLength, byteOrder);

    if (frameLength < 0) {
        in.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength);
    }

    frameLength += lengthAdjustment + lengthFieldEndOffset;

    if (frameLength < lengthFieldEndOffset) {
        in.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than lengthFieldEndOffset: " + lengthFieldEndOffset);
    }

    if (frameLength > maxFrameLength) {
        long discard = frameLength - in.readableBytes();
        tooLongFrameLength = frameLength;

        if (discard < 0) {
            // buffer contains more bytes then the frameLength so we can discard all now
            in.skipBytes((int) frameLength);
        } else {
            // Enter the discard mode and discard everything received so far.
            discardingTooLongFrame = true;
            bytesToDiscard = discard;
            in.skipBytes(in.readableBytes());
        }
        failIfNecessary(true);
        return null;
    }

    // never overflows because it's less than maxFrameLength
    int frameLengthInt = (int) frameLength;
    if (in.readableBytes() < frameLengthInt) {
        return null;
    }

    if (initialBytesToStrip > frameLengthInt) {
        in.skipBytes(frameLengthInt);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than initialBytesToStrip: " + initialBytesToStrip);
    }
    in.skipBytes(initialBytesToStrip);

    // extract frame
    int readerIndex = in.readerIndex();
    int actualFrameLength = frameLengthInt - initialBytesToStrip;
    ByteBuf frame = extractFrame(ctx, in, readerIndex, actualFrameLength);
    in.readerIndex(readerIndex + actualFrameLength);
    return frame;
}

From source file:com.cloudera.livy.client.local.rpc.KryoMessageCodec.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 4) {
        return;//w  ww .j  a va 2  s .c  o m
    }

    in.markReaderIndex();
    int msgSize = in.readInt();
    checkSize(msgSize);

    if (in.readableBytes() < msgSize) {
        // Incomplete message in buffer.
        in.resetReaderIndex();
        return;
    }

    try {
        ByteBuffer nioBuffer = maybeDecrypt(in.nioBuffer(in.readerIndex(), msgSize));
        Object msg = serializer.deserialize(nioBuffer);
        LOG.debug("Decoded message of type {} ({} bytes)", msg != null ? msg.getClass().getName() : msg,
                msgSize);
        out.add(msg);
    } finally {
        in.skipBytes(msgSize);
    }
}