Search in sources :

Example 1 with Publisher

use of com.tangosol.net.topic.Publisher in project coherence-spring by coherence-community.

the class CoherenceTopicListenerTest method shouldReceiveMessagesForMultipleSubscribersInSameGroup.

@Test
void shouldReceiveMessagesForMultipleSubscribersInSameGroup() {
    AtomicInteger count = new AtomicInteger();
    try (Publisher<String> publisher = getPublisher("Nineteen", Publisher.OrderByValue.value((v) -> count.getAndIncrement()))) {
        for (int i = 0; i < publisher.getChannelCount() * 2; i++) {
            publisher.publish("message-" + i);
        }
        int expected = count.get();
        Eventually.assertDeferred(() -> this.listenerFive.received(), is(expected));
        TreeSet<String> set = new TreeSet<>(this.listenerFive.listOne);
        set.addAll(this.listenerFive.listTwo);
        assertThat(set.size(), is(expected));
    }
}
Also used : DirtiesContext(org.springframework.test.annotation.DirtiesContext) CoreMatchers.is(org.hamcrest.CoreMatchers.is) Assertions.fail(org.junit.jupiter.api.Assertions.fail) Coherence(com.tangosol.net.Coherence) BeforeEach(org.junit.jupiter.api.BeforeEach) EnableCoherence(com.oracle.coherence.spring.configuration.annotation.EnableCoherence) CacheService(com.tangosol.net.CacheService) NamedTopic(com.tangosol.net.topic.NamedTopic) Publisher(com.tangosol.net.topic.Publisher) SubscriberGroup(com.oracle.coherence.spring.annotation.SubscriberGroup) IsIterableContainingInAnyOrder.containsInAnyOrder(org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder) CoreMatchers.not(org.hamcrest.CoreMatchers.not) Autowired(org.springframework.beans.factory.annotation.Autowired) CompletableFuture(java.util.concurrent.CompletableFuture) Singleton(javax.inject.Singleton) PropertyExtractor(com.oracle.coherence.spring.annotation.PropertyExtractor) TreeSet(java.util.TreeSet) Topic(com.oracle.coherence.spring.annotation.Topic) ArrayList(java.util.ArrayList) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) Inject(javax.inject.Inject) SpringJUnitConfig(org.springframework.test.context.junit.jupiter.SpringJUnitConfig) SendTo(org.springframework.messaging.handler.annotation.SendTo) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Subscriber(com.tangosol.net.topic.Subscriber) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) SubscriberGroupId(com.tangosol.internal.net.topic.impl.paged.model.SubscriberGroupId) Person(data.Person) EnableCaching(org.springframework.cache.annotation.EnableCaching) CoherenceTopicListener(com.oracle.coherence.spring.annotation.CoherenceTopicListener) WhereFilter(com.oracle.coherence.spring.annotation.WhereFilter) Mono(reactor.core.publisher.Mono) CommitStrategy(com.oracle.coherence.spring.annotation.CommitStrategy) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Configuration(org.springframework.context.annotation.Configuration) CountDownLatch(java.util.concurrent.CountDownLatch) Flux(reactor.core.publisher.Flux) List(java.util.List) PagedTopicCaches(com.tangosol.internal.net.topic.impl.paged.PagedTopicCaches) LocalDate(java.time.LocalDate) Bean(org.springframework.context.annotation.Bean) Eventually(com.oracle.bedrock.testsupport.deferred.Eventually) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TreeSet(java.util.TreeSet) Test(org.junit.jupiter.api.Test)

Example 2 with Publisher

use of com.tangosol.net.topic.Publisher in project coherence-spring by coherence-community.

the class CoherenceTopicListenerSubscribers method createSubscribers.

