Search in sources :

Example 26 with MessageId

use of org.apache.pulsar.client.api.MessageId in project incubator-pulsar by apache.

the class TopicTerminationTest method testCreateProducerOnTerminatedTopic.

@Test
public void testCreateProducerOnTerminatedTopic() throws Exception {
    Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).create();
    /* MessageId msgId1 = */
    producer.send("test-msg-1".getBytes());
    /* MessageId msgId2 = */
    producer.send("test-msg-2".getBytes());
    MessageId msgId3 = producer.send("test-msg-3".getBytes());
    MessageId lastMessageId = admin.persistentTopics().terminateTopicAsync(topicName).get();
    assertEquals(lastMessageId, msgId3);
    try {
        pulsarClient.newProducer().topic(topicName).create();
        fail("Should have thrown exception");
    } catch (PulsarClientException.TopicTerminatedException e) {
    // Expected
    }
}
Also used : PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) MessageId(org.apache.pulsar.client.api.MessageId) Test(org.testng.annotations.Test)

Example 27 with MessageId

use of org.apache.pulsar.client.api.MessageId in project incubator-pulsar by apache.

the class TopicTerminationTest method testSimpleTerminationReader.

@Test(timeOut = 20000)
public void testSimpleTerminationReader() throws Exception {
    Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).create();
    MessageId msgId1 = producer.send("test-msg-1".getBytes());
    MessageId msgId2 = producer.send("test-msg-2".getBytes());
    MessageId msgId3 = producer.send("test-msg-3".getBytes());
    MessageId lastMessageId = admin.persistentTopics().terminateTopicAsync(topicName).get();
    assertEquals(lastMessageId, msgId3);
    Reader<byte[]> reader = pulsarClient.newReader().topic(topicName).startMessageId(MessageId.earliest).create();
    Message<byte[]> msg1 = reader.readNext();
    assertEquals(msg1.getMessageId(), msgId1);
    Message<byte[]> msg2 = reader.readNext();
    assertEquals(msg2.getMessageId(), msgId2);
    Message<byte[]> msg3 = reader.readNext();
    assertEquals(msg3.getMessageId(), msgId3);
    Message<byte[]> msg4 = reader.readNext(100, TimeUnit.MILLISECONDS);
    assertNull(msg4);
    Thread.sleep(100);
    assertTrue(reader.hasReachedEndOfTopic());
}
Also used : MessageId(org.apache.pulsar.client.api.MessageId) Test(org.testng.annotations.Test)

Example 28 with MessageId

use of org.apache.pulsar.client.api.MessageId in project incubator-pulsar by apache.

the class PersistentTopic method subscribe.

