Example usage for io.netty.buffer ByteBuf capacity

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

Introduction

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

Prototype

public abstract ByteBuf capacity(int newCapacity);

Source Link

Document

Adjusts the capacity of this buffer.

Usage

From source file:appeng.core.sync.AppEngPacket.java

License:Open Source License

protected void configureWrite(final ByteBuf data) {
    data.capacity(data.readableBytes());
    this.p = new PacketBuffer(data);
}

From source file:appeng.fmp.CableBusPart.java

License:Open Source License

@Override
public void writeDesc(final MCDataOutput packet) {
    final ByteBuf stream = Unpooled.buffer();

    try {// w w  w  . j ava 2s . co m
        this.getCableBus().writeToStream(stream);
        packet.writeInt(stream.readableBytes());
        stream.capacity(stream.readableBytes());
        packet.writeByteArray(stream.array());
    } catch (final IOException e) {
        AELog.error(e);
    }
}

From source file:appeng.tile.AEBaseTile.java

License:Open Source License

/**
 * This builds a tag with the actual data that should be sent to the client for update syncs.
 * If the tile entity doesn't need update syncs, it returns null.
 *///  w w  w .  j a va  2s .com
private NBTTagCompound writeUpdateData() {
    final NBTTagCompound data = new NBTTagCompound();

    final ByteBuf stream = Unpooled.buffer();

    try {
        this.writeToStream(stream);
        if (stream.readableBytes() == 0) {
            return null;
        }
    } catch (final Throwable t) {
        AELog.debug(t);
    }

    stream.capacity(stream.readableBytes());
    data.setByteArray("X", stream.array());
    return data;
}

From source file:com.streamsets.pipeline.lib.parser.net.BaseNetworkMessageDataParser.java

License:Apache License

private void decodeMessages() throws IOException, DataParserException {
    byte[] bytes;
    if (inputStream != null) {
        bytes = IOUtils.toByteArray(inputStream);
    } else if (reader != null) {
        bytes = IOUtils.toByteArray(reader, charset);
    } else {//from   ww  w  . j  av a 2 s. com
        throw new IllegalStateException(
                "Both inputStream and reader were null in BaseNetworkMessageDataParser#decodeMessages");
    }

    ByteBuf buffer = Unpooled.copiedBuffer(bytes);
    if (maxObjectLen > 0) {
        buffer.capacity(maxObjectLen);
    }
    if (readerOffset != null && readerOffset > 0) {
        buffer.readerIndex(readerOffset.intValue());
    }
    try {
        performDecode(buffer);
        decodedMessagesIter = decodedMessages.listIterator();
        decoded = true;
    } catch (OnRecordErrorException e) {
        throw new DataParserException(Errors.SYSLOG_20, e.getMessage(), e);
    }
}

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 .  j a  v  a2s  . com*/
 * @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:de.unipassau.isl.evs.ssh.core.network.handler.CrypterTest.java

License:Open Source License

public void testRoundtrip() {
    ByteBuf buf = channel.alloc().buffer();
    for (int c : new int[] { 1, 1, 5, 10, 50, 100, 500, 1000, 5000, 10000 }) {
        buf.capacity(c);
        while (buf.writableBytes() > 0) {
            buf.writeByte(c);/*w ww . j a v a2s .  c om*/
        }

        channel.writeOutbound(buf.duplicate().retain());
        for (ByteBuf msg; (msg = channel.readOutbound()) != null;) {
            assertNotSame(buf, msg);
            channel.writeInbound(msg);
        }
        assertEquals(buf, channel.readInbound());
    }
    ReferenceCountUtil.release(buf);
}

From source file:de.unipassau.isl.evs.ssh.core.network.handler.SignerTest.java

License:Open Source License

public void testRoundtrip() {
    ByteBuf buf = channel.alloc().buffer();
    for (int c : new int[] { 1, 1, 5, 10, 50, 100, 500, 1000, 5000, 10000 }) {
        buf.capacity(c);
        while (buf.writableBytes() > 0) {
            buf.writeByte(c);/*from   w  ww  . j a va 2  s .  c o m*/
        }

        channel.writeOutbound(buf.duplicate().retain());
        channel.runPendingTasks();
        for (Object msg; (msg = channel.readOutbound()) != null;) {
            channel.writeInbound(msg);
        }
        assertEquals(buf, channel.readInbound());
    }
    ReferenceCountUtil.release(buf);
}