@SuppressWarnings({ "rawtypes", "unchecked" })
public void createSubscribers(Coherence coherence) {
    final Map<String, List<Method>> candidates = this.candidates.getCoherenceTopicListenerCandidateMethods();
    for (Map.Entry<String, List<Method>> entry : candidates.entrySet()) {
        final String beanName = entry.getKey();
        final List<Method> methods = entry.getValue();
        for (Method method : methods) {
            final Class<?> argumentClassType = method.getParameters()[0].getType();
            if (logger.isDebugEnabled()) {
                logger.debug(String.format("Handling Coherence %s - Bean: %s, method: %s", argumentClassType.getName(), beanName, method.getName()));
            }
            String topicName = Utils.getFirstTopicName(method).orElse(method.getName());
            SessionName sessionNameAnn = AnnotatedElementUtils.findMergedAnnotation(method, SessionName.class);
            String sessionName = (sessionNameAnn != null) ? sessionNameAnn.value() : Coherence.DEFAULT_NAME;
            if (!coherence.hasSession(sessionName)) {
                if (logger.isInfoEnabled()) {
                    logger.info(String.format("Skipping @CoherenceTopicListener annotated method subscription %s Session %s does not exist on Coherence instance %s", method, sessionName, coherence.getName()));
                }
                continue;
            }
            Session session = coherence.getSession(sessionName);
            Publisher[] sendToPublishers;
            String[] sendToTopics = getSendToTopicNames(method);
            if (sendToTopics.length > 0) {
                if (method.getReturnType().equals(Void.class)) {
                    if (logger.isInfoEnabled()) {
                        logger.info(String.format("Skipping @SendTo annotations for @CoherenceTopicListener annotated method %s - method return type is void", method));
                    }
                    sendToPublishers = new Publisher[0];
                } else {
                    sendToPublishers = new Publisher[sendToTopics.length];
                    for (int i = 0; i < sendToTopics.length; i++) {
                        NamedTopic<?> topic = session.getTopic(sendToTopics[i]);
                        sendToPublishers[i] = topic.createPublisher();
                    }
                }
            } else {
                sendToPublishers = new Publisher[0];
            }
            List<Subscriber.Option> options = new ArrayList<>();
            MergedAnnotation<SubscriberGroup> subscriberGroupAnn = MergedAnnotations.from(method).get(SubscriberGroup.class);
            subscriberGroupAnn.getValue("value", String.class).ifPresent((name) -> options.add(Subscriber.Name.of(name)));
            Set<Annotation> filterAnnotations = MergedAnnotations.from(method).stream().filter((mergedAnnotation) -> mergedAnnotation.getType().isAnnotationPresent(FilterBinding.class)).map(MergedAnnotation::synthesize).collect(Collectors.toSet());
            if (!filterAnnotations.isEmpty()) {
                Filter filter = this.filterService.resolve(filterAnnotations);
                if (filter != null) {
                    options.add(Subscriber.Filtered.by(filter));
                }
            }
            Set<Annotation> extractorAnnotations = MergedAnnotations.from(method).stream().filter((mergedAnnotation) -> mergedAnnotation.getType().isAnnotationPresent(ExtractorBinding.class)).map(MergedAnnotation::synthesize).collect(Collectors.toSet());
            if (!extractorAnnotations.isEmpty()) {
                ValueExtractor extractor = this.extractorService.resolve(extractorAnnotations);
                if (extractor != null) {
                    options.add(Subscriber.Convert.using(extractor));
                }
            }
            NamedTopic<?> topic = session.getTopic(topicName);
            Subscriber<?> subscriber = topic.createSubscriber(options.toArray(new Subscriber.Option[0]));
            Object bean = this.applicationContext.getBean(beanName);
            TopicSubscriber<?, ?, ?> topicSubscriber = new TopicSubscriber<>(topicName, subscriber, sendToPublishers, bean, method, this.scheduler);
            this.subscribers.add(topicSubscriber);
            topicSubscriber.nextMessage();
        }
    }
    this.subscribed = true;
}
Also used : ArrayList(java.util.ArrayList) SubscriberGroup(com.oracle.coherence.spring.annotation.SubscriberGroup) List(java.util.List) ArrayList(java.util.ArrayList) ExtractorBinding(com.oracle.coherence.spring.annotation.ExtractorBinding) Method(java.lang.reflect.Method) Publisher(com.tangosol.net.topic.Publisher) ValueExtractor(com.tangosol.util.ValueExtractor) SessionName(com.oracle.coherence.spring.annotation.SessionName) Annotation(java.lang.annotation.Annotation) MergedAnnotation(org.springframework.core.annotation.MergedAnnotation) FilterBinding(com.oracle.coherence.spring.annotation.FilterBinding) Filter(com.tangosol.util.Filter) Map(java.util.Map) Session(com.tangosol.net.Session)

