Example usage for io.netty.buffer ByteBuf markWriterIndex

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

Introduction

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

Prototype

public abstract ByteBuf markWriterIndex();

Source Link

Document

Marks the current writerIndex in this buffer.

Usage

From source file:com.lambdaworks.redis.protocol.CommandEncoder.java

License:Apache License

private void encode(ChannelHandlerContext ctx, ByteBuf out, RedisCommand<?, ?, ?> command) {

    try {//from  w w  w . j  a v a 2  s  .co  m
        out.markWriterIndex();
        command.encode(out);
    } catch (RuntimeException e) {
        out.resetWriterIndex();
        command.completeExceptionally(new EncoderException(
                "Cannot encode command. Please close the connection as the connection state may be out of sync.",
                e));
    }

    if (debugEnabled) {
        logger.debug("{} writing command {}", logPrefix(ctx.channel()), command);
        if (traceEnabled) {
            logger.trace("{} Sent: {}", logPrefix(ctx.channel()),
                    out.toString(Charset.defaultCharset()).trim());
        }
    }
}

From source file:com.ogarproject.ogar.server.net.packet.outbound.PacketOutUpdateNodes.java

License:Open Source License

@Override
public void writeData(ByteBuf buf) {
    // Removals by eating
    int lengthIndex = buf.writerIndex();
    int eaten = 0;
    buf.writerIndex(lengthIndex + 2);//  w w  w.j a v  a2s.com
    for (EntityImpl entity : removals) {
        if (entity.getConsumer() > 0) {
            eaten++;
            buf.writeInt(entity.getConsumer());
            buf.writeInt(entity.getID());
        }
    }
    buf.markWriterIndex();
    buf.writerIndex(lengthIndex);
    buf.writeShort(eaten);
    buf.resetWriterIndex();

    // Updates
    for (int id : updates) {
        EntityImpl entity = world.getEntity(id);
        if (entity == null) {
            // TODO - Theoretically this could be ignored, but it might cause other issues,
            // like having nonexistent entities on the player's screen. Re-evaluate this later?
            throw new MalformedPacketException("Attempted to update nonexistent entity");
        }

        buf.writeInt(entity.getID());
        buf.writeInt((int) entity.getPosition().getX());
        buf.writeInt((int) entity.getPosition().getY());
        buf.writeShort(entity.getPhysicalSize());
        buf.writeByte(entity.getColor().getRed());
        buf.writeByte(entity.getColor().getGreen());
        buf.writeByte(entity.getColor().getBlue());
        buf.writeBoolean(entity.isSpiked());
        // buf.skipBytes(18);
        if (entity instanceof CellImpl) {
            CellImpl cell = (CellImpl) entity;
            if (cell.getName() == null) {
                writeUTF16(buf, "");
            } else {
                writeUTF16(buf, cell.getName());
            }
        } else {
            writeUTF16(buf, "");
        }
    }
    buf.writeInt(0);

    // General removals
    buf.writeInt(removals.size());
    for (EntityImpl entity : removals) {
        buf.writeInt(entity.getID());
    }
}

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

License:Apache License

public void testBufferedChannel(int byteBufLength, int numOfWrites, int unpersistedBytesBound, boolean flush,
        boolean shouldForceWrite) throws Exception {
    File newLogFile = File.createTempFile("test", "log");
    newLogFile.deleteOnExit();/*  w w w  . j  av  a2  s.  co m*/
    FileChannel fileChannel = new RandomAccessFile(newLogFile, "rw").getChannel();

    BufferedChannel logChannel = new BufferedChannel(UnpooledByteBufAllocator.DEFAULT, fileChannel,
            INTERNAL_BUFFER_WRITE_CAPACITY, INTERNAL_BUFFER_READ_CAPACITY, unpersistedBytesBound);

    ByteBuf dataBuf = generateEntry(byteBufLength);
    dataBuf.markReaderIndex();
    dataBuf.markWriterIndex();

    for (int i = 0; i < numOfWrites; i++) {
        logChannel.write(dataBuf);
        dataBuf.resetReaderIndex();
        dataBuf.resetWriterIndex();
    }

    if (flush && shouldForceWrite) {
        logChannel.flushAndForceWrite(false);
    } else if (flush) {
        logChannel.flush();
    } else if (shouldForceWrite) {
        logChannel.forceWrite(false);
    }

    int expectedNumOfUnpersistedBytes = 0;

    if (flush && shouldForceWrite) {
        /*
         * if flush call is made with shouldForceWrite,
         * then expectedNumOfUnpersistedBytes should be zero.
         */
        expectedNumOfUnpersistedBytes = 0;
    } else if (!flush && shouldForceWrite) {
        /*
         * if flush is not called then internal write buffer is not flushed,
         * but while adding entries to BufferedChannel if writeBuffer has
         * reached its capacity then it will call flush method, and the data
         * gets added to the file buffer. So though explicitly we are not
         * calling flush method, implicitly flush gets called when
         * writeBuffer reaches its capacity.
         */
        expectedNumOfUnpersistedBytes = (byteBufLength * numOfWrites) % INTERNAL_BUFFER_WRITE_CAPACITY;
    } else {
        expectedNumOfUnpersistedBytes = (byteBufLength * numOfWrites) - unpersistedBytesBound;
    }

    Assert.assertEquals("Unpersisted bytes", expectedNumOfUnpersistedBytes, logChannel.getUnpersistedBytes());
    logChannel.close();
    fileChannel.close();
}