@Override
public CompletableFuture<Consumer> subscribe(final ServerCnx cnx, String subscriptionName, long consumerId, SubType subType, int priorityLevel, String consumerName, boolean isDurable, MessageId startMessageId, Map<String, String> metadata, boolean readCompacted, InitialPosition initialPosition) {
    final CompletableFuture<Consumer> future = new CompletableFuture<>();
    if (readCompacted && !(subType == SubType.Failover || subType == SubType.Exclusive)) {
        future.completeExceptionally(new NotAllowedException("readCompacted only allowed on failover or exclusive subscriptions"));
        return future;
    }
    if (isBlank(subscriptionName)) {
        if (log.isDebugEnabled()) {
            log.debug("[{}] Empty subscription name", topic);
        }
        future.completeExceptionally(new NamingException("Empty subscription name"));
        return future;
    }
    if (hasBatchMessagePublished && !cnx.isBatchMessageCompatibleVersion()) {
        if (log.isDebugEnabled()) {
            log.debug("[{}] Consumer doesn't support batch-message {}", topic, subscriptionName);
        }
        future.completeExceptionally(new UnsupportedVersionException("Consumer doesn't support batch-message"));
        return future;
    }
    if (subscriptionName.startsWith(replicatorPrefix) || subscriptionName.equals(DEDUPLICATION_CURSOR_NAME)) {
        log.warn("[{}] Failed to create subscription for {}", topic, subscriptionName);
        future.completeExceptionally(new NamingException("Subscription with reserved subscription name attempted"));
        return future;
    }
    lock.readLock().lock();
    try {
        if (isFenced) {
            log.warn("[{}] Attempting to subscribe to a fenced topic", topic);
            future.completeExceptionally(new TopicFencedException("Topic is temporarily unavailable"));
            return future;
        }
        USAGE_COUNT_UPDATER.incrementAndGet(this);
        if (log.isDebugEnabled()) {
            log.debug("[{}] [{}] [{}] Added consumer -- count: {}", topic, subscriptionName, consumerName, USAGE_COUNT_UPDATER.get(this));
        }
    } finally {
        lock.readLock().unlock();
    }
    CompletableFuture<? extends Subscription> subscriptionFuture = // 
    isDurable ? // 
    getDurableSubscription(subscriptionName, initialPosition) : getNonDurableSubscription(subscriptionName, startMessageId);
    int maxUnackedMessages = isDurable ? brokerService.pulsar().getConfiguration().getMaxUnackedMessagesPerConsumer() : 0;
    subscriptionFuture.thenAccept(subscription -> {
        try {
            Consumer consumer = new Consumer(subscription, subType, topic, consumerId, priorityLevel, consumerName, maxUnackedMessages, cnx, cnx.getRole(), metadata, readCompacted, initialPosition);
            subscription.addConsumer(consumer);
            if (!cnx.isActive()) {
                consumer.close();
                if (log.isDebugEnabled()) {
                    log.debug("[{}] [{}] [{}] Subscribe failed -- count: {}", topic, subscriptionName, consumer.consumerName(), USAGE_COUNT_UPDATER.get(PersistentTopic.this));
                }
                future.completeExceptionally(new BrokerServiceException("Connection was closed while the opening the cursor "));
            } else {
                log.info("[{}][{}] Created new subscription for {}", topic, subscriptionName, consumerId);
                future.complete(consumer);
            }
        } catch (BrokerServiceException e) {
            if (e instanceof ConsumerBusyException) {
                log.warn("[{}][{}] Consumer {} {} already connected", topic, subscriptionName, consumerId, consumerName);
            } else if (e instanceof SubscriptionBusyException) {
                log.warn("[{}][{}] {}", topic, subscriptionName, e.getMessage());
            }
            USAGE_COUNT_UPDATER.decrementAndGet(PersistentTopic.this);
            future.completeExceptionally(e);
        }
    }).exceptionally(ex -> {
        log.warn("[{}] Failed to create subscription for {}: ", topic, subscriptionName, ex.getMessage());
        USAGE_COUNT_UPDATER.decrementAndGet(PersistentTopic.this);
        future.completeExceptionally(new PersistenceException(ex));
        return null;
    });
    return future;
}
Also used : SubscriptionStats(org.apache.pulsar.common.policies.data.SubscriptionStats) NamingException(org.apache.pulsar.broker.service.BrokerServiceException.NamingException) Topic(org.apache.pulsar.broker.service.Topic) LedgerInfo(org.apache.pulsar.common.policies.data.PersistentTopicInternalStats.LedgerInfo) PersistentTopicStats(org.apache.pulsar.common.policies.data.PersistentTopicStats) AdminResource(org.apache.pulsar.broker.admin.AdminResource) NotAllowedException(org.apache.pulsar.broker.service.BrokerServiceException.NotAllowedException) SchemaVersion(org.apache.pulsar.common.schema.SchemaVersion) CloseCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.CloseCallback) UnsupportedVersionException(org.apache.pulsar.broker.service.BrokerServiceException.UnsupportedVersionException) LoggerFactory(org.slf4j.LoggerFactory) ObjectObjectHashMap(com.carrotsearch.hppc.ObjectObjectHashMap) ProducerBusyException(org.apache.pulsar.broker.service.BrokerServiceException.ProducerBusyException) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) OpenCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenCursorCallback) MessageImpl(org.apache.pulsar.client.impl.MessageImpl) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) Map(java.util.Map) DeleteCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCursorCallback) StatsOutputStream(org.apache.pulsar.utils.StatsOutputStream) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) ReplicationMetrics(org.apache.pulsar.broker.stats.ReplicationMetrics) ManagedLedgerAlreadyClosedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerAlreadyClosedException) Set(java.util.Set) Position(org.apache.bookkeeper.mledger.Position) BrokerService(org.apache.pulsar.broker.service.BrokerService) ReplicatorStats(org.apache.pulsar.common.policies.data.ReplicatorStats) IndividualDeletedEntries(org.apache.bookkeeper.mledger.ManagedCursor.IndividualDeletedEntries) NamespaceStats(org.apache.pulsar.broker.stats.NamespaceStats) Sets(com.google.common.collect.Sets) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) SubscriptionBusyException(org.apache.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) ManagedCursorImpl(org.apache.bookkeeper.mledger.impl.ManagedCursorImpl) ServerCnx(org.apache.pulsar.broker.service.ServerCnx) List(java.util.List) FutureUtil(org.apache.pulsar.common.util.FutureUtil) ConcurrentOpenHashSet(org.apache.pulsar.common.util.collections.ConcurrentOpenHashSet) BatchMessageIdImpl(org.apache.pulsar.client.impl.BatchMessageIdImpl) ConcurrentOpenHashMap(org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap) ManagedLedgerFencedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerFencedException) TopicTerminatedException(org.apache.pulsar.broker.service.BrokerServiceException.TopicTerminatedException) SchemaData(org.apache.pulsar.common.schema.SchemaData) Optional(java.util.Optional) ManagedLedgerTerminatedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerTerminatedException) PersistentTopicInternalStats(org.apache.pulsar.common.policies.data.PersistentTopicInternalStats) NamespaceBundleStats(org.apache.pulsar.policies.data.loadbalancer.NamespaceBundleStats) AsyncCallbacks(org.apache.bookkeeper.mledger.AsyncCallbacks) PublisherStats(org.apache.pulsar.common.policies.data.PublisherStats) Subscription(org.apache.pulsar.broker.service.Subscription) TopicName(org.apache.pulsar.common.naming.TopicName) CursorStats(org.apache.pulsar.common.policies.data.PersistentTopicInternalStats.CursorStats) Entry(org.apache.bookkeeper.mledger.Entry) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BacklogQuota(org.apache.pulsar.common.policies.data.BacklogQuota) CompletableFuture(java.util.concurrent.CompletableFuture) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Consumer(org.apache.pulsar.broker.service.Consumer) TerminateCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.TerminateCallback) TopicClosedException(org.apache.pulsar.broker.service.BrokerServiceException.TopicClosedException) ServerMetadataException(org.apache.pulsar.broker.service.BrokerServiceException.ServerMetadataException) DateFormatter(org.apache.pulsar.common.util.DateFormatter) Lists(com.google.common.collect.Lists) ByteBuf(io.netty.buffer.ByteBuf) CompactedTopicImpl(org.apache.pulsar.compaction.CompactedTopicImpl) FastThreadLocal(io.netty.util.concurrent.FastThreadLocal) ClusterReplicationMetrics(org.apache.pulsar.broker.stats.ClusterReplicationMetrics) ManagedLedgerImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl) Logger(org.slf4j.Logger) SubType(org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.SubType) KeeperException(org.apache.zookeeper.KeeperException) CompactedTopic(org.apache.pulsar.compaction.CompactedTopic) BrokerServiceException(org.apache.pulsar.broker.service.BrokerServiceException) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) MoreObjects(com.google.common.base.MoreObjects) AtomicLongFieldUpdater(java.util.concurrent.atomic.AtomicLongFieldUpdater) PersistenceException(org.apache.pulsar.broker.service.BrokerServiceException.PersistenceException) Producer(org.apache.pulsar.broker.service.Producer) TopicFencedException(org.apache.pulsar.broker.service.BrokerServiceException.TopicFencedException) Maps(com.google.common.collect.Maps) TimeUnit(java.util.concurrent.TimeUnit) Policies(org.apache.pulsar.common.policies.data.Policies) TopicBusyException(org.apache.pulsar.broker.service.BrokerServiceException.TopicBusyException) MessageId(org.apache.pulsar.client.api.MessageId) Compactor(org.apache.pulsar.compaction.Compactor) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) POLICIES(org.apache.pulsar.broker.cache.ConfigurationCacheService.POLICIES) Codec(org.apache.pulsar.common.util.Codec) ConsumerBusyException(org.apache.pulsar.broker.service.BrokerServiceException.ConsumerBusyException) Replicator(org.apache.pulsar.broker.service.Replicator) ConsumerStats(org.apache.pulsar.common.policies.data.ConsumerStats) InitialPosition(org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.InitialPosition) Collections(java.util.Collections) TopicFencedException(org.apache.pulsar.broker.service.BrokerServiceException.TopicFencedException) NotAllowedException(org.apache.pulsar.broker.service.BrokerServiceException.NotAllowedException) BrokerServiceException(org.apache.pulsar.broker.service.BrokerServiceException) CompletableFuture(java.util.concurrent.CompletableFuture) ConsumerBusyException(org.apache.pulsar.broker.service.BrokerServiceException.ConsumerBusyException) Consumer(org.apache.pulsar.broker.service.Consumer) PersistenceException(org.apache.pulsar.broker.service.BrokerServiceException.PersistenceException) NamingException(org.apache.pulsar.broker.service.BrokerServiceException.NamingException) SubscriptionBusyException(org.apache.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) UnsupportedVersionException(org.apache.pulsar.broker.service.BrokerServiceException.UnsupportedVersionException)