Example 3 with Publisher

use of com.tangosol.net.topic.Publisher in project micronaut-coherence by micronaut-projects.

the class CoherenceTopicListenerTest method shouldReceiveElementBinderArguments.

@Test
public void shouldReceiveElementBinderArguments() throws Exception {
    int channel = 1;
    try (Publisher<String> publisher = getPublisher("Eighteen", Publisher.OrderBy.id(channel))) {
        String message = "ABC";
        Publisher.Status status = publisher.publish(message).get(1, TimeUnit.MINUTES);
        listenerFour.latch.await(1, TimeUnit.MINUTES);
        assertThat(listenerFour.lastElementOne, is(notNullValue()));
        assertThat(listenerFour.lastElementOne.getChannel(), is(status.getChannel()));
        assertThat(listenerFour.lastElementOne.getPosition(), is(status.getPosition()));
        assertThat(listenerFour.lastElementOne.getValue(), is(message));
        assertThat(listenerFour.lastElementTwo, is(notNullValue()));
        assertThat(listenerFour.lastElementTwo.getChannel(), is(status.getChannel()));
        assertThat(listenerFour.lastElementTwo.getPosition(), is(status.getPosition()));
        assertThat(listenerFour.lastElementTwo.getValue(), is(message));
        assertThat(listenerFour.lastSubscriberTwo, is(notNullValue()));
        assertThat(listenerFour.lastValueThree, is(message));
        assertThat(listenerFour.lastChannelFour, is(status.getChannel()));
        assertThat(listenerFour.lastValueFour, is(message));
        assertThat(listenerFour.lastPositionFive, is(status.getPosition()));
        assertThat(listenerFour.lastValueFive, is(message));
        assertThat(listenerFour.lastBinary, is(notNullValue()));
        Serializer serializer = publisher.getNamedTopic().getService().getSerializer();
        assertThat(ExternalizableHelper.fromBinary(listenerFour.lastBinary, serializer), is(message));
    }
}
Also used : Publisher(com.tangosol.net.topic.Publisher) Serializer(com.tangosol.io.Serializer) MicronautTest(io.micronaut.test.extensions.junit5.annotation.MicronautTest) Test(org.junit.jupiter.api.Test)

Example 4 with Publisher

use of com.tangosol.net.topic.Publisher in project micronaut-coherence by micronaut-projects.

the class CoherenceTopicListenerTest method shouldReceiveMessagesForMultipleSubscribersInSameGroup.

@Test
public void shouldReceiveMessagesForMultipleSubscribersInSameGroup() {
    AtomicInteger count = new AtomicInteger();
    try (Publisher<String> publisher = getPublisher("Nineteen", Publisher.OrderByValue.value(v -> count.getAndIncrement()))) {
        for (int i = 0; i < publisher.getChannelCount() * 2; i++) {
            publisher.publish("message-" + i);
        }
        int expected = count.get();
        Eventually.assertDeferred(() -> listenerFive.received(), is(expected));
        TreeSet<String> set = new TreeSet<>(listenerFive.listOne);
        set.addAll(listenerFive.listTwo);
        assertThat(set.size(), is(expected));
    }
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) Coherence(com.tangosol.net.Coherence) BeforeEach(org.junit.jupiter.api.BeforeEach) java.util(java.util) CacheService(com.tangosol.net.CacheService) NamedTopic(com.tangosol.net.topic.NamedTopic) Publisher(com.tangosol.net.topic.Publisher) IsIterableContainingInAnyOrder.containsInAnyOrder(org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder) CoreMatchers.not(org.hamcrest.CoreMatchers.not) CompletableFuture(java.util.concurrent.CompletableFuture) io.micronaut.coherence.annotation(io.micronaut.coherence.annotation) Singleton(javax.inject.Singleton) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) Inject(javax.inject.Inject) TestInstance(org.junit.jupiter.api.TestInstance) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Subscriber(com.tangosol.net.topic.Subscriber) Requires(io.micronaut.context.annotation.Requires) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) SubscriberGroupId(com.tangosol.internal.net.topic.impl.paged.model.SubscriberGroupId) Person(data.Person) MicronautTest(io.micronaut.test.extensions.junit5.annotation.MicronautTest) Binary(com.tangosol.util.Binary) Mono(reactor.core.publisher.Mono) SendTo(io.micronaut.messaging.annotation.SendTo) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) Flux(reactor.core.publisher.Flux) ExternalizableHelper(com.tangosol.util.ExternalizableHelper) PagedTopicCaches(com.tangosol.internal.net.topic.impl.paged.PagedTopicCaches) Position(com.tangosol.net.topic.Position) LocalDate(java.time.LocalDate) Serializer(com.tangosol.io.Serializer) PagedTopicSubscriber(com.tangosol.internal.net.topic.impl.paged.PagedTopicSubscriber) Eventually(com.oracle.bedrock.testsupport.deferred.Eventually) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MicronautTest(io.micronaut.test.extensions.junit5.annotation.MicronautTest) Test(org.junit.jupiter.api.Test)

