Example usage for io.netty.buffer ByteBuf clear

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

Introduction

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

Prototype

public abstract ByteBuf clear();

Source Link

Document

Sets the readerIndex and writerIndex of this buffer to 0 .

Usage

From source file:io.moquette.parser.netty.SubscribeDecoderTest.java

License:Open Source License

private void initMultiTopic(ByteBuf buff, int messageID, SubscribeMessage.Couple... topics)
        throws IllegalAccessException {
    ByteBuf topicBuffer = Unpooled.buffer(4);
    topicBuffer.writeShort(messageID);/*w  w w  .  j  a v a2 s . c  o m*/
    for (SubscribeMessage.Couple couple : topics) {
        topicBuffer.writeBytes(Utils.encodeString(couple.topicFilter));
        topicBuffer.writeByte(couple.qos);
    }

    buff.clear().writeByte(AbstractMessage.SUBSCRIBE << 4 | (byte) 0x02)
            .writeBytes(Utils.encodeRemainingLength(topicBuffer.readableBytes()));
    buff.writeBytes(topicBuffer);
}

From source file:io.moquette.parser.netty.SubscribeDecoderTest.java

License:Open Source License

private void initPollutedTopic(ByteBuf buff, int messageID, SubscribeMessage.Couple topic)
        throws IllegalAccessException {
    ByteBuf topicBuffer = Unpooled.buffer(4);
    topicBuffer.writeShort(messageID);/*from  w ww .  jav a  2  s. c o m*/
    topicBuffer.writeBytes(Utils.encodeString(topic.topicFilter));
    topicBuffer.writeByte(0xF0 | topic.qos);

    buff.clear().writeByte(AbstractMessage.SUBSCRIBE << 4 | (byte) 0x02)
            .writeBytes(Utils.encodeRemainingLength(topicBuffer.readableBytes()));
    buff.writeBytes(topicBuffer);
}

From source file:io.moquette.parser.netty.UnsubscribeDecoderTest.java

License:Open Source License

private void initHeaderBadQos(ByteBuf buff) {
    buff.clear().writeByte(AbstractMessage.UNSUBSCRIBE << 4).writeByte(0);
}

From source file:io.moquette.parser.netty.UnsubscribeDecoderTest.java

License:Open Source License

private void initMultiTopic(ByteBuf buff, int messageID, String... topics) throws IllegalAccessException {
    ByteBuf topicBuffer = Unpooled.buffer(4);
    topicBuffer.writeShort(messageID);//  www.  j  av a 2s  .  c o  m
    for (String topic : topics) {
        topicBuffer.writeBytes(Utils.encodeString(topic));
    }

    buff.clear().writeByte(AbstractMessage.UNSUBSCRIBE << 4 | (byte) 0x02)
            .writeBytes(Utils.encodeRemainingLength(topicBuffer.readableBytes()));
    buff.writeBytes(topicBuffer);
}

From source file:me.melchor9000.net.resolver.DNSResolverTest.java

License:Open Source License

@Test
public void serializeCorrectly2() throws Exception {
    ByteBuf buff = Unpooled.buffer(160);

    DNSMessage message = new DNSMessage();
    message.setId(0xDEAD);//ww w . j  a  v  a  2s .  c  o  m
    message.setQueryOrResponse(false);
    message.setOpcode((byte) 0);
    message.setAuthoritativeResponse(false);
    message.setTruncated(false);
    message.setRecursionDesired(true);

    buff.writerIndex(99);
    DNSA a = new DNSA(buff);
    DNSAAAA aaaa = new DNSAAAA(buff);
    DNSMX mx = new DNSMX(buff);
    buff.clear();

    a.setAddress(192, 168, 1, 101);
    aaaa.setAddress((Inet6Address) Inet6Address.getByName("fd6b:587e:77a::c85:7e1b:1a5e:7fd1"));
    mx.setExchange("mbp-de-melchor.local");
    mx.setPreference(1);

    DNSResourceRecord recordA = new DNSResourceRecord();
    recordA.setName("mbp-de-melchor.local");
    recordA.setType(1);
    recordA.setClass(1);
    recordA.setTtl(123);
    recordA.setData(a);

    DNSResourceRecord recordAAAA = new DNSResourceRecord();
    recordAAAA.setName("mbp-de-melchor.local");
    recordAAAA.setType("AAAA");
    recordAAAA.setClass(1);
    recordAAAA.setTtl(123);
    recordAAAA.setData(aaaa);

    DNSResourceRecord recordMX = new DNSResourceRecord();
    recordMX.setName("mbp-de-melchor.local");
    recordMX.setType("MX");
    recordMX.setClass(1);
    recordMX.setTtl(123);
    recordMX.setData(mx);

    message.addAnswer(recordA);
    message.addAnswer(recordAAAA);
    message.addAnswer(recordMX);

    assertEquals(12 + (12 + 20 + 4) + (12 + 20 + 16) + (12 + 20 + 24), message.byteBufSize());

    byte data[] = new byte[message.byteBufSize()];
    message.toByteBuf(buff);
    buff.readBytes(data);

    assertEquals(0, buff.readableBytes());
    assertArrayEquals(
            new byte[] { (byte) 0xDE, (byte) 0xAD, 0x01, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00,

                    0x0E, 0x6d, 0x62, 0x70, 0x2d, 0x64, 0x65, 0x2d, 0x6d, 0x65, 0x6c, 0x63, 0x68, 0x6f, 0x72,
                    0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x7B,
                    0x00, 0x04, (byte) 192, (byte) 168, 1, 101,

                    0x0E, 0x6d, 0x62, 0x70, 0x2d, 0x64, 0x65, 0x2d, 0x6d, 0x65, 0x6c, 0x63, 0x68, 0x6f, 0x72,
                    0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00, 0x00, 0x1C, 0x00, 0x01, 0x00, 0x00, 0x00, 0x7B,
                    0x00, 0x10, (byte) 0xfd, 0x6b, 0x58, 0x7e, 0x07, 0x7a, 0x00, 0x00, 0x0c, (byte) 0x085, 0x7e,
                    0x1b, 0x1a, 0x5e, 0x7f, (byte) 0xd1,

                    0x0E, 0x6d, 0x62, 0x70, 0x2d, 0x64, 0x65, 0x2d, 0x6d, 0x65, 0x6c, 0x63, 0x68, 0x6f, 0x72,
                    0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0F, 0x00, 0x01, 0x00, 0x00, 0x00, 0x7B,
                    0x00, 0x18, 0x00, 0x01, 0x0E, 0x6d, 0x62, 0x70, 0x2d, 0x64, 0x65, 0x2d, 0x6d, 0x65, 0x6c,
                    0x63, 0x68, 0x6f, 0x72, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00, },
            data);
}

