Search in sources :

Example 6 with KeyValue

use of org.apache.pulsar.common.api.proto.KeyValue in project pulsar by apache.

the class TopicsImpl method getIndividualMsgsFromBatch.

private List<Message<byte[]>> getIndividualMsgsFromBatch(String topic, String msgId, byte[] data, Map<String, String> properties, MessageMetadata msgMetadataBuilder, BrokerEntryMetadata brokerEntryMetadata) {
    List<Message<byte[]>> ret = new ArrayList<>();
    int batchSize = Integer.parseInt(properties.get(BATCH_HEADER));
    ByteBuf buf = Unpooled.wrappedBuffer(data);
    for (int i = 0; i < batchSize; i++) {
        String batchMsgId = msgId + ":" + i;
        SingleMessageMetadata singleMessageMetadata = new SingleMessageMetadata();
        try {
            ByteBuf singleMessagePayload = Commands.deSerializeSingleMessageInBatch(buf, singleMessageMetadata, i, batchSize);
            if (singleMessageMetadata.getPropertiesCount() > 0) {
                for (KeyValue entry : singleMessageMetadata.getPropertiesList()) {
                    properties.put(entry.getKey(), entry.getValue());
                }
            }
            MessageImpl message = new MessageImpl<>(topic, batchMsgId, properties, singleMessagePayload, Schema.BYTES, msgMetadataBuilder);
            if (brokerEntryMetadata != null) {
                message.setBrokerEntryMetadata(brokerEntryMetadata);
            }
            ret.add(message);
        } catch (Exception ex) {
            log.error("Exception occurred while trying to get BatchMsgId: {}", batchMsgId, ex);
        }
    }
    buf.release();
    return ret;
}
Also used : KeyValue(org.apache.pulsar.common.api.proto.KeyValue) Message(org.apache.pulsar.client.api.Message) SingleMessageMetadata(org.apache.pulsar.common.api.proto.SingleMessageMetadata) ArrayList(java.util.ArrayList) ByteBuf(io.netty.buffer.ByteBuf) MessageImpl(org.apache.pulsar.client.impl.MessageImpl) NotFoundException(org.apache.pulsar.client.admin.PulsarAdminException.NotFoundException) PulsarAdminException(org.apache.pulsar.client.admin.PulsarAdminException)

Example 7 with KeyValue

use of org.apache.pulsar.common.api.proto.KeyValue in project pulsar by apache.

the class Commands method newSubscribe.

public static ByteBuf newSubscribe(String topic, String subscription, long consumerId, long requestId, SubType subType, int priorityLevel, String consumerName, boolean isDurable, MessageIdData startMessageId, Map<String, String> metadata, boolean readCompacted, boolean isReplicated, InitialPosition subscriptionInitialPosition, long startMessageRollbackDurationInSec, SchemaInfo schemaInfo, boolean createTopicIfDoesNotExist, KeySharedPolicy keySharedPolicy, Map<String, String> subscriptionProperties, long consumerEpoch) {
    BaseCommand cmd = localCmd(Type.SUBSCRIBE);
    CommandSubscribe subscribe = cmd.setSubscribe().setTopic(topic).setSubscription(subscription).setSubType(subType).setConsumerId(consumerId).setConsumerName(consumerName).setRequestId(requestId).setPriorityLevel(priorityLevel).setDurable(isDurable).setReadCompacted(readCompacted).setInitialPosition(subscriptionInitialPosition).setReplicateSubscriptionState(isReplicated).setForceTopicCreation(createTopicIfDoesNotExist).setConsumerEpoch(consumerEpoch);
    if (subscriptionProperties != null && !subscriptionProperties.isEmpty()) {
        List<KeyValue> keyValues = new ArrayList<>();
        subscriptionProperties.forEach((key, value) -> {
            KeyValue keyValue = new KeyValue();
            keyValue.setKey(key);
            keyValue.setValue(value);
            keyValues.add(keyValue);
        });
        subscribe.addAllSubscriptionProperties(keyValues);
    }
    if (keySharedPolicy != null) {
        KeySharedMeta keySharedMeta = subscribe.setKeySharedMeta();
        keySharedMeta.setAllowOutOfOrderDelivery(keySharedPolicy.isAllowOutOfOrderDelivery());
        keySharedMeta.setKeySharedMode(convertKeySharedMode(keySharedPolicy.getKeySharedMode()));
        if (keySharedPolicy instanceof KeySharedPolicy.KeySharedPolicySticky) {
            List<Range> ranges = ((KeySharedPolicy.KeySharedPolicySticky) keySharedPolicy).getRanges();
            for (Range range : ranges) {
                IntRange r = keySharedMeta.addHashRange();
                r.setStart(range.getStart());
                r.setEnd(range.getEnd());
            }
        }
    }
    if (startMessageId != null) {
        subscribe.setStartMessageId().copyFrom(startMessageId);
    }
    if (startMessageRollbackDurationInSec > 0) {
        subscribe.setStartMessageRollbackDurationSec(startMessageRollbackDurationInSec);
    }
    if (!metadata.isEmpty()) {
        metadata.entrySet().forEach(e -> subscribe.addMetadata().setKey(e.getKey()).setValue(e.getValue()));
    }
    if (schemaInfo != null) {
        if (subscribe.hasSchema()) {
            throw new IllegalStateException();
        }
        if (subscribe.setSchema().getPropertiesCount() > 0) {
            throw new IllegalStateException();
        }
        convertSchema(schemaInfo, subscribe.setSchema());
    }
    return serializeWithSize(cmd);
}
Also used : CommandSubscribe(org.apache.pulsar.common.api.proto.CommandSubscribe) KeyValue(org.apache.pulsar.common.api.proto.KeyValue) BaseCommand(org.apache.pulsar.common.api.proto.BaseCommand) ArrayList(java.util.ArrayList) IntRange(org.apache.pulsar.common.api.proto.IntRange) KeySharedMeta(org.apache.pulsar.common.api.proto.KeySharedMeta) Range(org.apache.pulsar.client.api.Range) IntRange(org.apache.pulsar.common.api.proto.IntRange)