Example 5 with Publisher

use of com.tangosol.net.topic.Publisher in project micronaut-coherence by micronaut-projects.

the class CoherenceTopicListenerProcessor method createSubscribers.

@SuppressWarnings({ "unchecked", "rawtypes" })
void createSubscribers(Coherence coherence) {
    for (MethodHolder holder : methods) {
        List<Subscriber.Option> options = new ArrayList<>();
        ExecutableMethod<?, ?> method = holder.getMethod();
        String topicName = Utils.getFirstTopicName(method).orElse(method.getMethodName());
        String sessionName = method.stringValue(SessionName.class).orElse(Coherence.DEFAULT_NAME);
        if (!coherence.hasSession(sessionName)) {
            LOG.info("Skipping @CoherenceTopicListener annotated method subscription {} Session {} does not exist on Coherence instance {}", method, sessionName, coherence.getName());
            return;
        }
        Session session = coherence.getSession(sessionName);
        Publisher[] sendToPublishers;
        String[] sendToTopics = Utils.getSendToTopicNames(method);
        if (sendToTopics.length > 0) {
            if (method.getReturnType().isVoid()) {
                LOG.info("Skipping @SendTo annotations for @CoherenceTopicListener annotated method {} - method return type is void", method);
                sendToPublishers = new Publisher[0];
            } else {
                sendToPublishers = new Publisher[sendToTopics.length];
                for (int i = 0; i < sendToTopics.length; i++) {
                    NamedTopic<?> topic = session.getTopic(sendToTopics[i]);
                    sendToPublishers[i] = topic.createPublisher();
                }
            }
        } else {
            sendToPublishers = new Publisher[0];
        }
        method.stringValue(SubscriberGroup.class).ifPresent(name -> options.add(Subscriber.Name.of(name)));
        List<String> filterBindings = method.getAnnotationNamesByStereotype(FilterBinding.class);
        if (!filterBindings.isEmpty()) {
            Set<Annotation> annotations = filterBindings.stream().map(s -> method.getAnnotationType(s).orElse(null)).filter(Objects::nonNull).map(method::synthesize).collect(Collectors.toSet());
            Filter filter = filterFactories.resolve(annotations);
            if (filter != null) {
                options.add(Subscriber.Filtered.by(filter));
            }
        }
        List<String> extractorBindings = method.getAnnotationNamesByStereotype(ExtractorBinding.class);
        if (!extractorBindings.isEmpty()) {
            Set<Annotation> annotations = extractorBindings.stream().map(s -> method.getAnnotationType(s).orElse(null)).filter(Objects::nonNull).map(method::synthesize).collect(Collectors.toSet());
            ValueExtractor extractor = extractorFactories.resolve(annotations);
            if (extractor != null) {
                options.add(Subscriber.Convert.using(extractor));
            }
        }
        BeanDefinition<?> beanDefinition = holder.getBeanDefinition();
        Class<?> clsBeanType = beanDefinition.getBeanType();
        Object bean = context.getBean(clsBeanType);
        NamedTopic<?> topic = session.getTopic(topicName);
        Subscriber<?> subscriber = topic.createSubscriber(options.toArray(options.toArray(new Subscriber.Option[0])));
        TopicSubscriber<?, ?, ?> topicSubscriber = new TopicSubscriber(topicName, subscriber, sendToPublishers, bean, method, registry, scheduler);
        subscribers.add(topicSubscriber);
        topicSubscriber.nextMessage();
    }
    subscribed = true;
}
Also used : Filter(com.tangosol.util.Filter) Coherence(com.tangosol.net.Coherence) java.util(java.util) Publishers(io.micronaut.core.async.publisher.Publishers) NamedTopic(com.tangosol.net.topic.NamedTopic) Publisher(com.tangosol.net.topic.Publisher) FluxSink(reactor.core.publisher.FluxSink) ArrayUtils(io.micronaut.core.util.ArrayUtils) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) ElementArgumentBinderRegistry(io.micronaut.coherence.messaging.binders.ElementArgumentBinderRegistry) io.micronaut.coherence.annotation(io.micronaut.coherence.annotation) Session(com.tangosol.net.Session) Singleton(javax.inject.Singleton) Scheduler(reactor.core.scheduler.Scheduler) Function(java.util.function.Function) ExecutableMethod(io.micronaut.inject.ExecutableMethod) Inject(javax.inject.Inject) PreDestroy(javax.annotation.PreDestroy) ValueExtractor(com.tangosol.util.ValueExtractor) TaskExecutors(io.micronaut.scheduling.TaskExecutors) ApplicationContext(io.micronaut.context.ApplicationContext) ExecutableBinder(io.micronaut.core.bind.ExecutableBinder) Subscriber(com.tangosol.net.topic.Subscriber) Schedulers(reactor.core.scheduler.Schedulers) Named(javax.inject.Named) Argument(io.micronaut.core.type.Argument) BoundExecutable(io.micronaut.core.bind.BoundExecutable) FilterFactories(io.micronaut.coherence.FilterFactories) ExecutorService(java.util.concurrent.ExecutorService) DefaultExecutableBinder(io.micronaut.core.bind.DefaultExecutableBinder) Blocking(io.micronaut.core.annotation.Blocking) Logger(org.slf4j.Logger) CancellationException(java.util.concurrent.CancellationException) Collectors(java.util.stream.Collectors) ExecutableMethodProcessor(io.micronaut.context.processor.ExecutableMethodProcessor) CoherenceLifecycleEvent(com.tangosol.net.events.CoherenceLifecycleEvent) Flux(reactor.core.publisher.Flux) CompletionStage(java.util.concurrent.CompletionStage) Annotation(java.lang.annotation.Annotation) BeanDefinition(io.micronaut.inject.BeanDefinition) ExtractorFactories(io.micronaut.coherence.ExtractorFactories) CoherenceSubscriberException(io.micronaut.coherence.messaging.exceptions.CoherenceSubscriberException) Subscriber(com.tangosol.net.topic.Subscriber) Publisher(com.tangosol.net.topic.Publisher) ValueExtractor(com.tangosol.util.ValueExtractor) Annotation(java.lang.annotation.Annotation) Filter(com.tangosol.util.Filter) Session(com.tangosol.net.Session)

Aggregations

Publisher (com.tangosol.net.topic.Publisher)5 Coherence (com.tangosol.net.Coherence)3 NamedTopic (com.tangosol.net.topic.NamedTopic)3 Subscriber (com.tangosol.net.topic.Subscriber)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 Inject (javax.inject.Inject)3 Singleton (javax.inject.Singleton)3 Test (org.junit.jupiter.api.Test)3 Eventually (com.oracle.bedrock.testsupport.deferred.Eventually)2 SubscriberGroup (com.oracle.coherence.spring.annotation.SubscriberGroup)2 PagedTopicCaches (com.tangosol.internal.net.topic.impl.paged.PagedTopicCaches)2 SubscriberGroupId (com.tangosol.internal.net.topic.impl.paged.model.SubscriberGroupId)2 Serializer (com.tangosol.io.Serializer)2 CacheService (com.tangosol.net.CacheService)2 Session (com.tangosol.net.Session)2 Filter (com.tangosol.util.Filter)2 ValueExtractor (com.tangosol.util.ValueExtractor)2 Person (data.Person)2 io.micronaut.coherence.annotation (io.micronaut.coherence.annotation)2 MicronautTest (io.micronaut.test.extensions.junit5.annotation.MicronautTest)2