Example usage for io.netty.buffer ByteBuf writerIndex

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

Introduction

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

Prototype

public abstract ByteBuf writerIndex(int writerIndex);

Source Link

Document

Sets the writerIndex of this buffer.

Usage

From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPParserTest.java

License:Apache License

@Theory
public void testParse(@FromDataPoints("frames") final String[] frames,
        @FromDataPoints("versions") final ZMTPVersion version) throws Exception {
    final List<String> input = asList(frames);
    final ZMTPWireFormat wireFormat = wireFormat(version);

    final ZMTPMessage inputMessage = ZMTPMessage.fromUTF8(ALLOC, input);

    final ExpectedOutput expected = new ExpectedOutput(inputMessage);

    final ByteBuf serialized = inputMessage.write(ALLOC, version);
    final int serializedLength = serialized.readableBytes();

    // Test parsing the whole message
    {//from  w ww . j  a  va2 s .c o m
        final VerifyingDecoder verifier = new VerifyingDecoder(expected);
        final ZMTPFramingDecoder decoder = new ZMTPFramingDecoder(wireFormat, verifier);
        decoder.decode(ctx, serialized, null);
        verifier.assertFinished();
        serialized.setIndex(0, serializedLength);
    }

    // Prepare for trivial message parsing test
    final ZMTPMessage trivial = ZMTPMessage.fromUTF8(ALLOC, "e", "", "a", "b", "c");
    final ByteBuf trivialSerialized = trivial.write(ALLOC, version);
    final int trivialLength = trivialSerialized.readableBytes();
    final ExpectedOutput trivialExpected = new ExpectedOutput(trivial);

    // Test parsing fragmented input
    final VerifyingDecoder verifier = new VerifyingDecoder();
    final ZMTPFramingDecoder decoder = new ZMTPFramingDecoder(wireFormat, verifier);
    new Fragmenter(serialized.readableBytes()).fragment(new Fragmenter.Consumer() {
        @Override
        public void fragments(final int[] limits, final int count) throws Exception {
            verifier.expect(expected);
            serialized.setIndex(0, serializedLength);
            for (int i = 0; i < count; i++) {
                final int limit = limits[i];
                serialized.writerIndex(limit);
                decoder.decode(ctx, serialized, null);
            }
            verifier.assertFinished();

            // Verify that the parser can be reused to parse the same message
            serialized.setIndex(0, serializedLength);
            decoder.decode(ctx, serialized, null);
            verifier.assertFinished();

            // Verify that the parser can be reused to parse a well-behaved message
            verifier.expect(trivialExpected);
            trivialSerialized.setIndex(0, trivialLength);
            decoder.decode(ctx, trivialSerialized, null);
            verifier.assertFinished();
        }
    });
}

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

License:Open Source License

private static int DecodeBlock(ByteBuf buff, ByteBuf outBuff, int offset, int size) {
    // decripted size
    int index = 0;

    if ((size % 11) != 0) {
        log.warn("Cannot decrypt packet, it's already decrypted!: Size " + size + " = " + ((size % 11)));
        log.warn(PrintData.printData(buff.nioBuffer()));
        return -1;
    }//from www  .  jav  a  2s.com

    ByteBuf encrypted = alloc.heapBuffer(11, 11).order(ByteOrder.LITTLE_ENDIAN);
    short[] uByteArray = new short[encrypted.capacity()];

    ByteBuf decrypted = alloc.heapBuffer(8, 8).order(ByteOrder.LITTLE_ENDIAN);
    ByteBuf converter = alloc.heapBuffer(4).order(ByteOrder.LITTLE_ENDIAN);

    for (int i = 0; i < size; i += 11) {
        buff.readBytes(encrypted);

        //System.out.println("ENC: "+PrintData.printData(encrypted.nioBuffer()));
        int Result = BlockDecode(decrypted, getAsUByteArray(encrypted, uByteArray), converter,
                MuKeyFactory.getClientToServerPacketDecKeys());
        if (Result != -1) {
            //Buffer.BlockCopy(Decrypted, 0, m_DecryptResult, (OffSet - 1) + DecSize, Result);

            outBuff.writerIndex((offset - 1) + index);
            outBuff.writeBytes(decrypted);

            //outBuff.writeBytes(decrypted);

            decrypted.clear();
            encrypted.clear();
            converter.clear();
            //System.arraycopy(Decrypted, 0, m_DecryptResult, (OffSet - 1) + DecSize, Result);

            index += Result;
        }
    }

    return index;
}

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

