repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/filter/CacheEventConverter.java
package org.infinispan.notifications.cachelistener.filter; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.util.Experimental; import org.infinispan.metadata.Metadata; /** * A converter that can be used to convert the value given for an event. This converter allows for converting based * on the previous value as well as the new updated value. The old value and old metadata are the previous values and * the new value and new metadata are the new values even for pre and post events. * @author wburns * @since 7.0 */ public interface CacheEventConverter<K, V, C> { /** * Converts the given newValue into something different possibly. * @param key The key for the entry that was changed for the event * @param oldValue The previous value before the event takes place * @param oldMetadata The old value before the event takes place * @param newValue The new value for the entry after the event takes place * @param newMetadata The new metadata for the entry after the event takes place * @param eventType The type of event that is being raised * @return The converted value to be used in the event */ C convert(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType); default MediaType format() { return MediaType.APPLICATION_OBJECT; } /** * @return if true, {@link #convert(Object, Object, Metadata, Object, Metadata, EventType)} will be presented with data * in the request format rather than the format specified in {@link #format()}. The request format is defined as the MediaType * that a cache was previously decorated with {@link org.infinispan.AdvancedCache#withMediaType(String, String)}. */ @Experimental default boolean useRequestFormat() { return false; } }
1,848
43.02381
129
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/filter/KeyValueFilterConverterAsCacheEventFilterConverter.java
package org.infinispan.notifications.cachelistener.filter; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.commons.marshall.Ids; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.filter.KeyValueFilterConverter; import org.infinispan.metadata.Metadata; /** * {@link CacheEventFilterConverter} that uses an underlying {@link KeyValueFilterConverter} to do the conversion and * filtering. The new value and metadata are used as arguments to the underlying filter converter as it doesn't take * both new and old. * @author wburns * @since 9.4 */ @Scope(Scopes.NONE) public class KeyValueFilterConverterAsCacheEventFilterConverter<K, V, C> implements CacheEventFilterConverter<K, V, C> { private final KeyValueFilterConverter<K, V, C> keyValueFilterConverter; public KeyValueFilterConverterAsCacheEventFilterConverter(KeyValueFilterConverter<K, V, C> keyValueFilterConverter) { this.keyValueFilterConverter = keyValueFilterConverter; } @Override public C filterAndConvert(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) { return keyValueFilterConverter.convert(key, newValue, newMetadata); } @Override public C convert(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) { return keyValueFilterConverter.convert(key, newValue, newMetadata); } @Override public boolean accept(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) { return keyValueFilterConverter.accept(key, newValue, newMetadata); } @Inject protected void injectDependencies(ComponentRegistry cr) { cr.wireDependencies(keyValueFilterConverter); } public static class Externalizer implements AdvancedExternalizer<KeyValueFilterConverterAsCacheEventFilterConverter> { @Override public void writeObject(ObjectOutput output, KeyValueFilterConverterAsCacheEventFilterConverter object) throws IOException { output.writeObject(object.keyValueFilterConverter); } @Override public KeyValueFilterConverterAsCacheEventFilterConverter readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new KeyValueFilterConverterAsCacheEventFilterConverter((KeyValueFilterConverter)input.readObject()); } @Override public Set<Class<? extends KeyValueFilterConverterAsCacheEventFilterConverter>> getTypeClasses() { return Collections.singleton(KeyValueFilterConverterAsCacheEventFilterConverter.class); } @Override public Integer getId() { return Ids.KEY_VALUE_FILTER_CONVERTER_AS_CACHE_EVENT_FILTER_CONVERTER; } } }
3,062
39.84
138
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/filter/CacheEventConverterAsConverter.java
package org.infinispan.notifications.cachelistener.filter; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.filter.Converter; import org.infinispan.marshall.core.Ids; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.event.Event; /** * Converter that is implemented by using the provided CacheEventConverter. The provided event type will always be * one that is not retried, post and of type CREATE, The old value and old metadata in both pre and post events will * be the data that was in the cache before the event occurs. The new value and new metadata in both pre and post * events will be the data that is in the cache after the event occurs. * * @author wburns * @since 7.0 */ @Scope(Scopes.NONE) public class CacheEventConverterAsConverter<K, V, C> implements Converter<K, V, C> { private static final EventType CREATE_EVENT = new EventType(false, false, Event.Type.CACHE_ENTRY_CREATED); private final CacheEventConverter<K, V, C> converter; public CacheEventConverterAsConverter(CacheEventConverter<K, V, C> converter) { this.converter = converter; } @Override public C convert(K key, V value, Metadata metadata) { return converter.convert(key, null, null, value, metadata, CREATE_EVENT); } @Inject protected void injectDependencies(ComponentRegistry cr) { cr.wireDependencies(converter); } public static class Externalizer extends AbstractExternalizer<CacheEventConverterAsConverter> { @Override public Set<Class<? extends CacheEventConverterAsConverter>> getTypeClasses() { return Collections.singleton(CacheEventConverterAsConverter.class); } @Override public void writeObject(ObjectOutput output, CacheEventConverterAsConverter object) throws IOException { output.writeObject(object.converter); } @Override public CacheEventConverterAsConverter readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new CacheEventConverterAsConverter((CacheEventConverter)input.readObject()); } @Override public Integer getId() { return Ids.CACHE_EVENT_CONVERTER_AS_CONVERTER; } } }
2,598
36.128571
118
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/filter/CacheEventFilterConverterAsKeyValueFilterConverter.java
package org.infinispan.notifications.cachelistener.filter; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.filter.AbstractKeyValueFilterConverter; import org.infinispan.marshall.core.Ids; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.event.Event; /** * @author anistor@redhat.com * @since 7.2 */ @Scope(Scopes.NONE) public class CacheEventFilterConverterAsKeyValueFilterConverter<K, V, C> extends AbstractKeyValueFilterConverter<K, V, C> { private static final EventType CREATE_EVENT = new EventType(false, false, Event.Type.CACHE_ENTRY_CREATED); private final CacheEventFilterConverter<K, V, C> cacheEventFilterConverter; public CacheEventFilterConverterAsKeyValueFilterConverter(CacheEventFilterConverter<K, V, C> cacheEventFilterConverter) { this.cacheEventFilterConverter = cacheEventFilterConverter; } @Override public C filterAndConvert(K key, V value, Metadata metadata) { return cacheEventFilterConverter.filterAndConvert(key, null, null, value, metadata, CREATE_EVENT); } @Inject protected void injectDependencies(ComponentRegistry cr) { cr.wireDependencies(cacheEventFilterConverter); } public static class Externalizer extends AbstractExternalizer<CacheEventFilterConverterAsKeyValueFilterConverter> { @Override public Set<Class<? extends CacheEventFilterConverterAsKeyValueFilterConverter>> getTypeClasses() { return Collections.singleton(CacheEventFilterConverterAsKeyValueFilterConverter.class); } @Override public void writeObject(ObjectOutput output, CacheEventFilterConverterAsKeyValueFilterConverter object) throws IOException { output.writeObject(object.cacheEventFilterConverter); } @Override public CacheEventFilterConverterAsKeyValueFilterConverter readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new CacheEventFilterConverterAsKeyValueFilterConverter((CacheEventFilterConverter) input.readObject()); } @Override public Integer getId() { return Ids.CACHE_EVENT_FILTER_CONVERTER_AS_KEY_VALUE_FILTER_CONVERTER; } } }
2,562
37.253731
138
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/filter/CacheEventFilterAsKeyValueFilter.java
package org.infinispan.notifications.cachelistener.filter; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.filter.KeyValueFilter; import org.infinispan.marshall.core.Ids; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.event.Event; /** * KeyValueFilter that is implemented by using the provided CacheEventFilter. The provided event type will always be * one that is not retried, post and of type CREATE, The old value and old metadata in both pre and post events will * be the data that was in the cache before the event occurs. The new value and new metadata in both pre and post * events will be the data that is in the cache after the event occurs. * * @author wburns * @since 7.0 */ @Scope(Scopes.NONE) public class CacheEventFilterAsKeyValueFilter<K, V> implements KeyValueFilter<K, V> { private static final EventType CREATE_EVENT = new EventType(false, false, Event.Type.CACHE_ENTRY_CREATED); private final CacheEventFilter<K, V> filter; public CacheEventFilterAsKeyValueFilter(CacheEventFilter<K, V> filter) { this.filter = filter; } @Override public boolean accept(K key, V value, Metadata metadata) { return filter.accept(key, null, null, value, metadata, CREATE_EVENT); } @Inject protected void injectDependencies(ComponentRegistry cr) { cr.wireDependencies(filter); } public static class Externalizer extends AbstractExternalizer<CacheEventFilterAsKeyValueFilter> { @Override public Set<Class<? extends CacheEventFilterAsKeyValueFilter>> getTypeClasses() { return Collections.singleton(CacheEventFilterAsKeyValueFilter.class); } @Override public void writeObject(ObjectOutput output, CacheEventFilterAsKeyValueFilter object) throws IOException { output.writeObject(object.filter); } @Override public CacheEventFilterAsKeyValueFilter readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new CacheEventFilterAsKeyValueFilter((CacheEventFilter)input.readObject()); } @Override public Integer getId() { return Ids.CACHE_EVENT_FILTER_AS_KEY_VALUE_FILTER; } } }
2,592
36.042857
120
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/filter/AbstractCacheEventFilterConverter.java
package org.infinispan.notifications.cachelistener.filter; import org.infinispan.metadata.Metadata; /** * This is a base class that should be used when implementing a CacheEventFilterConverter that provides default * implementations for the {@link org.infinispan.notifications.cachelistener.filter.CacheEventFilter#accept(Object, Object, org.infinispan.metadata.Metadata, Object, org.infinispan.metadata.Metadata, EventType)} * and {@link org.infinispan.filter.Converter#convert(Object, Object, org.infinispan.metadata.Metadata)} methods so they just call the * {@link org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverter#filterAndConvert(Object, Object, org.infinispan.metadata.Metadata, Object, org.infinispan.metadata.Metadata, EventType)} * method and then do the right thing. * * @author wburns * @since 7.0 */ public abstract class AbstractCacheEventFilterConverter<K, V, C> implements CacheEventFilterConverter<K, V, C> { @Override public final C convert(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) { return filterAndConvert(key, oldValue, oldMetadata, newValue, newMetadata, eventType); } @Override public final boolean accept(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) { return filterAndConvert(key, oldValue, oldMetadata, newValue, newMetadata, eventType) != null; } }
1,450
54.807692
211
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/filter/CacheEventFilterConverterFactory.java
package org.infinispan.notifications.cachelistener.filter; /** * Factory that can produce {@link CacheEventFilterConverter} instances. * * @since 7.2 */ public interface CacheEventFilterConverterFactory { /** * Retrieves a cache event filter and converter instance from this factory. * * @param params parameters for the factory to be used to create converter instances * @return a {@link CacheEventFilterConverter} instance used * to filter and reduce size of event payloads */ <K, V, C> CacheEventFilterConverter<K, V, C> getFilterConverter(Object[] params); }
600
29.05
87
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/filter/CacheEventFilterFactory.java
package org.infinispan.notifications.cachelistener.filter; /** * Factory that can produce CacheEventFilters * * @author wburns * @since 7.0 */ public interface CacheEventFilterFactory { /** * Retrieves a cache event filter instance from this factory. * * @param params parameters for the factory to be used to create filter instances * @return a filter instance for keys with their values */ <K, V> CacheEventFilter<K, V> getFilter(Object[] params); }
486
23.35
84
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/filter/KeyValueFilterAsCacheEventFilter.java
package org.infinispan.notifications.cachelistener.filter; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.filter.KeyValueFilter; import org.infinispan.marshall.core.Ids; import org.infinispan.metadata.Metadata; /** * CacheEventFilter that implements it's filtering solely on the use of the provided KeyValueFilter * * @author wburns * @since 7.0 */ @Scope(Scopes.NONE) public class KeyValueFilterAsCacheEventFilter<K, V> implements CacheEventFilter<K, V> { private final KeyValueFilter<? super K, ? super V> filter; public KeyValueFilterAsCacheEventFilter(KeyValueFilter<? super K, ? super V> filter) { this.filter = filter; } @Override public boolean accept(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) { return filter.accept(key, newValue, newMetadata); } @Inject protected void injectDependencies(ComponentRegistry cr) { cr.wireDependencies(filter); } public static class Externalizer extends AbstractExternalizer<KeyValueFilterAsCacheEventFilter> { @Override public Set<Class<? extends KeyValueFilterAsCacheEventFilter>> getTypeClasses() { return Collections.singleton(KeyValueFilterAsCacheEventFilter.class); } @Override public void writeObject(ObjectOutput output, KeyValueFilterAsCacheEventFilter object) throws IOException { output.writeObject(object.filter); } @Override public KeyValueFilterAsCacheEventFilter readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new KeyValueFilterAsCacheEventFilter((KeyValueFilter)input.readObject()); } @Override public Integer getId() { return Ids.KEY_VALUE_FILTER_AS_CACHE_EVENT_FILTER; } } }
2,164
32.828125
122
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/filter/IndexedFilter.java
package org.infinispan.notifications.cachelistener.filter; /** * A marker interface for filters that can be handled efficiently by a {@link FilterIndexingServiceProvider}. Such * filters can still be executed by calling the {@link #filterAndConvert} method but a {@link * FilterIndexingServiceProvider} could take advantage of this specific filter and execute it more efficiently by using * an alternative approach. * * @author anistor@redhat.com * @since 7.2 */ public interface IndexedFilter<K, V, C> extends CacheEventFilterConverter<K, V, C> { }
559
39
119
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/PersistenceAvailabilityChangedEvent.java
package org.infinispan.notifications.cachelistener.event; public interface PersistenceAvailabilityChangedEvent<K, V> extends Event<K, V> { /** * @return true if the {@link org.infinispan.persistence.manager.PersistenceManager} is available. */ boolean isAvailable(); }
284
30.666667
101
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/CacheEntryEvent.java
package org.infinispan.notifications.cachelistener.event; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; /** * A transactional event subtype that additionally expose a key as such events pertain to a specific cache entry. * * @author Manik Surtani * @since 4.0 */ public interface CacheEntryEvent<K, V> extends TransactionalEvent<K, V> { /** * @return the key to the affected cache entry. */ K getKey(); /** * Retrieves the value of the affected cache entry * * @return the value of the cache entry */ V getValue(); /** * Retrieves the metadata associated with the entry. * * @return the metadata of the cache entry * @since 7.0 */ Metadata getMetadata(); /** * @return True if this event is generated from an existing entry as the listener * has {@link Listener#includeCurrentState()} set to <code>true</code>. * @since 9.3 */ default boolean isCurrentState() { return false; } /** * @return an identifier of the transaction or cache invocation that triggered the event. * In a transactional cache, it is the same as {@link #getGlobalTransaction()}. * In a non-transactional cache, it is an internal object that identifies the cache invocation. */ default Object getSource() { return null; } }
1,378
26.039216
113
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/CacheEntryRemovedEvent.java
package org.infinispan.notifications.cachelistener.event; import org.infinispan.metadata.Metadata; /** * This event subtype is passed in to any method annotated with {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved}. * <p /> * The {@link #getValue()} method would return the <i>old</i> value prior to deletion, if <tt>isPre()</tt> is <tt>true</tt>. * If <tt>isPre()</tt> is <tt>false</tt>, {@link #getValue()} will return <tt>null</tt>. * * @author Manik Surtani * @since 4.0 */ public interface CacheEntryRemovedEvent<K, V> extends CacheEntryEvent<K, V> { /** * Retrieves the value of the entry being deleted. * <p /> * @return the value of the entry being deleted, if <tt>isPre()</tt> is <tt>true</tt>. <tt>null</tt> otherwise. */ V getValue(); /** * Regardless of whether <tt>isPre()</tt> is <tt>true</tt> or is * <tt>false</tt>, this method returns the value of the entry being * deleted. This method is useful for situations where cache listeners * need to know what the old value being deleted is when getting * <tt>isPre()</tt> is <tt>false</tt> callbacks. * * @return the value of the entry being deleted, regardless of * <tt>isPre()</tt> value */ V getOldValue(); /** * Regardless of whether <tt>isPre()</tt> is <tt>true</tt> or is * <tt>false</tt>, this method returns the metadata of the entry being * deleted. This method is useful for situations where cache listeners * need to know what the old value being deleted is when getting * <tt>isPre()</tt> is <tt>false</tt> callbacks. * * @return the metadata of the entry being deleted, regardless of * <tt>isPre()</tt> value */ Metadata getOldMetadata(); /** * This will be true if the write command that caused this had to be retried again due to a topology change. This * could be a sign that this event has been duplicated or another event was dropped and replaced * (eg: ModifiedEvent replaced CreateEvent) * @return Whether the command that caused this event was retried */ boolean isCommandRetried(); }
2,147
38.054545
144
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/package-info.java
/** * {@link Cache}-specific listener events * * @api.public */ package org.infinispan.notifications.cachelistener.event;
126
17.142857
57
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/CacheEntryInvalidatedEvent.java
package org.infinispan.notifications.cachelistener.event; /** * Notifies a listener of an invalidation event. * <p> * Eviction has no notion of pre/post event since 4.2.0.ALPHA4. This event is only * raised once after the eviction has occurred with the pre event flag being false. * * @author Manik Surtani * @since 4.0 */ public interface CacheEntryInvalidatedEvent<K, V> extends CacheEntryEvent<K, V> { /** * Retrieves the value of the entry being invalidated. * * @return the value of the invalidated entry */ V getValue(); }
561
27.1
83
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/Event.java
package org.infinispan.notifications.cachelistener.event; import org.infinispan.Cache; /** * An interface that defines common characteristics of events * * @author Manik Surtani * @since 4.0 */ public interface Event<K, V> { enum Type { CACHE_ENTRY_ACTIVATED, CACHE_ENTRY_PASSIVATED, CACHE_ENTRY_VISITED, CACHE_ENTRY_LOADED, CACHE_ENTRY_EVICTED, CACHE_ENTRY_CREATED, CACHE_ENTRY_REMOVED, CACHE_ENTRY_MODIFIED, TRANSACTION_COMPLETED, TRANSACTION_REGISTERED, CACHE_ENTRY_INVALIDATED, CACHE_ENTRY_EXPIRED, DATA_REHASHED, TOPOLOGY_CHANGED, PARTITION_STATUS_CHANGED, PERSISTENCE_AVAILABILITY_CHANGED; private static final Type[] CACHED_VALUES = values(); public static Type valueOf(int ordinal) { return CACHED_VALUES[ordinal]; } } /** * @return the type of event represented by this instance. */ Type getType(); /** * @return <tt>true</tt> if the notification is before the event has occurred, <tt>false</tt> if after the event has occurred. */ boolean isPre(); /** * @return a handle to the cache instance that generated this notification. */ Cache<K, V> getCache(); }
1,177
28.45
129
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/PartitionStatusChangedEvent.java
package org.infinispan.notifications.cachelistener.event; import org.infinispan.partitionhandling.AvailabilityMode; /** * The event passed in to methods annotated with * {@link org.infinispan.notifications.cachelistener.annotation.PartitionStatusChanged}. * * @author William Burns * @since 7.0 */ public interface PartitionStatusChangedEvent<K, V> extends Event<K, V> { /** * The mode the current cluster is in. This determines which operations can be ran in the cluster. * @return the mode */ AvailabilityMode getAvailabilityMode(); }
565
27.3
102
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/CacheEntryActivatedEvent.java
package org.infinispan.notifications.cachelistener.event; /** * This event subtype is passed in to any method annotated with {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated}. * * @author Manik Surtani * @since 4.0 */ public interface CacheEntryActivatedEvent<K, V> extends CacheEntryEvent<K, V> { /** * Retrieves the value of the entry being activated. * * @return the value of the activated entry */ V getValue(); }
478
27.176471
146
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/CacheEntryCreatedEvent.java
package org.infinispan.notifications.cachelistener.event; /** * This event subtype is passed in to any method annotated with * {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated}. * * @author Manik Surtani * @since 4.0 */ public interface CacheEntryCreatedEvent<K, V> extends CacheEntryEvent<K, V> { /** * Retrieves the value of the entry being created. * * @return null if {@link #isPre()} is true, or the value being created * if {@link #isPre()} is false. */ V getValue(); /** * This will be true if the write command that caused this had to be retried again due to a topology change. This * could be a sign that this event has been duplicated or another event was dropped and replaced * (eg: ModifiedEvent replaced CreateEvent) * @return Whether the command that caused this event was retried */ boolean isCommandRetried(); }
921
30.793103
117
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/CacheEntryPassivatedEvent.java
package org.infinispan.notifications.cachelistener.event; /** * This event subtype is passed in to any method annotated with * {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated}. * * @author Manik Surtani * @author Galder Zamarreño * @since 5.0 */ public interface CacheEntryPassivatedEvent<K, V> extends CacheEntryEvent<K, V> { /** * Retrieves the value of the entry being passivated. * <p /> * @return the value of the entry being passivated, if <tt>isPre()</tt> is <tt>true</tt>. <tt>null</tt> otherwise. */ V getValue(); }
590
30.105263
118
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/TransactionRegisteredEvent.java
package org.infinispan.notifications.cachelistener.event; /** * This event is passed in to any method annotated with {@link org.infinispan.notifications.cachelistener.annotation.TransactionRegistered}. * <p/> * Note that this event is only delivered <i>after the fact</i>, i.e., you will never see an instance of this event with * {@link #isPre()} being set to <tt>true</tt>. * * @author Manik Surtani * @since 4.0 */ public interface TransactionRegisteredEvent<K, V> extends TransactionalEvent<K, V> { }
514
35.785714
140
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/CacheEntryExpiredEvent.java
package org.infinispan.notifications.cachelistener.event; /** * This event subtype is passed in to any method annotated with * {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired}. * <p /> * The {@link #getValue()} method returns the value of the entry before it expired. Note this value may be null if * the entry expired from a cache store * <p> * This is a post only event * <p> * This event can be raised multiple times in sequence for a single expiration event if concurrent reads for the same * key occur on different nodes. This should rarely happen though since this window is narrowed internally by the * cache. * @author William Burns * @since 8.0 */ public interface CacheEntryExpiredEvent<K, V> extends CacheEntryEvent<K, V> { /** * Retrieves the value of the entry being expired. Note this event is raised after the value has been expired. * <p /> * @return the value of the entry expired */ @Override V getValue(); }
1,002
34.821429
117
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/TransactionalEvent.java
package org.infinispan.notifications.cachelistener.event; import org.infinispan.transaction.xa.GlobalTransaction; /** * An event subtype that includes a transaction context - if one exists - as well as a boolean as to whether the call * originated locally or remotely. * * @author Manik Surtani * @since 4.0 */ public interface TransactionalEvent<K, V> extends Event<K, V> { /** * @return the Transaction associated with the current call. May be null if the current call is outside the scope of * a transaction. */ GlobalTransaction getGlobalTransaction(); /** * @return true if the call originated on the local cache instance; false if originated from a remote one. */ boolean isOriginLocal(); }
747
30.166667
120
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/CacheEntryModifiedEvent.java
package org.infinispan.notifications.cachelistener.event; import org.infinispan.metadata.Metadata; /** * This event subtype is passed in to any method annotated with {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryModified} * <p /> * The {@link #getValue()} method's behavior is specific to whether the callback is triggered before or after the event * in question. For example, if <tt>event.isPre()</tt> is <tt>true</tt>, then <tt>event.getValue()</tt> would return the * <i>old</i> value, prior to modification. If <tt>event.isPre()</tt> is <tt>false</tt>, then <tt>event.getValue()</tt> * would return new <i>new</i> value. If the event is creating and inserting a new entry, the old value would be <tt>null</tt>. * <p /> * @author Manik Surtani * @since 4.0 */ public interface CacheEntryModifiedEvent<K, V> extends CacheEntryEvent<K, V> { /** * Retrieves the value of the entry being modified. * <p /> * @return the previous or new value of the entry, depending on whether isPre() is true or false. * @deprecated use {@link #getOldValue()} or {@link #getNewValue()} instead */ @Deprecated V getValue(); /** * Retrieves the old value of the entry being modified. * <p /> * @return the previous value of the entry, regardless of whether isPre() is true or false. */ V getOldValue(); /** * Retrieves the new value of the entry being modified. * <p /> * @return the new value of the entry, regardless of whether isPre() is true or false. */ V getNewValue(); /** * Regardless of whether <tt>isPre()</tt> is <tt>true</tt> or is * <tt>false</tt>, this method returns the metadata of the entry being * deleted. This method is useful for situations where cache listeners * need to know what the old value being deleted is when getting * <tt>isPre()</tt> is <tt>false</tt> callbacks. * * @return the metadata of the entry being deleted, regardless of * <tt>isPre()</tt> value */ Metadata getOldMetadata(); /** * Indicates whether the cache entry modification event is the result of * the cache entry being created. This method helps determine if the cache * entry was created when <tt>event.isPre()</tt> is <tt>false</tt>. * * @return true if the event is the result of the entry being created, * otherwise it returns false indicating that the event was the result of * a cache entry being updated */ boolean isCreated(); /** * This will be true if the write command that caused this had to be retried again due to a topology change. This * could be a sign that this event has been duplicated or another event was dropped and replaced * (eg: ModifiedEvent replaced CreateEvent) * @return Whether the command that caused this event was retried */ boolean isCommandRetried(); }
2,896
38.684932
144
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/TopologyChangedEvent.java
package org.infinispan.notifications.cachelistener.event; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.notifications.cachelistener.annotation.TopologyChanged; /** * The event passed in to methods annotated with {@link TopologyChanged}. * * @author Manik Surtani * @since 5.0 */ public interface TopologyChangedEvent<K, V> extends Event<K, V> { /** * @return retrieves the consistent hash at the start of a topology change * * @deprecated since 9.0 use {@link #getReadConsistentHashAtStart()} or {@link #getWriteConsistentHashAtStart()} */ @Deprecated default ConsistentHash getConsistentHashAtStart() { return getReadConsistentHashAtStart(); } ConsistentHash getReadConsistentHashAtStart(); ConsistentHash getWriteConsistentHashAtStart(); /** * @return retrieves the consistent hash at the end of a topology change * * @deprecated since 9.0 use {@link #getReadConsistentHashAtEnd()} or {@link #getWriteConsistentHashAtEnd()} */ @Deprecated default ConsistentHash getConsistentHashAtEnd() { return getWriteConsistentHashAtEnd(); } ConsistentHash getReadConsistentHashAtEnd(); ConsistentHash getWriteConsistentHashAtEnd(); int getNewTopologyId(); }
1,275
28
115
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/TransactionCompletedEvent.java
package org.infinispan.notifications.cachelistener.event; /** * This event is passed in to any method annotated with {@link org.infinispan.notifications.cachelistener.annotation.TransactionCompleted}. * <p/> * Note that this event is only delivered <i>after the fact</i>, i.e., you will never see an instance of this event with * {@link #isPre()} being set to <tt>true</tt>. * * @author Manik Surtani * @since 4.0 */ public interface TransactionCompletedEvent<K, V> extends TransactionalEvent<K, V> { /** * @return if <tt>true</tt>, the transaction completed by committing successfully. If <tt>false</tt>, the * transaction completed with a rollback. */ boolean isTransactionSuccessful(); }
727
37.315789
139
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/CacheEntryLoadedEvent.java
package org.infinispan.notifications.cachelistener.event; /** * This event subtype is passed in to any method annotated with {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryLoaded}. * * @author Manik Surtani * @since 4.0 */ public interface CacheEntryLoadedEvent<K, V> extends CacheEntryEvent<K, V> { /** * Retrieves the value of the entry being loaded. * * @return the value of the loaded entry */ V getValue(); }
466
26.470588
143
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/CacheEntryVisitedEvent.java
package org.infinispan.notifications.cachelistener.event; /** * This event subtype is passed in to any method annotated with {@link org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited}. * * @author Manik Surtani * @since 4.0 */ public interface CacheEntryVisitedEvent<K, V> extends CacheEntryEvent<K, V> { /** * Retrieves the value of the entry being visited. * * @return the value of the visited entry */ V getValue(); }
470
26.705882
144
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/CacheEntriesEvictedEvent.java
package org.infinispan.notifications.cachelistener.event; import java.util.Map; /** * This event subtype is passed in to any method annotated with * {@link org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted}. * * @author Manik Surtani * @author Galder Zamarreño * @since 5.0 */ public interface CacheEntriesEvictedEvent<K, V> extends Event<K, V> { /** * Retrieves entries being evicted. * * @return A map containing the key/value pairs of the * cache entries being evicted. */ Map<K, V> getEntries(); }
571
22.833333
85
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/DataRehashedEvent.java
package org.infinispan.notifications.cachelistener.event; import java.util.Collection; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.notifications.cachelistener.annotation.DataRehashed; import org.infinispan.remoting.transport.Address; /** * An event passed in to methods annotated with {@link DataRehashed}. * * <p>The result of the {@link #getNewTopologyId()} method is not guaranteed to be the same for the "pre" * and the "post" notification, either. However, the "post" value is guaranteed to be greater than or equal to * the "pre" value.</p> * * @author Manik Surtani * @author Dan Berindei * @since 5.0 */ public interface DataRehashedEvent<K, V> extends Event<K, V> { /** * @return Retrieves the list of members before rehashing started. */ Collection<Address> getMembersAtStart(); /** * @return Retrieves the list of members after rehashing ended. */ Collection<Address> getMembersAtEnd(); /** * @return The current consistent hash that was installed prior to the rehash. * It is used both for reading and writing before the rebalance. */ ConsistentHash getConsistentHashAtStart(); /** * @return The consistent hash that will be installed after the rebalance. * It will be used both for reading and writing once the rebalance is complete. */ ConsistentHash getConsistentHashAtEnd(); /** * @return The union of the current and future consistent hashes. * * @deprecated Since 9.0 */ @Deprecated ConsistentHash getUnionConsistentHash(); /** * @return Retrieves the new topology id after rehashing was triggered. */ int getNewTopologyId(); }
1,716
29.122807
110
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/event/impl/EventImpl.java
package org.infinispan.notifications.cachelistener.event.impl; import java.util.Collection; import java.util.Collections; import java.util.Map; import org.infinispan.Cache; import org.infinispan.commons.util.Util; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.event.CacheEntriesEvictedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryActivatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryExpiredEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryInvalidatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryLoadedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryPassivatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent; import org.infinispan.notifications.cachelistener.event.DataRehashedEvent; import org.infinispan.notifications.cachelistener.event.PartitionStatusChangedEvent; import org.infinispan.notifications.cachelistener.event.PersistenceAvailabilityChangedEvent; import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent; import org.infinispan.notifications.cachelistener.event.TransactionCompletedEvent; import org.infinispan.notifications.cachelistener.event.TransactionRegisteredEvent; import org.infinispan.partitionhandling.AvailabilityMode; import org.infinispan.remoting.transport.Address; import org.infinispan.transaction.xa.GlobalTransaction; import net.jcip.annotations.NotThreadSafe; /** * Basic implementation of an event that covers all event types. * * @author Manik Surtani * @since 4.0 */ @NotThreadSafe public class EventImpl<K, V> implements CacheEntryActivatedEvent, CacheEntryCreatedEvent, CacheEntriesEvictedEvent, CacheEntryLoadedEvent, CacheEntryModifiedEvent, CacheEntryPassivatedEvent, CacheEntryRemovedEvent, CacheEntryVisitedEvent, TransactionCompletedEvent, TransactionRegisteredEvent, CacheEntryInvalidatedEvent, DataRehashedEvent, TopologyChangedEvent, CacheEntryExpiredEvent, PartitionStatusChangedEvent, PersistenceAvailabilityChangedEvent, Cloneable { private boolean pre = false; // by default events are after the fact private transient Cache<K, V> cache; private K key; private Object source; private Metadata metadata; private Metadata oldMetadata; private boolean originLocal = true; // by default events all originate locally private boolean transactionSuccessful; private Type type; private V value; private V newValue; private V oldValue; private ConsistentHash readConsistentHashAtStart, writeConsistentHashAtStart, readConsistentHashAtEnd, writeConsistentHashAtEnd, unionConsistentHash; private int newTopologyId; private Map<? extends K, ? extends V> entries; private boolean created; private boolean commandRetried; private boolean isCurrentState; private AvailabilityMode mode; private boolean available; public EventImpl() { } public static <K, V> EventImpl<K, V> createEvent(Cache<K, V> cache, Type type) { EventImpl<K, V> e = new EventImpl<>(); e.cache = cache; e.type = type; return e; } @Override public Type getType() { return type; } @Override public boolean isPre() { return pre; } @Override public Cache<K, V> getCache() { return cache; } @Override @SuppressWarnings("unchecked") public K getKey() { return key; } @Override public GlobalTransaction getGlobalTransaction() { if (this.source instanceof GlobalTransaction) return (GlobalTransaction) this.source; return null; } @Override public Object getSource() { return source; } @Override public boolean isOriginLocal() { return originLocal; } @Override public boolean isTransactionSuccessful() { return transactionSuccessful; } // ------------------------------ setters ----------------------------- public void setPre(boolean pre) { this.pre = pre; } public void setKey(K key) { this.key = key; } /** * @deprecated Since 12.0, will be removed in 15.0 */ @Deprecated public void setTransactionId(GlobalTransaction transaction) { setSource(transaction); } /** * @param source An identifier of the transaction or cache invocation that triggered the event. * In a transactional cache, it is the same as {@link #getGlobalTransaction()}. * In a non-transactional cache, it is an internal object that identifies the cache invocation. */ public void setSource(Object source) { this.source = source; } public void setOriginLocal(boolean originLocal) { this.originLocal = originLocal; } public void setTransactionSuccessful(boolean transactionSuccessful) { this.transactionSuccessful = transactionSuccessful; } public void setReadConsistentHashAtStart(ConsistentHash readConsistentHashAtStart) { this.readConsistentHashAtStart = readConsistentHashAtStart; } public void setWriteConsistentHashAtStart(ConsistentHash writeConsistentHashAtStart) { this.writeConsistentHashAtStart = writeConsistentHashAtStart; } public void setReadConsistentHashAtEnd(ConsistentHash readConsistentHashAtEnd) { this.readConsistentHashAtEnd = readConsistentHashAtEnd; } public void setWriteConsistentHashAtEnd(ConsistentHash writeConsistentHashAtEnd) { this.writeConsistentHashAtEnd = writeConsistentHashAtEnd; } public void setUnionConsistentHash(ConsistentHash unionConsistentHash) { this.unionConsistentHash = unionConsistentHash; } public void setNewTopologyId(int newTopologyId) { this.newTopologyId = newTopologyId; } public void setMetadata(Metadata metadata) { this.metadata = metadata; } @Override public Metadata getMetadata() { return metadata; } @Override public boolean isCurrentState() { return isCurrentState; } public void setCurrentState(boolean currentState) { isCurrentState = currentState; } public void setOldMetadata(Metadata metadata) { this.oldMetadata = metadata; } public Metadata getOldMetadata() { return oldMetadata; } @Override @SuppressWarnings("unchecked") public V getValue() { return value; } public void setCommandRetried(boolean commandRetried) { this.commandRetried = commandRetried; } @Override public boolean isCommandRetried() { return commandRetried; } @Override public boolean isCreated() { return created; } public V getNewValue() { return newValue; } @Override public V getOldValue() { return oldValue; } public void setValue(V value) { this.value = value; this.newValue = value; } public void setEntries(Map<? extends K, ? extends V> entries) { this.entries = entries; } public void setCreated(boolean created) { this.created = created; } public void setNewValue(V newValue) { this.newValue = newValue; } public void setOldValue(V oldValue) { this.oldValue = oldValue; } public boolean isAvailable() { return available; } public void setAvailable(boolean available) { this.available = available; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EventImpl<?, ?> event = (EventImpl<?, ?>) o; if (originLocal != event.originLocal) return false; if (pre != event.pre) return false; if (transactionSuccessful != event.transactionSuccessful) return false; if (cache != null ? !cache.equals(event.cache) : event.cache != null) return false; if (key != null ? !key.equals(event.key) : event.key != null) return false; if (source != null ? !source.equals(event.source) : event.source != null) return false; if (type != event.type) return false; if (value != null ? !value.equals(event.value) : event.value != null) return false; if (!Util.safeEquals(readConsistentHashAtStart, event.readConsistentHashAtStart)) return false; if (!Util.safeEquals(writeConsistentHashAtStart, event.writeConsistentHashAtStart)) return false; if (!Util.safeEquals(readConsistentHashAtEnd, event.readConsistentHashAtEnd)) return false; if (!Util.safeEquals(writeConsistentHashAtEnd, event.writeConsistentHashAtEnd)) return false; if (!Util.safeEquals(unionConsistentHash, event.unionConsistentHash)) return false; if (newTopologyId != event.newTopologyId) return false; if (created != event.created) return false; if (isCurrentState != event.isCurrentState) return false; if (oldValue != null ? !oldValue.equals(event.oldValue) : event.oldValue != null) return false; if (newValue != null ? !newValue.equals(event.newValue) : event.newValue != null) return false; return available == event.available; } @Override public int hashCode() { int result = (pre ? 1 : 0); result = 31 * result + (cache != null ? cache.hashCode() : 0); result = 31 * result + (key != null ? key.hashCode() : 0); result = 31 * result + (source != null ? source.hashCode() : 0); result = 31 * result + (originLocal ? 1 : 0); result = 31 * result + (transactionSuccessful ? 1 : 0); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (value != null ? value.hashCode() : 0); result = 31 * result + (readConsistentHashAtStart != null ? readConsistentHashAtStart.hashCode() : 0); result = 31 * result + (writeConsistentHashAtStart != null ? writeConsistentHashAtStart.hashCode() : 0); result = 31 * result + (readConsistentHashAtEnd != null ? readConsistentHashAtEnd.hashCode() : 0); result = 31 * result + (writeConsistentHashAtEnd != null ? writeConsistentHashAtEnd.hashCode() : 0); result = 31 * result + (unionConsistentHash != null ? unionConsistentHash.hashCode() : 0); result = 31 * result + newTopologyId; result = 31 * result + (created ? 1 : 0) + (isCurrentState ? 2 : 0); result = 31 * result + (oldValue != null ? oldValue.hashCode() : 0); result = 31 * result + (newValue != null ? newValue.hashCode() : 0); result = 31 * result + (available ? 1 : 0); return result; } @Override public String toString() { if (type == Type.TOPOLOGY_CHANGED || type == Type.DATA_REHASHED) return "EventImpl{" + "type=" + type + ", pre=" + pre + ", cache=" + cache + ", readConsistentHashAtStart=" + readConsistentHashAtStart + ", writeConsistentHashAtStart=" + writeConsistentHashAtStart + ", readConsistentHashAtEnd=" + readConsistentHashAtEnd + ", writeConsistentHashAtEnd=" + writeConsistentHashAtEnd + ", unionConsistentHash=" + unionConsistentHash + ", newTopologyId=" + newTopologyId + '}'; return "EventImpl{" + "type=" + type + ", pre=" + pre + ", cache=" + cache + ", key=" + key + ", value=" + value + ", newValue=" + newValue + ", oldValue=" + oldValue + ", source=" + source + ", originLocal=" + originLocal + ", transactionSuccessful=" + transactionSuccessful + ", entries=" + entries + ", created=" + created + ", isCurrentState=" + isCurrentState + ", available=" + available + '}'; } @Override public Collection<Address> getMembersAtStart() { return readConsistentHashAtStart != null ? readConsistentHashAtStart.getMembers() : Collections.<Address>emptySet(); } @Override public Collection<Address> getMembersAtEnd() { return readConsistentHashAtEnd != null ? readConsistentHashAtEnd.getMembers() : Collections.<Address>emptySet(); } @Override public ConsistentHash getConsistentHashAtStart() { return readConsistentHashAtStart; } @Override public ConsistentHash getConsistentHashAtEnd() { return writeConsistentHashAtEnd; } @Override public ConsistentHash getReadConsistentHashAtStart() { return readConsistentHashAtStart; } @Override public ConsistentHash getWriteConsistentHashAtStart() { return writeConsistentHashAtStart; } @Override public ConsistentHash getReadConsistentHashAtEnd() { return readConsistentHashAtEnd; } @Override public ConsistentHash getWriteConsistentHashAtEnd() { return writeConsistentHashAtEnd; } @Override public ConsistentHash getUnionConsistentHash() { return unionConsistentHash; } @Override public int getNewTopologyId() { return newTopologyId; } @Override public AvailabilityMode getAvailabilityMode() { return mode; } public void setAvailabilityMode(AvailabilityMode mode) { this.mode = mode; } @Override public Map<? extends K, ? extends V> getEntries() { return entries; } @Override public EventImpl<K, V> clone() { try { return (EventImpl<K, V>) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException("Should never happen!", e); } } }
13,993
32.398568
169
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/cluster/ClusterEvent.java
package org.infinispan.notifications.cachelistener.cluster; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.infinispan.Cache; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.marshall.MarshallUtil; import org.infinispan.marshall.core.Ids; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryExpiredEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.infinispan.notifications.cachelistener.event.TransactionalEvent; import org.infinispan.notifications.cachelistener.event.impl.EventImpl; import org.infinispan.remoting.transport.Address; import org.infinispan.transaction.xa.GlobalTransaction; /** * This is an event designed for use with cluster listeners solely. This is the event that is serialized across the * wire when sending the event back to the node where the cluster listener is registered. You should only create * a ClusterEvent through the use of the {@link ClusterEvent#fromEvent(CacheEntryEvent)} method. * * @author wburns * @since 7.0 */ public class ClusterEvent<K, V> implements CacheEntryCreatedEvent<K, V>, CacheEntryRemovedEvent<K, V>, CacheEntryModifiedEvent<K, V>, CacheEntryExpiredEvent<K, V> { transient Cache<K, V> cache; private final K key; private final V value; private final V oldValue; private final Metadata metadata; private final Type type; private final GlobalTransaction transaction; private final Address origin; private final boolean commandRetried; public static <K, V> ClusterEvent<K, V> fromEvent(CacheEntryEvent<K, V> event) { if (event instanceof ClusterEvent) { return (ClusterEvent<K, V>) event; } V oldValue = null; Type eventType = event.getType(); boolean commandRetried; switch (eventType) { case CACHE_ENTRY_REMOVED: oldValue = ((CacheEntryRemovedEvent<K, V>)event).getOldValue(); commandRetried = ((CacheEntryRemovedEvent<K, V>)event).isCommandRetried(); break; case CACHE_ENTRY_CREATED: commandRetried = ((CacheEntryCreatedEvent<K, V>)event).isCommandRetried(); break; case CACHE_ENTRY_MODIFIED: commandRetried = ((CacheEntryModifiedEvent<K, V>)event).isCommandRetried(); break; case CACHE_ENTRY_EXPIRED: // Expired doesn't have a retry commandRetried = false; break; default: throw new IllegalArgumentException("Cluster Event can only be created from a CacheEntryRemoved, CacheEntryCreated or CacheEntryModified event!"); } GlobalTransaction transaction = ((TransactionalEvent)event).getGlobalTransaction(); Metadata metadata = null; if (event instanceof EventImpl) { metadata = ((EventImpl)event).getMetadata(); } ClusterEvent<K, V> clusterEvent = new ClusterEvent<>(event.getKey(), event.getValue(), oldValue, metadata, eventType, event.getCache().getCacheManager().getAddress(), transaction, commandRetried); clusterEvent.cache = event.getCache(); return clusterEvent; } ClusterEvent(K key, V value, V oldValue, Metadata metadata, Type type, Address origin, GlobalTransaction transaction, boolean commandRetried) { this.key = key; this.value = value; this.oldValue = oldValue; this.metadata = metadata; this.type = type; this.origin = origin; this.transaction = transaction; this.commandRetried = commandRetried; } @Override public V getValue() { return value; } @Override public V getNewValue() { return value; } @Override public Metadata getMetadata() { return metadata; } @Override public Metadata getOldMetadata() { throw new UnsupportedOperationException(); } @Override public boolean isCommandRetried() { return commandRetried; } @Override public V getOldValue() { return oldValue; } @Override public boolean isCreated() { return type == Type.CACHE_ENTRY_CREATED; } @Override public K getKey() { return key; } @Override public GlobalTransaction getGlobalTransaction() { return transaction; } @Override public boolean isOriginLocal() { if (cache != null) { return cache.getCacheManager().getAddress().equals(origin); } return false; } @Override public Type getType() { return type; } @Override public boolean isPre() { // Cluster events are always sent after the value has been updated return false; } @Override public Cache<K, V> getCache() { return cache; } public static class Externalizer extends AbstractExternalizer<ClusterEvent> { @Override public Set<Class<? extends ClusterEvent>> getTypeClasses() { return Collections.singleton(ClusterEvent.class); } @Override public void writeObject(ObjectOutput output, ClusterEvent object) throws IOException { output.writeObject(object.key); output.writeObject(object.value); output.writeObject(object.oldValue); output.writeObject(object.metadata); MarshallUtil.marshallEnum(object.type, output); output.writeObject(object.origin); output.writeObject(object.transaction); output.writeBoolean(object.commandRetried); } @Override public ClusterEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new ClusterEvent(input.readObject(), input.readObject(), input.readObject(), (Metadata)input.readObject(),MarshallUtil.unmarshallEnum(input, Type::valueOf), (Address)input.readObject(), (GlobalTransaction)input.readObject(), input.readBoolean()); } @Override public Integer getId() { return Ids.CLUSTER_EVENT; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClusterEvent that = (ClusterEvent) o; if (commandRetried != that.commandRetried) return false; if (cache != null ? !cache.equals(that.cache) : that.cache != null) return false; if (key != null ? !key.equals(that.key) : that.key != null) return false; if (metadata != null ? !metadata.equals(that.metadata) : that.metadata != null) return false; if (oldValue != null ? !oldValue.equals(that.oldValue) : that.oldValue != null) return false; if (origin != null ? !origin.equals(that.origin) : that.origin != null) return false; if (transaction != null ? !transaction.equals(that.transaction) : that.transaction != null) return false; if (type != that.type) return false; if (value != null ? !value.equals(that.value) : that.value != null) return false; return true; } @Override public int hashCode() { int result = cache != null ? cache.hashCode() : 0; result = 31 * result + (key != null ? key.hashCode() : 0); result = 31 * result + (value != null ? value.hashCode() : 0); result = 31 * result + (oldValue != null ? oldValue.hashCode() : 0); result = 31 * result + (metadata != null ? metadata.hashCode() : 0); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (transaction != null ? transaction.hashCode() : 0); result = 31 * result + (origin != null ? origin.hashCode() : 0); result = 31 * result + (commandRetried ? 1 : 0); return result; } @Override public String toString() { return "ClusterEvent {" + "type=" + type + ", cache=" + cache + ", key=" + key + ", value=" + value + ", oldValue=" + oldValue + ", transaction=" + transaction + ", retryCommand=" + commandRetried + ", origin=" + origin + '}'; } }
8,578
33.592742
157
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/cluster/RemoteClusterListener.java
package org.infinispan.notifications.cachelistener.cluster; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Queue; import java.util.UUID; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.CacheNotifier; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.annotation.TransactionCompleted; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.TransactionCompletedEvent; import org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifier; import org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged; import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent; import org.infinispan.remoting.transport.Address; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import net.jcip.annotations.ThreadSafe; /** * A listener that installed locally on each node when a cluster listener is installed on a given node. * * @author wburns * @since 7.0 */ @ThreadSafe @Listener(primaryOnly = true, observation = Listener.Observation.POST) public class RemoteClusterListener { private static final Log log = LogFactory.getLog(RemoteClusterListener.class); private final UUID id; private final Address origin; private final CacheNotifier cacheNotifier; private final CacheManagerNotifier cacheManagerNotifier; private final ClusterEventManager eventManager; private final boolean sync; private final ConcurrentMap<GlobalTransaction, Queue<CacheEntryEvent>> transactionChanges = new ConcurrentHashMap<>(); public RemoteClusterListener(UUID id, Address origin, CacheNotifier cacheNotifier, CacheManagerNotifier cacheManagerNotifier, ClusterEventManager eventManager, boolean sync) { this.id = id; this.origin = origin; this.cacheNotifier = cacheNotifier; this.cacheManagerNotifier = cacheManagerNotifier; this.eventManager = eventManager; this.sync = sync; } public UUID getId() { return id; } public Address getOwnerAddress() { return origin; } @ViewChanged public CompletionStage<Void> viewChange(ViewChangedEvent event) { if (!event.getNewMembers().contains(origin)) { if (log.isTraceEnabled()) { log.tracef("Origin %s storing cluster listener is gone, removing local listener", origin); } return removeListener(); } return CompletableFutures.completedNull(); } public CompletionStage<Void> removeListener() { return CompletionStages.allOf(cacheNotifier.removeListenerAsync(this), cacheManagerNotifier.removeListenerAsync(this)); } @CacheEntryCreated @CacheEntryModified @CacheEntryRemoved @CacheEntryExpired public CompletionStage<Void> handleClusterEvents(CacheEntryEvent event) { GlobalTransaction transaction = event.getGlobalTransaction(); if (transaction != null) { // If we are in a transaction, queue up those events so we can send them as 1 batch. Queue<CacheEntryEvent> events = transactionChanges.get(transaction); if (events == null) { events = new ConcurrentLinkedQueue<>(); Queue<CacheEntryEvent> otherQueue = transactionChanges.putIfAbsent(transaction, events); if (otherQueue != null) { events = otherQueue; } } events.add(event); } else { // Send event back to origin who has the cluster listener if (log.isTraceEnabled()) { log.tracef("Passing Event to manager %s to send to %s", event, origin); } // Non tx event batching is keyed by the invoking thread. eventManager.addEvents(Thread.currentThread(), origin, id, Collections.singleton(ClusterEvent.fromEvent(event)), sync); } return CompletableFutures.completedNull(); } @TransactionCompleted public CompletionStage<Void> transactionCompleted(TransactionCompletedEvent event) { GlobalTransaction transaction = event.getGlobalTransaction(); Queue<CacheEntryEvent> events = transactionChanges.remove(transaction); if (event.isTransactionSuccessful() && events != null) { List<ClusterEvent> eventsToSend = new ArrayList<>(events.size()); for (CacheEntryEvent cacheEvent : events) { eventsToSend.add(ClusterEvent.fromEvent(cacheEvent)); // Send event back to origin who has the cluster listener if (log.isTraceEnabled()) { log.tracef("Passing Event(s) to manager %s to send to %s", eventsToSend, origin); } } eventManager.addEvents(transaction, origin, id, eventsToSend, sync); } return CompletableFutures.completedNull(); } }
5,610
40.562963
128
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerRemoveCallable.java
package org.infinispan.notifications.cachelistener.cluster; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import java.util.UUID; import java.util.function.Function; import org.infinispan.Cache; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.core.Ids; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * This DistributedCallable is used to remove registered {@link RemoteClusterListener} on each of the various nodes * when a cluster listener is unregistered from the cache. * * @author wburns * @since 7.0 */ public class ClusterListenerRemoveCallable implements Function<EmbeddedCacheManager, Void> { private static final Log log = LogFactory.getLog(ClusterListenerRemoveCallable.class); private final String cacheName; private final UUID identifier; public ClusterListenerRemoveCallable(String cacheName, UUID identifier) { this.cacheName = cacheName; this.identifier = identifier; } @Override public Void apply(EmbeddedCacheManager embeddedCacheManager) { Cache<Object, Object> cache = embeddedCacheManager.getCache(cacheName); // Remove the listener from the cache now Set<Object> listeners = cache.getListeners(); for (Object listener : listeners) { if (listener instanceof RemoteClusterListener) { RemoteClusterListener clusterListener = (RemoteClusterListener)listener; if (identifier.equals(clusterListener.getId())) { if (log.isTraceEnabled()) { log.tracef("Removing local cluster listener due to parent cluster listener was removed : %s", identifier); } clusterListener.removeListener(); } } } return null; } public static class Externalizer extends AbstractExternalizer<ClusterListenerRemoveCallable> { @Override public Set<Class<? extends ClusterListenerRemoveCallable>> getTypeClasses() { return Collections.singleton(ClusterListenerRemoveCallable.class); } @Override public void writeObject(ObjectOutput output, ClusterListenerRemoveCallable object) throws IOException { output.writeObject(object.cacheName); output.writeObject(object.identifier); } @Override public ClusterListenerRemoveCallable readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new ClusterListenerRemoveCallable((String) input.readObject(), (UUID)input.readObject()); } @Override public Integer getId() { return Ids.CLUSTER_LISTENER_REMOVE_CALLABLE; } } }
2,828
35.269231
124
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/cluster/MultiClusterEventCommand.java
package org.infinispan.notifications.cachelistener.cluster; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import java.util.concurrent.CompletionStage; import org.infinispan.commands.remote.BaseRpcCommand; import org.infinispan.factories.ComponentRegistry; import org.infinispan.remoting.transport.Address; import org.infinispan.util.ByteString; import org.infinispan.util.concurrent.AggregateCompletionStage; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * This command is used to send cluster events for multiple listeners on the same node * * @author wburns * @since 10.0 */ public class MultiClusterEventCommand<K, V> extends BaseRpcCommand { public static final int COMMAND_ID = 19; private static final Log log = LogFactory.getLog(MultiClusterEventCommand.class); private Map<UUID, Collection<ClusterEvent<K, V>>> multiEvents; public MultiClusterEventCommand() { super(null); } public MultiClusterEventCommand(ByteString cacheName) { super(cacheName); } public MultiClusterEventCommand(ByteString cacheName, Map<UUID, Collection<ClusterEvent<K, V>>> events) { super(cacheName); this.multiEvents = events; } @Override public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) { if (log.isTraceEnabled()) { log.tracef("Received multiple cluster event(s) %s", multiEvents); } AggregateCompletionStage<Void> innerComposed = CompletionStages.aggregateCompletionStage(); for (Entry<UUID, Collection<ClusterEvent<K, V>>> event : multiEvents.entrySet()) { UUID identifier = event.getKey(); Collection<ClusterEvent<K, V>> events = event.getValue(); for (ClusterEvent<K, V> ce : events) { ce.cache = componentRegistry.getCache().wired(); } ClusterCacheNotifier<K, V> clusterCacheNotifier = componentRegistry.getClusterCacheNotifier().running(); innerComposed.dependsOn(clusterCacheNotifier.notifyClusterListeners(events, identifier)); } return innerComposed.freeze(); } @Override public byte getCommandId() { return COMMAND_ID; } @Override public boolean isReturnValueExpected() { return false; } @Override public void writeTo(ObjectOutput output) throws IOException { output.writeObject(getOrigin()); if (multiEvents.size() == 1) { output.writeBoolean(true); Entry entry = multiEvents.entrySet().iterator().next(); output.writeObject(entry.getKey()); output.writeObject(entry.getValue()); } else { output.writeBoolean(false); output.writeObject(multiEvents); } } @Override public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { setOrigin((Address) input.readObject()); boolean single = input.readBoolean(); if (single) { multiEvents = Collections.singletonMap((UUID) input.readObject(), (Collection<ClusterEvent<K, V>>) input.readObject()); } else { multiEvents = (Map<UUID, Collection<ClusterEvent<K, V>>>)input.readObject(); } } }
3,412
32.460784
128
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/cluster/ClusterListenerReplicateCallable.java
package org.infinispan.notifications.cachelistener.cluster; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.lang.annotation.Annotation; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.UUID; import java.util.function.BiConsumer; import java.util.function.Function; import org.infinispan.Cache; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.commons.marshall.MarshallUtil; import org.infinispan.encoding.DataConversion; import org.infinispan.factories.ComponentRegistry; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.core.Ids; import org.infinispan.notifications.cachelistener.CacheNotifier; import org.infinispan.notifications.cachelistener.ListenerHolder; import org.infinispan.notifications.cachelistener.filter.CacheEventConverter; import org.infinispan.notifications.cachelistener.filter.CacheEventFilter; import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverter; import org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifier; import org.infinispan.remoting.transport.Address; import org.infinispan.security.actions.SecurityActions; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * This DistributedCallable is used to install a {@link RemoteClusterListener} on the resulting node. This class * also has checks to ensure that if the listener is attempted to be installed from more than 1 source only 1 will be * installed as well if a node goes down while installing will also remove the listener. * * @author wburns * @since 7.0 */ public class ClusterListenerReplicateCallable<K, V> implements Function<EmbeddedCacheManager, Void>, BiConsumer<EmbeddedCacheManager, Cache<K, V>> { private static final Log log = LogFactory.getLog(ClusterListenerReplicateCallable.class); private final String cacheName; private final UUID identifier; private final CacheEventFilter<K, V> filter; private final CacheEventConverter<K, V, ?> converter; private final Address origin; private final boolean sync; private final Set<Class<? extends Annotation>> filterAnnotations; private final DataConversion keyDataConversion; private final DataConversion valueDataConversion; private final boolean useStorageFormat; public ClusterListenerReplicateCallable(String cacheName, UUID identifier, Address origin, CacheEventFilter<K, V> filter, CacheEventConverter<K, V, ?> converter, boolean sync, Set<Class<? extends Annotation>> filterAnnotations, DataConversion keyDataConversion, DataConversion valueDataConversion, boolean useStorageFormat) { this.cacheName = cacheName; this.identifier = identifier; this.origin = origin; this.filter = filter; this.converter = converter; this.sync = sync; this.filterAnnotations = filterAnnotations; this.keyDataConversion = keyDataConversion; this.valueDataConversion = valueDataConversion; this.useStorageFormat = useStorageFormat; if (log.isTraceEnabled()) log.tracef("Created clustered listener replicate callable for: %s", filterAnnotations); } @Override public Void apply(EmbeddedCacheManager cacheManager) { Cache<K, V> cache = SecurityActions.getCache(cacheManager, cacheName); accept(cacheManager, cache); return null; } @Override public void accept(EmbeddedCacheManager cacheManager, Cache<K, V> cache) { ComponentRegistry componentRegistry = SecurityActions.getCacheComponentRegistry(cache.getAdvancedCache()); CacheNotifier<K, V> cacheNotifier = componentRegistry.getComponent(CacheNotifier.class); CacheManagerNotifier cacheManagerNotifier = componentRegistry.getComponent(CacheManagerNotifier.class); Address ourAddress = cache.getCacheManager().getAddress(); ClusterEventManager<K, V> eventManager = componentRegistry.getComponent(ClusterEventManager.class); if (filter != null) { componentRegistry.wireDependencies(filter); } if (converter != null && converter != filter) { componentRegistry.wireDependencies(converter); } // Only register listeners if we aren't the ones that registered the cluster listener if (!ourAddress.equals(origin)) { // Make sure the origin is around otherwise don't register the listener - some way with identifier (CHM maybe?) if (cacheManager.getMembers().contains(origin)) { // Prevent multiple invocations to get in here at once, which should prevent concurrent registration of // the same id. Note we can't use a static CHM due to running more than 1 node in same JVM synchronized (cacheNotifier) { boolean alreadyInstalled = false; // First make sure the listener is not already installed, if it is we don't do anything. for (Object installedListener : cacheNotifier.getListeners()) { if (installedListener instanceof RemoteClusterListener && identifier.equals(((RemoteClusterListener) installedListener).getId())) { alreadyInstalled = true; break; } } if (!alreadyInstalled) { RemoteClusterListener listener = new RemoteClusterListener(identifier, origin, cacheNotifier, cacheManagerNotifier, eventManager, sync); ListenerHolder listenerHolder = new ListenerHolder(listener, keyDataConversion, valueDataConversion, useStorageFormat); cacheNotifier.addFilteredListener(listenerHolder, filter, converter, filterAnnotations); cacheManagerNotifier.addListener(listener); // It is possible the member is now gone after registered, if so we have to remove just to be sure if (!cacheManager.getMembers().contains(origin)) { cacheNotifier.removeListener(listener); cacheManagerNotifier.removeListener(listener); if (log.isTraceEnabled()) { log.tracef("Removing local cluster listener for remote cluster listener that was just registered, as the origin %s went away concurrently", origin); } } else if (log.isTraceEnabled()) { log.tracef("Registered local cluster listener for remote cluster listener from origin %s with id %s", origin, identifier); } } else if (log.isTraceEnabled()) { log.tracef("Local cluster listener from origin %s with id %s was already installed, ignoring", origin, identifier); } } } else if (log.isTraceEnabled()) { log.tracef("Not registering local cluster listener for remote cluster listener from origin %s, as the origin went away", origin); } } else if (log.isTraceEnabled()) { log.trace("Not registering local cluster listener as we are the node who registered the cluster listener"); } } public static class Externalizer extends AbstractExternalizer<ClusterListenerReplicateCallable> { @Override public Set<Class<? extends ClusterListenerReplicateCallable>> getTypeClasses() { return Collections.singleton(ClusterListenerReplicateCallable.class); } @Override public void writeObject(ObjectOutput output, ClusterListenerReplicateCallable object) throws IOException { output.writeObject(object.cacheName); output.writeObject(object.identifier); output.writeObject(object.origin); output.writeObject(object.filter); if (object.filter == object.converter && object.filter instanceof CacheEventFilterConverter) { output.writeBoolean(true); } else { output.writeBoolean(false); output.writeObject(object.converter); } output.writeBoolean(object.sync); MarshallUtil.marshallCollection(object.filterAnnotations, output); DataConversion.writeTo(output, object.keyDataConversion); DataConversion.writeTo(output, object.valueDataConversion); output.writeBoolean(object.useStorageFormat); } @Override public ClusterListenerReplicateCallable readObject(ObjectInput input) throws IOException, ClassNotFoundException { String cacheName = (String) input.readObject(); UUID id = (UUID) input.readObject(); Address address = (Address) input.readObject(); CacheEventFilter filter = (CacheEventFilter) input.readObject(); boolean sameConverter = input.readBoolean(); CacheEventConverter converter; if (sameConverter) { converter = (CacheEventFilterConverter) filter; } else { converter = (CacheEventConverter) input.readObject(); } boolean sync = input.readBoolean(); Set<Class<? extends Annotation>> filterAnnotations = MarshallUtil.unmarshallCollection(input, HashSet::new); DataConversion keyDataConversion = DataConversion.readFrom(input); DataConversion valueDataConversion = DataConversion.readFrom(input); boolean raw = input.readBoolean(); return new ClusterListenerReplicateCallable(cacheName, id, address, filter, converter, sync, filterAnnotations, keyDataConversion, valueDataConversion, raw); } @Override public Integer getId() { return Ids.CLUSTER_LISTENER_REPLICATE_CALLABLE; } } @Override public String toString() { return "ClusterListenerReplicateCallable{" + "cacheName='" + cacheName + '\'' + ", identifier=" + identifier + ", origin=" + origin + ", sync=" + sync + '}'; } }
10,210
48.328502
172
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/cluster/ClusterCacheNotifier.java
package org.infinispan.notifications.cachelistener.cluster; import java.util.Collection; import java.util.UUID; import java.util.concurrent.CompletionStage; import org.infinispan.notifications.cachelistener.CacheNotifier; /** * This interface describes methods required for a cluster listener to be able to be bootstrapped and properly notified * when a new event has been raised from the cluster. * * @author wburns * @since 7.0 */ public interface ClusterCacheNotifier<K, V> extends CacheNotifier<K, V> { /** * Method that is invoked on the node that has the given cluster listener that when registered generated the given * listenerId. Note this will notify only cluster listeners and regular listeners are not notified of the events. * Will fire the events in the order of the iteration of the collection. * @param events * @param listenerId */ CompletionStage<Void> notifyClusterListeners(Collection<ClusterEvent<K, V>> events, UUID listenerId); /** * This method is invoked so that this node can send the details required for a new node to be bootstrapped with * the existing cluster listeners that are already installed. * @return A collection of callables that should be invoked on the new node to properly install cluster listener information */ Collection<ClusterListenerReplicateCallable<K, V>> retrieveClusterListenerCallablesToInstall(); }
1,416
41.939394
127
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/cluster/ClusterEventManager.java
package org.infinispan.notifications.cachelistener.cluster; import java.util.Collection; import java.util.UUID; import java.util.concurrent.CompletionStage; import org.infinispan.remoting.transport.Address; public interface ClusterEventManager<K, V> { /** * Adds additional cluster events that need to be sent remotely for an event originating locally. * These events are batched by the {@code batchIdentifier} pending their submission when * {@link ClusterEventManager#sendEvents(Object)} is invoked or cancelled when {@link #dropEvents(Object)} is invoked. * @param batchIdentifier identifier for the batch * @param target The target node this event was meant for * @param identifier The cluster listener that is identified for these events * @param events The events that were generated * @param sync Whether these events need to be sent synchronously or not */ void addEvents(Object batchIdentifier, Address target, UUID identifier, Collection<ClusterEvent<K, V>> events, boolean sync); /** * Sends all previously added events for the given identifier */ CompletionStage<Void> sendEvents(Object batchIdentifier); /** * Drops and ignores all previously added events for the given identifier. */ void dropEvents(Object batchIdentifier); }
1,316
40.15625
128
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/cluster/ClusterEventManagerFactory.java
package org.infinispan.notifications.cachelistener.cluster; import org.infinispan.factories.AbstractNamedCacheComponentFactory; import org.infinispan.factories.AutoInstantiableFactory; import org.infinispan.factories.annotations.DefaultFactoryFor; import org.infinispan.notifications.cachelistener.cluster.impl.BatchingClusterEventManagerImpl; /** * Constructs the data container. * * @author William Burns * @since 7.1 */ @DefaultFactoryFor(classes = ClusterEventManager.class) public class ClusterEventManagerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { return new BatchingClusterEventManagerImpl(); } }
730
32.227273
119
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/cluster/impl/ClusterEventManagerStub.java
package org.infinispan.notifications.cachelistener.cluster.impl; import java.util.Collection; import java.util.UUID; import java.util.concurrent.CompletionStage; import org.infinispan.factories.annotations.SurvivesRestarts; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.notifications.cachelistener.cluster.ClusterEvent; import org.infinispan.notifications.cachelistener.cluster.ClusterEventManager; import org.infinispan.remoting.transport.Address; import org.infinispan.commons.util.concurrent.CompletableFutures; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ @Scope(Scopes.NAMED_CACHE) @SurvivesRestarts public class ClusterEventManagerStub<K, V> implements ClusterEventManager<K, V> { @Override public void addEvents(Object batchIdentifier, Address target, UUID identifier, Collection<ClusterEvent<K, V>> clusterEvents, boolean sync) { } @Override public CompletionStage<Void> sendEvents(Object batchIdentifier) { return CompletableFutures.completedNull(); } @Override public void dropEvents(Object batchIdentifier) { } }
1,145
30.833333
143
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/cluster/impl/BatchingClusterEventManagerImpl.java
package org.infinispan.notifications.cachelistener.cluster.impl; import java.lang.invoke.MethodHandles; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import org.infinispan.commands.CommandsFactory; import org.infinispan.configuration.cache.ClusteringConfiguration; import org.infinispan.configuration.cache.Configuration; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.factories.impl.ComponentRef; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.cachelistener.cluster.ClusterEvent; import org.infinispan.notifications.cachelistener.cluster.ClusterEventManager; import org.infinispan.notifications.cachelistener.cluster.MultiClusterEventCommand; import org.infinispan.remoting.inboundhandler.DeliverOrder; import org.infinispan.remoting.responses.ValidResponse; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.rpc.RpcOptions; import org.infinispan.remoting.transport.Address; import org.infinispan.remoting.transport.impl.SingleResponseCollector; import org.infinispan.util.concurrent.AggregateCompletionStage; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; @Scope(Scopes.NAMED_CACHE) public class BatchingClusterEventManagerImpl<K, V> implements ClusterEventManager<K, V> { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); @Inject EmbeddedCacheManager cacheManager; @Inject Configuration configuration; @Inject RpcManager rpcManager; @Inject ComponentRef<CommandsFactory> commandsFactory; private long timeout; private final Map<Object, EventContext<K, V>> eventContextMap = new ConcurrentHashMap<>(); @Start public void start() { timeout = configuration.clustering().remoteTimeout(); configuration.clustering().attributes().attribute(ClusteringConfiguration.REMOTE_TIMEOUT) .addListener((a, ignored) -> { timeout = a.get(); }); } @Override public void addEvents(Object batchIdentifier, Address target, UUID identifier, Collection<ClusterEvent<K, V>> events, boolean sync) { eventContextMap.compute(batchIdentifier, (ignore, eventContext) -> { if (eventContext == null) { if (log.isTraceEnabled()) { log.tracef("Created new unicast event context for identifier %s", batchIdentifier); } eventContext = new UnicastEventContext<>(); } if (log.isTraceEnabled()) { log.tracef("Adding new events %s for identifier %s", events, batchIdentifier); } eventContext.addTargets(target, identifier, events, sync); return eventContext; }); } @Override public CompletionStage<Void> sendEvents(Object batchIdentifier) { EventContext<K, V> ctx = eventContextMap.remove(batchIdentifier); if (ctx != null) { if (log.isTraceEnabled()) { log.tracef("Sending events for identifier %s", batchIdentifier); } return ctx.sendToTargets(); } else if (log.isTraceEnabled()) { log.tracef("No events to send for identifier %s", batchIdentifier); } return CompletableFutures.completedNull(); } @Override public void dropEvents(Object batchIdentifier) { EventContext<K, V> ctx = eventContextMap.remove(batchIdentifier); if (log.isTraceEnabled()) { if (ctx != null) { log.tracef("Dropping events for identifier %s", batchIdentifier); } else { log.tracef("No events to drop for identifier %s", batchIdentifier); } } } private interface EventContext<K, V> { void addTargets(Address address, UUID identifier, Collection<ClusterEvent<K, V>> events, boolean sync); CompletionStage<Void> sendToTargets(); } protected class UnicastEventContext<K, V> implements EventContext<K, V> { protected final Map<Address, TargetEvents<K, V>> targets = new HashMap<>(); @Override public void addTargets(Address address, UUID identifier, Collection<ClusterEvent<K, V>> events, boolean sync) { TargetEvents<K, V> targetEvents = targets.get(address); if (targetEvents == null) { targetEvents = new TargetEvents<>(); targets.put(address, targetEvents); } Map<UUID, Collection<ClusterEvent<K, V>>> listenerEvents = targetEvents.events; // This shouldn't be set before, so do put instead of doing get then put Collection<ClusterEvent<K, V>> prevEvents = listenerEvents.put(identifier, events); if (prevEvents != null) { // If we have multiple events to the same node for the same uuid condense them. This shouldn't really happen... events.addAll(prevEvents); } if (sync) { targetEvents.sync = true; } } @Override public CompletionStage<Void> sendToTargets() { AggregateCompletionStage<Void> aggregateCompletionStage = CompletionStages.aggregateCompletionStage(); CommandsFactory factory = commandsFactory.running(); for (Entry<Address, TargetEvents<K, V>> entry : targets.entrySet()) { TargetEvents<K, V> multiEvents = entry.getValue(); MultiClusterEventCommand<K, V> callable = factory.buildMultiClusterEventCommand(multiEvents.events); CompletionStage<ValidResponse> stage = rpcManager.invokeCommand(entry.getKey(), callable, SingleResponseCollector.validOnly(), new RpcOptions(DeliverOrder.NONE, timeout, TimeUnit.MILLISECONDS)); if (multiEvents.sync) { aggregateCompletionStage.dependsOn(stage); } } return aggregateCompletionStage.freeze(); } } private static class TargetEvents<K, V> { final Map<UUID, Collection<ClusterEvent<K, V>>> events = new HashMap<>(); boolean sync = false; } }
6,481
41.366013
138
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/CacheEntryVisited.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when a cache entry is visited. * <p/> * Methods annotated with this annotation should accept a single parameter, a {@link * org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent} otherwise a {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your listener. * <p/> * Locking: notification is performed WITHOUT locks on the given key (unless {@link org.infinispan.context.Flag#FORCE_WRITE_LOCK} is used for this call). * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @see org.infinispan.notifications.Listener * @since 4.0 */ // ensure this annotation is available at runtime. @Retention(RetentionPolicy.RUNTIME) // ensure that this annotation is applied to classes. @Target(ElementType.METHOD) public @interface CacheEntryVisited { }
1,310
42.7
154
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/package-info.java
/** * {@link org.infinispan.Cache}-specific listener annotations * * @api.public */ package org.infinispan.notifications.cachelistener.annotation;
151
20.714286
62
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/CacheEntryActivated.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when a cache entry is activated. * <p/> * Methods annotated with this annotation should be public and take in a single parameter, a {@link * org.infinispan.notifications.cachelistener.event.CacheEntryActivatedEvent} otherwise an {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your cache listener. * Locking: notification is performed WITH locks on the given key. * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @see org.infinispan.notifications.Listener * @see CacheEntryPassivated * @since 4.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CacheEntryActivated { }
1,165
40.642857
116
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/TopologyChanged.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.infinispan.distribution.DistributionManager; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.notifications.IncorrectListenerException; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent; /** * This annotation should be used on methods that need to be notified when the {@link ConsistentHash} implementation * in use by the {@link DistributionManager} changes due to a change in cluster topology. * This is not fired for {@link org.infinispan.configuration.cache.CacheMode#LOCAL} caches. * <p/> * Methods annotated with this annotation should accept a single parameter, a {@link TopologyChangedEvent} otherwise a * {@link IncorrectListenerException} will be thrown when registering your listener. * <p/> * Note that methods marked with this annotation will be fired <i>before</i> and <i>after</i> the updated {@link ConsistentHash} * is installed, i.e., your method will be called twice, with {@link Event#isPre()} being set to <tt>true</tt> as well * as <tt>false</tt>. * <p/> * * @author Manik Surtani * @see org.infinispan.notifications.Listener * @since 5.0 */ // ensure this annotation is available at runtime. @Retention(RetentionPolicy.RUNTIME) // ensure that this annotation is applied to classes. @Target(ElementType.METHOD) public @interface TopologyChanged { }
1,642
43.405405
128
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/TransactionCompleted.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when the cache is called to participate in a * transaction and the transaction completes, either with a commit or a rollback. * <p/> * Methods annotated with this annotation should accept a single parameter, a {@link * org.infinispan.notifications.cachelistener.event.TransactionCompletedEvent} otherwise a {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your listener. * <p/> * Note that methods marked with this annotation will only be fired <i>after the fact</i>, i.e., your method will never * be called with {@link org.infinispan.notifications.cachelistener.event.Event#isPre()} being set to <tt>true</tt>. * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @see org.infinispan.notifications.Listener * @since 4.0 */ // ensure this annotation is available at runtime. @Retention(RetentionPolicy.RUNTIME) // ensure that this annotation is applied to classes. @Target(ElementType.METHOD) public @interface TransactionCompleted { }
1,493
45.6875
119
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/CacheEntryRemoved.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when a cache entry is removed from the cache. * <p/> * Methods annotated with this annotation should accept a single parameter, a {@link * org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent} otherwise a {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your listener. * <p/> * Locking: notification is performed WITH locks on the given key. * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @see org.infinispan.notifications.Listener * @since 4.0 */ // ensure this annotation is available at runtime. @Retention(RetentionPolicy.RUNTIME) // ensure that this annotation is applied to classes. @Target(ElementType.METHOD) public @interface CacheEntryRemoved { }
1,235
41.62069
116
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/CacheEntryLoaded.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.infinispan.notifications.IncorrectListenerException; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.event.CacheEntryLoadedEvent; import org.infinispan.persistence.spi.CacheLoader; /** * This annotation should be used on methods that need to be notified when a cache entry is loaded from a {@link * CacheLoader}. * <p/> * Methods annotated with this annotation should be public and take in a single parameter, a {@link * CacheEntryLoadedEvent} otherwise an {@link IncorrectListenerException} will be thrown when registering your cache * listener. * <p/> * Locking: notification is performed WITH locks on the given key. * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @see Listener * @since 4.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CacheEntryLoaded { }
1,296
38.30303
116
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/CacheEntryPassivated.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when cache entries are passivated. * <p/> * Methods annotated with this annotation should accept a single parameter, a {@link * org.infinispan.notifications.cachelistener.event.CacheEntryPassivatedEvent} otherwise a {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your listener. * <p/> * Locking: notification is performed WITH locks on the given key. * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * * @author Manik Surtani * @author Galder Zamarreño * @see org.infinispan.notifications.Listener * @since 5.0 */ // ensure this annotation is available at runtime. @Retention(RetentionPolicy.RUNTIME) // ensure that this annotation is applied to classes. @Target(ElementType.METHOD) public @interface CacheEntryPassivated { }
1,224
38.516129
116
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/PersistenceAvailabilityChanged.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Use this annotation on methods that require notification when the availability of the PersistenceManager changes. * When Cache stores are configured, but the connection to at least one store is lost, the PersistenceManager becomes * unavailable. As a result, {@link org.infinispan.persistence.spi.StoreUnavailableException} is thrown on all read/write * operations that require the PersistenceManager until all stores become available again. * <p/> * Methods that use this annotation should be public and take one parameter, {@link * org.infinispan.notifications.cachelistener.event.CacheEntryActivatedEvent}. Otherwise {@link * org.infinispan.notifications.IncorrectListenerException} is thrown when registering your cache listener. * Locking: notification is performed WITH locks on the given key. * <p/> * If the listener throws any exceptions, the call aborts. No other listeners are called. Any transactions in progress * are rolled back. * * @author Ryan Emerson * @see org.infinispan.notifications.Listener * @since 9.3 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface PersistenceAvailabilityChanged { }
1,396
45.566667
121
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/CacheEntryModified.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when a cache entry has been modified. * <p/> * Methods annotated with this annotation should be public and take in a single parameter, a {@link * org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent} otherwise an {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your cache listener. * <p/> * Locking: notification is performed WITH locks on the given key. * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @see org.infinispan.notifications.Listener * @since 4.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CacheEntryModified { }
1,144
41.407407
116
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/CacheEntriesEvicted.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when cache entries are evicted. * <p/> * Methods annotated with this annotation should be public and take in a single parameter, a {@link * org.infinispan.notifications.cachelistener.event.CacheEntriesEvictedEvent} otherwise an {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your cache listener. * <p/> * Locking: notification is performed WITH locks on the given key. * <p/> * * @author Manik Surtani * @author Galder Zamarreño * @see org.infinispan.notifications.Listener * @see CacheEntryLoaded * @since 5.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CacheEntriesEvicted { }
986
34.25
112
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/DataRehashed.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.infinispan.notifications.IncorrectListenerException; import org.infinispan.notifications.cachelistener.event.DataRehashedEvent; import org.infinispan.notifications.cachelistener.event.Event; /** * This annotation should be used on methods that need to be notified when a rehash starts or ends. * A "rehash" (or "rebalance") is the interval during which nodes are transferring data between each * other. When the event with {@code pre = false} is fired all nodes have received all data; Some nodes can * still keep old data, though - old data cleanup is executed after this event is fired. * <p/> * Methods annotated with this annotation should accept a single parameter, a {@link DataRehashedEvent} otherwise a * {@link IncorrectListenerException} will be thrown when registering your listener. * <p/> * Note that methods marked with this annotation will be fired <i>before</i> and <i>after</i> rehashing takes place, * i.e., your method will be called twice, with {@link Event#isPre()} being set to <tt>true</tt> as well as <tt>false</tt>. * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * * @author Manik Surtani * @see org.infinispan.notifications.Listener * @since 5.0 */ // ensure this annotation is available at runtime. @Retention(RetentionPolicy.RUNTIME) // ensure that this annotation is applied to classes. @Target(ElementType.METHOD) public @interface DataRehashed { }
1,767
46.783784
123
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/TransactionRegistered.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when the cache is called to participate in a * transaction and registers a {@link javax.transaction.Synchronization} with a registered {@link * javax.transaction.TransactionManager}. * <p/> * Methods annotated with this annotation should accept a single parameter, a {@link * org.infinispan.notifications.cachelistener.event.TransactionRegisteredEvent} otherwise a {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your listener. * <p/> * Note that methods marked with this annotation will only be fired <i>after the fact</i>, i.e., your method will never * be called with {@link org.infinispan.notifications.cachelistener.event.Event#isPre()} being set to <tt>true</tt>. * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @see org.infinispan.notifications.Listener * @since 4.0 */ // ensure this annotation is available at runtime. @Retention(RetentionPolicy.RUNTIME) // ensure that this annotation is applied to classes. @Target(ElementType.METHOD) public @interface TransactionRegistered { }
1,553
46.090909
119
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/CacheEntryExpired.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when a cache entry is expired * <p/> * Methods annotated with this annotation should be public and take in a single parameter, a {@link * org.infinispan.notifications.cachelistener.event.CacheEntryExpiredEvent} otherwise an {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your cache listener. * <p/> * Locking: there is no guarantee as to whether the lock is acquired for this key, however there is internal * guarantees to make sure these events are not out of order * <p/> * It is possible yet highly unlikely to receive this event right after a remove event even though the value * was previously removed. This can happen in the case when an expired entry in a store (not present in memory) is * found by the reaper thread and a remove occurs at the same time. * @author William Burns * @see org.infinispan.notifications.Listener * @since 8.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CacheEntryExpired { }
1,321
44.586207
115
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/CacheEntryInvalidated.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when a cache entry is invalidated. * <p/> * Methods annotated with this annotation should be public and take in a single parameter, a {@link * org.infinispan.notifications.cachelistener.event.CacheEntryInvalidatedEvent} otherwise an {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your cache listener. * <p/> * Locking: notification is performed WITH locks on the given key. * <p> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @see org.infinispan.notifications.Listener * @since 4.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CacheEntryInvalidated { }
1,151
40.142857
116
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/PartitionStatusChanged.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.infinispan.configuration.cache.CacheMode; /** * This annotation should be used on methods that need to be notified when the * {@link org.infinispan.partitionhandling.AvailabilityMode} in use by the * {@link org.infinispan.partitionhandling.impl.PartitionHandlingManager} changes due to a change in cluster topology. * This is only fired in a {@link CacheMode#DIST_SYNC}, {@link CacheMode#DIST_ASYNC}, {@link CacheMode#REPL_SYNC} or * {@link CacheMode#REPL_ASYNC} configured cache. * <p/> * Methods annotated with this annotation should accept a single parameter, a * {@link org.infinispan.notifications.cachelistener.event.PartitionStatusChangedEvent} otherwise a * {@link org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your listener. * <p/> * Note that methods marked with this annotation will be fired <i>before</i> and <i>after</i> the updated * {@link org.infinispan.partitionhandling.AvailabilityMode} * is updated, i.e., your method will be called twice, with * {@link org.infinispan.notifications.cachelistener.event.Event#isPre()} being set to <tt>true</tt> as well * as <tt>false</tt>. * <p/> * * @author William Burns * @see org.infinispan.notifications.Listener * @since 7.0 */ // ensure this annotation is available at runtime. @Retention(RetentionPolicy.RUNTIME) // ensure that this annotation is applied to classes. @Target(ElementType.METHOD) public @interface PartitionStatusChanged { }
1,704
43.868421
118
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachelistener/annotation/CacheEntryCreated.java
package org.infinispan.notifications.cachelistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when a cache entry is created. * <p/> * Methods annotated with this annotation should be public and take in a single parameter, a {@link * org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent} otherwise an {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your cache listener. * <p/> * Locking: notification is performed WITH locks on the given key. * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @see org.infinispan.notifications.Listener * @since 4.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CacheEntryCreated { }
1,138
39.678571
116
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/CacheManagerNotifierImpl.java
package org.infinispan.notifications.cachemanagerlistener; import java.lang.annotation.Annotation; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.CopyOnWriteArrayList; import jakarta.transaction.Transaction; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.SurvivesRestarts; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachemanagerlistener.annotation.CacheStarted; import org.infinispan.notifications.cachemanagerlistener.annotation.CacheStopped; import org.infinispan.notifications.cachemanagerlistener.annotation.ConfigurationChanged; import org.infinispan.notifications.cachemanagerlistener.annotation.Merged; import org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged; import org.infinispan.notifications.cachemanagerlistener.event.CacheStartedEvent; import org.infinispan.notifications.cachemanagerlistener.event.CacheStoppedEvent; import org.infinispan.notifications.cachemanagerlistener.event.ConfigurationChangedEvent; import org.infinispan.notifications.cachemanagerlistener.event.Event; import org.infinispan.notifications.cachemanagerlistener.event.MergeEvent; import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent; import org.infinispan.notifications.cachemanagerlistener.event.impl.EventImpl; import org.infinispan.notifications.impl.AbstractListenerImpl; import org.infinispan.notifications.impl.ListenerInvocation; import org.infinispan.remoting.transport.Address; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Global, shared notifications on the cache manager. * * @author Manik Surtani * @since 4.0 */ @Scope(Scopes.GLOBAL) @SurvivesRestarts public class CacheManagerNotifierImpl extends AbstractListenerImpl<Event, ListenerInvocation<Event>> implements CacheManagerNotifier { private static final Log log = LogFactory.getLog(CacheManagerNotifierImpl.class); private static final Map<Class<? extends Annotation>, Class<?>> allowedListeners = new HashMap<>(4); static { allowedListeners.put(CacheStarted.class, CacheStartedEvent.class); allowedListeners.put(CacheStopped.class, CacheStoppedEvent.class); allowedListeners.put(ViewChanged.class, ViewChangedEvent.class); allowedListeners.put(Merged.class, MergeEvent.class); allowedListeners.put(ConfigurationChanged.class, ConfigurationChangedEvent.class); } final List<ListenerInvocation<Event>> cacheStartedListeners = new CopyOnWriteArrayList<>(); final List<ListenerInvocation<Event>> cacheStoppedListeners = new CopyOnWriteArrayList<>(); final List<ListenerInvocation<Event>> viewChangedListeners = new CopyOnWriteArrayList<>(); final List<ListenerInvocation<Event>> mergeListeners = new CopyOnWriteArrayList<>(); final List<ListenerInvocation<Event>> configurationChangedListeners = new CopyOnWriteArrayList<>(); @Inject EmbeddedCacheManager cacheManager; public CacheManagerNotifierImpl() { listenersMap.put(CacheStarted.class, cacheStartedListeners); listenersMap.put(CacheStopped.class, cacheStoppedListeners); listenersMap.put(ViewChanged.class, viewChangedListeners); listenersMap.put(Merged.class, mergeListeners); listenersMap.put(ConfigurationChanged.class, configurationChangedListeners); } protected class DefaultBuilder extends AbstractInvocationBuilder { @Override public ListenerInvocation<Event> build() { return new ListenerInvocationImpl<>(target, method, sync, classLoader, subject); } } @Override public CompletionStage<Void> notifyViewChange(List<Address> members, List<Address> oldMembers, Address myAddress, int viewId) { if (!viewChangedListeners.isEmpty()) { EventImpl e = new EventImpl(); e.setLocalAddress(myAddress); e.setMergeView(false); e.setViewId(viewId); e.setNewMembers(members); e.setOldMembers(oldMembers); e.setCacheManager(cacheManager); e.setType(Event.Type.VIEW_CHANGED); return invokeListeners(e, viewChangedListeners); } return CompletableFutures.completedNull(); } @Override public CompletionStage<Void> notifyMerge(List<Address> members, List<Address> oldMembers, Address myAddress, int viewId, List<List<Address>> subgroupsMerged) { if (!mergeListeners.isEmpty()) { EventImpl e = new EventImpl(); e.setLocalAddress(myAddress); e.setViewId(viewId); e.setMergeView(true); e.setNewMembers(members); e.setOldMembers(oldMembers); e.setCacheManager(cacheManager); e.setSubgroupsMerged(subgroupsMerged); e.setType(Event.Type.MERGED); return invokeListeners(e, mergeListeners); } return CompletableFutures.completedNull(); } @Override public CompletionStage<Void> notifyCacheStarted(String cacheName) { if (!cacheStartedListeners.isEmpty()) { EventImpl e = new EventImpl(); e.setCacheName(cacheName); e.setCacheManager(cacheManager); e.setType(Event.Type.CACHE_STARTED); return invokeListeners(e, cacheStartedListeners); } return CompletableFutures.completedNull(); } @Override public CompletionStage<Void> notifyCacheStopped(String cacheName) { if (!cacheStoppedListeners.isEmpty()) { EventImpl e = new EventImpl(); e.setCacheName(cacheName); e.setCacheManager(cacheManager); e.setType(Event.Type.CACHE_STOPPED); return invokeListeners(e, cacheStoppedListeners); } return CompletableFutures.completedNull(); } @Override public CompletionStage<Void> notifyConfigurationChanged(ConfigurationChangedEvent.EventType eventType, String entityType, String entityName) { if (!configurationChangedListeners.isEmpty()) { EventImpl e = new EventImpl(); e.setConfigurationEventType(eventType); e.setConfigurationEntityType(entityType); e.setConfigurationEntityName(entityName); e.setType(Event.Type.CONFIGURATION_CHANGED); return invokeListeners(e, configurationChangedListeners); } return CompletableFutures.completedNull(); } @Override protected void handleException(Throwable t) { // Only cache entry-related listeners should be able to throw an exception to veto the operation. // Just log the exception thrown by the invoker, it should contain all the relevant information. log.failedInvokingCacheManagerListener(t); } @Override public CompletionStage<Void> addListenerAsync(Object listener) { validateAndAddListenerInvocations(listener, new DefaultBuilder()); return CompletableFutures.completedNull(); } @Override public CompletionStage<Void> removeListenerAsync(Object listener) { removeListenerFromMaps(listener); return CompletableFutures.completedNull(); } @Override protected Log getLog() { return log; } @Override protected Map<Class<? extends Annotation>, Class<?>> getAllowedMethodAnnotations(Listener l) { return allowedListeners; } @Override protected final Transaction suspendIfNeeded() { return null; //no-op } @Override protected final void resumeIfNeeded(Transaction transaction) { //no-op } public void start() { // no-op } }
7,787
38.532995
162
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/package-info.java
/** * {@link CacheManager}-specific notifications and eventing. */ package org.infinispan.notifications.cachemanagerlistener;
128
24.8
60
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/CacheManagerNotifier.java
package org.infinispan.notifications.cachemanagerlistener; import java.lang.annotation.Annotation; import java.util.List; import java.util.concurrent.CompletionStage; import org.infinispan.notifications.Listenable; import org.infinispan.notifications.cachemanagerlistener.event.ConfigurationChangedEvent; import org.infinispan.remoting.transport.Address; /** * Notifications for the cache manager * * @author Manik Surtani * @since 4.0 */ public interface CacheManagerNotifier extends Listenable { /** * Notifies all registered listeners of a viewChange event. Note that viewChange notifications are ALWAYS sent * immediately. */ CompletionStage<Void> notifyViewChange(List<Address> members, List<Address> oldMembers, Address myAddress, int viewId); CompletionStage<Void> notifyCacheStarted(String cacheName); CompletionStage<Void> notifyCacheStopped(String cacheName); CompletionStage<Void> notifyMerge(List<Address> members, List<Address> oldMembers, Address myAddress, int viewId, List<List<Address>> subgroupsMerged); /** * Notifies all registered listeners of a configurationChange event. * @param eventType the type of event (CREATE or REMOVE) * @param entityType the type of configuration that has changed (e.g. cache, counter, ...) * @param entityName the name of the configuration item that has been changed * @return a {@link CompletionStage} which completes when the notification has been sent. */ CompletionStage<Void> notifyConfigurationChanged(ConfigurationChangedEvent.EventType eventType, String entityType, String entityName); /** * Returns whether there is at least one listener registered for the given annotation * @param annotationClass annotation to test for * @return true if there is a listener mapped to the annotation, otherwise false */ boolean hasListener(Class<? extends Annotation> annotationClass); }
1,925
40.869565
154
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/event/package-info.java
/** * {@link org.infinispan.manager.EmbeddedCacheManager}-specific listener events * * @api.public */ package org.infinispan.notifications.cachemanagerlistener.event;
171
23.571429
79
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/event/Event.java
package org.infinispan.notifications.cachemanagerlistener.event; import org.infinispan.manager.EmbeddedCacheManager; /** * Common characteristics of events that occur on a cache manager * * @author Manik Surtani * @since 4.0 */ public interface Event { enum Type { CACHE_STARTED, CACHE_STOPPED, VIEW_CHANGED, MERGED, CONFIGURATION_CHANGED } EmbeddedCacheManager getCacheManager(); Type getType(); }
426
20.35
79
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/event/CacheStartedEvent.java
package org.infinispan.notifications.cachemanagerlistener.event; /** * This event is passed in to any method annotated with {@link org.infinispan.notifications.cachemanagerlistener.annotation.CacheStarted}. * * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @since 4.0 */ public interface CacheStartedEvent extends Event { String getCacheName(); }
371
30
138
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/event/ViewChangedEvent.java
package org.infinispan.notifications.cachemanagerlistener.event; import java.util.List; import org.infinispan.remoting.transport.Address; /** * This event is passed in to any method annotated with {@link org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged}. * It represents a JGroups view change event. * * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @since 4.0 */ public interface ViewChangedEvent extends Event { /** * Gets the current list of members. * * @return the new view associated with this view change. List cannot be null. */ List<Address> getNewMembers(); /** * Gets the previous list of members. * * @return the old view associated with this view change. List cannot be null. */ List<Address> getOldMembers(); Address getLocalAddress(); /** * Get JGroups view id. * @return */ int getViewId(); boolean isMergeView(); }
953
22.85
137
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/event/ConfigurationChangedEvent.java
package org.infinispan.notifications.cachemanagerlistener.event; /** * This event is passed in to any method annotated with {@link org.infinispan.notifications.cachemanagerlistener.annotation.ConfigurationChanged}. * * @author Tristan Tarrant * @since 13.0 */ public interface ConfigurationChangedEvent extends Event { enum EventType { CREATE, UPDATE, REMOVE } EventType getConfigurationEventType(); String getConfigurationEntityType(); String getConfigurationEntityName(); }
518
22.590909
146
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/event/CacheStoppedEvent.java
package org.infinispan.notifications.cachemanagerlistener.event; /** * This event is passed in to any method annotated with {@link org.infinispan.notifications.cachemanagerlistener.annotation.CacheStopped}. * * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @since 4.0 */ public interface CacheStoppedEvent extends Event { String getCacheName(); }
371
30
138
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/event/MergeEvent.java
package org.infinispan.notifications.cachemanagerlistener.event; import java.util.List; import org.infinispan.remoting.transport.Address; /** * This event is passed in to any method annotated with {@link org.infinispan.notifications.cachemanagerlistener.annotation.Merged}. * * @author Manik Surtani * @version 4.2 */ public interface MergeEvent extends ViewChangedEvent { List<List<Address>> getSubgroupsMerged(); }
428
25.8125
132
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/event/impl/EventImpl.java
package org.infinispan.notifications.cachemanagerlistener.event.impl; import java.util.Collections; import java.util.List; import java.util.Objects; import org.infinispan.commons.util.Util; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.cachemanagerlistener.event.CacheStartedEvent; import org.infinispan.notifications.cachemanagerlistener.event.CacheStoppedEvent; import org.infinispan.notifications.cachemanagerlistener.event.ConfigurationChangedEvent; import org.infinispan.notifications.cachemanagerlistener.event.MergeEvent; import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent; import org.infinispan.remoting.transport.Address; /** * Implementation of cache manager events * * @author Manik Surtani * @since 4.0 */ public class EventImpl implements CacheStartedEvent, CacheStoppedEvent, ViewChangedEvent, MergeEvent, ConfigurationChangedEvent { private String cacheName; private EmbeddedCacheManager cacheManager; private Type type; private List<Address> newMembers, oldMembers; private Address localAddress; private int viewId; private List<List<Address>> subgroupsMerged; private boolean mergeView; private String configurationEntityType; private String configurationEntityName; private EventType configurationEventType; public EventImpl() { } public EventImpl(String cacheName, EmbeddedCacheManager cacheManager, Type type, List<Address> newMemberList, List<Address> oldMemberList, Address localAddress, int viewId) { this.cacheName = cacheName; this.cacheManager = cacheManager; this.type = type; this.newMembers = newMemberList; this.oldMembers = oldMemberList; this.localAddress = localAddress; this.viewId = viewId; } @Override public String getCacheName() { return cacheName; } public void setCacheName(String cacheName) { this.cacheName = cacheName; } @Override public EmbeddedCacheManager getCacheManager() { return cacheManager; } public void setCacheManager(EmbeddedCacheManager cacheManager) { this.cacheManager = cacheManager; } @Override public Type getType() { return type; } public void setType(Type type) { this.type = type; } @Override public List<Address> getNewMembers() { if (newMembers == null) { return Collections.emptyList(); } return newMembers; } public void setNewMembers(List<Address> newMembers) { this.newMembers = newMembers; } public void setOldMembers(List<Address> oldMembers) { this.oldMembers = oldMembers; } @Override public List<Address> getOldMembers() { if (oldMembers == null) { return Collections.emptyList(); } return this.oldMembers; } @Override public Address getLocalAddress() { return localAddress; } @Override public int getViewId() { return viewId; } public void setViewId(int viewId) { this.viewId = viewId; } public void setLocalAddress(Address localAddress) { this.localAddress = localAddress; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EventImpl event = (EventImpl) o; if (viewId != event.viewId) return false; if (!Objects.equals(cacheName, event.cacheName)) return false; if (!Objects.equals(localAddress, event.localAddress)) return false; if (!Objects.equals(newMembers, event.newMembers)) return false; if (!Objects.equals(oldMembers, event.oldMembers)) return false; if (!Util.safeEquals(subgroupsMerged, event.subgroupsMerged)) return false; if (type != event.type) return false; return true; } @Override public int hashCode() { int result = cacheName != null ? cacheName.hashCode() : 0; result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (newMembers != null ? newMembers.hashCode() : 0); result = 31 * result + (oldMembers != null ? oldMembers.hashCode() : 0); result = 31 * result + (localAddress != null ? localAddress.hashCode() : 0); result = 31 * result + viewId; result = 31 * result + (subgroupsMerged == null ? 0 : subgroupsMerged.hashCode()); result = 31 * result + (mergeView ? 1 : 0); return result; } @Override public String toString() { return "EventImpl{" + "type=" + type + ", newMembers=" + newMembers + ", oldMembers=" + oldMembers + ", localAddress=" + localAddress + ", viewId=" + viewId + ", subgroupsMerged=" + subgroupsMerged + ", mergeView=" + mergeView + '}'; } public void setSubgroupsMerged(List<List<Address>> subgroupsMerged) { this.subgroupsMerged = subgroupsMerged; } @Override public List<List<Address>> getSubgroupsMerged() { return this.subgroupsMerged; } @Override public boolean isMergeView() { return mergeView; } public void setMergeView(boolean b) { mergeView = b; } public void setConfigurationEventType(EventType eventType) { configurationEventType = eventType; } public void setConfigurationEntityType(String type) { configurationEntityType = type; } public void setConfigurationEntityName(String name) { configurationEntityName = name; } @Override public EventType getConfigurationEventType() { return configurationEventType; } @Override public String getConfigurationEntityType() { return configurationEntityType; } @Override public String getConfigurationEntityName() { return configurationEntityName; } }
5,853
27.280193
177
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/annotation/package-info.java
/** * {@link org.infinispan.manager.EmbeddedCacheManager}-specific listener annotations * * @api.public */ package org.infinispan.notifications.cachemanagerlistener.annotation;
181
25
84
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/annotation/Merged.java
package org.infinispan.notifications.cachemanagerlistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when the cache is used in a cluster and the * cluster topology experiences a merge event after a cluster split. * <p/> * Methods annotated with this annotation should accept a single parameter, a {@link * org.infinispan.notifications.cachemanagerlistener.event.MergeEvent} otherwise a {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your listener. * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @see org.infinispan.notifications.Listener * @since 4.2 */ // ensure this annotation is available at runtime. @Retention(RetentionPolicy.RUNTIME) // ensure that this annotation is applied to classes. @Target(ElementType.METHOD) public @interface Merged { }
1,219
41.068966
116
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/annotation/CacheStarted.java
package org.infinispan.notifications.cachemanagerlistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when a cache is started. * <p/> * Methods annotated with this annotation should accept a single parameter, a {@link * org.infinispan.notifications.cachemanagerlistener.event.CacheStartedEvent} otherwise a {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your listener. * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * * * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @see org.infinispan.notifications.Listener * @since 4.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CacheStarted { }
1,042
37.62963
116
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/annotation/ViewChanged.java
package org.infinispan.notifications.cachemanagerlistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when the cache is used in a cluster and the * cluster topology changes (i.e., a member joins or leaves the cluster). * <p/> * Methods annotated with this annotation should accept a single parameter, a {@link * org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent} otherwise a {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your listener. * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @see org.infinispan.notifications.Listener * @since 4.0 */ // ensure this annotation is available at runtime. @Retention(RetentionPolicy.RUNTIME) // ensure that this annotation is applied to classes. @Target(ElementType.METHOD) public @interface ViewChanged { }
1,235
41.62069
116
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/annotation/CacheStopped.java
package org.infinispan.notifications.cachemanagerlistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when a cache is stopped. * <p/> * Methods annotated with this annotation should accept a single parameter, a {@link * org.infinispan.notifications.cachemanagerlistener.event.CacheStoppedEvent} otherwise a {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your listener. * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * * @author <a href="mailto:manik@jboss.org">Manik Surtani</a> * @see org.infinispan.notifications.Listener * @since 4.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CacheStopped { }
1,039
39
116
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/cachemanagerlistener/annotation/ConfigurationChanged.java
package org.infinispan.notifications.cachemanagerlistener.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation should be used on methods that need to be notified when a configuration is changed. * <p/> * Methods annotated with this annotation should accept a single parameter, a {@link * org.infinispan.notifications.cachemanagerlistener.event.ConfigurationChangedEvent} otherwise a {@link * org.infinispan.notifications.IncorrectListenerException} will be thrown when registering your listener. * <p/> * Any exceptions thrown by the listener will abort the call. Any other listeners not yet called will not be called, * and any transactions in progress will be rolled back. * * * @author Tristan Tarrant * @see org.infinispan.notifications.Listener * @since 13.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ConfigurationChanged { }
1,032
37.259259
116
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/impl/ListenerInvocation.java
package org.infinispan.notifications.impl; import java.util.concurrent.CompletionStage; /** * Defines simple listener invocation. * * @param <T> The type of event to listen to * @author wburns * @since 7.0 */ public interface ListenerInvocation<T> { /** * Invokes the event * @param event * @return null if event was ignored or already complete otherwise the event will be completely notified when * the provided stage is completed */ CompletionStage<Void> invoke(T event); /** * The listener instance that is notified of events */ Object getTarget(); }
603
22.230769
112
java
null
infinispan-main/core/src/main/java/org/infinispan/notifications/impl/AbstractListenerImpl.java
package org.infinispan.notifications.impl; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.Executor; import java.util.function.Supplier; import javax.security.auth.Subject; import jakarta.transaction.Transaction; import org.infinispan.commons.CacheException; import org.infinispan.commons.util.ReflectionUtil; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.factories.KnownComponentNames; import org.infinispan.factories.annotations.ComponentName; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Stop; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.notifications.IncorrectListenerException; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.security.Security; import org.infinispan.util.concurrent.AggregateCompletionStage; import org.infinispan.util.concurrent.BlockingManager; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.logging.Log; /** * Functionality common to both {@link org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifierImpl} and * {@link org.infinispan.notifications.cachelistener.CacheNotifierImpl} * @param <T> Defines the type of event that will be used by the subclass * @param <L> Defines the type of ListenerInvocations that the subclasses use * @author Manik Surtani * @author William Burns */ @Scope(Scopes.NONE) public abstract class AbstractListenerImpl<T, L extends ListenerInvocation<T>> { @Inject @ComponentName(KnownComponentNames.ASYNC_NOTIFICATION_EXECUTOR) protected Executor asyncProcessor; @Inject BlockingManager blockingManager; protected final Map<Class<? extends Annotation>, List<L>> listenersMap = new HashMap<>(16, 0.99f); protected abstract class AbstractInvocationBuilder { protected Object target; protected Method method; protected Class<? extends Annotation> annotation; protected boolean sync; protected ClassLoader classLoader; protected Subject subject; public Object getTarget() { return target; } public Method getMethod() { return method; } public AbstractInvocationBuilder setAnnotation(Class<? extends Annotation> annotation) { this.annotation = annotation; return this; } public boolean isSync() { return sync; } public ClassLoader getClassLoader() { return classLoader; } public Subject getSubject() { return subject; } public AbstractInvocationBuilder setTarget(Object target) { this.target = target; return this; } public AbstractInvocationBuilder setMethod(Method method) { this.method = method; return this; } public AbstractInvocationBuilder setSync(boolean sync) { this.sync = sync; return this; } public AbstractInvocationBuilder setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; return this; } public AbstractInvocationBuilder setSubject(Subject subject) { this.subject = subject; return this; } public abstract L build(); } /** * Removes all listeners from the notifier */ @Stop(priority = 99) public void stop() { for (List<L> list : listenersMap.values()) { if (list != null) list.clear(); } } protected CompletionStage<Void> resumeOnCPU(CompletionStage<Void> stage, Object traceId) { return blockingManager.continueOnNonBlockingThread(stage, traceId); } protected abstract Log getLog(); protected abstract Map<Class<? extends Annotation>, Class<?>> getAllowedMethodAnnotations(Listener l); public boolean hasListener(Class<? extends Annotation> annotationClass) { List<L> annotations = listenersMap.get(annotationClass); return annotations != null && !annotations.isEmpty(); } protected List<L> getListenerCollectionForAnnotation(Class<? extends Annotation> annotation) { List<L> list = listenersMap.get(annotation); if (list == null) throw new CacheException("Unknown listener annotation: " + annotation); return list; } public abstract CompletionStage<Void> removeListenerAsync(Object listener); /** * If the given <b>stage</b> is null or normally completed returns the provided <b>aggregateCompletionStage</b> as is. * Otherwise the <b>stage</b> is used as a dependant for the provided <b>aggregateCompletionStage</b> if provided or a * new one is created that depends upon the provided <b>stage</b>. The existing or new <b>aggregateCompletionStage</b> is then * returned to the caller. * @param aggregateCompletionStage the existing composed stage or null * @param stage the stage to rely upon * @return null or a composed stage that relies upon the provided stage */ protected static AggregateCompletionStage<Void> composeStageIfNeeded( AggregateCompletionStage<Void> aggregateCompletionStage, CompletionStage<Void> stage) { if (stage != null && !CompletionStages.isCompletedSuccessfully(stage)) { if (aggregateCompletionStage == null) { aggregateCompletionStage = CompletionStages.aggregateCompletionStage(); } aggregateCompletionStage.dependsOn(stage); } return aggregateCompletionStage; } protected void removeListenerFromMaps(Object listener) { for (Class<? extends Annotation> annotation : getAllowedMethodAnnotations(testListenerClassValidity(listener.getClass())).keySet()) removeListenerInvocation(annotation, listener); } protected Set<L> removeListenerInvocation(Class<? extends Annotation> annotation, Object listener) { List<L> l = getListenerCollectionForAnnotation(annotation); Set<L> markedForRemoval = new HashSet<L>(4); for (L li : l) { if (listener.equals(li.getTarget())) markedForRemoval.add(li); } l.removeAll(markedForRemoval); return markedForRemoval; } public Set<Object> getListeners() { Set<Object> result = new HashSet<Object>(listenersMap.size()); for (List<L> list : listenersMap.values()) { for (ListenerInvocation li : list) result.add(li.getTarget()); } return Collections.unmodifiableSet(result); } /** * Loops through all valid methods on the object passed in, and caches the relevant methods as {@link * ListenerInvocation} for invocation by reflection. * The builder provided will be used to create the listener invocations. This method will set the target, subject * sync, and methods as needed. If other values are needed to be set they should be invoked before passing to this method. * * @param listener object to be considered as a listener. * @param builder The builder to use to build the invocation * @return {@code true} if annotated listener methods were found or {@code false} otherwise */ protected boolean validateAndAddListenerInvocations(Object listener, AbstractInvocationBuilder builder) { Listener l = testListenerClassValidity(listener.getClass()); boolean foundMethods = false; builder.setTarget(listener); builder.setSubject(Security.getSubject()); builder.setSync(l.sync()); Map<Class<? extends Annotation>, Class<?>> allowedListeners = getAllowedMethodAnnotations(l); // now try all methods on the listener for anything that we like. Note that only PUBLIC methods are scanned. for (Method m : listener.getClass().getMethods()) { // Skip bridge methods as we don't want to count them as well. if (!m.isSynthetic() || !m.isBridge()) { // loop through all valid method annotations for (Map.Entry<Class<? extends Annotation>, Class<?>> annotationEntry : allowedListeners.entrySet()) { final Class<? extends Annotation> annotationClass = annotationEntry.getKey(); if (m.isAnnotationPresent(annotationClass)) { final Class<?> eventClass = annotationEntry.getValue(); testListenerMethodValidity(m, eventClass, annotationClass.getName()); ReflectionUtil.setAccessible(m); builder.setMethod(m); builder.setAnnotation(annotationClass); L invocation = builder.build(); getLog().tracef("Add listener invocation %s for %s", invocation, annotationClass); getListenerCollectionForAnnotation(annotationClass).add(invocation); foundMethods = true; } } } } if (!foundMethods) getLog().noAnnotateMethodsFoundInListener(listener.getClass()); return foundMethods; } protected boolean validateAndAddFilterListenerInvocations(Object listener, AbstractInvocationBuilder builder, Set<Class<? extends Annotation>> filterAnnotations) { Listener l = testListenerClassValidity(listener.getClass()); boolean foundMethods = false; builder.setTarget(listener); builder.setSubject(Security.getSubject()); builder.setSync(l.sync()); Map<Class<? extends Annotation>, Class<?>> allowedListeners = getAllowedMethodAnnotations(l); // now try all methods on the listener for anything that we like. Note that only PUBLIC methods are scanned. for (Method m : listener.getClass().getMethods()) { // Skip bridge methods as we don't want to count them as well. if (!m.isSynthetic() || !m.isBridge()) { // loop through all valid method annotations for (Map.Entry<Class<? extends Annotation>, Class<?>> annotationEntry : allowedListeners.entrySet()) { final Class<? extends Annotation> annotationClass = annotationEntry.getKey(); if (m.isAnnotationPresent(annotationClass) && canApply(filterAnnotations, annotationClass)) { final Class<?> eventClass = annotationEntry.getValue(); testListenerMethodValidity(m, eventClass, annotationClass.getName()); ReflectionUtil.setAccessible(m); builder.setMethod(m); builder.setAnnotation(annotationClass); L invocation = builder.build(); getLog().tracef("Add listener invocation %s for %s", invocation, annotationClass); getListenerCollectionForAnnotation(annotationClass).add(invocation); foundMethods = true; } } } } if (!foundMethods) getLog().noAnnotateMethodsFoundInListener(listener.getClass()); return foundMethods; } public boolean canApply(Set<Class<? extends Annotation>> filterAnnotations, Class<? extends Annotation> annotationClass) { // Annotations such ViewChange or TransactionCompleted should be applied regardless return (annotationClass != CacheEntryCreated.class && annotationClass != CacheEntryModified.class && annotationClass != CacheEntryRemoved.class && annotationClass != CacheEntryExpired.class) || (filterAnnotations.contains(annotationClass)); } protected Set<Class<? extends Annotation>> findListenerCallbacks(Object listener) { // TODO: Partly duplicates validateAndAddListenerInvocations Set<Class<? extends Annotation>> listenerInterests = new HashSet<>(); Listener l = testListenerClassValidity(listener.getClass()); Map<Class<? extends Annotation>, Class<?>> allowedListeners = getAllowedMethodAnnotations(l); for (Method m : listener.getClass().getMethods()) { // Skip bridge methods as we don't want to count them as well. if (!m.isSynthetic() || !m.isBridge()) { // loop through all valid method annotations for (Map.Entry<Class<? extends Annotation>, Class<?>> annotationEntry : allowedListeners.entrySet()) { final Class<? extends Annotation> annotationClass = annotationEntry.getKey(); if (m.isAnnotationPresent(annotationClass)) { final Class<?> eventClass = annotationEntry.getValue(); testListenerMethodValidity(m, eventClass, annotationClass.getName()); ReflectionUtil.setAccessible(m); listenerInterests.add(annotationClass); } } } } return listenerInterests; } /** * Tests if a class is properly annotated as a CacheListener and returns the Listener annotation. * * @param listenerClass class to inspect * @return the Listener annotation */ protected static Listener testListenerClassValidity(Class<?> listenerClass) { Listener l = ReflectionUtil.getAnnotation(listenerClass, Listener.class); if (l == null) throw new IncorrectListenerException(String.format("Cache listener class %s must be annotated with org.infinispan.notifications.Listener", listenerClass.getName())); return l; } /** * Tests that a method is a valid listener method, that is that it has a single argument that is assignable to * <b>allowedParameter</b>. The method must also return either void or a CompletionStage, meaning the * method promises not block. * @param m method to test * @param allowedParameter what parameter is allowed for the method argument * @param annotationName name of the annotation * @throws IncorrectListenerException if the listener is not a valid target */ protected static void testListenerMethodValidity(Method m, Class<?> allowedParameter, String annotationName) { if (m.getParameterCount() != 1 || !m.getParameterTypes()[0].isAssignableFrom(allowedParameter)) throw new IncorrectListenerException("Methods annotated with " + annotationName + " must accept exactly one parameter, of assignable from type " + allowedParameter.getName()); Class<?> returnType = m.getReturnType(); if (!returnType.equals(void.class) && !CompletionStage.class.isAssignableFrom(returnType)) { throw new IncorrectListenerException("Methods annotated with " + annotationName + " should have a return type of void or CompletionStage."); } } protected CompletionStage<Void> invokeListeners(T event, Collection<L> listeners) { AggregateCompletionStage<Void> aggregateCompletionStage = null; for (L listener : listeners) { aggregateCompletionStage = composeStageIfNeeded(aggregateCompletionStage, invokeListener(listener, event)); } if (aggregateCompletionStage != null) { return resumeOnCPU(aggregateCompletionStage.freeze(), event); } return CompletableFutures.completedNull(); } private CompletionStage<Void> invokeListener(L listener, T e) { try { CompletionStage<Void> stage = listener.invoke(e); if (stage != null && !CompletionStages.isCompletedSuccessfully(stage)) { return stage.exceptionally(t -> { handleException(t); return null; }); } } catch (Exception x) { handleException(x); } return null; } protected void handleException(Throwable t) { } protected abstract Transaction suspendIfNeeded(); protected abstract void resumeIfNeeded(Transaction transaction); /** * Class that encapsulates a valid invocation for a given registered listener - containing a reference to the method * to be invoked as well as the target object. */ protected class ListenerInvocationImpl<A> implements ListenerInvocation<A> { final Object target; final Method method; final boolean sync; final WeakReference<ClassLoader> classLoader; final Subject subject; public ListenerInvocationImpl(Object target, Method method, boolean sync, ClassLoader classLoader, Subject subject) { this.target = target; this.method = method; this.sync = sync; this.classLoader = new WeakReference<>(classLoader); this.subject = subject; } @Override public CompletionStage<Void> invoke(final A event) { Supplier<Object> r = () -> { ClassLoader contextClassLoader = null; Transaction transaction = suspendIfNeeded(); if (classLoader.get() != null) { contextClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader.get()); } try { Object result; if (subject != null) { try { result = Security.doAs(subject, () -> { // Don't want to print out Subject as it could have sensitive information getLog().tracef("Invoking listener: %s passing event %s using subject", target, event); try { return method.invoke(target, event); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } }); } catch (Exception e) { Throwable cause = e.getCause(); if (cause instanceof InvocationTargetException) { throw (InvocationTargetException)cause; } else if (cause instanceof IllegalAccessException) { throw (IllegalAccessException)cause; } else { throw new InvocationTargetException(cause); } } } else { getLog().tracef("Invoking listener: %s passing event %s", target, event); result = method.invoke(target, event); } return result; } catch (InvocationTargetException exception) { Throwable cause = getRealException(exception); if (sync) { throw getLog().exceptionInvokingListener( cause.getClass().getName(), method, target, cause); } else { getLog().unableToInvokeListenerMethod(method, target, cause); } } catch (IllegalAccessException exception) { getLog().unableToInvokeListenerMethodAndRemoveListener(method, target, exception); // Don't worry about return, just let it fire async removeListenerAsync(target); } finally { if (classLoader.get() != null) { Thread.currentThread().setContextClassLoader(contextClassLoader); } resumeIfNeeded(transaction); } return null; }; if (sync) { // Sync can run in a blocking (null) or non blocking (CompletionStage) fashion Object result = r.get(); if (result instanceof CompletionStage) { CompletionStage<Void> stage = (CompletionStage<Void>) result; if (getLog().isTraceEnabled()) { stage = stage.whenComplete((v, t) -> { getLog().tracef("Listener %s has completed event %s", target, event); }); } return stage; } } else { asyncProcessor.execute(r::get); getLog().tracef("Listener %s has completed event %s", target, event); } return CompletableFutures.completedNull(); } @Override public Object getTarget() { return target; } } private Throwable getRealException(Throwable re) { if (re.getCause() == null) return re; Throwable cause = re.getCause(); if (cause instanceof RuntimeException || cause instanceof Error) return getRealException(cause); else return re; } }
20,944
42.185567
184
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/Constants.java
package org.infinispan.metrics; /** * Various public constant names, used by Infinispan's metrics support. * * @author anistor@redhat.com * @since 10.1 */ public interface Constants { String NODE_TAG_NAME = "node"; String CACHE_MANAGER_TAG_NAME = "cache_manager"; String CACHE_TAG_NAME = "cache"; }
317
17.705882
71
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/package-info.java
/** * Micrometer based metrics. All exported metrics are placed in VENDOR scope. * * @api.public */ package org.infinispan.metrics;
136
18.571429
77
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/config/MicrometerMeterRegisterConfigurationBuilder.java
package org.infinispan.metrics.config; import java.util.Objects; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.prometheus.PrometheusMeterRegistry; /** * Builder to inject an instance of {@link MeterRegistry}. * <p> * If not configured, Infinispan will create a new instance of {@link PrometheusMeterRegistry}. * * @since 15.0 */ public class MicrometerMeterRegisterConfigurationBuilder implements Builder<MicrometerMeterRegistryConfiguration> { private MeterRegistry meterRegistry; public MicrometerMeterRegisterConfigurationBuilder(GlobalConfigurationBuilder builder) { //required because GlobalConfigurationBuilder#addModule uses reflection } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } /** * Set the {@link MeterRegistry} instance to use by Infinispan. * <p> * If set to {@code null}, Infinispan will create a new instance of {@link PrometheusMeterRegistry}. * * @param registry The {@link MeterRegistry} to use or {@code null}. */ public MicrometerMeterRegisterConfigurationBuilder meterRegistry(MeterRegistry registry) { meterRegistry = registry; return this; } @Override public MicrometerMeterRegistryConfiguration create() { return new MicrometerMeterRegistryConfiguration(meterRegistry); } @Override public MicrometerMeterRegisterConfigurationBuilder read(MicrometerMeterRegistryConfiguration template, Combine combine) { meterRegistry(template.meterRegistry()); return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MicrometerMeterRegisterConfigurationBuilder)) return false; MicrometerMeterRegisterConfigurationBuilder that = (MicrometerMeterRegisterConfigurationBuilder) o; return Objects.equals(meterRegistry, that.meterRegistry); } @Override public int hashCode() { return meterRegistry != null ? meterRegistry.hashCode() : 0; } @Override public String toString() { return "MicrometerMeterRegisterConfigurationBuilder{" + "meterRegistry=" + meterRegistry + '}'; } }
2,453
30.461538
124
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/config/MicrometerMeterRegistryConfiguration.java
package org.infinispan.metrics.config; import java.util.Objects; import org.infinispan.configuration.serializing.SerializedWith; import io.micrometer.core.instrument.MeterRegistry; /** * A configuration class to inject a custom {@link MeterRegistry} instance. * * @since 15.0 */ @SerializedWith(MicrometerMeterRegistryConfigurationSerializer.class) public class MicrometerMeterRegistryConfiguration { private final MeterRegistry registry; public MicrometerMeterRegistryConfiguration(MeterRegistry registry) { this.registry = registry; } /** * @return The {@link MeterRegistry} instance injected or {@code null} if not configured. */ public MeterRegistry meterRegistry() { return registry; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MicrometerMeterRegistryConfiguration)) return false; MicrometerMeterRegistryConfiguration that = (MicrometerMeterRegistryConfiguration) o; return Objects.equals(registry, that.registry); } @Override public int hashCode() { return registry != null ? registry.hashCode() : 0; } @Override public String toString() { return "MicrometerMeterRegistryConfiguration{" + "registry=" + registry + '}'; } }
1,319
24.384615
92
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/config/MicrometerMeterRegistryConfigurationSerializer.java
package org.infinispan.metrics.config; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.configuration.serializing.ConfigurationSerializer; /** * A {@link ConfigurationSerializer} implementation to serialize {@link MicrometerMeterRegistryConfiguration}. * <p> * This class is a no-op. * * @since 15.0 */ public class MicrometerMeterRegistryConfigurationSerializer implements ConfigurationSerializer<MicrometerMeterRegistryConfiguration> { @Override public void serialize(ConfigurationWriter writer, MicrometerMeterRegistryConfiguration configuration) { //no-op } }
628
32.105263
134
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/impl/TimerTrackerImpl.java
package org.infinispan.metrics.impl; import java.time.Duration; import java.util.Objects; import java.util.concurrent.TimeUnit; import org.infinispan.commons.stat.TimerTracker; import io.micrometer.core.instrument.Timer; /** * A {@link TimerTracker} implementation that updates a {@link Timer} instance. * * @author Pedro Ruivo * @author Fabio Massimo Ercoli * @since 13.0 */ public class TimerTrackerImpl implements TimerTracker { private final Timer timer; TimerTrackerImpl(Timer timer) { this.timer = Objects.requireNonNull(timer, "Timer cannot be null."); } @Override public void update(Duration duration) { timer.record(duration); } @Override public void update(long value, TimeUnit timeUnit) { timer.record(Duration.ofNanos(timeUnit.toNanos(value))); } }
820
21.805556
79
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/impl/package-info.java
/** * Micrometer-based metrics. All exported metrics are placed in VENDOR scope. * All io.micrometer.* references must be contained in MetricsCollector/MetricsCollectorFactory classes in a way * that allows the application to run without these dependencies. * * @api.private */ package org.infinispan.metrics.impl;
321
34.777778
112
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/impl/VendorAdditionalMetrics.java
package org.infinispan.metrics.impl; import java.lang.management.BufferPoolMXBean; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.util.List; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.binder.BaseUnits; import io.micrometer.core.instrument.binder.MeterBinder; import io.micrometer.core.lang.NonNullApi; import io.micrometer.core.lang.NonNullFields; @NonNullApi @NonNullFields class VendorAdditionalMetrics implements MeterBinder { static final String PREFIX = "vendor."; @Override public void bindTo(MeterRegistry registry) { List<BufferPoolMXBean> bufferPoolBeans = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class); for (BufferPoolMXBean bufferPoolBean : bufferPoolBeans) { String name = bufferPoolBean.getName(); // avoid illegal characters due to beans named for example: "mapped - 'non-volatile memory'" String metricName = normalizeMetricName(name); Gauge.builder(PREFIX + "BufferPool.used.memory." + metricName, bufferPoolBean, BufferPoolMXBean::getMemoryUsed) .baseUnit(BaseUnits.BYTES) .description("The memory used by the NIO pool:" + name) .register(registry); } List<MemoryPoolMXBean> memoryPoolBeans = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean memoryPoolBean : memoryPoolBeans) { String name = memoryPoolBean.getName(); // avoid illegal characters due to beans named for example: "CodeHeap 'non-nmethods'" String metricName = normalizeMetricName(name); Gauge.builder(PREFIX + "memoryPool." + metricName + ".usage", memoryPoolBean, (mem) -> mem.getUsage().getUsed()) .baseUnit(BaseUnits.BYTES) .description("Current usage of the " + name + " memory pool") .register(registry); Gauge.builder(PREFIX + "memoryPool." + metricName + ".usage.max", memoryPoolBean, (mem) -> mem.getPeakUsage().getUsed()) .baseUnit(BaseUnits.BYTES) .description("Peak usage of the " + name + " memory pool") .register(registry); } } private static String normalizeMetricName(String name) { return NameUtils // map all illegal characters to "_" .filterIllegalChars(name) // remove underscores at the start and end of the name .replaceAll("^_", "").replaceAll("_$", ""); } }
2,582
42.05
129
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/impl/CustomMetricsSupplier.java
package org.infinispan.metrics.impl; import static org.infinispan.factories.impl.MBeanMetadata.AttributeMetadata; import java.util.Collection; import java.util.function.BiConsumer; import java.util.function.Function; import org.infinispan.jmx.annotations.ManagedAttribute; /** * Interface to implement if the class want to register more metrics to Micrometer than the methods annotated with * {@link ManagedAttribute}. * <p> * The main goal is to allow some dynamic metrics (i.e. metrics that depends on some configuration). As an example, the * Cross-Site response time for each configured site. * <p> * {@link MetricUtils#createGauge(String, String, Function)} or {@link MetricUtils#createTimer(String, String, * BiConsumer)} can be used to create this custom metrics. * * @author Pedro Ruivo * @since 13.0 */ public interface CustomMetricsSupplier { /** * @return A list of {@link AttributeMetadata} to be registered. */ Collection<AttributeMetadata> getCustomMetrics(); }
1,008
30.53125
119
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/impl/CacheMetricsRegistration.java
package org.infinispan.metrics.impl; import java.util.Collection; import java.util.Set; import org.infinispan.configuration.cache.Configuration; import org.infinispan.factories.KnownComponentNames; import org.infinispan.factories.annotations.ComponentName; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.SurvivesRestarts; import org.infinispan.factories.impl.MBeanMetadata; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; /** * Creates and registers metrics for all components from a cache's component registry. * * @author anistor@redhat.com * @since 10.1.3 */ @Scope(Scopes.NAMED_CACHE) @SurvivesRestarts public final class CacheMetricsRegistration extends AbstractMetricsRegistration { @Inject Configuration cacheConfiguration; @ComponentName(KnownComponentNames.CACHE_NAME) @Inject String cacheName; @Override public boolean metricsEnabled() { return metricsCollector != null && cacheConfiguration.statistics().enabled(); } @Override protected String initNamePrefix() { String prefix = super.initNamePrefix(); if (!globalConfig.metrics().namesAsTags()) { prefix += "cache_" + NameUtils.filterIllegalChars(cacheName) + '_'; } return prefix; } @Override protected Set<Object> internalRegisterMetrics(Object instance, Collection<MBeanMetadata.AttributeMetadata> attributes, String metricPrefix) { return metricsCollector.registerMetrics(instance, attributes, metricPrefix, cacheName); } }
1,584
30.078431
144
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/impl/BaseOperatingSystemAdditionalMetrics.java
package org.infinispan.metrics.impl; import static org.infinispan.metrics.impl.BaseAdditionalMetrics.PREFIX; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.binder.MeterBinder; import io.micrometer.core.lang.NonNullApi; import io.micrometer.core.lang.NonNullFields; @NonNullApi @NonNullFields /** * Provides process metrics. * <p> * Inspired by io.micrometer.core.instrument.binder.system.ProcessorMetrics */ public class BaseOperatingSystemAdditionalMetrics implements MeterBinder { private static final Log log = LogFactory.getLog(BaseOperatingSystemAdditionalMetrics.class); static { operatingSystemBean = ManagementFactory.getOperatingSystemMXBean(); Class<?> operatingSystemBeanClass = getOperatingSystemMXBeanImpl(); processCpuLoadMethod = detectMethod(operatingSystemBeanClass, "getProcessCpuLoad"); processCpuTimeMethod = detectMethod(operatingSystemBeanClass, "getProcessCpuTime"); } private static final OperatingSystemMXBean operatingSystemBean; private static final Method processCpuLoadMethod; private static final Method processCpuTimeMethod; @Override public void bindTo(MeterRegistry registry) { Gauge.builder(PREFIX + "cpu.availableProcessors", operatingSystemBean, OperatingSystemMXBean::getAvailableProcessors) .description("Displays the number of processors available to the Java virtual machine. This value may change during a particular invocation of the virtual machine.") .register(registry); Gauge.builder(PREFIX + "cpu.systemLoadAverage", operatingSystemBean, OperatingSystemMXBean::getSystemLoadAverage) .description("Displays the system load average for the last minute. The system load average is the sum of the number of runnable entities queued to the available processors and the number of runnable entities running on the available processors averaged over a period of time. The way in which the load average is calculated is operating system specific but is typically a damped time-dependent average. If the load average is not available, a negative value is displayed. This attribute is designed to provide a hint about the system load and may be queried frequently. The load average might be unavailable on some platforms where it is expensive to implement this method.") .register(registry); if (processCpuLoadMethod != null) { Gauge.builder(PREFIX + "cpu.processCpuLoad", () -> invoke(processCpuLoadMethod)) .description("Displays the \"recent cpu usage\" for the Java virtual machine process.") .register(registry); } if (processCpuTimeMethod != null) { Gauge.builder(PREFIX + "cpu.processCpuTime", () -> invoke(processCpuTimeMethod)) .description("Displays the CPU time, in nanoseconds, used by the process on which the Java virtual machine is running.") .register(registry); } } private static Class<?> getOperatingSystemMXBeanImpl() { List<String> classNames = Arrays.asList( "com.ibm.lang.management.OperatingSystemMXBean", // J9 "com.sun.management.OperatingSystemMXBean" // HotSpot ); for (String className : classNames) { try { return Class.forName(className); } catch (ClassNotFoundException ignore) { } } return null; } private static Method detectMethod(Class<?> operatingSystemBeanClass, String name) { if (operatingSystemBeanClass == null) { return null; } try { // ensure the Bean we have is actually an instance of the interface operatingSystemBeanClass.cast(operatingSystemBean); return operatingSystemBeanClass.getDeclaredMethod(name); } catch (ClassCastException | NoSuchMethodException | SecurityException e) { return null; } } private double invoke(Method method) { try { Object returnedValue = method.invoke(operatingSystemBean); if (returnedValue instanceof Long) { return ((Long) returnedValue).doubleValue(); } return (double) returnedValue; } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { log.warn("An error occurred while invoking method %1$1.", method, e); return -1; } } }
4,790
43.361111
688
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/impl/BaseMemoryAdditionalMetrics.java
package org.infinispan.metrics.impl; import static org.infinispan.metrics.impl.BaseAdditionalMetrics.PREFIX; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.binder.BaseUnits; import io.micrometer.core.instrument.binder.MeterBinder; public class BaseMemoryAdditionalMetrics implements MeterBinder { @Override public void bindTo(MeterRegistry registry) { MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); Gauge.builder(PREFIX + "memory.committedHeap", memoryBean, (mem) -> mem.getHeapMemoryUsage().getCommitted()) .baseUnit(BaseUnits.BYTES) .description("Displays the amount of memory that is committed for the Java virtual machine to use.") .register(registry); Gauge.builder(PREFIX + "memory.maxHeap", memoryBean, (mem) -> mem.getHeapMemoryUsage().getMax()) .baseUnit(BaseUnits.BYTES) .description("Displays the maximum amount of memory, in bytes, that can be used for memory management.") .register(registry); Gauge.builder(PREFIX + "memory.usedHeap", memoryBean, (mem) -> mem.getHeapMemoryUsage().getUsed()) .baseUnit(BaseUnits.BYTES) .description("Displays the amount of used memory.") .register(registry); Gauge.builder(PREFIX + "memory.initHeap", memoryBean, (mem) -> mem.getHeapMemoryUsage().getInit()) .baseUnit(BaseUnits.BYTES) .description("Displays the initial amount of allocated heap memory in bytes.") .register(registry); Gauge.builder(PREFIX + "memory.committedNonHeap", memoryBean, (mem) -> mem.getNonHeapMemoryUsage().getCommitted()) .baseUnit(BaseUnits.BYTES) .description("Displays the amount of memory that is committed for the Java virtual machine to use.") .register(registry); Gauge.builder(PREFIX + "memory.maxNonHeap", memoryBean, (mem) -> mem.getNonHeapMemoryUsage().getMax()) .baseUnit(BaseUnits.BYTES) .description("Displays the maximum amount of memory in bytes that can be used for memory management.") .register(registry); Gauge.builder(PREFIX + "memory.usedNonHeap", memoryBean, (mem) -> mem.getNonHeapMemoryUsage().getUsed()) .baseUnit(BaseUnits.BYTES) .description("Displays the amount of used memory.") .register(registry); Gauge.builder(PREFIX + "memory.initNonHeap", memoryBean, (mem) -> mem.getNonHeapMemoryUsage().getInit()) .baseUnit(BaseUnits.BYTES) .description("Displays the initial amount of allocated memory, in bytes, for off-heap storage.") .register(registry); } }
2,864
46.75
120
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/impl/NameUtils.java
package org.infinispan.metrics.impl; /** * @author anistor@redhat.com * @since 10.1.3 */ final class NameUtils { /** * Replace illegal metric name chars with underscores. */ public static String filterIllegalChars(String name) { return name.replaceAll("[^\\w]+", "_"); } /** * Transform a camel-cased name to snake-case, because Micrometer metrics loves underscores. Eventual sequences of * multiple underscores are replaced with a single underscore. Illegal characters are also replaced with underscore. */ public static String decamelize(String name) { StringBuilder sb = new StringBuilder(name); for (int i = 1; i < sb.length(); i++) { if (Character.isUpperCase(sb.charAt(i))) { sb.insert(i++, '_'); while (i < sb.length() && Character.isUpperCase(sb.charAt(i))) { i++; } } } return filterIllegalChars(sb.toString().toLowerCase()).replaceAll("_+", "_"); } }
1,004
29.454545
119
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/impl/MetricsCollector.java
package org.infinispan.metrics.impl; import java.net.InetAddress; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; import org.infinispan.commons.stat.TimerTracker; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.global.GlobalMetricsConfiguration; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.factories.annotations.Stop; import org.infinispan.factories.annotations.SurvivesRestarts; import org.infinispan.factories.impl.ComponentRef; import org.infinispan.factories.impl.MBeanMetadata; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.metrics.Constants; import org.infinispan.metrics.config.MicrometerMeterRegistryConfiguration; import org.infinispan.remoting.transport.Transport; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.Meter; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Timer; import io.micrometer.prometheus.PrometheusConfig; import io.micrometer.prometheus.PrometheusMeterRegistry; /** * Keeps a reference to the Micrometer MeterRegistry. Optional component in component registry. Availability based on * available jars in classpath! See {@link MetricsCollectorFactory}. * * @author anistor@redhat.com * @since 10.1 */ @Scope(Scopes.GLOBAL) @SurvivesRestarts public class MetricsCollector implements Constants { private static final Log log = LogFactory.getLog(MetricsCollector.class); private MeterRegistry registry; private Tag nodeTag; private Tag cacheManagerTag; @Inject GlobalConfiguration globalConfig; @Inject ComponentRef<Transport> transportRef; protected MetricsCollector() { } public PrometheusMeterRegistry registry() { return registry instanceof PrometheusMeterRegistry ? (PrometheusMeterRegistry) registry : null; } @Start protected void start() { createMeterRegistry(); new BaseAdditionalMetrics().bindTo(registry); new VendorAdditionalMetrics().bindTo(registry); Transport transport = transportRef.running(); String nodeName = transport != null ? transport.getAddress().toString() : globalConfig.transport().nodeName(); if (nodeName == null) { //TODO [anistor] Maybe we should just ensure a unique node name was set in all tests and also in real life usage, even for local cache managers nodeName = generateRandomName(); //throw new CacheConfigurationException("Node name must always be specified in configuration if metrics are enabled."); } nodeTag = Tag.of(NODE_TAG_NAME, nodeName); if (globalConfig.metrics().namesAsTags()) { cacheManagerTag = Tag.of(CACHE_MANAGER_TAG_NAME, globalConfig.cacheManagerName()); } } @Stop protected void stop() { if (registry != null) { registry.close(); registry = null; } } /** * Generate a not so random name based on host name. */ private static String generateRandomName() { String hostName = null; try { hostName = InetAddress.getLocalHost().getHostName(); } catch (Throwable ignored) { } if (hostName == null) { try { hostName = InetAddress.getByName(null).getHostName(); } catch (Throwable ignored) { } } if (hostName == null) { hostName = "localhost"; } else { int dotPos = hostName.indexOf('.'); if (dotPos > 0 && !Character.isDigit(hostName.charAt(0))) { hostName = hostName.substring(0, dotPos); } } int rand = 1 + ThreadLocalRandom.current().nextInt(Short.MAX_VALUE * 2); return hostName + '-' + rand; } public Set<Object> registerMetrics(Object instance, Collection<MBeanMetadata.AttributeMetadata> attributes, String namePrefix, String cacheName) { return registerMetrics(instance, attributes, namePrefix, asTag(CACHE_TAG_NAME, cacheName), nodeTag); } public Set<Object> registerMetrics(Object instance, Collection<MBeanMetadata.AttributeMetadata> attributes, String namePrefix, String cacheName, String nodeName) { return registerMetrics(instance, attributes, namePrefix, asTag(CACHE_TAG_NAME, cacheName), asTag(NODE_TAG_NAME, nodeName)); } private Set<Object> registerMetrics(Object instance, Collection<MBeanMetadata.AttributeMetadata> attributes, String namePrefix, Tag ...initialTags) { Set<Object> metricIds = new HashSet<>(attributes.size()); GlobalMetricsConfiguration metricsCfg = globalConfig.metrics(); List<Tag> tags = prepareTags(initialTags); for (MBeanMetadata.AttributeMetadata attr : attributes) { Supplier<Number> getter = (Supplier<Number>) attr.getter(instance); Consumer<TimerTracker> setter = (Consumer<TimerTracker>) attr.setter(instance); if (getter != null || setter != null) { String metricName = VendorAdditionalMetrics.PREFIX + namePrefix + NameUtils.decamelize(attr.getName()); if (getter != null) { if (metricsCfg.gauges()) { Gauge gauge = Gauge.builder(metricName, getter) .tags(tags) .strongReference(true) .description(attr.getDescription()) .register(registry); Meter.Id id = gauge.getId(); if (log.isTraceEnabled()) { log.tracef("Registering gauge metric %s", id); } metricIds.add(id); } } else { if (metricsCfg.histograms()) { Timer timer = Timer.builder(metricName) .tags(tags) .description(attr.getDescription()) .register(registry); Meter.Id id = timer.getId(); if (log.isTraceEnabled()) { log.tracef("Registering histogram metric %s", id); } setter.accept(new TimerTrackerImpl(timer)); metricIds.add(id); } } } } if (log.isTraceEnabled()) { log.tracef("Registered %d metrics. Metric registry @%x contains %d metrics.", metricIds.size(), System.identityHashCode(registry), registry.getMeters().size()); } return metricIds; } private List<Tag> prepareTags(Tag ...tags) { List<Tag> allTags = Arrays.stream(tags).filter(Objects::nonNull).collect(Collectors.toList()); if (cacheManagerTag != null) allTags.add(cacheManagerTag); return allTags; } private Tag asTag(String key, String value) { return value != null ? Tag.of(key, value) : null; } public void unregisterMetric(Object metricId) { if (registry == null) { return; } Meter removed = registry.remove((Meter.Id) metricId); if (log.isTraceEnabled()) { if (removed != null) { log.tracef("Unregistered metric \"%s\". Metric registry @%x contains %d metrics.", metricId, System.identityHashCode(registry), registry.getMeters().size()); } else { log.tracef("Could not remove unexisting metric \"%s\". Metric registry @%x contains %d metrics.", metricId, System.identityHashCode(registry), registry.getMeters().size()); } } } private void createMeterRegistry() { MicrometerMeterRegistryConfiguration configuration = globalConfig.module(MicrometerMeterRegistryConfiguration.class); registry = configuration == null ? null : configuration.meterRegistry(); if (registry == null) { registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); } } }
8,367
35.701754
166
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/impl/AbstractMetricsRegistration.java
package org.infinispan.metrics.impl; import static org.infinispan.factories.impl.MBeanMetadata.AttributeMetadata; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.infinispan.commons.CacheException; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.factories.annotations.Stop; import org.infinispan.factories.impl.BasicComponentRegistry; import org.infinispan.factories.impl.ComponentRef; import org.infinispan.factories.impl.MBeanMetadata; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; /** * Parent class for metrics registration. Gathers all components in component registry and registers * metrics for them. * * @author anistor@redhat.com * @since 10.1.3 */ @Scope(Scopes.NONE) abstract class AbstractMetricsRegistration { @Inject GlobalConfiguration globalConfig; @Inject BasicComponentRegistry basicComponentRegistry; @Inject MetricsCollector metricsCollector; private String namePrefix; private Set<Object> metricIds; @Start protected void start() { if (metricsEnabled()) { namePrefix = initNamePrefix(); metricIds = Collections.synchronizedSet(new HashSet<>()); try { processComponents(); } catch (Exception e) { throw new CacheException("A failure occurred while registering metrics.", e); } } } @Stop protected void stop() { if (metricIds != null) { unregisterMetrics(metricIds); metricIds = null; } } public abstract boolean metricsEnabled(); /** * Subclasses should override this and return the metric prefix to be used for registration. This is invoked only if * metrics are enabled. */ protected String initNamePrefix() { String prefix = globalConfig.metrics().namesAsTags() ? "" : "cache_manager_" + NameUtils.filterIllegalChars(globalConfig.cacheManagerName()) + '_'; String globalPrefix = globalConfig.metrics().prefix(); return globalPrefix != null && !globalPrefix.isEmpty() ? globalPrefix + '_' + prefix : prefix; } private void processComponents() { for (ComponentRef<?> component : basicComponentRegistry.getRegisteredComponents()) { if (!component.isAlias()) { Object instance = component.wired(); if (instance != null) { MBeanMetadata beanMetadata = basicComponentRegistry.getMBeanMetadata(instance.getClass().getName()); if (beanMetadata != null) { Set<Object> ids = registerMetrics(instance, beanMetadata.getJmxObjectName(), beanMetadata.getAttributes(), null, component.getName(), null); metricIds.addAll(ids); if (instance instanceof CustomMetricsSupplier) { metricIds.addAll(registerMetrics(instance, beanMetadata.getJmxObjectName(), ((CustomMetricsSupplier) instance).getCustomMetrics(), null, component.getName(), null)); } } } } } } private Set<Object> registerMetrics(Object instance, String jmxObjectName, Collection<AttributeMetadata> attributes, String type, String componentName, String prefix) { if (jmxObjectName == null) { jmxObjectName = componentName; } if (jmxObjectName == null) { throw new IllegalArgumentException("No MBean name and no component name was specified."); } String metricPrefix = namePrefix; if (!jmxObjectName.equals("Cache") && !jmxObjectName.equals("CacheManager")) { if (prefix != null) { metricPrefix += NameUtils.decamelize(prefix) + '_'; } if (type != null && !type.equals(jmxObjectName)) { metricPrefix += NameUtils.decamelize(type) + '_'; } metricPrefix += NameUtils.decamelize(jmxObjectName) + '_'; } return internalRegisterMetrics(instance, attributes, metricPrefix); } protected abstract Set<Object> internalRegisterMetrics(Object instance, Collection<AttributeMetadata> attributes, String metricPrefix); /** * Register metrics for a component that was manually registered later, after component registry startup. The metric * ids will be tracked and unregistration will be performed automatically on stop. */ public void registerMetrics(Object instance, String type, String componentName) { if (metricsCollector == null) { throw new IllegalStateException("Metrics are not initialized."); } MBeanMetadata beanMetadata = basicComponentRegistry.getMBeanMetadata(instance.getClass().getName()); if (beanMetadata == null) { throw new IllegalArgumentException("No MBean metadata available for " + instance.getClass().getName()); } Set<Object> ids = registerMetrics(instance, beanMetadata.getJmxObjectName(), beanMetadata.getAttributes(), type, componentName, null); metricIds.addAll(ids); } /** * Register metrics for a component that was manually registered later, after component registry startup. The metric * ids will <b>NOT</b> be tracked and unregistration will <b>NOT</b> be performed automatically on stop. */ public Set<Object> registerExternalMetrics(Object instance, String prefix) { if (metricsCollector == null) { throw new IllegalStateException("Metrics are not initialized."); } MBeanMetadata beanMetadata = basicComponentRegistry.getMBeanMetadata(instance.getClass().getName()); if (beanMetadata == null) { throw new IllegalArgumentException("No MBean metadata available for " + instance.getClass().getName()); } return registerMetrics(instance, beanMetadata.getJmxObjectName(), beanMetadata.getAttributes(), null, null, prefix); } public void unregisterMetrics(Set<Object> metricIds) { if (metricsCollector == null) { throw new IllegalStateException("Metrics are not initialized."); } try { for (Object metricId : metricIds) { metricsCollector.unregisterMetric(metricId); } } catch (Exception e) { throw new CacheException("A failure occurred while unregistering metrics.", e); } } }
6,447
38.802469
186
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/impl/CacheManagerMetricsRegistration.java
package org.infinispan.metrics.impl; import java.util.Collection; import java.util.Set; import org.infinispan.factories.annotations.SurvivesRestarts; import org.infinispan.factories.impl.MBeanMetadata; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; /** * Creates and registers metrics for all components from a cache manager's global component registry. * * @author anistor@redhat.com * @since 10.1.3 */ @Scope(Scopes.GLOBAL) @SurvivesRestarts public final class CacheManagerMetricsRegistration extends AbstractMetricsRegistration { @Override public boolean metricsEnabled() { return metricsCollector != null && globalConfig.statistics(); } @Override protected Set<Object> internalRegisterMetrics(Object instance, Collection<MBeanMetadata.AttributeMetadata> attributes, String metricPrefix) { return metricsCollector.registerMetrics(instance, attributes, metricPrefix, null); } }
966
30.193548
144
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/impl/MetricsCollectorFactory.java
package org.infinispan.metrics.impl; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.AutoInstantiableFactory; import org.infinispan.factories.ComponentFactory; import org.infinispan.factories.annotations.DefaultFactoryFor; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Produces instances of {@link MetricsCollector}. MetricsCollector is optional, * based on the presence of Micrometer in classpath and the enabling of metrics in config. * * @author anistor@redhat.com * @author Fabio Massimo Ercoli * @since 10.1 */ @DefaultFactoryFor(classes = MetricsCollector.class) @Scope(Scopes.GLOBAL) public final class MetricsCollectorFactory implements ComponentFactory, AutoInstantiableFactory { private static final Log log = LogFactory.getLog(MetricsCollectorFactory.class); @Inject GlobalConfiguration globalConfig; @Override public Object construct(String componentName) { if (!globalConfig.metrics().enabled()) { return null; } // try cautiously try { return new MetricsCollector(); } catch (Throwable e) { // missing dependency log.debug("Micrometer metrics are not available because classpath dependencies are missing.", e); return null; } } }
1,496
31.543478
106
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/impl/BaseAdditionalMetrics.java
package org.infinispan.metrics.impl; import java.lang.management.ClassLoadingMXBean; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.lang.management.ThreadMXBean; import io.micrometer.core.instrument.FunctionCounter; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tags; import io.micrometer.core.instrument.binder.MeterBinder; import io.micrometer.core.lang.NonNullApi; import io.micrometer.core.lang.NonNullFields; @NonNullApi @NonNullFields class BaseAdditionalMetrics implements MeterBinder { static final String PREFIX = "base."; @Override public void bindTo(MeterRegistry registry) { bindClassLoaderMetrics(registry); new BaseOperatingSystemAdditionalMetrics().bindTo(registry); bindGarbageCollectionMetrics(registry); bindRuntimeMetrics(registry); new BaseMemoryAdditionalMetrics().bindTo(registry); bindThreadingMetrics(registry); } private void bindClassLoaderMetrics(MeterRegistry registry) { ClassLoadingMXBean classLoadingBean = ManagementFactory.getClassLoadingMXBean(); Gauge.builder(PREFIX + "classloader.loadedClasses.count", classLoadingBean, ClassLoadingMXBean::getLoadedClassCount) .description("Displays the number of classes that are currently loaded in the Java virtual machine.") .register(registry); FunctionCounter.builder(PREFIX + "classloader.loadedClasses.total", classLoadingBean, ClassLoadingMXBean::getTotalLoadedClassCount) .description("Displays the total number of classes that have been loaded since the Java virtual machine has started execution.") .register(registry); FunctionCounter.builder(PREFIX + "classloader.unloadedClasses.total", classLoadingBean, ClassLoadingMXBean::getUnloadedClassCount) .description("Displays the total number of classes unloaded since the Java virtual machine has started execution.") .register(registry); } private void bindGarbageCollectionMetrics(MeterRegistry registry) { for (GarbageCollectorMXBean garbageCollectorBean : ManagementFactory.getGarbageCollectorMXBeans()) { FunctionCounter.builder(PREFIX + "gc.total", garbageCollectorBean, GarbageCollectorMXBean::getCollectionCount) .tags(Tags.of("name", garbageCollectorBean.getName())) .description("Displays the total number of collections that have occurred. This attribute lists -1 if the collection count is undefined for this collector.") .register(registry); FunctionCounter.builder(PREFIX + "gc.time", garbageCollectorBean, GarbageCollectorMXBean::getCollectionTime) .tags(Tags.of("name", garbageCollectorBean.getName())) .description("Displays the approximate accumulated collection elapsed time in milliseconds. This attribute displays -1 if the collection elapsed time is undefined for this collector. The Java virtual machine implementation may use a high resolution timer to measure the elapsed time. This attribute might display the same value even if the collection count has been incremented if the collection elapsed time is very short.") .register(registry); } } private void bindRuntimeMetrics(MeterRegistry registry) { RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); Gauge.builder(PREFIX + "jvm.uptime", runtimeBean, RuntimeMXBean::getUptime) .description("Displays the uptime of the Java virtual machine.") .register(registry); } private void bindThreadingMetrics(MeterRegistry registry) { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); Gauge.builder(PREFIX + "thread.count", threadBean, ThreadMXBean::getThreadCount) .description("Displays the current thread count.") .register(registry); Gauge.builder(PREFIX + "thread.daemon.count", threadBean, ThreadMXBean::getDaemonThreadCount) .description("Displays the current number of live daemon threads.") .register(registry); Gauge.builder(PREFIX + "thread.max.count", threadBean, ThreadMXBean::getPeakThreadCount) .description("Displays the peak live thread count since the Java virtual machine started or peak was reset. This includes daemon and non-daemon threads.") .register(registry); Gauge.builder(PREFIX + "thread.totalStarted", threadBean, ThreadMXBean::getTotalStartedThreadCount) .description("Displays the total number of started threads.") .register(registry); } }
4,763
51.351648
440
java
null
infinispan-main/core/src/main/java/org/infinispan/metrics/impl/MetricUtils.java
package org.infinispan.metrics.impl; import static org.infinispan.factories.impl.MBeanMetadata.AttributeMetadata; import java.util.function.BiConsumer; import java.util.function.Function; import org.infinispan.commons.stat.TimerTracker; /** * Utility methods for metrics. * * @author Pedro Ruivo * @since 13.0 */ public final class MetricUtils { private MetricUtils() { } /** * Creates a Gauge metric. * * @param name The metric name. * @param description The metric description. * @param getterFunction The {@link Function} invoked to return the metric value * @param <C> The instance type. * @return The {@link AttributeMetadata} to be registered. */ public static <C> AttributeMetadata createGauge(String name, String description, Function<C, Number> getterFunction) { return new AttributeMetadata(name, description, false, false, null, false, getterFunction, null); } /** * Creates a Timer metric. * * @param name The metric name. * @param description The metrics description. * @param setterFunction The {@link BiConsumer} invoked with the {@link TimerTracker} instance to update. * @param <C> The instance type. * @return The {@link AttributeMetadata} to be registered. */ public static <C> AttributeMetadata createTimer(String name, String description, BiConsumer<C, TimerTracker> setterFunction) { return new AttributeMetadata(name, description, false, false, null, false, null, setterFunction); } }
1,588
30.156863
108
java
null
infinispan-main/core/src/main/java/org/infinispan/factories/EntryMetaFactory.java
package org.infinispan.factories; import org.infinispan.container.impl.EntryFactory; import org.infinispan.container.impl.EntryFactoryImpl; import org.infinispan.container.impl.InternalEntryFactory; import org.infinispan.container.impl.InternalEntryFactoryImpl; import org.infinispan.factories.annotations.DefaultFactoryFor; @DefaultFactoryFor(classes = {EntryFactory.class, InternalEntryFactory.class}) public class EntryMetaFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override @SuppressWarnings("unchecked") public Object construct(String componentName) { if (componentName.equals(EntryFactory.class.getName())) { return new EntryFactoryImpl(); } else { return new InternalEntryFactoryImpl(); } } }
798
33.73913
109
java
null
infinispan-main/core/src/main/java/org/infinispan/factories/InternalCacheFactory.java
package org.infinispan.factories; import static java.util.Objects.requireNonNull; import static org.infinispan.encoding.DataConversion.newKeyDataConversion; import static org.infinispan.encoding.DataConversion.newValueDataConversion; import static org.infinispan.util.logging.Log.CONTAINER; import java.util.Collection; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.cache.impl.AbstractDelegatingAdvancedCache; import org.infinispan.cache.impl.CacheImpl; import org.infinispan.cache.impl.EncoderCache; import org.infinispan.cache.impl.SimpleCacheImpl; import org.infinispan.cache.impl.StatsCollectingCache; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.marshall.StreamingMarshaller; import org.infinispan.commons.time.TimeService; import org.infinispan.commons.util.EnumUtil; import org.infinispan.configuration.cache.Configuration; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.context.Flag; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.context.impl.ImmutableContext; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.encoding.DataConversion; import org.infinispan.eviction.impl.PassivationManager; import org.infinispan.eviction.impl.PassivationManagerStub; import org.infinispan.expiration.impl.InternalExpirationManager; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.SurvivesRestarts; import org.infinispan.factories.impl.BasicComponentRegistry; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.interceptors.impl.CacheMgmtInterceptor; import org.infinispan.jmx.CacheJmxRegistration; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.metrics.impl.CacheMetricsRegistration; import org.infinispan.notifications.cachelistener.CacheNotifier; import org.infinispan.notifications.cachelistener.cluster.ClusterEventManager; import org.infinispan.notifications.cachelistener.cluster.impl.ClusterEventManagerStub; import org.infinispan.partitionhandling.PartitionHandling; import org.infinispan.partitionhandling.impl.PartitionHandlingManager; import org.infinispan.transaction.xa.recovery.RecoveryAdminOperations; import org.infinispan.upgrade.RollingUpgradeManager; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.xsite.XSiteAdminOperations; /** * An internal factory for constructing Caches. Used by the {@link org.infinispan.manager.DefaultCacheManager}, this is * not intended as public API. * <p/> * This is a special instance of a {@link AbstractComponentFactory} which contains bootstrap information for the {@link * ComponentRegistry}. * <p/> * * @author <a href="mailto:manik@jboss.org">Manik Surtani (manik@jboss.org)</a> * @since 4.0 */ public class InternalCacheFactory<K, V> { private ComponentRegistry componentRegistry; private BasicComponentRegistry basicComponentRegistry; /** * This implementation clones the configuration passed in before using it. * * @param configuration to use * @param globalComponentRegistry global component registry to attach the cache to * @param cacheName name of the cache * @return a cache * @throws CacheConfigurationException if there are problems with the cfg */ public Cache<K, V> createCache(Configuration configuration, GlobalComponentRegistry globalComponentRegistry, String cacheName) throws CacheConfigurationException { try { if (configuration.simpleCache()) { return createSimpleCache(configuration, globalComponentRegistry, cacheName); } else { return createAndWire(configuration, globalComponentRegistry, cacheName); } } catch (RuntimeException re) { throw re; } catch (Exception e) { throw new RuntimeException(e); } } private AdvancedCache<K, V> createAndWire(Configuration configuration, GlobalComponentRegistry globalComponentRegistry, String cacheName) { StreamingMarshaller marshaller = globalComponentRegistry.getOrCreateComponent(StreamingMarshaller.class, KnownComponentNames.INTERNAL_MARSHALLER); AdvancedCache<K, V> cache = new CacheImpl<>(cacheName); // We can optimize REPL reads that meet some criteria. This allows us to bypass interceptor chain if (configuration.clustering().cacheMode().isReplicated() && !configuration.persistence().usingStores() && !configuration.transaction().transactionMode().isTransactional() && configuration.clustering().stateTransfer().awaitInitialTransfer() && configuration.clustering().hash().capacityFactor() != 0f && !globalComponentRegistry.getGlobalConfiguration().isZeroCapacityNode()) { cache = new GetReplCache<>(new CacheImpl<>(cacheName)); if (configuration.statistics().available()) { cache = new StatsCache<>(cache); } if (configuration.clustering().partitionHandling().whenSplit() != PartitionHandling.ALLOW_READ_WRITES) { cache = new PartitionHandlingCache<>(cache); } } AdvancedCache<K, V> encodedCache = buildEncodingCache(cache); // TODO Register the cache without encoding in the component registry bootstrap(cacheName, encodedCache, configuration, globalComponentRegistry, marshaller); if (marshaller != null) { componentRegistry.wireDependencies(marshaller, false); } return encodedCache; } private AdvancedCache<K, V> buildEncodingCache(AdvancedCache<K, V> wrappedCache) { DataConversion keyDataConversion = newKeyDataConversion(); DataConversion valueDataConversion = newValueDataConversion(); return new EncoderCache<>(wrappedCache, null, null, keyDataConversion, valueDataConversion); } private AdvancedCache<K, V> createSimpleCache(Configuration configuration, GlobalComponentRegistry globalComponentRegistry, String cacheName) { AdvancedCache<K, V> cache; if (configuration.statistics().available()) { cache = buildEncodingCache(new StatsCollectingCache<>(cacheName)); } else { cache = buildEncodingCache(new SimpleCacheImpl<>(cacheName)); } componentRegistry = new SimpleComponentRegistry<>(cacheName, configuration, cache, globalComponentRegistry); basicComponentRegistry = componentRegistry.getComponent(BasicComponentRegistry.class); basicComponentRegistry.registerAlias(Cache.class.getName(), AdvancedCache.class.getName(), AdvancedCache.class); basicComponentRegistry.registerComponent(AdvancedCache.class, cache, false); componentRegistry.registerComponent(new CacheJmxRegistration(), CacheJmxRegistration.class); componentRegistry.registerComponent(new CacheMetricsRegistration(), CacheMetricsRegistration.class); componentRegistry.registerComponent(new RollingUpgradeManager(), RollingUpgradeManager.class); return cache; } /** * Bootstraps this factory with a Configuration and a ComponentRegistry. */ private void bootstrap(String cacheName, AdvancedCache<?, ?> cache, Configuration configuration, GlobalComponentRegistry globalComponentRegistry, StreamingMarshaller globalMarshaller) { // injection bootstrap stuff componentRegistry = new ComponentRegistry(cacheName, configuration, cache, globalComponentRegistry, globalComponentRegistry.getClassLoader()); /* -------------------------------------------------------------------------------------------------------------- This is where the bootstrap really happens. Registering the cache in the component registry will cause the component registry to look at the cache's @Inject methods, and construct various components and their dependencies, in turn. -------------------------------------------------------------------------------------------------------------- */ basicComponentRegistry = componentRegistry.getComponent(BasicComponentRegistry.class); basicComponentRegistry.registerAlias(Cache.class.getName(), AdvancedCache.class.getName(), AdvancedCache.class); basicComponentRegistry.registerComponent(AdvancedCache.class.getName(), cache, false); componentRegistry.registerComponent(new CacheJmxRegistration(), CacheJmxRegistration.class.getName(), true); componentRegistry.registerComponent(new CacheMetricsRegistration(), CacheMetricsRegistration.class.getName(), true); if (configuration.transaction().recovery().enabled()) { componentRegistry.registerComponent(new RecoveryAdminOperations(), RecoveryAdminOperations.class.getName(), true); } if (configuration.sites().hasBackups()) { componentRegistry.registerComponent(new XSiteAdminOperations(), XSiteAdminOperations.class.getName(), true); } // The RollingUpgradeManager should always be added so it is registered in JMX. componentRegistry.registerComponent(new RollingUpgradeManager(), RollingUpgradeManager.class.getName(), true); } private static void assertKeyNotNull(Object key) { requireNonNull(key, "Null keys are not supported!"); } private static void checkCanRun(Cache<?, ?> cache, String cacheName) { ComponentStatus status = cache.getStatus(); if (status == ComponentStatus.FAILED || status == ComponentStatus.TERMINATED) { throw CONTAINER.cacheIsTerminated(cacheName, status.toString()); } } @Scope(Scopes.NAMED_CACHE) static abstract class AbstractGetAdvancedCache<K, V, T extends AbstractGetAdvancedCache<K, V, T>> extends AbstractDelegatingAdvancedCache<K, V> { @Inject protected ComponentRegistry componentRegistry; @Inject InternalExpirationManager<K, V> expirationManager; @Inject KeyPartitioner keyPartitioner; public AbstractGetAdvancedCache(AdvancedCache<K, V> cache) { super(cache); } /** * This method is for additional components that need to be wired after the field wiring is complete */ @Inject public void wireRealCache() { // Wire the cache to ensure all components are ready componentRegistry.wireDependencies(cache, false); } /** * This is to be extended when an entry is injected via component registry and you have to do it manually when a * new delegating cache is created due to methods like {@link AdvancedCache#withFlags(Flag...)}. This method will * call {@link #wireRealCache()} at the very end - so all methods should be initialized before. * * @param cache */ protected void internalWire(T cache) { componentRegistry = cache.componentRegistry; expirationManager = cache.expirationManager; keyPartitioner = cache.keyPartitioner; wireRealCache(); } @Override public InternalDataContainer<K, V> getDataContainer() { return (InternalDataContainer<K, V>) super.getDataContainer(); } @Override public V get(Object key) { InternalCacheEntry<K, V> ice = getCacheEntry(key); if (ice != null) { return ice.getValue(); } return null; } @Override public V getOrDefault(Object key, V defaultValue) { V value = get(key); return value != null ? value : defaultValue; } @Override public boolean containsKey(Object key) { return get(key) != null; } @Override public InternalCacheEntry<K, V> getCacheEntry(Object key) { assertKeyNotNull(key); checkCanRun(cache, cache.getName()); int segment = keyPartitioner.getSegment(key); InternalCacheEntry<K, V> ice = getDataContainer().peek(segment, key); if (ice != null && ice.canExpire()) { CompletionStage<Boolean> stage = expirationManager.handlePossibleExpiration(ice, segment, false); if (CompletionStages.join(stage)) { ice = null; } } return ice; } } static class PartitionHandlingCache<K, V> extends AbstractGetAdvancedCache<K, V, PartitionHandlingCache<K, V>> { @Inject PartitionHandlingManager manager; // We store the flags as bits passed from AdvancedCache.withFlags etc. private final long bitFlags; public PartitionHandlingCache(AdvancedCache<K, V> cache) { this(cache, 0L); } private PartitionHandlingCache(AdvancedCache<K, V> cache, long bitFlags) { super(cache); this.bitFlags = bitFlags; } @Override public AdvancedCache rewrap(AdvancedCache newDelegate) { PartitionHandlingCache newCache = new PartitionHandlingCache<>(newDelegate, this.bitFlags); newCache.internalWire(this); return newCache; } @Override protected void internalWire(PartitionHandlingCache<K, V> cache) { manager = cache.manager; super.internalWire(cache); } @Override public V get(Object key) { V value = cache.get(key); if (!EnumUtil.containsAny(bitFlags, FlagBitSets.CACHE_MODE_LOCAL | FlagBitSets.SKIP_OWNERSHIP_CHECK)) { manager.checkRead(key, bitFlags); } return value; } @Override public AdvancedCache<K, V> withFlags(Flag... flags) { long newFlags = EnumUtil.bitSetOf(flags); long updatedFlags = EnumUtil.mergeBitSets(bitFlags, newFlags); if (bitFlags != updatedFlags) { PartitionHandlingCache<K, V> newCache = new PartitionHandlingCache<>(super.withFlags(flags), updatedFlags); newCache.internalWire(this); return newCache; } return this; } @Override public AdvancedCache<K, V> withFlags(Collection<Flag> flags) { long newFlags = EnumUtil.bitSetOf(flags); long updatedFlags = EnumUtil.mergeBitSets(bitFlags, newFlags); if (bitFlags != updatedFlags) { PartitionHandlingCache<K, V> newCache = new PartitionHandlingCache<>(super.withFlags(flags), updatedFlags); newCache.internalWire(this); return newCache; } return this; } @Override public AdvancedCache<K, V> noFlags() { if (bitFlags != 0) { PartitionHandlingCache<K, V> newCache = new PartitionHandlingCache<>(super.noFlags(), 0L); newCache.internalWire(this); return newCache; } return this; } } static class StatsCache<K, V> extends AbstractGetAdvancedCache<K, V, StatsCache<K, V>> { @Inject TimeService timeService; private CacheMgmtInterceptor interceptor; public StatsCache(AdvancedCache<K, V> cache) { super(cache); } @Override public AdvancedCache rewrap(AdvancedCache newDelegate) { StatsCache newCache = new StatsCache<>(newDelegate); newCache.internalWire(this); newCache.interceptorStart(); return newCache; } @Override protected void internalWire(StatsCache<K, V> cache) { this.timeService = cache.timeService; super.internalWire(cache); } private void interceptorStart() { // This has to be done after the cache is wired - otherwise we can get a circular dependency interceptor = cache.getAsyncInterceptorChain().findInterceptorWithClass(CacheMgmtInterceptor.class); } @Override public V get(Object key) { V value; if (interceptor == null) { interceptorStart(); } if (interceptor.getStatisticsEnabled()) { long beginTime = timeService.time(); value = cache.get(key); interceptor.addDataRead(value != null, timeService.timeDuration(beginTime, TimeUnit.NANOSECONDS)); } else { value = cache.get(key); } return value; } } static class GetReplCache<K, V> extends AbstractGetAdvancedCache<K, V, GetReplCache<K, V>> { @Inject CacheNotifier<K, V> cacheNotifier; // The hasListeners is commented out until EncoderCache can properly pass down the addListener invocation // to the next delegate in the chain. Otherwise we miss listener additions and don't fire events properly. // This is detailed in https://issues.jboss.org/browse/ISPN-9240 // private final AtomicBoolean hasListeners; // // GetReplCache(AdvancedCache<K, V> cache) { // this(cache, new AtomicBoolean()); // } private GetReplCache(AdvancedCache<K, V> cache/*, AtomicBoolean hasListeners*/) { super(cache); // this.hasListeners = hasListeners; } @Override public AdvancedCache rewrap(AdvancedCache newDelegate) { GetReplCache newCache = new GetReplCache<>(newDelegate/*, oldCache.hasListeners*/); newCache.internalWire(this); return newCache; } @Override protected void internalWire(GetReplCache<K, V> cache) { cacheNotifier = cache.cacheNotifier; super.internalWire(cache); } // private boolean canFire(Object listener) { // for (Method m : listener.getClass().getMethods()) { // // Visitor listeners are very rare, so optimize to not call when we don't have any registered // if (m.isAnnotationPresent(CacheEntryVisited.class)) { // return true; // } // } // return false; // } // // @Override // public void addListener(Object listener, KeyFilter<? super K> filter) { // super.addListener(listener, filter); // if (!hasListeners.get() && canFire(listener)) { // hasListeners.set(true); // } // } // // @Override // public <C> void addListener(Object listener, CacheEventFilter<? super K, ? super V> filter, CacheEventConverter<? super K, ? super V, C> converter) { // super.addListener(listener, filter, converter); // if (!hasListeners.get() && canFire(listener)) { // hasListeners.set(true); // } // } // // @Override // public void addListener(Object listener) { // super.addListener(listener); // if (!hasListeners.get() && canFire(listener)) { // hasListeners.set(true); // } // } // // @Override // public <C> void addFilteredListener(Object listener, CacheEventFilter<? super K, ? super V> filter, // CacheEventConverter<? super K, ? super V, C> converter, Set<Class<? extends Annotation>> filterAnnotations) { // super.addFilteredListener(listener, filter, converter, filterAnnotations); // if (!hasListeners.get() && canFire(listener)) { // hasListeners.set(true); // } // } @Override public V get(Object key) { V value = super.get(key); if (value != null/* && hasListeners.get()*/) { CompletionStages.join(cacheNotifier.notifyCacheEntryVisited((K) key, value, true, ImmutableContext.INSTANCE, null)); CompletionStages.join(cacheNotifier.notifyCacheEntryVisited((K) key, value, false, ImmutableContext.INSTANCE, null)); } return value; } } @SurvivesRestarts class SimpleComponentRegistry<K, V> extends ComponentRegistry { public SimpleComponentRegistry(String cacheName, Configuration configuration, AdvancedCache<K, V> cache, GlobalComponentRegistry globalComponentRegistry) { super(cacheName, configuration, cache, globalComponentRegistry, globalComponentRegistry.getClassLoader()); } @Override protected void bootstrapComponents() { registerComponent(new ClusterEventManagerStub<K, V>(), ClusterEventManager.class); registerComponent(new PassivationManagerStub(), PassivationManager.class); } @Override public void cacheComponents() { getOrCreateComponent(InternalExpirationManager.class); } } }
20,800
40.853119
157
java
null
infinispan-main/core/src/main/java/org/infinispan/factories/TransportFactory.java
package org.infinispan.factories; import org.infinispan.factories.annotations.DefaultFactoryFor; import org.infinispan.remoting.transport.Transport; /** * Factory for Transport implementations. * * @author Manik Surtani * @since 4.0 */ @DefaultFactoryFor(classes = Transport.class) public class TransportFactory extends AbstractComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { return globalConfiguration.transport().transport(); } }
519
25
99
java
null
infinispan-main/core/src/main/java/org/infinispan/factories/AuthorizationManagerFactory.java
package org.infinispan.factories; import org.infinispan.factories.annotations.DefaultFactoryFor; import org.infinispan.security.AuthorizationManager; import org.infinispan.security.impl.AuthorizationManagerImpl; @DefaultFactoryFor(classes = AuthorizationManager.class) public class AuthorizationManagerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override @SuppressWarnings("unchecked") public Object construct(String componentName) { if (configuration.security().authorization().enabled()) return new AuthorizationManagerImpl(); else return null; } }
640
34.611111
120
java