Example 8 with KeyValue

use of org.apache.pulsar.common.api.proto.KeyValue in project pulsar by yahoo.

the class InterceptorsTest method testConsumerInterceptorForAcknowledgeCumulative.

@Test
public void testConsumerInterceptorForAcknowledgeCumulative() throws PulsarClientException {
    List<MessageId> ackHolder = new ArrayList<>();
    ConsumerInterceptor<String> interceptor = new ConsumerInterceptor<String>() {

        @Override
        public void close() {
        }

        @Override
        public Message<String> beforeConsume(Consumer<String> consumer, Message<String> message) {
            MessageImpl<String> msg = (MessageImpl<String>) message;
            msg.getMessageBuilder().addProperty().setKey("beforeConsumer").setValue("1");
            return msg;
        }

        @Override
        public void onAcknowledge(Consumer<String> consumer, MessageId messageId, Throwable cause) {
            log.info("onAcknowledge messageId: {}", messageId, cause);
        }

        @Override
        public void onAcknowledgeCumulative(Consumer<String> consumer, MessageId messageId, Throwable cause) {
            long acknowledged = ackHolder.stream().filter(m -> (m.compareTo(messageId) <= 0)).count();
            Assert.assertEquals(acknowledged, 100);
            ackHolder.clear();
            log.info("onAcknowledgeCumulative messageIds: {}", messageId, cause);
        }

        @Override
        public void onNegativeAcksSend(Consumer<String> consumer, Set<MessageId> messageIds) {
        }

        @Override
        public void onAckTimeoutSend(Consumer<String> consumer, Set<MessageId> messageIds) {
        }
    };
    Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING).topic("persistent://my-property/my-ns/my-topic").subscriptionType(SubscriptionType.Failover).intercept(interceptor).subscriptionName("my-subscription").subscribe();
    Producer<String> producer = pulsarClient.newProducer(Schema.STRING).topic("persistent://my-property/my-ns/my-topic").create();
    for (int i = 0; i < 100; i++) {
        producer.newMessage().value("Hello Pulsar!").send();
    }
    int keyCount = 0;
    for (int i = 0; i < 100; i++) {
        Message<String> received = consumer.receive();
        MessageImpl<String> msg = (MessageImpl<String>) received;
        for (KeyValue keyValue : msg.getMessageBuilder().getPropertiesList()) {
            if ("beforeConsumer".equals(keyValue.getKey())) {
                keyCount++;
            }
        }
        ackHolder.add(received.getMessageId());
        if (i == 99) {
            consumer.acknowledgeCumulative(received);
        }
    }
    Assert.assertEquals(100, keyCount);
    producer.close();
    consumer.close();
}
Also used : RandomUtils(org.apache.commons.lang3.RandomUtils) Arrays(java.util.Arrays) DataProvider(org.testng.annotations.DataProvider) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cleanup(lombok.Cleanup) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Test(org.testng.annotations.Test) AfterMethod(org.testng.annotations.AfterMethod) KeyValue(org.apache.pulsar.common.api.proto.KeyValue) SchemaType(org.apache.pulsar.common.schema.SchemaType) ArrayList(java.util.ArrayList) MessageImpl(org.apache.pulsar.client.impl.MessageImpl) Assert(org.testng.Assert) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) TopicMessageImpl(org.apache.pulsar.client.impl.TopicMessageImpl) Logger(org.slf4j.Logger) SchemaCompatibilityStrategy(org.apache.pulsar.common.policies.data.SchemaCompatibilityStrategy) BeforeMethod(org.testng.annotations.BeforeMethod) Set(java.util.Set) Sets(com.google.common.collect.Sets) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) RandomStringUtils(org.apache.commons.lang3.RandomStringUtils) Awaitility(org.awaitility.Awaitility) Set(java.util.Set) KeyValue(org.apache.pulsar.common.api.proto.KeyValue) ArrayList(java.util.ArrayList) MessageImpl(org.apache.pulsar.client.impl.MessageImpl) TopicMessageImpl(org.apache.pulsar.client.impl.TopicMessageImpl) Test(org.testng.annotations.Test)