License:Open Source License

public static ByteBuf EncodePacket(ByteBuf buff, int serial) {
    int header = GetHeaderSize(buff);
    int packetSize = GetPacketSize(buff);
    int contentSize = packetSize - header;

    int encodedSize = (((contentSize / 8) + (((contentSize % 8) > 0) ? 1 : 0)) * 11) + header;

    int size = header;
    int originalHead = buff.getUnsignedByte(0);

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

    //buff.writerIndex(buff.writerIndex() + 1);
    short[] Contents = new short[contentSize + 1];
    Contents[0] = (short) serial; // XXX:  Check this

    buff.readerIndex(header - 1);//w  w w .  j  a va2 s .co m

    buff.setByte(header - 1, serial);

    MuCryptUtils.readAsUByteArray(buff, Contents);

    //System.out.println("Encoding: "+PrintData.printData(Contents));

    size += EncodeBuffer(Contents, out, header, (contentSize + 1));

    out.writerIndex(0);

    // Header
    out.writeByte(originalHead);

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

    out.writerIndex(size);

    return out;
}

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

License:Open Source License

/**
 * @param contents/*from w  ww .  j  a va 2 s  . c o  m*/
 * @param out
 * @param header
 * @param Size
 * @param toServer 
 * @return 
 */
private static int EncodeBuffer(short[] contents, ByteBuf out, int header, int Size) {
    int i = 0;
    int EncSize = 0;

    while (i < Size) {
        short[] Encrypted = new short[11];

        if (i + 8 < Size) {
            short[] Decrypted = new short[8];
            System.arraycopy(contents, i, Decrypted, 0, 8);
            BlockEncode(Encrypted, Decrypted, 8, MuKeyFactory.getServerToClientPacketEncKeys());
        } else {
            short[] Decrypted = new short[Size - i];
            System.arraycopy(contents, i, Decrypted, 0, Decrypted.length);

            BlockEncode(Encrypted, Decrypted, (Size - i), MuKeyFactory.getServerToClientPacketEncKeys());
        }

        out.writerIndex(header + EncSize);
        for (int j = 0; j < Encrypted.length; j++) {
            out.writeByte(Encrypted[j]);
        }

        i += 8;
        EncSize += 11;
    }

    return EncSize;
}

From source file:com.yahoo.pulsar.client.impl.ProducerImpl.java

License:Apache License

/**
 * Strips checksum from {@link OpSendMsg} command if present else ignore it.   
 * /*  w w w  .ja  va 2 s  .c  o m*/
 * @param op
 */
private void stripChecksum(OpSendMsg op) {
    op.cmd.markReaderIndex();
    int totalMsgBufSize = op.cmd.readableBytes();
    DoubleByteBuf msg = getDoubleByteBuf(op.cmd);
    if (msg != null) {
        ByteBuf headerFrame = msg.getFirst();
        msg.markReaderIndex();
        headerFrame.markReaderIndex();
        try {
            headerFrame.skipBytes(4); // skip [total-size]
            int cmdSize = (int) headerFrame.readUnsignedInt();

            // verify if checksum present
            headerFrame.skipBytes(cmdSize);

            if (!hasChecksum(headerFrame)) {
                headerFrame.resetReaderIndex();
                return;
            }

            int headerSize = 4 + 4 + cmdSize; // [total-size] [cmd-length] [cmd-size]
            int checksumSize = 4 + 2; // [magic-number] [checksum-size]
            int checksumMark = (headerSize + checksumSize); // [header-size] [checksum-size]
            int metaPayloadSize = (totalMsgBufSize - checksumMark); // metadataPayload = totalSize - checksumMark
            int newTotalFrameSizeLength = 4 + cmdSize + metaPayloadSize; // new total-size without checksum
            headerFrame.resetReaderIndex();
            int headerFrameSize = headerFrame.readableBytes();

            headerFrame.setInt(0, newTotalFrameSizeLength); // rewrite new [total-size]
            ByteBuf metadata = headerFrame.slice(checksumMark, headerFrameSize - checksumMark); // sliced only
                                                                                                // metadata
            headerFrame.writerIndex(headerSize); // set headerFrame write-index to overwrite metadata over checksum
            metadata.readBytes(headerFrame, metadata.readableBytes());
            headerFrame.capacity(headerFrameSize - checksumSize); // reduce capacity by removed checksum bytes
            headerFrame.resetReaderIndex();

        } finally {
            op.cmd.resetReaderIndex();
        }
    } else {
        log.warn("[{}] Failed while casting {} into DoubleByteBuf", producerName, op.cmd.getClass().getName());
    }
}

