Search in sources :

Example 21 with Session

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

the class NamedCacheConfiguration method getCacheInternal.

/**
 * Create a {@link NamedCache} instance.
 * <p>
 * If the injection point has a type of {@link ContinuousQueryCache} or is qualified with the {@link View}
 * annotation then a {@link ContinuousQueryCache} instance will be returned otherwise a {@link NamedCache} will be
 * returned.
 * @param injectionPoint the {@link InjectionPoint} that the {@link NamedCache} will be retrieved from
 * @param isCQC a flag specifying whether to return a {@link ContinuousQueryCache}
 * @param <K> the type of the cache keys
 * @param <V> the type of the cache values
 * @return a {@link NamedCache} instance to inject into the injection point
 */
private <K, V> NamedCache<K, V> getCacheInternal(InjectionPoint injectionPoint, boolean isCQC) {
    final MergedAnnotations mergedAnnotations;
    if (injectionPoint.getMethodParameter() != null) {
        mergedAnnotations = MergedAnnotations.from(injectionPoint.getMethodParameter().getParameterAnnotations());
    } else {
        mergedAnnotations = MergedAnnotations.from(injectionPoint.getAnnotatedElement());
    }
    final MergedAnnotation<Name> mergedNameAnnotation = mergedAnnotations.get(Name.class);
    final MergedAnnotation<SessionName> mergedSessionNameAnnotation = mergedAnnotations.get(SessionName.class);
    final MergedAnnotation<View> mergedViewAnnotation = mergedAnnotations.get(View.class);
    final String sessionName;
    final String cacheName = this.determineCacheName(injectionPoint, mergedNameAnnotation);
    if (!mergedSessionNameAnnotation.isPresent() || mergedSessionNameAnnotation.synthesize().value().trim().isEmpty()) {
        sessionName = Coherence.DEFAULT_NAME;
    } else {
        sessionName = mergedSessionNameAnnotation.synthesize().value();
    }
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Going to retrieve NamedCache '%s' for session '%s'.", cacheName, sessionName));
    }
    if (cacheName == null || cacheName.trim().isEmpty()) {
        throw new IllegalArgumentException("Cannot determine cache/map name. No @Name qualifier and injection point is not named");
    }
    final Session session = Coherence.findSession(sessionName).orElseThrow(() -> new IllegalStateException(String.format("No Session is configured with name '%s'.", sessionName)));
    final NamedCache<K, V> cache = session.getCache(cacheName);
    if (isCQC || mergedViewAnnotation.isPresent()) {
        boolean hasValues = (!mergedViewAnnotation.isPresent()) || mergedViewAnnotation.synthesize().cacheValues();
        final Filter filter = this.filterService.getFilter(injectionPoint);
        final ValueExtractor extractor = this.extractorService.getExtractor(injectionPoint, true);
        return new ContinuousQueryCache<>(cache, filter, hasValues, null, extractor);
    }
    return cache;
}
Also used : ValueExtractor(com.tangosol.util.ValueExtractor) View(com.oracle.coherence.spring.annotation.View) SessionName(com.oracle.coherence.spring.annotation.SessionName) Name(com.oracle.coherence.spring.annotation.Name) SessionName(com.oracle.coherence.spring.annotation.SessionName) Filter(com.tangosol.util.Filter) ContinuousQueryCache(com.tangosol.net.cache.ContinuousQueryCache) MergedAnnotations(org.springframework.core.annotation.MergedAnnotations) Session(com.tangosol.net.Session)

Example 22 with Session

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

the class NamedTopicConfiguration method getTopicInternal.

private <V> NamedTopic<V> getTopicInternal(InjectionPoint injectionPoint) {
    final MergedAnnotations mergedAnnotations = MergedAnnotations.from(injectionPoint.getAnnotatedElement());
    final MergedAnnotation<SessionName> mergedSessionNameAnnotation = mergedAnnotations.get(SessionName.class);
    final MergedAnnotation<Name> mergedNameAnnotation = mergedAnnotations.get(Name.class);
    final String sessionName;
    final String topicName = this.determineTopicName(injectionPoint, mergedNameAnnotation);
    if (!mergedSessionNameAnnotation.isPresent() || mergedSessionNameAnnotation.synthesize().value().trim().isEmpty()) {
        sessionName = Coherence.DEFAULT_NAME;
    } else {
        sessionName = mergedSessionNameAnnotation.synthesize().value();
    }
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Going to retrieve NamedTopic '%s' for session '%s'.", topicName, sessionName));
    }
    if (topicName == null || topicName.trim().isEmpty()) {
        throw new IllegalArgumentException("Cannot determine topic name. No @Name qualifier and injection point is not named");
    }
    final Session session = Coherence.findSession(sessionName).orElseThrow(() -> new IllegalStateException(String.format("No Session is configured with name '%s'.", sessionName)));
    return session.getTopic(topicName);
}
Also used : MergedAnnotations(org.springframework.core.annotation.MergedAnnotations) SessionName(com.oracle.coherence.spring.annotation.SessionName) Name(com.oracle.coherence.spring.annotation.Name) SessionName(com.oracle.coherence.spring.annotation.SessionName) Session(com.tangosol.net.Session)

Example 23 with Session

use of com.tangosol.net.Session 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 24 with Session

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

the class CoherenceEventListenerProcessor method registerMapListeners.