From source file:net.floodlightcontroller.hasupport.ServerChannelInboundHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf message) throws Exception {
    ByteBuf rep = Unpooled.copiedBuffer(message);
    ByteBuf resp = Unpooled.copiedBuffer(processServerMessage(rep.toString(CharsetUtil.UTF_8)).getBytes());
    ctx.writeAndFlush(resp);/*from   w  w  w  .j ava 2  s  . c  o  m*/
    message.clear();
}

From source file:org.apache.activemq.artemis.core.replication.ReplicationManager.java

License:Apache License

/**
 * Sends large files in reasonably sized chunks to the backup during replication synchronization.
 *
 * @param content        journal type or {@code null} for large-messages and pages
 * @param pageStore      page store name for pages, or {@code null} otherwise
 * @param id             journal file id or (large) message id
 * @param file//from  w w  w. j  a  v a  2 s.c o m
 * @param maxBytesToSend maximum number of bytes to read and send from the file
 * @throws Exception
 */
private void sendLargeFile(AbstractJournalStorageManager.JournalContent content, SimpleString pageStore,
        final long id, SequentialFile file, long maxBytesToSend) throws Exception {
    if (!enabled)
        return;
    if (!file.isOpen()) {
        file.open();
    }
    int size = 32 * 1024;

    int flowControlSize = 10;

    int packetsSent = 0;
    FlushAction action = new FlushAction();

    try {
        try (FileInputStream fis = new FileInputStream(file.getJavaFile());
                FileChannel channel = fis.getChannel()) {

            // We can afford having a single buffer here for this entire loop
            // because sendReplicatePacket will encode the packet as a NettyBuffer
            // through ActiveMQBuffer class leaving this buffer free to be reused on the next copy
            while (true) {
                final ByteBuf buffer = PooledByteBufAllocator.DEFAULT.directBuffer(size, size);
                buffer.clear();
                ByteBuffer byteBuffer = buffer.writerIndex(size).readerIndex(0).nioBuffer();
                final int bytesRead = channel.read(byteBuffer);
                int toSend = bytesRead;
                if (bytesRead > 0) {
                    if (bytesRead >= maxBytesToSend) {
                        toSend = (int) maxBytesToSend;
                        maxBytesToSend = 0;
                    } else {
                        maxBytesToSend = maxBytesToSend - bytesRead;
                    }
                }
                logger.debug("sending " + buffer.writerIndex() + " bytes on file " + file.getFileName());
                // sending -1 or 0 bytes will close the file at the backup
                // We cannot simply send everything of a file through the executor,
                // otherwise we would run out of memory.
                // so we don't use the executor here
                sendReplicatePacket(new ReplicationSyncFileMessage(content, pageStore, id, toSend, buffer),
                        true);
                packetsSent++;

                if (packetsSent % flowControlSize == 0) {
                    flushReplicationStream(action);
                }
                if (bytesRead == -1 || bytesRead == 0 || maxBytesToSend == 0)
                    break;
            }
        }
        flushReplicationStream(action);
    } finally {
        if (file.isOpen())
            file.close();
    }
}

From source file:org.apache.bookkeeper.bookie.EntryLogger.java

License:Apache License

