Example usage for io.netty.buffer ByteBuf retainedDuplicate

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

Introduction

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

Prototype

public abstract ByteBuf retainedDuplicate();

Source Link

Document

Returns a retained buffer which shares the whole region of this buffer.

Usage

From source file:io.airlift.drift.transport.netty.codec.HeaderTransport.java

License:Apache License

public static Optional<FrameInfo> tryDecodeFrameInfo(ByteBuf input) {
    ByteBuf buffer = input.retainedDuplicate();
    try {// w  ww.  j  av  a  2  s  . c  o  m
        if (buffer.readableBytes() < FRAME_HEADER_SIZE) {
            return Optional.empty();
        }
        // skip magic
        buffer.readShort();
        short flags = buffer.readShort();
        boolean outOfOrderResponse = (flags & FLAG_SUPPORT_OUT_OF_ORDER_MASK) == 1;
        int headerSequenceId = buffer.readInt();
        int headerSize = buffer.readShort() << 2;

        if (buffer.readableBytes() < headerSize) {
            return Optional.empty();
        }

        byte protocolId = buffer.getByte(buffer.readerIndex());
        Protocol protocol = Protocol.getProtocolByHeaderTransportId(protocolId);

        buffer.skipBytes(headerSize);
        SimpleFrameInfoDecoder simpleFrameInfoDecoder = new SimpleFrameInfoDecoder(HEADER, protocol,
                outOfOrderResponse);
        Optional<FrameInfo> frameInfo = simpleFrameInfoDecoder.tryDecodeFrameInfo(buffer);
        if (frameInfo.isPresent()) {
            int messageSequenceId = frameInfo.get().getSequenceId();
            checkArgument(headerSequenceId == messageSequenceId,
                    "Sequence ids don't match. headerSequenceId: %s. messageSequenceId: %s", headerSequenceId,
                    messageSequenceId);
        }
        return frameInfo;
    } finally {
        buffer.release();
    }
}

From source file:io.airlift.drift.transport.netty.codec.SimpleFrameInfoDecoder.java

License:Apache License

@Override
public Optional<FrameInfo> tryDecodeFrameInfo(ByteBuf buffer) {
    TChannelBufferInputTransport transport = new TChannelBufferInputTransport(buffer.retainedDuplicate());
    try {//from  ww  w. j a va  2  s .  co m
        TProtocol protocol = protocolType.createProtocol(transport);
        TMessage message;
        try {
            message = protocol.readMessageBegin();
        } catch (TException | RuntimeException e) {
            // not enough bytes in the input to decode sequence id
            return Optional.empty();
        }
        return Optional.of(new FrameInfo(message.getName(), message.getType(), message.getSequenceId(),
                transportType, protocolType, assumeClientsSupportOutOfOrderResponses));
    } finally {
        transport.release();
    }
}

From source file:io.airlift.drift.transport.netty.codec.TestHeaderTransport.java

License:Apache License

@Test
public void testTryDecodeSequenceId() throws Exception {
    try (TestingPooledByteBufAllocator allocator = new TestingPooledByteBufAllocator()) {
        ByteBuf message = createTestFrame(allocator, "method", CALL, 0xFFAA, BINARY, true);
        try {//from   w  w w  . j  a v  a  2s  .co m
            assertDecodeFrameInfo(message.retainedSlice(0, 0), Optional.empty());
            assertDecodeFrameInfo(message.retainedSlice(0, 1), Optional.empty());
            assertDecodeFrameInfo(message.retainedSlice(0, 5), Optional.empty());
            assertDecodeFrameInfo(message.retainedSlice(0, 10), Optional.empty());
            assertDecodeFrameInfo(message.retainedSlice(0, 15), Optional.empty());
            assertDecodeFrameInfo(message.retainedDuplicate(),
                    Optional.of(new FrameInfo("method", CALL, 0xFFAA, HEADER, BINARY, true)));
        } finally {
            message.release();
        }
        assertDecodeFrameInfo(createTestFrame(allocator, "method1", ONEWAY, 123, FB_COMPACT, false),
                Optional.of(new FrameInfo("method1", ONEWAY, 123, HEADER, FB_COMPACT, false)));
    }
}

From source file:io.moquette.spi.impl.MessagesPublisher.java

License:Open Source License

void publish2Subscribers(IMessagesStore.StoredMessage pubMsg, Topic topic) {
    List<Subscription> topicMatchingSubscriptions = subscriptions.matches(topic);
    final String topic1 = pubMsg.getTopic();
    final MqttQoS publishingQos = pubMsg.getQos();
    final ByteBuf origPayload = pubMsg.getPayload();

    for (final Subscription sub : topicMatchingSubscriptions) {
        MqttQoS qos = lowerQosToTheSubscriptionDesired(sub, publishingQos);
        ClientSession targetSession = m_sessionsStore.sessionForClient(sub.getClientId());

        boolean targetIsActive = this.connectionDescriptors.isConnected(sub.getClientId());
        //TODO move all this logic into messageSender, which puts into the flightZone only the messages that pull out of the queue.
        if (targetIsActive) {
            LOG.debug("Sending PUBLISH message to active subscriber. CId={}, topicFilter={}, qos={}",
                    sub.getClientId(), sub.getTopicFilter(), qos);
            // we need to retain because duplicate only copy r/w indexes and don't retain() causing
            // refCnt = 0
            ByteBuf payload = origPayload.retainedDuplicate();
            MqttPublishMessage publishMsg;
            if (qos != MqttQoS.AT_MOST_ONCE) {
                // QoS 1 or 2
                int messageId = targetSession.inFlightAckWaiting(pubMsg);
                // set the PacketIdentifier only for QoS > 0
                publishMsg = notRetainedPublishWithMessageId(topic1, qos, payload, messageId);
            } else {
                publishMsg = notRetainedPublish(topic1, qos, payload);
            }//from w w w  . j  a  va 2s  . c  o  m
            this.messageSender.sendPublish(targetSession, publishMsg);
        } else {
            if (!targetSession.isCleanSession()) {
                LOG.debug("Storing pending PUBLISH inactive message. CId={}, topicFilter={}, qos={}",
                        sub.getClientId(), sub.getTopicFilter(), qos);
                // store the message in targetSession queue to deliver
                targetSession.enqueue(pubMsg);
            }
        }
    }
}

From source file:org.apache.pulsar.broker.service.nonpersistent.NonPersistentTopic.java

License:Apache License

@Override
public void publishMessage(ByteBuf data, PublishContext callback) {
    callback.completed(null, 0L, 0L);/*www.  java 2 s .c o  m*/
    ENTRIES_ADDED_COUNTER_UPDATER.incrementAndGet(this);

    subscriptions.forEach((name, subscription) -> {
        ByteBuf duplicateBuffer = data.retainedDuplicate();
        Entry entry = create(0L, 0L, duplicateBuffer);
        // entry internally retains data so, duplicateBuffer should be release here
        duplicateBuffer.release();
        if (subscription.getDispatcher() != null) {
            subscription.getDispatcher().sendMessages(Collections.singletonList(entry));
        } else {
            // it happens when subscription is created but dispatcher is not created as consumer is not added
            // yet
            entry.release();
        }
    });

    if (!replicators.isEmpty()) {
        replicators.forEach((name, replicator) -> {
            ByteBuf duplicateBuffer = data.retainedDuplicate();
            Entry entry = create(0L, 0L, duplicateBuffer);
            // entry internally retains data so, duplicateBuffer should be release here
            duplicateBuffer.release();
            ((NonPersistentReplicator) replicator).sendMessage(entry);
        });
    }
}