From source file:org.mobicents.protocols.ss7.m3ua.impl.message.MessageFactoryImpl.java

License:Open Source License

public M3UAMessageImpl createMessage(ByteBuf message) {
    int dataLen;/* www.  j a v  a 2  s.  com*/
    if (message.readableBytes() < 8) {
        return null;
    }

    // obtain message class and type from header
    message.markReaderIndex();
    message.skipBytes(2);
    int messageClass = message.readUnsignedByte();
    int messageType = message.readUnsignedByte();

    // obtain remaining length of the message and prepare buffer
    dataLen = message.readInt() - 8;
    if (message.readableBytes() < dataLen) {
        message.resetReaderIndex();
        return null;
    }

    // construct new message instance
    M3UAMessageImpl messageTemp = this.createMessage(messageClass, messageType);

    // parsing params of this message
    message.markWriterIndex();
    message.writerIndex(message.readerIndex() + dataLen);
    messageTemp.decode(message);
    message.resetWriterIndex();

    return messageTemp;
}

From source file:org.restcomm.protocols.ss7.m3ua.impl.message.M3UAMessageImpl.java

License:Open Source License

public void encode(ByteBuf byteBuf) {
    byteBuf.writeByte(1);//  ww  w  .j  a  va2 s . com
    byteBuf.writeByte(0);
    byteBuf.writeByte(messageClass);
    byteBuf.writeByte(messageType);

    byteBuf.markWriterIndex();
    byteBuf.writeInt(8);
    int currIndex = byteBuf.writerIndex();

    encodeParams(byteBuf);

    int newIndex = byteBuf.writerIndex();
    byteBuf.resetWriterIndex();
    byteBuf.writeInt(newIndex - currIndex + 8);
    byteBuf.writerIndex(newIndex);
}

From source file:qunar.tc.qmq.protocol.MessagesPayloadHolder.java

License:Apache License

private void serializeMessage(BaseMessage message, ByteBuf out) {
    int crcIndex = out.writerIndex();
    // sizeof(bodyCrc<long>)
    out.ensureWritable(8);/*from   w  w w  . j a v  a 2s.  co  m*/
    out.writerIndex(crcIndex + 8);

    final int messageStart = out.writerIndex();

    // flag
    byte flag = 0;
    //?(1)?(0)?(1)?(0)?Tag
    flag = Flags.setDelay(flag, DelayUtil.isDelayMessage(message));

    //in avoid add tag after sendMessage
    Set<String> tags = new HashSet<>(message.getTags());
    flag = Flags.setTags(flag, hasTags(tags));

    out.writeByte(flag);

    // created time
    out.writeLong(message.getCreatedTime().getTime());
    if (Flags.isDelay(flag)) {
        out.writeLong(message.getScheduleReceiveTime().getTime());
    } else {
        // expired time
        out.writeLong(System.currentTimeMillis());
    }
    // subject
    PayloadHolderUtils.writeString(message.getSubject(), out);
    // message id
    PayloadHolderUtils.writeString(message.getMessageId(), out);

    writeTags(tags, out);

    out.markWriterIndex();
    // writerIndex + sizeof(bodyLength<int>)
    final int bodyStart = out.writerIndex() + 4;
    out.ensureWritable(4);
    out.writerIndex(bodyStart);

    serializeMap(message.getAttrs(), out);
    final int bodyEnd = out.writerIndex();

    final int messageEnd = out.writerIndex();

    final int bodyLen = bodyEnd - bodyStart;
    final int messageLength = bodyEnd - messageStart;

    // write body length
    out.resetWriterIndex();
    out.writeInt(bodyLen);

    // write message crc
    out.writerIndex(crcIndex);
    out.writeLong(messageCrc(out, messageStart, messageLength));

    out.writerIndex(messageEnd);
}