From source file:com.yahoo.pulsar.common.api.DoubleByteBuf.java

License:Apache License

@Override
public ByteBuffer nioBuffer(int index, int length) {
    ByteBuffer dst = ByteBuffer.allocate(length);
    ByteBuf b = Unpooled.wrappedBuffer(dst);
    b.writerIndex(0);
    getBytes(index, b, length);/*from  w  ww.ja  v a  2s  . c o m*/
    return dst;
}

From source file:com.yahoo.pulsar.common.compression.CompressionCodecLZ4.java

License:Apache License

@Override
public ByteBuf encode(ByteBuf source) {
    int uncompressedLength = source.readableBytes();
    int maxLength = compressor.maxCompressedLength(uncompressedLength);

    ByteBuffer sourceNio = source.nioBuffer(source.readerIndex(), source.readableBytes());

    ByteBuf target = PooledByteBufAllocator.DEFAULT.buffer(maxLength, maxLength);
    ByteBuffer targetNio = target.nioBuffer(0, maxLength);

    int compressedLength = compressor.compress(sourceNio, 0, uncompressedLength, targetNio, 0, maxLength);
    target.writerIndex(compressedLength);
    return target;
}

From source file:com.yahoo.pulsar.common.compression.CompressionCodecLZ4.java

License:Apache License

@Override
public ByteBuf decode(ByteBuf encoded, int uncompressedLength) throws IOException {
    ByteBuf uncompressed = PooledByteBufAllocator.DEFAULT.buffer(uncompressedLength, uncompressedLength);
    ByteBuffer uncompressedNio = uncompressed.nioBuffer(0, uncompressedLength);

    ByteBuffer encodedNio = encoded.nioBuffer(encoded.readerIndex(), encoded.readableBytes());
    decompressor.decompress(encodedNio, encodedNio.position(), uncompressedNio, uncompressedNio.position(),
            uncompressedNio.remaining());

    uncompressed.writerIndex(uncompressedLength);
    return uncompressed;
}

From source file:com.yahoo.pulsar.common.compression.CompressionCodecZLib.java

License:Apache License

@Override
public ByteBuf decode(ByteBuf encoded, int uncompressedLength) throws IOException {
    ByteBuf uncompressed = PooledByteBufAllocator.DEFAULT.heapBuffer(uncompressedLength, uncompressedLength);

    int len = encoded.readableBytes();

    byte[] array;
    int offset;//from   ww w  .  jav  a2  s.co  m
    if (encoded.hasArray()) {
        array = encoded.array();
        offset = encoded.arrayOffset() + encoded.readerIndex();
    } else {
        array = new byte[len];
        encoded.getBytes(encoded.readerIndex(), array);
        offset = 0;
    }

    int resultLength;
    synchronized (inflater) {
        inflater.setInput(array, offset, len);
        try {
            resultLength = inflater.inflate(uncompressed.array(), uncompressed.arrayOffset(),
                    uncompressedLength);
        } catch (DataFormatException e) {
            throw new IOException(e);
        }
        inflater.reset();
    }

    checkArgument(resultLength == uncompressedLength);

    uncompressed.writerIndex(uncompressedLength);
    return uncompressed;
}

From source file:cubicchunks.network.WorldEncoder.java

License:MIT License

public static ByteBuf createByteBufForWrite(byte[] data) {
    ByteBuf bytebuf = Unpooled.wrappedBuffer(data);
    bytebuf.writerIndex(0);
    return bytebuf;
}