From source file:de.unipassau.isl.evs.ssh.core.network.handler.SignerTest.java

License:Open Source License

public void testModify() {
    ByteBuf buf = channel.alloc().buffer();
    buf.capacity(1000);
    while (buf.writableBytes() > 0) {
        buf.writeByte(buf.writableBytes());
    }//  ww w. java 2s .c  o  m

    try {
        channel.writeOutbound(buf.duplicate().retain());
        for (ByteBuf msg; (msg = channel.readOutbound()) != null;) {
            msg.setByte(500, ~msg.getByte(500));
            channel.writeInbound(msg);
        }

        channel.checkException();

        if (false)
            throw new SignatureException();
        fail("Missing exception");
    } catch (SignatureException e) {
    }
    if (channel.isOpen()) {
        fail("Channel not closed");
    }
}

From source file:dorkbox.network.pipeline.ByteBufOutput.java

License:Apache License

/** Writes the length and string, or null. Short strings are checked and if ASCII they are written more efficiently, else they
 * are written as UTF8. If a string is known to be ASCII, {@link #writeAscii(String)} may be used. The string can be read using
 * {@link ByteBufInput#readString()} or {@link ByteBufInput#readStringBuilder()}.
 * @param value May be null. *//*from www . ja  va 2s  .  c om*/
@Override
public void writeString(String value) throws KryoException {
    if (value == null) {
        writeByte(0x80); // 0 means null, bit 8 means UTF8.
        return;
    }
    int charCount = value.length();
    if (charCount == 0) {
        writeByte(1 | 0x80); // 1 means empty string, bit 8 means UTF8.
        return;
    }
    // Detect ASCII.
    boolean ascii = false;
    if (charCount > 1 && charCount < 64) { // only snoop 64 chars in
        ascii = true;
        for (int i = 0; i < charCount; i++) {
            int c = value.charAt(i);
            if (c > 127) {
                ascii = false;
                break;
            }
        }
    }

    ByteBuf buffer = byteBuf;
    if (buffer.writableBytes() < charCount) {
        buffer.capacity(buffer.capacity() + charCount + 1);
    }

    if (!ascii) {
        writeUtf8Length(charCount + 1);
    }

    int charIndex = 0;
    // Try to write 8 bit chars.
    for (; charIndex < charCount; charIndex++) {
        int c = value.charAt(charIndex);
        if (c > 127) {
            break; // whoops! detect ascii. have to continue with a slower method!
        }
        buffer.writeByte((byte) c);
    }
    if (charIndex < charCount) {
        writeString_slow(value, charCount, charIndex);
    } else if (ascii) {
        // specify it's ASCII
        int i = buffer.writerIndex() - 1;
        buffer.setByte(i, buffer.getByte(i) | 0x80); // Bit 8 means end of ASCII.
    }
}

From source file:dorkbox.network.pipeline.ByteBufOutput.java

License:Apache License

/** Writes the length and CharSequence as UTF8, or null. The string can be read using {@link ByteBufInput#readString()} or
 * {@link ByteBufInput#readStringBuilder()}.
 * @param value May be null. *//*from  w  ww . j a v a2  s  .  co  m*/
@Override
public void writeString(CharSequence value) throws KryoException {
    if (value == null) {
        writeByte(0x80); // 0 means null, bit 8 means UTF8.
        return;
    }
    int charCount = value.length();
    if (charCount == 0) {
        writeByte(1 | 0x80); // 1 means empty string, bit 8 means UTF8.
        return;
    }
    writeUtf8Length(charCount + 1);

    ByteBuf buffer = byteBuf;
    if (buffer.writableBytes() < charCount) {
        buffer.capacity(buffer.capacity() + charCount + 1);
    }
    int charIndex = 0;
    // Try to write 8 bit chars.
    for (; charIndex < charCount; charIndex++) {
        int c = value.charAt(charIndex);
        if (c > 127) {
            break; // whoops! have to continue with a slower method!
        }
        buffer.writeByte((byte) c);
    }
    if (charIndex < charCount) {
        writeString_slow(value, charCount, charIndex);
    }
}