From source file:qunar.tc.qmq.store.IndexLog.java

License:Apache License

private void partialCopy(ByteBuffer src, ByteBuf to) {
    while (to.isWritable(Long.BYTES)) {
        src.mark();/* w  w  w  . j a  v a 2 s . c o  m*/
        to.markWriterIndex();
        if (!to.isWritable(Long.BYTES))
            break;
        to.writeLong(src.getLong());

        if (!to.isWritable(Long.BYTES)) {
            src.reset();
            to.resetWriterIndex();
            break;
        }
        to.writeLong(src.getLong());

        // subject
        if (!writeString(src, to))
            break;

        // msgId
        if (!writeString(src, to))
            break;
    }
}

From source file:qunar.tc.qmq.sync.master.MessageIndexSyncWorker.java

License:Apache License

@Override
protected SegmentBuffer getSyncLog(SyncRequest syncRequest) {
    final long originalOffset = syncRequest.getMessageLogOffset();
    long startSyncOffset = originalOffset;

    long minMessageOffset = storage.getMinMessageOffset();
    if (startSyncOffset < minMessageOffset) {
        startSyncOffset = minMessageOffset;
        LOG.info("reset message log sync offset from {} to {}", originalOffset, startSyncOffset);
    }/* w w  w  . j ava 2  s .  c om*/

    try (MessageLogRecordVisitor visitor = storage.newMessageLogVisitor(startSyncOffset)) {
        LogSegment logSegment = null;
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.ioBuffer(batchSize);
        long nextSyncOffset = startSyncOffset;
        try {
            for (int i = 0; i < MAX_SYNC_NUM; ++i) {
                LogVisitorRecord<MessageLogRecord> record = visitor.nextRecord();
                if (record.isNoMore()) {
                    nextSyncOffset = visitor.getStartOffset() + visitor.visitedBufferSize();
                    break;
                }

                if (!record.hasData()) {
                    nextSyncOffset = visitor.getStartOffset() + visitor.visitedBufferSize();
                    continue;
                }

                MessageLogRecord data = record.getData();
                logSegment = data.getLogSegment();

                if (!byteBuf.isWritable(Long.BYTES))
                    break;
                byteBuf.markWriterIndex();
                byteBuf.writeLong(data.getSequence());

                if (!byteBuf.isWritable(Long.BYTES)) {
                    byteBuf.resetWriterIndex();
                    break;
                }

                ByteBuffer body = data.getPayload();
                //skip flag
                body.get();
                long createTime = body.getLong();
                //skip expireTime
                body.getLong();

                //subject
                short len = body.getShort();
                byte[] subject = new byte[len];
                body.get(subject);

                //message id
                len = body.getShort();
                byte[] messageId = new byte[len];
                body.get(messageId);

                byteBuf.writeLong(createTime);

                if (!byteBuf.isWritable(Short.BYTES + subject.length)) {
                    byteBuf.resetWriterIndex();
                    break;
                }
                PayloadHolderUtils.writeString(subject, byteBuf);

                if (!byteBuf.isWritable(Short.BYTES + messageId.length)) {
                    byteBuf.resetWriterIndex();
                    break;
                }
                PayloadHolderUtils.writeString(messageId, byteBuf);

                nextSyncOffset = visitor.getStartOffset() + visitor.visitedBufferSize();
            }
        } finally {
            if (!byteBuf.isReadable()) {
                byteBuf.release();
            }
        }

        if (originalOffset == nextSyncOffset) {
            return null;
        }

        //FIXME: ????
        if (byteBuf.isReadable()) {
            return new ByteBufSegmentBuffer(nextSyncOffset, logSegment, byteBuf, byteBuf.readableBytes());
        } else {
            return new ByteBufSegmentBuffer(nextSyncOffset);
        }
    }
}