/**
 * Listen for {@link com.tangosol.net.events.partition.cache.CacheLifecycleEvent.Type#CREATED Created}
 * {@link com.tangosol.net.events.partition.cache.CacheLifecycleEvent CacheLifecycleEvents}
 * and register relevant map listeners when caches are created.
 *
 * @param event the {@link com.tangosol.net.events.partition.cache.CacheLifecycleEvent}
 */
@CoherenceEventListener
@SuppressWarnings({ "rawtypes", "unchecked" })
void registerMapListeners(@Created CacheLifecycleEvent event) {
    String cacheName = event.getCacheName();
    String eventScope = event.getScopeName();
    String eventSession = event.getSessionName();
    String eventService = event.getServiceName();
    Set<AnnotatedMapListener<?, ?>> setListeners = getMapListeners(removeScope(eventService), cacheName);
    Session session = Coherence.findSession(eventSession).orElseThrow(() -> new IllegalStateException("Cannot find a Session with name " + eventSession));
    NamedCache cache = session.getCache(cacheName);
    for (AnnotatedMapListener<?, ?> listener : setListeners) {
        if (listener.hasFilterAnnotation()) {
            // ensure that the listener's filter has been resolved as this
            // was not possible as discovery time.
            listener.resolveFilter(filterProducer);
        }
        if (listener.hasTransformerAnnotation()) {
            // ensure that the listener's transformer has been resolved as this
            // was not possible as discovery time.
            listener.resolveTransformer(transformerProducer);
        }
        String sScope = listener.getScopeName();
        boolean fScopeOK = sScope == null || sScope.equals(eventScope);
        String sSession = listener.getSessionName();
        boolean fSessionOK = sSession == null || sSession.equals(eventSession);
        if (fScopeOK && fSessionOK) {
            Filter filter = listener.getFilter();
            if (filter != null && !(filter instanceof MapEventFilter)) {
                filter = new MapEventFilter(MapEventFilter.E_ALL, filter);
            }
            MapEventTransformer transformer = listener.getTransformer();
            if (transformer != null) {
                filter = new MapEventTransformerFilter(filter, transformer);
            }
            try {
                boolean fLite = listener.isLite();
                if (listener.isSynchronous()) {
                    cache.addMapListener(listener.synchronous(), filter, fLite);
                } else {
                    cache.addMapListener(listener, filter, fLite);
                }
            } catch (Exception e) {
                throw Exceptions.ensureRuntimeException(e);
            }
        }
    }
}
Also used : MapEventFilter(com.tangosol.util.filter.MapEventFilter) MapEventTransformer(com.tangosol.util.MapEventTransformer) MapEventTransformerFilter(com.tangosol.util.filter.MapEventTransformerFilter) NamedCache(com.tangosol.net.NamedCache) Filter(com.tangosol.util.Filter) MapEventFilter(com.tangosol.util.filter.MapEventFilter) MapEventTransformerFilter(com.tangosol.util.filter.MapEventTransformerFilter) Session(com.tangosol.net.Session) CoherenceEventListener(io.micronaut.coherence.annotation.CoherenceEventListener)

Example 25 with Session

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

the class NamedTopicFactories method getTopicInternal.

private <V> NamedTopic<V> getTopicInternal(InjectionPoint<?> injectionPoint) {
    AnnotationMetadata metadata = injectionPoint.getAnnotationMetadata();
    String sessionName = metadata.getValue(SessionName.class, String.class).orElse(Coherence.DEFAULT_NAME);
    String name = metadata.getValue(Name.class, String.class).orElse(getName(injectionPoint));
    if (name == null || name.trim().isEmpty()) {
        throw new IllegalArgumentException("Cannot determine topic name. No @Name qualifier and injection point is not named");
    }
    try {
        Session session = beanContext.createBean(Session.class, sessionName);
        return session.getTopic(name);
    } catch (Exception e) {
        LOG.error("Error getting NamedTopic " + name + " from session " + sessionName, e);
        throw new IllegalStateException("Failed getting NamedTopic " + name + " from session " + sessionName);
    }
}
Also used : AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) Session(com.tangosol.net.Session)

Aggregations

Session (com.tangosol.net.Session)28 Test (org.junit.jupiter.api.Test)14 GrpcSessionConfiguration (com.oracle.coherence.client.GrpcSessionConfiguration)5 Coherence (com.tangosol.net.Coherence)5 Filter (com.tangosol.util.Filter)5 LocalPlatform (com.oracle.bedrock.runtime.LocalPlatform)4 Platform (com.oracle.bedrock.runtime.Platform)4 GetClusterSize (com.oracle.bedrock.runtime.coherence.callables.GetClusterSize)4 GetLocalMemberId (com.oracle.bedrock.runtime.coherence.callables.GetLocalMemberId)4 AbstractTest (com.oracle.bedrock.testsupport.junit.AbstractTest)4 MicronautTest (io.micronaut.test.extensions.junit5.annotation.MicronautTest)4 SessionName (com.oracle.coherence.spring.annotation.SessionName)3 NamedCache (com.tangosol.net.NamedCache)3 ValueExtractor (com.tangosol.util.ValueExtractor)3 Channel (io.grpc.Channel)3 Name (com.oracle.coherence.spring.annotation.Name)2 NamedMap (com.tangosol.net.NamedMap)2 Publisher (com.tangosol.net.topic.Publisher)2 MapEventTransformer (com.tangosol.util.MapEventTransformer)2 MapEventFilter (com.tangosol.util.filter.MapEventFilter)2