Example 9 with KeyValue

use of org.apache.pulsar.common.api.proto.KeyValue in project pulsar by yahoo.

the class ConsumerImpl method createEncryptionContext.

/**
 * Create EncryptionContext if message payload is encrypted.
 *
 * @param msgMetadata
 * @return {@link Optional}<{@link EncryptionContext}>
 */
private Optional<EncryptionContext> createEncryptionContext(MessageMetadata msgMetadata) {
    EncryptionContext encryptionCtx = null;
    if (msgMetadata.getEncryptionKeysCount() > 0) {
        encryptionCtx = new EncryptionContext();
        Map<String, EncryptionKey> keys = msgMetadata.getEncryptionKeysList().stream().collect(Collectors.toMap(EncryptionKeys::getKey, e -> new EncryptionKey(e.getValue(), e.getMetadatasList().stream().collect(Collectors.toMap(KeyValue::getKey, KeyValue::getValue)))));
        byte[] encParam = msgMetadata.getEncryptionParam();
        Optional<Integer> batchSize = Optional.ofNullable(msgMetadata.hasNumMessagesInBatch() ? msgMetadata.getNumMessagesInBatch() : null);
        encryptionCtx.setKeys(keys);
        encryptionCtx.setParam(encParam);
        if (msgMetadata.hasEncryptionAlgo()) {
            encryptionCtx.setAlgorithm(msgMetadata.getEncryptionAlgo());
        }
        encryptionCtx.setCompressionType(CompressionCodecProvider.convertFromWireProtocol(msgMetadata.getCompression()));
        encryptionCtx.setUncompressedMessageSize(msgMetadata.getUncompressedSize());
        encryptionCtx.setBatchSize(batchSize);
    }
    return Optional.ofNullable(encryptionCtx);
}
Also used : EncryptionKey(org.apache.pulsar.common.api.EncryptionContext.EncryptionKey) SubscriptionMode(org.apache.pulsar.client.api.SubscriptionMode) MessageIdData(org.apache.pulsar.common.api.proto.MessageIdData) Producer(org.apache.pulsar.client.api.Producer) LoggerFactory(org.slf4j.LoggerFactory) MessageCryptoBc(org.apache.pulsar.client.impl.crypto.MessageCryptoBc) MessageCrypto(org.apache.pulsar.client.api.MessageCrypto) StringUtils(org.apache.commons.lang3.StringUtils) KeyValue(org.apache.pulsar.common.api.proto.KeyValue) ByteBuffer(java.nio.ByteBuffer) GrowableArrayBlockingQueue(org.apache.pulsar.common.util.collections.GrowableArrayBlockingQueue) ProtocolVersion(org.apache.pulsar.common.api.proto.ProtocolVersion) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) TxnID(org.apache.pulsar.client.api.transaction.TxnID) Handle(io.netty.util.Recycler.Handle) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorProvider(org.apache.pulsar.client.util.ExecutorProvider) Runnables.catchingAndLoggingThrowables(org.apache.pulsar.common.util.Runnables.catchingAndLoggingThrowables) Map(java.util.Map) Messages(org.apache.pulsar.client.api.Messages) RetryMessageUtil(org.apache.pulsar.client.util.RetryMessageUtil) CompletableFutureCancellationHandler(org.apache.pulsar.common.util.CompletableFutureCancellationHandler) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) BrokerEntryMetadata(org.apache.pulsar.common.api.proto.BrokerEntryMetadata) Crc32cIntChecksum(com.scurrilous.circe.checksum.Crc32cIntChecksum) ValidationError(org.apache.pulsar.common.api.proto.CommandAck.ValidationError) BitSetRecyclable(org.apache.pulsar.common.util.collections.BitSetRecyclable) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) EncryptionContext(org.apache.pulsar.common.api.EncryptionContext) ComparisonChain(com.google.common.collect.ComparisonChain) Collectors(java.util.stream.Collectors) PulsarByteBufAllocator(org.apache.pulsar.common.allocator.PulsarByteBufAllocator) Recycler(io.netty.util.Recycler) Objects(java.util.Objects) Consumer(org.apache.pulsar.client.api.Consumer) List(java.util.List) FutureUtil(org.apache.pulsar.common.util.FutureUtil) MessageMetadata(org.apache.pulsar.common.api.proto.MessageMetadata) ConcurrentOpenHashMap(org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap) EncryptionKeys(org.apache.pulsar.common.api.proto.EncryptionKeys) CommandMessage(org.apache.pulsar.common.api.proto.CommandMessage) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) Optional(java.util.Optional) SchemaInfo(org.apache.pulsar.common.schema.SchemaInfo) SortedMap(java.util.SortedMap) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) CompressionCodec(org.apache.pulsar.common.compression.CompressionCodec) Iterables(com.google.common.collect.Iterables) AtomicIntegerFieldUpdater(java.util.concurrent.atomic.AtomicIntegerFieldUpdater) ConsumerCryptoFailureAction(org.apache.pulsar.client.api.ConsumerCryptoFailureAction) TopicName(org.apache.pulsar.common.naming.TopicName) ConsumerConfigurationData(org.apache.pulsar.client.impl.conf.ConsumerConfigurationData) AckType(org.apache.pulsar.common.api.proto.CommandAck.AckType) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Message(org.apache.pulsar.client.api.Message) SubscriptionInitialPosition(org.apache.pulsar.client.api.SubscriptionInitialPosition) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) SchemaType(org.apache.pulsar.common.schema.SchemaType) ArrayList(java.util.ArrayList) Commands(org.apache.pulsar.common.protocol.Commands) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Commands.hasChecksum(org.apache.pulsar.common.protocol.Commands.hasChecksum) TopicDoesNotExistException(org.apache.pulsar.client.api.PulsarClientException.TopicDoesNotExistException) CompressionCodecProvider(org.apache.pulsar.common.compression.CompressionCodecProvider) CompressionType(org.apache.pulsar.common.api.proto.CompressionType) TypedMessageBuilder(org.apache.pulsar.client.api.TypedMessageBuilder) SafeCollectionUtils(org.apache.pulsar.common.util.SafeCollectionUtils) DEFAULT_CONSUMER_EPOCH(org.apache.pulsar.common.protocol.Commands.DEFAULT_CONSUMER_EPOCH) Timeout(io.netty.util.Timeout) Logger(org.slf4j.Logger) TransactionImpl(org.apache.pulsar.client.impl.transaction.TransactionImpl) InitialPosition(org.apache.pulsar.common.api.proto.CommandSubscribe.InitialPosition) DeadLetterPolicy(org.apache.pulsar.client.api.DeadLetterPolicy) IOException(java.io.IOException) AtomicLongFieldUpdater(java.util.concurrent.atomic.AtomicLongFieldUpdater) SubscriptionType(org.apache.pulsar.client.api.SubscriptionType) Schema(org.apache.pulsar.client.api.Schema) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) MessageId(org.apache.pulsar.client.api.MessageId) TreeMap(java.util.TreeMap) SingleMessageMetadata(org.apache.pulsar.common.api.proto.SingleMessageMetadata) Collections(java.util.Collections) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) KeyValue(org.apache.pulsar.common.api.proto.KeyValue) EncryptionContext(org.apache.pulsar.common.api.EncryptionContext) EncryptionKey(org.apache.pulsar.common.api.EncryptionContext.EncryptionKey)