Example 29 with MessageId

use of org.apache.pulsar.client.api.MessageId in project incubator-pulsar by apache.

the class PersistentTopic method terminate.

public CompletableFuture<MessageId> terminate() {
    CompletableFuture<MessageId> future = new CompletableFuture<>();
    ledger.asyncTerminate(new TerminateCallback() {

        @Override
        public void terminateComplete(Position lastCommittedPosition, Object ctx) {
            producers.forEach(Producer::disconnect);
            subscriptions.forEach((name, sub) -> sub.topicTerminated());
            PositionImpl lastPosition = (PositionImpl) lastCommittedPosition;
            MessageId messageId = new MessageIdImpl(lastPosition.getLedgerId(), lastPosition.getEntryId(), -1);
            log.info("[{}] Topic terminated at {}", getName(), messageId);
            future.complete(messageId);
        }

        @Override
        public void terminateFailed(ManagedLedgerException exception, Object ctx) {
            future.completeExceptionally(exception);
        }
    }, null);
    return future;
}
Also used : SubscriptionStats(org.apache.pulsar.common.policies.data.SubscriptionStats) NamingException(org.apache.pulsar.broker.service.BrokerServiceException.NamingException) Topic(org.apache.pulsar.broker.service.Topic) LedgerInfo(org.apache.pulsar.common.policies.data.PersistentTopicInternalStats.LedgerInfo) PersistentTopicStats(org.apache.pulsar.common.policies.data.PersistentTopicStats) AdminResource(org.apache.pulsar.broker.admin.AdminResource) NotAllowedException(org.apache.pulsar.broker.service.BrokerServiceException.NotAllowedException) SchemaVersion(org.apache.pulsar.common.schema.SchemaVersion) CloseCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.CloseCallback) UnsupportedVersionException(org.apache.pulsar.broker.service.BrokerServiceException.UnsupportedVersionException) LoggerFactory(org.slf4j.LoggerFactory) ObjectObjectHashMap(com.carrotsearch.hppc.ObjectObjectHashMap) ProducerBusyException(org.apache.pulsar.broker.service.BrokerServiceException.ProducerBusyException) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) OpenCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenCursorCallback) MessageImpl(org.apache.pulsar.client.impl.MessageImpl) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) Map(java.util.Map) DeleteCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCursorCallback) StatsOutputStream(org.apache.pulsar.utils.StatsOutputStream) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) ReplicationMetrics(org.apache.pulsar.broker.stats.ReplicationMetrics) ManagedLedgerAlreadyClosedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerAlreadyClosedException) Set(java.util.Set) Position(org.apache.bookkeeper.mledger.Position) BrokerService(org.apache.pulsar.broker.service.BrokerService) ReplicatorStats(org.apache.pulsar.common.policies.data.ReplicatorStats) IndividualDeletedEntries(org.apache.bookkeeper.mledger.ManagedCursor.IndividualDeletedEntries) NamespaceStats(org.apache.pulsar.broker.stats.NamespaceStats) Sets(com.google.common.collect.Sets) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) SubscriptionBusyException(org.apache.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) ManagedCursorImpl(org.apache.bookkeeper.mledger.impl.ManagedCursorImpl) ServerCnx(org.apache.pulsar.broker.service.ServerCnx) List(java.util.List) FutureUtil(org.apache.pulsar.common.util.FutureUtil) ConcurrentOpenHashSet(org.apache.pulsar.common.util.collections.ConcurrentOpenHashSet) BatchMessageIdImpl(org.apache.pulsar.client.impl.BatchMessageIdImpl) ConcurrentOpenHashMap(org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap) ManagedLedgerFencedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerFencedException) TopicTerminatedException(org.apache.pulsar.broker.service.BrokerServiceException.TopicTerminatedException) SchemaData(org.apache.pulsar.common.schema.SchemaData) Optional(java.util.Optional) ManagedLedgerTerminatedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerTerminatedException) PersistentTopicInternalStats(org.apache.pulsar.common.policies.data.PersistentTopicInternalStats) NamespaceBundleStats(org.apache.pulsar.policies.data.loadbalancer.NamespaceBundleStats) AsyncCallbacks(org.apache.bookkeeper.mledger.AsyncCallbacks) PublisherStats(org.apache.pulsar.common.policies.data.PublisherStats) Subscription(org.apache.pulsar.broker.service.Subscription) TopicName(org.apache.pulsar.common.naming.TopicName) CursorStats(org.apache.pulsar.common.policies.data.PersistentTopicInternalStats.CursorStats) Entry(org.apache.bookkeeper.mledger.Entry) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BacklogQuota(org.apache.pulsar.common.policies.data.BacklogQuota) CompletableFuture(java.util.concurrent.CompletableFuture) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Consumer(org.apache.pulsar.broker.service.Consumer) TerminateCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.TerminateCallback) TopicClosedException(org.apache.pulsar.broker.service.BrokerServiceException.TopicClosedException) ServerMetadataException(org.apache.pulsar.broker.service.BrokerServiceException.ServerMetadataException) DateFormatter(org.apache.pulsar.common.util.DateFormatter) Lists(com.google.common.collect.Lists) ByteBuf(io.netty.buffer.ByteBuf) CompactedTopicImpl(org.apache.pulsar.compaction.CompactedTopicImpl) FastThreadLocal(io.netty.util.concurrent.FastThreadLocal) ClusterReplicationMetrics(org.apache.pulsar.broker.stats.ClusterReplicationMetrics) ManagedLedgerImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl) Logger(org.slf4j.Logger) SubType(org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.SubType) KeeperException(org.apache.zookeeper.KeeperException) CompactedTopic(org.apache.pulsar.compaction.CompactedTopic) BrokerServiceException(org.apache.pulsar.broker.service.BrokerServiceException) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) MoreObjects(com.google.common.base.MoreObjects) AtomicLongFieldUpdater(java.util.concurrent.atomic.AtomicLongFieldUpdater) PersistenceException(org.apache.pulsar.broker.service.BrokerServiceException.PersistenceException) Producer(org.apache.pulsar.broker.service.Producer) TopicFencedException(org.apache.pulsar.broker.service.BrokerServiceException.TopicFencedException) Maps(com.google.common.collect.Maps) TimeUnit(java.util.concurrent.TimeUnit) Policies(org.apache.pulsar.common.policies.data.Policies) TopicBusyException(org.apache.pulsar.broker.service.BrokerServiceException.TopicBusyException) MessageId(org.apache.pulsar.client.api.MessageId) Compactor(org.apache.pulsar.compaction.Compactor) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) POLICIES(org.apache.pulsar.broker.cache.ConfigurationCacheService.POLICIES) Codec(org.apache.pulsar.common.util.Codec) ConsumerBusyException(org.apache.pulsar.broker.service.BrokerServiceException.ConsumerBusyException) Replicator(org.apache.pulsar.broker.service.Replicator) ConsumerStats(org.apache.pulsar.common.policies.data.ConsumerStats) InitialPosition(org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.InitialPosition) Collections(java.util.Collections) CompletableFuture(java.util.concurrent.CompletableFuture) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) TerminateCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.TerminateCallback) Position(org.apache.bookkeeper.mledger.Position) InitialPosition(org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.InitialPosition) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) BatchMessageIdImpl(org.apache.pulsar.client.impl.BatchMessageIdImpl) MessageId(org.apache.pulsar.client.api.MessageId)