long addEntryForCompaction(long ledgerId, ByteBuf entry) throws IOException {
    synchronized (compactionLogLock) {
        int entrySize = entry.readableBytes() + 4;
        if (compactionLogChannel == null) {
            createNewCompactionLog();/*from   w ww  .j  av  a  2s  .  com*/
        }

        ByteBuf sizeBuffer = this.sizeBuffer.get();
        sizeBuffer.clear();
        sizeBuffer.writeInt(entry.readableBytes());
        compactionLogChannel.write(sizeBuffer);

        long pos = compactionLogChannel.position();
        compactionLogChannel.write(entry);
        compactionLogChannel.registerWrittenEntry(ledgerId, entrySize);
        return (compactionLogChannel.getLogId() << 32L) | pos;
    }
}

From source file:org.apache.bookkeeper.bookie.EntryLogger.java

License:Apache License

private EntryLogEntry getFCForEntryInternal(long ledgerId, long entryId, long entryLogId, long pos)
        throws EntryLookupException, IOException {
    ByteBuf sizeBuff = sizeBuffer.get();
    sizeBuff.clear();
    pos -= 4; // we want to get the entrySize as well as the ledgerId and entryId
    BufferedReadChannel fc;// w ww .jav  a 2  s .  c o m
    try {
        fc = getChannelForLogId(entryLogId);
    } catch (FileNotFoundException e) {
        throw new EntryLookupException.MissingLogFileException(ledgerId, entryId, entryLogId, pos);
    }

    try {
        if (readFromLogChannel(entryLogId, fc, sizeBuff, pos) != sizeBuff.capacity()) {
            throw new EntryLookupException.MissingEntryException(ledgerId, entryId, entryLogId, pos);
        }
    } catch (BufferedChannelBase.BufferedChannelClosedException | AsynchronousCloseException e) {
        throw new EntryLookupException.MissingLogFileException(ledgerId, entryId, entryLogId, pos);
    }
    pos += 4;
    int entrySize = sizeBuff.readInt();

    // entrySize does not include the ledgerId
    if (entrySize > maxSaneEntrySize) {
        LOG.warn("Sanity check failed for entry size of " + entrySize + " at location " + pos + " in "
                + entryLogId);
    }
    if (entrySize < MIN_SANE_ENTRY_SIZE) {
        LOG.error("Read invalid entry length {}", entrySize);
        throw new EntryLookupException.InvalidEntryLengthException(ledgerId, entryId, entryLogId, pos);
    }

    long thisLedgerId = sizeBuff.getLong(4);
    long thisEntryId = sizeBuff.getLong(12);
    if (thisLedgerId != ledgerId || thisEntryId != entryId) {
        throw new EntryLookupException.WrongEntryException(thisEntryId, thisLedgerId, ledgerId, entryId,
                entryLogId, pos);
    }
    return new EntryLogEntry(entrySize, fc);
}

From source file:org.apache.bookkeeper.bookie.EntryLogger.java

License:Apache License

/**
 * Scan entry log.//  w  ww.  j a  v  a 2 s  .c  om
 *
 * @param entryLogId Entry Log Id
 * @param scanner Entry Log Scanner
 * @throws IOException
 */
public void scanEntryLog(long entryLogId, EntryLogScanner scanner) throws IOException {
    // Buffer where to read the entrySize (4 bytes) and the ledgerId (8 bytes)
    ByteBuf headerBuffer = Unpooled.buffer(4 + 8);
    BufferedReadChannel bc;
    // Get the BufferedChannel for the current entry log file
    try {
        bc = getChannelForLogId(entryLogId);
    } catch (IOException e) {
        LOG.warn("Failed to get channel to scan entry log: " + entryLogId + ".log");
        throw e;
    }
    // Start the read position in the current entry log file to be after
    // the header where all of the ledger entries are.
    long pos = LOGFILE_HEADER_SIZE;

    // Start with a reasonably sized buffer size
    ByteBuf data = allocator.directBuffer(1024 * 1024);

    try {

        // Read through the entry log file and extract the ledger ID's.
        while (true) {
            // Check if we've finished reading the entry log file.
            if (pos >= bc.size()) {
                break;
            }
            if (readFromLogChannel(entryLogId, bc, headerBuffer, pos) != headerBuffer.capacity()) {
                LOG.warn("Short read for entry size from entrylog {}", entryLogId);
                return;
            }
            long offset = pos;
            pos += 4;
            int entrySize = headerBuffer.readInt();
            long ledgerId = headerBuffer.readLong();
            headerBuffer.clear();

            if (ledgerId == INVALID_LID || !scanner.accept(ledgerId)) {
                // skip this entry
                pos += entrySize;
                continue;
            }
            // read the entry

            data.clear();
            data.capacity(entrySize);
            int rc = readFromLogChannel(entryLogId, bc, data, pos);
            if (rc != entrySize) {
                LOG.warn("Short read for ledger entry from entryLog {}@{} ({} != {})", entryLogId, pos, rc,
                        entrySize);
                return;
            }
            // process the entry
            scanner.process(ledgerId, offset, data);

            // Advance position to the next entry
            pos += entrySize;
        }
    } finally {
        data.release();
    }
}