Example 10 with KeyValue

use of org.apache.pulsar.common.api.proto.KeyValue in project pulsar by yahoo.

the class Commands method newSubscribe.

public static ByteBuf newSubscribe(String topic, String subscription, long consumerId, long requestId, SubType subType, int priorityLevel, String consumerName, boolean isDurable, MessageIdData startMessageId, Map<String, String> metadata, boolean readCompacted, boolean isReplicated, InitialPosition subscriptionInitialPosition, long startMessageRollbackDurationInSec, SchemaInfo schemaInfo, boolean createTopicIfDoesNotExist, KeySharedPolicy keySharedPolicy, Map<String, String> subscriptionProperties, long consumerEpoch) {
    BaseCommand cmd = localCmd(Type.SUBSCRIBE);
    CommandSubscribe subscribe = cmd.setSubscribe().setTopic(topic).setSubscription(subscription).setSubType(subType).setConsumerId(consumerId).setConsumerName(consumerName).setRequestId(requestId).setPriorityLevel(priorityLevel).setDurable(isDurable).setReadCompacted(readCompacted).setInitialPosition(subscriptionInitialPosition).setReplicateSubscriptionState(isReplicated).setForceTopicCreation(createTopicIfDoesNotExist).setConsumerEpoch(consumerEpoch);
    if (subscriptionProperties != null && !subscriptionProperties.isEmpty()) {
        List<KeyValue> keyValues = new ArrayList<>();
        subscriptionProperties.forEach((key, value) -> {
            KeyValue keyValue = new KeyValue();
            keyValue.setKey(key);
            keyValue.setValue(value);
            keyValues.add(keyValue);
        });
        subscribe.addAllSubscriptionProperties(keyValues);
    }
    if (keySharedPolicy != null) {
        KeySharedMeta keySharedMeta = subscribe.setKeySharedMeta();
        keySharedMeta.setAllowOutOfOrderDelivery(keySharedPolicy.isAllowOutOfOrderDelivery());
        keySharedMeta.setKeySharedMode(convertKeySharedMode(keySharedPolicy.getKeySharedMode()));
        if (keySharedPolicy instanceof KeySharedPolicy.KeySharedPolicySticky) {
            List<Range> ranges = ((KeySharedPolicy.KeySharedPolicySticky) keySharedPolicy).getRanges();
            for (Range range : ranges) {
                IntRange r = keySharedMeta.addHashRange();
                r.setStart(range.getStart());
                r.setEnd(range.getEnd());
            }
        }
    }
    if (startMessageId != null) {
        subscribe.setStartMessageId().copyFrom(startMessageId);
    }
    if (startMessageRollbackDurationInSec > 0) {
        subscribe.setStartMessageRollbackDurationSec(startMessageRollbackDurationInSec);
    }
    if (!metadata.isEmpty()) {
        metadata.entrySet().forEach(e -> subscribe.addMetadata().setKey(e.getKey()).setValue(e.getValue()));
    }
    if (schemaInfo != null) {
        if (subscribe.hasSchema()) {
            throw new IllegalStateException();
        }
        if (subscribe.setSchema().getPropertiesCount() > 0) {
            throw new IllegalStateException();
        }
        convertSchema(schemaInfo, subscribe.setSchema());
    }
    return serializeWithSize(cmd);
}
Also used : CommandSubscribe(org.apache.pulsar.common.api.proto.CommandSubscribe) KeyValue(org.apache.pulsar.common.api.proto.KeyValue) BaseCommand(org.apache.pulsar.common.api.proto.BaseCommand) ArrayList(java.util.ArrayList) IntRange(org.apache.pulsar.common.api.proto.IntRange) KeySharedMeta(org.apache.pulsar.common.api.proto.KeySharedMeta) Range(org.apache.pulsar.client.api.Range) IntRange(org.apache.pulsar.common.api.proto.IntRange)

Aggregations

KeyValue (org.apache.pulsar.common.api.proto.KeyValue)44 Set (java.util.Set)18 MessageImpl (org.apache.pulsar.client.impl.MessageImpl)18 ArrayList (java.util.ArrayList)15 CompletableFuture (java.util.concurrent.CompletableFuture)12 TopicMessageImpl (org.apache.pulsar.client.impl.TopicMessageImpl)12 Test (org.testng.annotations.Test)12 HashMap (java.util.HashMap)10 ByteBuf (io.netty.buffer.ByteBuf)9 List (java.util.List)9 Map (java.util.Map)9 TreeMap (java.util.TreeMap)9 TimeUnit (java.util.concurrent.TimeUnit)9 EncryptionKeys (org.apache.pulsar.common.api.proto.EncryptionKeys)9 MessageMetadata (org.apache.pulsar.common.api.proto.MessageMetadata)9 Logger (org.slf4j.Logger)9 LoggerFactory (org.slf4j.LoggerFactory)9 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 IOException (java.io.IOException)6 Collections (java.util.Collections)6