Example 30 with MessageId

use of org.apache.pulsar.client.api.MessageId in project incubator-pulsar by apache.

the class CreateSubscriptionTest method createSubscriptionSingleTopic.

@Test
public void createSubscriptionSingleTopic() throws Exception {
    String topic = "persistent://prop-xyz/use/ns1/my-topic";
    admin.persistentTopics().createSubscription(topic, "sub-1", MessageId.latest);
    // Create should fail if the subscription already exists
    try {
        admin.persistentTopics().createSubscription(topic, "sub-1", MessageId.latest);
        fail("Should have failed");
    } catch (ConflictException e) {
        assertEquals(((ClientErrorException) e.getCause()).getResponse().getStatus(), Status.CONFLICT.getStatusCode());
    }
    assertEquals(admin.persistentTopics().getSubscriptions(topic), Lists.newArrayList("sub-1"));
    Producer<byte[]> p1 = pulsarClient.newProducer().topic(topic).create();
    p1.send("test-1".getBytes());
    p1.send("test-2".getBytes());
    MessageId m3 = p1.send("test-3".getBytes());
    assertEquals(admin.persistentTopics().getStats(topic).subscriptions.get("sub-1").msgBacklog, 3);
    admin.persistentTopics().createSubscription(topic, "sub-2", MessageId.latest);
    assertEquals(admin.persistentTopics().getStats(topic).subscriptions.get("sub-2").msgBacklog, 0);
    admin.persistentTopics().createSubscription(topic, "sub-3", MessageId.earliest);
    assertEquals(admin.persistentTopics().getStats(topic).subscriptions.get("sub-3").msgBacklog, 3);
    admin.persistentTopics().createSubscription(topic, "sub-5", m3);
    assertEquals(admin.persistentTopics().getStats(topic).subscriptions.get("sub-5").msgBacklog, 1);
}
Also used : ConflictException(org.apache.pulsar.client.admin.PulsarAdminException.ConflictException) MessageId(org.apache.pulsar.client.api.MessageId) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Aggregations

MessageId (org.apache.pulsar.client.api.MessageId)65 Test (org.testng.annotations.Test)42 CompletableFuture (java.util.concurrent.CompletableFuture)25 Message (org.apache.pulsar.client.api.Message)22 PulsarClientException (org.apache.pulsar.client.api.PulsarClientException)16 List (java.util.List)14 TimeUnit (java.util.concurrent.TimeUnit)14 Producer (org.apache.pulsar.client.api.Producer)14 Future (java.util.concurrent.Future)13 Consumer (org.apache.pulsar.client.api.Consumer)13 MessageIdImpl (org.apache.pulsar.client.impl.MessageIdImpl)13 ExecutorService (java.util.concurrent.ExecutorService)11 Logger (org.slf4j.Logger)11 LoggerFactory (org.slf4j.LoggerFactory)11 ByteBuf (io.netty.buffer.ByteBuf)10 HashSet (java.util.HashSet)10 Map (java.util.Map)10 Lists (com.google.common.collect.Lists)8 IOException (java.io.IOException)8 ArrayList (java.util.ArrayList)8