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/BaseCacheStream.java
package org.infinispan; import java.util.Comparator; import java.util.Iterator; import java.util.PrimitiveIterator; import java.util.Set; import java.util.Spliterator; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.BaseStream; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; /** * Interface that defines the base methods of all streams returned from a {@link Cache}. This interface * is useful to hold a reference to any of the types while still being able to invoke some methods. * @author wburns * @since 9.0 */ public interface BaseCacheStream<T, S extends BaseStream<T, S>> extends BaseStream<T, S> { /** * This would disable sending requests to all other remote nodes compared to one at a time. This can reduce memory * pressure on the originator node at the cost of performance. * <p>Parallel distribution is enabled by default except for {@link CacheStream#iterator()} and * {@link CacheStream#spliterator()}</p> * @return a stream with parallel distribution disabled */ BaseCacheStream sequentialDistribution(); /** * This would enable sending requests to all other remote nodes when a terminal operator is performed. This * requires additional overhead as it must process results concurrently from various nodes, but should perform * faster in the majority of cases. * <p>Parallel distribution is enabled by default except for {@link CacheStream#iterator()} and * {@link CacheStream#spliterator()}</p> * @return a stream with parallel distribution enabled. */ BaseCacheStream parallelDistribution(); /** * Filters which entries are returned by what segment they are present in. This method can be substantially more * efficient than using a regular {@link CacheStream#filter(Predicate)} method as this can control what nodes are * asked for data and what entries are read from the underlying CacheStore if present. * @param segments The segments to use for this stream operation. Any segments not in this set will be ignored. * @return a stream with the segments filtered. * @deprecated since 9.3 This is to be replaced by {@link #filterKeySegments(IntSet)} */ BaseCacheStream filterKeySegments(Set<Integer> segments); /** * Filters which entries are returned by what segment they are present in. This method can be substantially more * efficient than using a regular {@link CacheStream#filter(Predicate)} method as this can control what nodes are * asked for data and what entries are read from the underlying CacheStore if present. * @param segments The segments to use for this stream operation. Any segments not in this set will be ignored. * @return a stream with the segments filtered. * @since 9.3 */ BaseCacheStream filterKeySegments(IntSet segments); /** * Filters which entries are returned by only returning ones that map to the given key. This method will * be faster than a regular {@link CacheStream#filter(Predicate)} if the filter is holding references to the same * keys. * @param keys The keys that this stream will only operate on. * @return a stream with the keys filtered. */ BaseCacheStream filterKeys(Set<?> keys); /** * Controls how many keys are returned from a remote node when using a stream terminal operation with a distributed * cache to back this stream. This value is ignored when terminal operators that don't track keys are used. Key * tracking terminal operators are {@link CacheStream#iterator()}, {@link CacheStream#spliterator()}, * {@link CacheStream#forEach(Consumer)}. Please see those methods for additional information on how this value * may affect them. * <p>This value may be used in the case of a a terminal operator that doesn't track keys if an intermediate * operation is performed that requires bringing keys locally to do computations. Examples of such intermediate * operations are {@link CacheStream#sorted()}, {@link CacheStream#sorted(Comparator)}, * {@link CacheStream#distinct()}, {@link CacheStream#limit(long)}, {@link CacheStream#skip(long)}</p> * <p>This value is <b>always</b> ignored when this stream is backed by a cache that is not distributed as all * values are already local.</p> * @param batchSize The size of each batch. This defaults to the state transfer chunk size. * @return a stream with the batch size updated */ BaseCacheStream distributedBatchSize(int batchSize); /** * Allows registration of a segment completion listener that is notified when a segment has completed * processing. If the terminal operator has a short circuit this listener may never be called. * <p>This method is designed for the sole purpose of use with the {@link CacheStream#iterator()} to allow for * a user to track completion of segments as they are returned from the iterator. Behavior of other methods * is not specified. Please see {@link CacheStream#iterator()} for more information.</p> * <p>Multiple listeners may be registered upon multiple invocations of this method. The ordering of notified * listeners is not specified.</p> * <p>This is only used if this stream did not invoke {@link BaseCacheStream#disableRehashAware()} and has no * flat map based operations. If this is done no segments will be notified.</p> * @param listener The listener that will be called back as segments are completed. * @return a stream with the listener registered. */ BaseCacheStream segmentCompletionListener(SegmentCompletionListener listener); /** * Disables tracking of rehash events that could occur to the underlying cache. If a rehash event occurs while * a terminal operation is being performed it is possible for some values that are in the cache to not be found. * Note that you will never have an entry duplicated when rehash awareness is disabled, only lost values. * <p>Most terminal operations will run faster with rehash awareness disabled even without a rehash occuring. * However if a rehash occurs with this disabled be prepared to possibly receive only a subset of values.</p> * @return a stream with rehash awareness disabled. */ BaseCacheStream disableRehashAware(); /** * Sets a given time to wait for a remote operation to respond by. This timeout does nothing if the terminal * operation does not go remote. * <p>If a timeout does occur then a {@link java.util.concurrent.TimeoutException} is thrown from the terminal * operation invoking thread or on the next call to the {@link Iterator} or {@link Spliterator}.</p> * <p>Note that if a rehash occurs this timeout value is reset for the subsequent retry if rehash aware is * enabled.</p> * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @return a stream with the timeout set */ BaseCacheStream timeout(long timeout, TimeUnit unit); /** * Functional interface that is used as a callback when segments are completed. Please see * {@link BaseCacheStream#segmentCompletionListener(SegmentCompletionListener)} for more details. * @author wburns * @since 9.0 */ @FunctionalInterface interface SegmentCompletionListener extends Consumer<Supplier<PrimitiveIterator.OfInt>> { /** * Method invoked when the segment has been found to be consumed properly by the terminal operation. * @param segments The segments that were completed * @deprecated This method requires boxing for each segment. Please use {@link SegmentCompletionListener#accept(Supplier)} instead */ @Deprecated void segmentCompleted(Set<Integer> segments); /** * Invoked each time a given number of segments have completed and the terminal operation has consumed all * entries in the given segment * @param segments The segments that were completed */ default void accept(Supplier<PrimitiveIterator.OfInt> segments) { segmentCompleted(IntSets.from(segments.get())); } } }
8,295
53.222222
136
java
null
infinispan-main/core/src/main/java/org/infinispan/Version.java
package org.infinispan; import net.jcip.annotations.Immutable; /** * Contains version information about this release of Infinispan. * * @author Bela Ban * @since 4.0 * @deprecated Use {@link org.infinispan.commons.util.Version} instead */ @Immutable @Deprecated public class Version { public static String getVersion() { return org.infinispan.commons.util.Version.getVersion(); } public static String getBrandName() { return org.infinispan.commons.util.Version.getBrandName(); } public static String getCodename() { return org.infinispan.commons.util.Version.getCodename(); } public static String getModuleSlot() { return org.infinispan.commons.util.Version.getModuleSlot(); } public static short getMarshallVersion() { return org.infinispan.commons.util.Version.getMarshallVersion(); } public static String getSchemaVersion() { return org.infinispan.commons.util.Version.getSchemaVersion(); } public static String getMajorMinor() { return org.infinispan.commons.util.Version.getMajorMinor(); } public static String getMajor() { return org.infinispan.commons.util.Version.getMajor(); } public static boolean compareTo(byte[] v) { return org.infinispan.commons.util.Version.compareTo(v); } public static short getVersionShort() { return org.infinispan.commons.util.Version.getVersionShort(); } public static short getVersionShort(String versionString) { return org.infinispan.commons.util.Version.getVersionShort(versionString); } public static String decodeVersion(short version) { return org.infinispan.commons.util.Version.decodeVersion(version); } /** * Serialization only looks at major and minor, not micro or below. */ public static String decodeVersionForSerialization(short version) { return org.infinispan.commons.util.Version.decodeVersionForSerialization(version); } /** * Prints version information. */ public static void main(String[] args) { org.infinispan.commons.util.Version.main(args); } /** * Prints full version information to the standard output. */ public static void printFullVersionInformation() { org.infinispan.commons.util.Version.printFullVersionInformation(); } /** * Returns version information as a string. */ public static String printVersion() { return org.infinispan.commons.util.Version.printVersion(); } }
2,502
26.206522
88
java
null
infinispan-main/core/src/main/java/org/infinispan/DoubleCacheStream.java
package org.infinispan; import java.util.OptionalDouble; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleConsumer; import java.util.function.DoubleFunction; import java.util.function.DoublePredicate; import java.util.function.DoubleToIntFunction; import java.util.function.DoubleToLongFunction; import java.util.function.DoubleUnaryOperator; import java.util.function.ObjDoubleConsumer; import java.util.function.Supplier; import java.util.stream.DoubleStream; import org.infinispan.util.function.SerializableBiConsumer; import org.infinispan.util.function.SerializableDoubleBinaryOperator; import org.infinispan.util.function.SerializableDoubleConsumer; import org.infinispan.util.function.SerializableDoubleFunction; import org.infinispan.util.function.SerializableDoublePredicate; import org.infinispan.util.function.SerializableDoubleToIntFunction; import org.infinispan.util.function.SerializableDoubleToLongFunction; import org.infinispan.util.function.SerializableDoubleUnaryOperator; import org.infinispan.util.function.SerializableObjDoubleConsumer; import org.infinispan.util.function.SerializableSupplier; /** * A {@link DoubleStream} that has additional methods to allow for Serializable instances. Please see * {@link CacheStream} for additional details about various methods. * * @author wburns * @since 9.0 */ public interface DoubleCacheStream extends DoubleStream, BaseCacheStream<Double, DoubleStream> { /** * {@inheritDoc} * @return a stream with parallel distribution disabled. */ DoubleCacheStream sequentialDistribution(); /** * @inheritDoc * @return a stream with parallel distribution enabled. */ DoubleCacheStream parallelDistribution(); /** * {@inheritDoc} * @return a stream with the segments filtered. */ DoubleCacheStream filterKeySegments(Set<Integer> segments); /** * {@inheritDoc} * @return a stream with the keys filtered. */ DoubleCacheStream filterKeys(Set<?> keys); /** * {@inheritDoc} * @return a stream with the batch size updated */ DoubleCacheStream distributedBatchSize(int batchSize); /** * {@inheritDoc} * @return a stream with the listener registered. */ DoubleCacheStream segmentCompletionListener(SegmentCompletionListener listener); /** * {@inheritDoc} * @return a stream with rehash awareness disabled. */ DoubleCacheStream disableRehashAware(); /** * {@inheritDoc} * @return a stream with the timeout set */ DoubleCacheStream timeout(long timeout, TimeUnit unit); /** * {@inheritDoc} * @return the new cache double stream */ @Override DoubleCacheStream filter(DoublePredicate predicate); /** * Same as {@link DoubleCacheStream#filter(DoublePredicate)} except that the DoublePredicate must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param predicate a non-interfering, stateless * predicate to apply to each element to determine if it * should be included * @return the new cache double stream */ default DoubleCacheStream filter(SerializableDoublePredicate predicate) { return filter((DoublePredicate) predicate); } /** * {@inheritDoc} * @return the new cache double stream */ @Override DoubleCacheStream map(DoubleUnaryOperator mapper); /** * Same as {@link DoubleCacheStream#map(DoubleUnaryOperator)} except that the DoubleUnaryOperator must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param mapper a non-interfering, stateless * function to apply to each element * @return the new cache double stream */ default DoubleCacheStream map(SerializableDoubleUnaryOperator mapper) { return map((DoubleUnaryOperator) mapper); } /** * {@inheritDoc} * @return the new cache stream */ @Override <U> CacheStream<U> mapToObj(DoubleFunction<? extends U> mapper); /** * Same as {@link DoubleCacheStream#mapToObj(DoubleFunction)} except that the DoubleFunction must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param <U> the element type of the new stream * @param mapper a non-interfering, stateless * function to apply to each element * @return the new cache stream */ default <U> CacheStream<U> mapToObj(SerializableDoubleFunction<? extends U> mapper) { return mapToObj((DoubleFunction<? extends U>) mapper); } /** * {@inheritDoc} * @return the new cache int stream */ @Override IntCacheStream mapToInt(DoubleToIntFunction mapper); /** * Same as {@link DoubleCacheStream#mapToInt(DoubleToIntFunction)} except that the DoubleToIntFunction must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param mapper a non-interfering, stateless * function to apply to each element * @return the new cache int stream */ default IntCacheStream mapToInt(SerializableDoubleToIntFunction mapper) { return mapToInt((DoubleToIntFunction) mapper); } /** * {@inheritDoc} * @return the new cache long stream */ @Override LongCacheStream mapToLong(DoubleToLongFunction mapper); /** * Same as {@link DoubleCacheStream#mapToLong(DoubleToLongFunction)} except that the DoubleToLongFunction must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param mapper a non-interfering, stateless * function to apply to each element * @return the new cache long stream */ default LongCacheStream mapToLong(SerializableDoubleToLongFunction mapper) { return mapToLong((DoubleToLongFunction) mapper); } /** * {@inheritDoc} * @return the new cache double stream */ @Override DoubleCacheStream flatMap(DoubleFunction<? extends DoubleStream> mapper); /** * Same as {@link DoubleCacheStream#flatMap(DoubleFunction)} except that the DoubleFunction must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param mapper a non-interfering, stateless * function to apply to each element which produces a * {@code DoubleStream} of new values * @return the new cache double stream */ default DoubleCacheStream flatMap(SerializableDoubleFunction<? extends DoubleStream> mapper) { return flatMap((DoubleFunction<? extends DoubleStream>) mapper); } /** * {@inheritDoc} * @return the new cache double stream */ @Override DoubleCacheStream distinct(); /** * {@inheritDoc} * @return the new cache double stream */ @Override DoubleCacheStream sorted(); /** * {@inheritDoc} * @return the new cache double stream */ @Override DoubleCacheStream peek(DoubleConsumer action); /** * Same as {@link DoubleCacheStream#flatMap(DoubleFunction)} except that the DoubleFunction must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param action a non-interfering action to perform on the elements as * they are consumed from the stream * @return the new cache double stream */ default DoubleCacheStream peek(SerializableDoubleConsumer action) { return peek((DoubleConsumer) action); } /** * {@inheritDoc} * @return the new cache double stream */ @Override DoubleCacheStream limit(long maxSize); /** * {@inheritDoc} * @return the new cache double stream */ @Override DoubleCacheStream skip(long n); /** * Same as {@link DoubleCacheStream#forEach(DoubleConsumer)} except that the DoubleConsumer must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param action a non-interfering action to perform on the elements */ default void forEach(SerializableDoubleConsumer action) { forEach((DoubleConsumer) action); } /** * Same as {@link DoubleCacheStream#forEach(DoubleConsumer)} except that it takes an {@link ObjDoubleConsumer} that * provides access to the underlying {@link Cache} that is backing this stream. * <p> * Note that the <code>CacheAware</code> interface is not supported for injection using this method as the cache * is provided in the consumer directly. * @param action consumer to be ran for each element in the stream * @param <K> key type of the cache * @param <V> value type of the cache */ <K, V> void forEach(ObjDoubleConsumer<Cache<K, V>> action); /** * Same as {@link DoubleCacheStream#forEach(ObjDoubleConsumer)} except that the <code>BiConsumer</code> must also implement * <code>Serializable</code> * @param action consumer to be ran for each element in the stream * @param <K> key type of the cache * @param <V> value type of the cache */ default <K, V> void forEach(SerializableObjDoubleConsumer<Cache<K, V>> action) { forEach((ObjDoubleConsumer<Cache<K, V>>) action); } /** * Same as {@link DoubleCacheStream#reduce(double, DoubleBinaryOperator)} except that the DoubleBinaryOperator must * also implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param identity the identity value for the accumulating function * @param op an associative, non-interfering, stateless * function for combining two values * @return the result of the reduction */ default double reduce(double identity, SerializableDoubleBinaryOperator op) { return reduce(identity, (DoubleBinaryOperator) op); } /** * Same as {@link DoubleCacheStream#reduce(DoubleBinaryOperator)} except that the DoubleBinaryOperator must * also implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param op an associative, non-interfering, stateless * function for combining two values * @return the result of the reduction */ default OptionalDouble reduce(SerializableDoubleBinaryOperator op) { return reduce((DoubleBinaryOperator) op); } /** * Same as {@link DoubleCacheStream#collect(Supplier, ObjDoubleConsumer, BiConsumer)} except that the arguments must * also implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param <R> type of the result * @param supplier a function that creates a new result container. For a * parallel execution, this function may be called * multiple times and must return a fresh value each time. * @param accumulator an associative, non-interfering, stateless * function for incorporating an additional element into a result * @param combiner an associative, non-interfering, stateless * function for combining two values, which must be * compatible with the accumulator function * @return the result of the reduction */ default <R> R collect(SerializableSupplier<R> supplier, SerializableObjDoubleConsumer<R> accumulator, SerializableBiConsumer<R, R> combiner) { return collect((Supplier<R>) supplier, accumulator, combiner); } /** * Same as {@link DoubleCacheStream#anyMatch(DoublePredicate)} except that the DoublePredicate must * also implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param predicate a non-interfering, stateless * predicate to apply to elements of this stream * @return {@code true} if any elements of the stream match the provided * predicate, otherwise {@code false} */ default boolean anyMatch(SerializableDoublePredicate predicate) { return anyMatch((DoublePredicate) predicate); } /** * Same as {@link DoubleCacheStream#allMatch(DoublePredicate)} except that the DoublePredicate must * also implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param predicate a non-interfering, stateless * predicate to apply to elements of this stream * @return {@code true} if either all elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} */ default boolean allMatch(SerializableDoublePredicate predicate) { return allMatch((DoublePredicate) predicate); } /** * Same as {@link DoubleCacheStream#noneMatch(DoublePredicate)} except that the DoublePredicate must * also implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param predicate a non-interfering, stateless * predicate to apply to elements of this stream * @return {@code true} if either no elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} */ default boolean noneMatch(SerializableDoublePredicate predicate) { return noneMatch((DoublePredicate) predicate); } /** * {@inheritDoc} * @return the new cache stream containing doubles */ @Override CacheStream<Double> boxed(); /** * {@inheritDoc} * @return a sequential cache double stream */ @Override DoubleCacheStream sequential(); /** * {@inheritDoc} * @return a parallel cache double stream */ @Override DoubleCacheStream parallel(); /** * {@inheritDoc} * @return an unordered cache double stream */ @Override DoubleCacheStream unordered(); /** * {@inheritDoc} * @return a cache double stream with the handler applied */ @Override DoubleCacheStream onClose(Runnable closeHandler); }
15,025
35.120192
126
java
null
infinispan-main/core/src/main/java/org/infinispan/AdvancedCache.java
package org.infinispan; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; import java.util.function.Function; import javax.security.auth.Subject; import javax.transaction.xa.XAResource; import org.infinispan.batch.BatchContainer; import org.infinispan.cache.impl.DecoratedCache; import org.infinispan.commons.api.TransactionalCache; import org.infinispan.commons.dataconversion.Encoder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.Wrapper; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.PartitionHandlingConfiguration; import org.infinispan.container.DataContainer; import org.infinispan.container.entries.CacheEntry; import org.infinispan.context.Flag; import org.infinispan.distribution.DistributionManager; import org.infinispan.encoding.DataConversion; import org.infinispan.eviction.EvictionManager; import org.infinispan.expiration.ExpirationManager; import org.infinispan.factories.ComponentRegistry; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.metadata.Metadata; import org.infinispan.partitionhandling.AvailabilityMode; import org.infinispan.partitionhandling.impl.PartitionHandlingManager; import org.infinispan.persistence.spi.CacheLoader; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.security.AuthorizationManager; import org.infinispan.stats.Stats; import org.infinispan.transaction.LockingMode; import org.infinispan.util.concurrent.locks.LockManager; import org.infinispan.util.function.SerializableBiFunction; import org.infinispan.util.function.SerializableFunction; /** * An advanced interface that exposes additional methods not available on {@link Cache}. * * @author Manik Surtani * @author Galder Zamarreño * @author Tristan Tarrant * @since 4.0 */ public interface AdvancedCache<K, V> extends Cache<K, V>, TransactionalCache { /** * A method that adds flags to any API call. For example, consider the following code snippet: * <pre> * cache.withFlags(Flag.FORCE_WRITE_LOCK).get(key); * </pre> * will invoke a cache.get() with a write lock forced. * <p/> * <b>Note</b> that for the flag to take effect, the cache operation <b>must</b> be invoked on the instance returned * by this method. * <p/> * As an alternative to setting this on every invocation, users should also consider saving the decorated * cache, as this allows for more readable code. E.g.: * <pre> * AdvancedCache&lt;?, ?&gt; forceWriteLockCache = cache.withFlags(Flag.FORCE_WRITE_LOCK); * forceWriteLockCache.get(key1); * forceWriteLockCache.get(key2); * forceWriteLockCache.get(key3); * </pre> * * @param flags a set of flags to apply. See the {@link Flag} documentation. * @return an {@link AdvancedCache} instance on which a real operation is to be invoked, if the flags are to be * applied. */ AdvancedCache<K, V> withFlags(Flag... flags); /** * An alternative to {@link #withFlags(Flag...)} not requiring array allocation. * * @since 9.2 */ default AdvancedCache<K, V> withFlags(Collection<Flag> flags) { if (flags == null) return this; int numFlags = flags.size(); if (numFlags == 0) return this; return withFlags(flags.toArray(new Flag[numFlags])); } /** * An alternative to {@link #withFlags(Flag...)} optimized for a single flag. * * @since 10.0 */ default AdvancedCache<K, V> withFlags(Flag flag) { return withFlags(new Flag[]{flag}); } /** * Unset all flags set on this cache using {@link #withFlags(Flag...)} or {@link #withFlags(Collection)} methods. * * @return Cache not applying any flags to the command; possibly <code>this</code>. */ default AdvancedCache<K, V> noFlags() { throw new UnsupportedOperationException(); } /** * Apply the <code>transformation</code> on each {@link AdvancedCache} instance in a delegation chain, starting * with the innermost implementation. * * @param transformation * @return The outermost transformed cache. */ default AdvancedCache<K, V> transform(Function<AdvancedCache<K, V>, ? extends AdvancedCache<K, V>> transformation) { throw new UnsupportedOperationException(); } /** * Performs any cache operations using the specified {@link Subject}. Only applies to caches with authorization * enabled (see {@link ConfigurationBuilder#security()}). * * @param subject * @return an {@link AdvancedCache} instance on which a real operation is to be invoked, using the specified subject */ AdvancedCache<K, V> withSubject(Subject subject); /** * Allows the modification of the interceptor chain. * * @deprecated Since 10.0, will be removed without a replacement */ @Deprecated AsyncInterceptorChain getAsyncInterceptorChain(); /** * @return the eviction manager - if one is configured - for this cache instance * * @deprecated Since 10.1, will be removed without a replacement */ @Deprecated EvictionManager getEvictionManager(); /** * @return the expiration manager - if one is configured - for this cache instance */ ExpirationManager<K, V> getExpirationManager(); /** * @return the component registry for this cache instance * @deprecated Since 10.0, with no public API replacement */ @Deprecated ComponentRegistry getComponentRegistry(); /** * Retrieves a reference to the {@link org.infinispan.distribution.DistributionManager} if the cache is configured to * use Distribution. Otherwise, returns a null. * * @return a DistributionManager, or null. */ DistributionManager getDistributionManager(); /** * Retrieves the {@link AuthorizationManager} if the cache has security enabled. Otherwise returns null * * @return an AuthorizationManager or null */ AuthorizationManager getAuthorizationManager(); /** * Whenever this cache acquires a lock it will do so using the given Object as the owner of said lock. * <p> * This can be useful when a lock may have been manually acquired and you wish to reuse that lock across * invocations. * <p> * Great care should be taken with this command as misuse can very easily lead to deadlocks. * * @param lockOwner the lock owner to lock any keys as * @return an {@link AdvancedCache} instance on which when an operation is invoked it will use lock owner object to * acquire any locks */ AdvancedCache<K, V> lockAs(Object lockOwner); /** * Locks a given key or keys eagerly across cache nodes in a cluster. * <p> * Keys can be locked eagerly in the context of a transaction only. * * @param keys the keys to lock * @return true if the lock acquisition attempt was successful for <i>all</i> keys; false will only be returned if * the lock acquisition timed out and the operation has been called with {@link Flag#FAIL_SILENTLY}. * @throws org.infinispan.util.concurrent.TimeoutException if the lock cannot be acquired within the configured lock * acquisition time. */ boolean lock(K... keys); /** * Locks collections of keys eagerly across cache nodes in a cluster. * <p> * Collections of keys can be locked eagerly in the context of a transaction only. * * @param keys collection of keys to lock * @return true if the lock acquisition attempt was successful for <i>all</i> keys; false will only be returned if * the lock acquisition timed out and the operation has been called with {@link Flag#FAIL_SILENTLY}. * @throws org.infinispan.util.concurrent.TimeoutException if the lock cannot be acquired within the configured lock * acquisition time. */ boolean lock(Collection<? extends K> keys); /** * Returns the component in charge of communication with other caches in the cluster. If the cache's {@link * org.infinispan.configuration.cache.ClusteringConfiguration#cacheMode()} is {@link * org.infinispan.configuration.cache.CacheMode#LOCAL}, this method will return null. * * @return the RPC manager component associated with this cache instance or null */ RpcManager getRpcManager(); /** * Returns the component in charge of batching cache operations. * * @return the batching component associated with this cache instance */ BatchContainer getBatchContainer(); /** * Returns the container where data is stored in the cache. Users should interact with this component with care * because direct calls on it bypass the internal interceptors and other infrastructure in place to guarantee the * consistency of data. * * @return the data container associated with this cache instance */ DataContainer<K, V> getDataContainer(); /** * Returns the component that deals with all aspects of acquiring and releasing locks for cache entries. * * @return retrieves the lock manager associated with this cache instance */ LockManager getLockManager(); /** * Returns a {@link Stats} object that allows several statistics associated with this cache at runtime. * * @return this cache's {@link Stats} object */ Stats getStats(); /** * Returns the {@link XAResource} associated with this cache which can be used to do transactional recovery. * * @return an instance of {@link XAResource} */ XAResource getXAResource(); /** * Returns the cache loader associated associated with this cache. As an alternative to setting this on every * invocation, users could also consider using the {@link DecoratedCache} wrapper. * * @return this cache's cache loader */ ClassLoader getClassLoader(); /** * @deprecated Since 9.4, unmarshalling always uses the classloader from the global configuration. */ @Deprecated AdvancedCache<K, V> with(ClassLoader classLoader); /** * An overloaded form of {@link #put(K, V)}, which takes in an instance of {@link org.infinispan.metadata.Metadata} * which can be used to provide metadata information for the entry being stored, such as lifespan, version of * value...etc. * * @param key key to use * @param value value to store * @param metadata information to store alongside the value * @return the previous value associated with <tt>key</tt>, or <tt>null</tt> if there was no mapping for * <tt>key</tt>. * @since 5.3 */ V put(K key, V value, Metadata metadata); /** * An overloaded form of {@link #putAll(Map)}, which takes in an instance of {@link org.infinispan.metadata.Metadata} * which can be used to provide metadata information for the entries being stored, such as lifespan, version of * value...etc. * * @param map the values to store * @param metadata information to store alongside the value(s) * @since 7.2 */ void putAll(Map<? extends K, ? extends V> map, Metadata metadata); default CompletableFuture<Void> putAllAsync(Map<? extends K, ? extends V> map, Metadata metadata) { return putAllAsync(map, metadata.lifespan(), TimeUnit.MILLISECONDS, metadata.maxIdle(), TimeUnit.MILLISECONDS); } /** * An overloaded form of {@link #replace(K, V)}, which takes in an instance of {@link Metadata} which can be used to * provide metadata information for the entry being stored, such as lifespan, version of value...etc. The {@link * Metadata} is only stored if the call is successful. * * @param key key with which the specified value is associated * @param value value to be associated with the specified key * @param metadata information to store alongside the new value * @return the previous value associated with the specified key, or <tt>null</tt> if there was no mapping for the * key. * @since 5.3 */ V replace(K key, V value, Metadata metadata); /** * An overloaded form of {@link #replaceAsync(K, V)}, which takes in an instance of {@link Metadata} which can be used to * provide metadata information for the entry being stored, such as lifespan, version of value...etc. The {@link * Metadata} is only stored if the call is successful. * * @param key key with which the specified value is associated * @param value value to be associated with the specified key * @param metadata information to store alongside the new value * @return the future that contains previous value associated with the specified key, or <tt>null</tt> * if there was no mapping for the key. * @since 9.2 */ default CompletableFuture<V> replaceAsync(K key, V value, Metadata metadata) { return replaceAsync(key, value, metadata.lifespan(), TimeUnit.MILLISECONDS, metadata.maxIdle(), TimeUnit.MILLISECONDS); } /** * An extension of {@link #replaceAsync(K, V, Metadata)}, which returns a {@link CacheEntry} instead of * only the value. * * @param key key with which the specified value is associated * @param value value to be associated with the specified key * @param metadata information to store alongside the new value * @return the future that contains previous {@link CacheEntry} associated with the specified key, * or <tt>null</tt> if there was no mapping for the key. * @since 14.0 * @see #replaceAsync(K, V, Metadata) */ CompletableFuture<CacheEntry<K, V>> replaceAsyncEntry(K key, V value, Metadata metadata); /** * An overloaded form of {@link #replace(K, V, V)}, which takes in an instance of {@link Metadata} which can be used * to provide metadata information for the entry being stored, such as lifespan, version of value...etc. The {@link * Metadata} is only stored if the call is successful. * * @param key key with which the specified value is associated * @param oldValue value expected to be associated with the specified key * @param newValue value to be associated with the specified key * @param metadata information to store alongside the new value * @return <tt>true</tt> if the value was replaced * @since 5.3 */ boolean replace(K key, V oldValue, V newValue, Metadata metadata); default CompletableFuture<Boolean> replaceAsync(K key, V oldValue, V newValue, Metadata metadata) { return replaceAsync(key, oldValue, newValue, metadata.lifespan(), TimeUnit.MILLISECONDS, metadata.maxIdle(), TimeUnit.MILLISECONDS); } /** * An overloaded form of {@link #putIfAbsent(K, V)}, which takes in an instance of {@link Metadata} which can be used * to provide metadata information for the entry being stored, such as lifespan, version of value...etc. The {@link * Metadata} is only stored if the call is successful. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @param metadata information to store alongside the new value * @return the previous value associated with the specified key, or <tt>null</tt> if there was no mapping for the * key. * @since 5.3 */ V putIfAbsent(K key, V value, Metadata metadata); /** * An overloaded form of {@link #putIfAbsentAsync(K, V)}, which takes in an instance of {@link Metadata} which can be used * to provide metadata information for the entry being stored, such as lifespan, version of value...etc. The {@link * Metadata} is only stored if the call is successful. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @param metadata information to store alongside the new value * @return A future containing the previous value associated with the specified key, or <tt>null</tt> if there was no mapping for the * key. * @since 9.2 */ default CompletableFuture<V> putIfAbsentAsync(K key, V value, Metadata metadata) { return putIfAbsentAsync(key, value, metadata.lifespan(), TimeUnit.MILLISECONDS, metadata.maxIdle(), TimeUnit.MILLISECONDS); } /** * An extension form of {@link #putIfAbsentAsync(K, V, Metadata)}, which returns a {@link CacheEntry} instead of * only the value. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @param metadata information to store alongside the new value * @return the future that contains previous {@link CacheEntry} associated with the specified key, * or <tt>null</tt> if there was no mapping for the key. * @since 14.0 * @see #putIfAbsentAsync(K, V, Metadata) */ CompletableFuture<CacheEntry<K, V>> putIfAbsentAsyncEntry(K key, V value, Metadata metadata); /** * An overloaded form of {@link #putForExternalRead(K, V)}, which takes in an instance of {@link Metadata} which can * be used to provide metadata information for the entry being stored, such as lifespan, version of value...etc. The * {@link Metadata} is only stored if the call is successful. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @param metadata information to store alongside the new value * @since 7.0 */ void putForExternalRead(K key, V value, Metadata metadata); /** * An overloaded form of {@link #compute(K, BiFunction)}, which takes in an instance of {@link Metadata} which can be * used to provide metadata information for the entry being stored, such as lifespan, version of value...etc. * * @param key key with which the specified value is associated * @param remappingFunction function to be applied to the specified key/value * @param metadata information to store alongside the new value * @return the previous value associated with the specified key, or <tt>null</tt> if remapping function is gives * null. * @since 9.1 */ V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, Metadata metadata); /** * Overloaded {@link #compute(Object, BiFunction, Metadata)} with {@link SerializableBiFunction} */ default V compute(K key, SerializableBiFunction<? super K, ? super V, ? extends V> remappingFunction, Metadata metadata) { return this.compute(key, (BiFunction<? super K, ? super V, ? extends V>) remappingFunction, metadata); } /** * An overloaded form of {@link #computeIfPresent(K, BiFunction)}, which takes in an instance of {@link Metadata} * which can be used to provide metadata information for the entry being stored, such as lifespan, version of * value...etc. The {@link Metadata} is only stored if the call is successful. * * @param key key with which the specified value is associated * @param remappingFunction function to be applied to the specified key/value * @param metadata information to store alongside the new value * @return the previous value associated with the specified key, or <tt>null</tt> if there was no mapping for the * key. * @since 9.1 */ V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, Metadata metadata); /** * Overloaded {@link #computeIfPresent(Object, BiFunction, Metadata)} with {@link SerializableBiFunction} */ default V computeIfPresent(K key, SerializableBiFunction<? super K, ? super V, ? extends V> remappingFunction, Metadata metadata) { return this.computeIfPresent(key, (BiFunction<? super K, ? super V, ? extends V>) remappingFunction, metadata); } /** * An overloaded form of {@link #computeIfAbsent(K, Function)}, which takes in an instance of {@link Metadata} which * can be used to provide metadata information for the entry being stored, such as lifespan, version of value...etc. * The {@link Metadata} is only stored if the call is successful. * * @param key key with which the specified value is associated * @param mappingFunction function to be applied to the specified key * @param metadata information to store alongside the new value * @return the value created with the mapping function associated with the specified key, or the previous value * associated with the specified key if the key is not absent. * @since 9.1 */ V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction, Metadata metadata); /** * Overloaded {@link #computeIfAbsent(Object, Function, Metadata)} with {@link SerializableFunction} */ default V computeIfAbsent(K key, SerializableFunction<? super K, ? extends V> mappingFunction, Metadata metadata) { return this.computeIfAbsent(key, (Function<? super K, ? extends V>) mappingFunction, metadata); } /** * An overloaded form of {@link #merge(Object, Object, BiFunction)}, which takes in an instance of {@link Metadata} * which can be used to provide metadata information for the entry being stored, such as lifespan, version of * value...etc. The {@link Metadata} is only stored if the call is successful. * * @param key, key with which the resulting value is to be associated * @param value, the non-null value to be merged with the existing value associated with the key or, if * no existing value or a null value is associated with the key, to be associated with the * key * @param remappingFunction, the function to recompute a value if present * @param metadata, information to store alongside the new value * @return the new value associated with the specified key, or null if no value is associated with the key * @since 9.2 */ V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, Metadata metadata); /** * Overloaded {@link #merge(Object, Object, BiFunction, Metadata)} with {@link SerializableBiFunction} */ default V merge(K key, V value, SerializableBiFunction<? super V, ? super V, ? extends V> remappingFunction, Metadata metadata) { return this.merge(key, value, (BiFunction<? super V, ? super V, ? extends V>) remappingFunction, metadata); } /** * Asynchronous version of {@link #put(Object, Object, Metadata)} which stores metadata alongside the value. This * method does not block on remote calls, even if your cache mode is synchronous. Has no benefit over {@link * #put(Object, Object, Metadata)} if used in LOCAL mode. * <p/> * * @param key key to use * @param value value to store * @param metadata information to store alongside the new value * @return a future containing the old value replaced. * @since 5.3 */ CompletableFuture<V> putAsync(K key, V value, Metadata metadata); /** * Extension of {@link #putAsync(K, V, Metadata)} which returns a {@link CacheEntry} instead of only the * previous value. * * @param key key to use * @param value value to store * @param metadata information to store alongside the new value * @return a future containing the old {@link CacheEntry} replaced. * @since 14.0 */ CompletableFuture<CacheEntry<K, V>> putAsyncEntry(K key, V value, Metadata metadata); /** * Overloaded {@link #computeAsync(K, BiFunction)}, which stores metadata alongside the value. This * method does not block on remote calls, even if your cache mode is synchronous. * * @param key key with which the specified value is associated * @param remappingFunction function to be applied to the specified key/value * @param metadata information to store alongside the new value * @return the previous value associated with the specified key, or <tt>null</tt> if remapping function is gives * null. * @since 9.4 */ CompletableFuture<V> computeAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, Metadata metadata); /** * Overloaded {@link #computeAsync(Object, BiFunction, Metadata)} with {@link SerializableBiFunction} * @since 9.4 */ default CompletableFuture<V> computeAsync(K key, SerializableBiFunction<? super K, ? super V, ? extends V> remappingFunction, Metadata metadata) { return this.computeAsync(key, (BiFunction<? super K, ? super V, ? extends V>) remappingFunction, metadata); } /** * Overloaded {@link #computeIfPresentAsync(K, BiFunction)}, which takes in an instance of {@link Metadata} * which can be used to provide metadata information for the entry being stored, such as lifespan, version of * value...etc. The {@link Metadata} is only stored if the call is successful. * * @param key key with which the specified value is associated * @param remappingFunction function to be applied to the specified key/value * @param metadata information to store alongside the new value * @return the previous value associated with the specified key, or <tt>null</tt> if there was no mapping for the * key. * @since 9.4 */ CompletableFuture<V> computeIfPresentAsync(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, Metadata metadata); /** * Overloaded {@link #computeIfPresentAsync(Object, BiFunction, Metadata)} with {@link SerializableBiFunction} * @since 9.4 */ default CompletableFuture<V> computeIfPresentAsync(K key, SerializableBiFunction<? super K, ? super V, ? extends V> remappingFunction, Metadata metadata) { return this.computeIfPresentAsync(key, (BiFunction<? super K, ? super V, ? extends V>) remappingFunction, metadata); } /** * Overloaded {@link #computeIfAbsentAsync(K, Function)}, which takes in an instance of {@link Metadata} which * can be used to provide metadata information for the entry being stored, such as lifespan, version of value...etc. * The {@link Metadata} is only stored if the call is successful. * * @param key key with which the specified value is associated * @param mappingFunction function to be applied to the specified key * @param metadata information to store alongside the new value * @return the value created with the mapping function associated with the specified key, or the previous value * associated with the specified key if the key is not absent. * @since 9.4 */ CompletableFuture<V> computeIfAbsentAsync(K key, Function<? super K, ? extends V> mappingFunction, Metadata metadata); /** * Overloaded {@link #computeIfAbsentAsync(Object, Function, Metadata)} with {@link SerializableFunction} * @since 9.4 */ default CompletableFuture<V> computeIfAbsentAsync(K key, SerializableFunction<? super K, ? extends V> mappingFunction, Metadata metadata) { return this.computeIfAbsentAsync(key, (Function<? super K, ? extends V>) mappingFunction, metadata); } /** * Overloaded {@link #mergeAsync(Object, Object, BiFunction)}, which takes in an instance of {@link Metadata} * which can be used to provide metadata information for the entry being stored, such as lifespan, version of * value...etc. The {@link Metadata} is only stored if the call is successful. * * @param key, key with which the resulting value is to be associated * @param value, the non-null value to be merged with the existing value associated with the key or, if * no existing value or a null value is associated with the key, to be associated with the * key * @param remappingFunction, the function to recompute a value if present * @param metadata, information to store alongside the new value * @return the new value associated with the specified key, or null if no value is associated with the key * @since 9.4 */ CompletableFuture<V> mergeAsync(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, Metadata metadata); /** * Overloaded {@link #mergeAsync(Object, Object, BiFunction, Metadata)} with {@link SerializableBiFunction} */ default CompletableFuture<V> mergeAsync(K key, V value, SerializableBiFunction<? super V, ? super V, ? extends V> remappingFunction, Metadata metadata) { return this.mergeAsync(key, value, (BiFunction<? super V, ? super V, ? extends V>) remappingFunction, metadata); } // TODO: Even better: add replace/remove calls that apply the changes if a given function is successful // That way, you could do comparison not only on the cache value, but also based on version...etc /** * Gets a collection of entries, returning them as {@link Map} of the values associated with the set of keys * requested. * <p> * If the cache is configured read-through, and a get for a key would return null because an entry is missing from * the cache, the Cache's {@link CacheLoader} is called in an attempt to load the entry. If an entry cannot be loaded * for a given key, the returned Map will contain null for value of the key. * <p> * Unlike other bulk methods if this invoked in an existing transaction all entries will be stored in the current * transactional context * <p> * The returned {@link Map} will be a copy and updates to the map will not be reflected in the Cache and vice versa. * The keys and values themselves however may not be copies depending on if storeAsBinary is enabled and the value * was retrieved from the local node. * * @param keys The keys whose associated values are to be returned. * @return A map of entries that were found for the given keys. If an entry is not found for a given key, it will not * be in the returned map. * @throws NullPointerException if keys is null or if keys contains a null */ Map<K, V> getAll(Set<?> keys); /** * Retrieves a CacheEntry corresponding to a specific key. * * @param key the key whose associated cache entry is to be returned * @return the cache entry to which the specified key is mapped, or {@code null} if this map contains no mapping for * the key * @since 5.3 */ CacheEntry<K, V> getCacheEntry(Object key); /** * Retrieves a CacheEntry corresponding to a specific key. * * @param key the key whose associated cache entry is to be returned * @return a future with the cache entry to which the specified key is mapped, or with {@code null} * if this map contains no mapping for the key * @since 9.2 */ default CompletableFuture<CacheEntry<K, V>> getCacheEntryAsync(Object key) { throw new UnsupportedOperationException("getCacheEntryAsync"); } /** * Gets a collection of entries from the {@link AdvancedCache}, returning them as {@link Map} of the cache entries * associated with the set of keys requested. * <p> * If the cache is configured read-through, and a get for a key would return null because an entry is missing from * the cache, the Cache's {@link CacheLoader} is called in an attempt to load the entry. If an entry cannot be loaded * for a given key, the returned Map will contain null for value of the key. * <p> * Unlike other bulk methods if this invoked in an existing transaction all entries will be stored in the current * transactional context * <p> * The returned {@link Map} will be a copy and updates to the map will not be reflected in the Cache and vice versa. * The keys and values themselves however may not be copies depending on if storeAsBinary is enabled and the value * was retrieved from the local node. * * @param keys The keys whose associated values are to be returned. * @return A map of entries that were found for the given keys. Keys not found in the cache are present in the map * with null values. * @throws NullPointerException if keys is null or if keys contains a null */ Map<K, CacheEntry<K, V>> getAllCacheEntries(Set<?> keys); /** * Executes an equivalent of {@link Map#putAll(Map)}, returning previous values of the modified entries. * * @param map mappings to be stored in this map * @return A map of previous values for the given keys. If the previous mapping does not exist it will not be in the * returned map. * @since 9.1 */ default Map<K, V> getAndPutAll(Map<? extends K, ? extends V> map) { Map<K, V> result = new HashMap<>(map.size()); for (Entry<? extends K, ? extends V> entry : map.entrySet()) { V prev = put(entry.getKey(), entry.getValue()); if (prev != null) { result.put(entry.getKey(), prev); } } return result; } /** * It fetches all the keys which belong to the group. * <p/> * Semantically, it iterates over all the keys in memory and persistence, and performs a read operation in the keys * found. Multiple invocations inside a transaction ensures that all the keys previous read are returned and it may * return newly added keys to the group from other committed transactions (also known as phantom reads). * <p/> * The {@code map} returned is immutable and represents the group at the time of the invocation. If you want to add * or remove keys from a group use {@link #put(Object, Object)} and {@link #remove(Object)}. To remove all the keys * in the group use {@link #removeGroup(String)}. * <p/> * To improve performance you may use the {@code flag} {@link org.infinispan.context.Flag#SKIP_CACHE_LOAD} to avoid * fetching the key/value from persistence. However, you will get an inconsistent snapshot of the group. * * @param groupName the group name. * @return an immutable {@link java.util.Map} with the key/value pairs. */ Map<K, V> getGroup(String groupName); /** * It removes all the key which belongs to a group. * <p/> * Semantically, it fetches the most recent group keys/values and removes them. * <p/> * Note that, concurrent addition perform by other transactions/threads to the group may not be removed. * * @param groupName the group name. */ void removeGroup(String groupName); /** * Returns the cache's availability. In local mode this method will always return {@link AvailabilityMode#AVAILABLE}. * In clustered mode, the {@link PartitionHandlingManager} is queried to obtain the availability mode. */ AvailabilityMode getAvailability(); /** * Manually change the availability of the cache. Doesn't change anything if the cache is not clustered or {@link * PartitionHandlingConfiguration#whenSplit()} is set to {@link org.infinispan.partitionhandling.PartitionHandling#ALLOW_READ_WRITES}. */ void setAvailability(AvailabilityMode availabilityMode); /** * Touches the given key if present. This will refresh its last access time, used for max idle, and count as a recent * access for eviction purposes. * <p> * Note that it is possible to touch an entry that is expired via max idle if {@code touchEvenIfExpired} argument is * {@code true}. * <p> * This method will return without blocking and complete the returned stage with a value after all appropriate nodes * have actually touched the value. * @param key key of the entry to touch * @param touchEvenIfExpired true if the entry should be touched even if already expired via max idle, effectively * making it so the entry is no longer expired via max idle * @return true if the entry was actually touched */ CompletionStage<Boolean> touch(Object key, boolean touchEvenIfExpired); /** * The same as {@link #touch(Object, boolean)} except that the segment is already known. This can be helpful to reduce * an extra segment computation * @param key key of the entry to touch * @param segment segment of the key * @param touchEvenIfExpired true if the entry should be touched even if already expired via max idle, effectively * making it so the entry is no longer expired via max idle * @return true if the entry was actually touched */ CompletionStage<Boolean> touch(Object key, int segment, boolean touchEvenIfExpired); /** * Identical to {@link Cache#entrySet()} but is typed to return CacheEntries instead of Entries. Please see the * other method for a description of its behaviors. * <p> * This method is needed since nested generics do not support covariance * * @return the entry set containing all of the CacheEntries * @see Cache#entrySet() */ CacheSet<CacheEntry<K, V>> cacheEntrySet(); /** * Returns a sequential stream using this Cache as the source. This stream is very similar to using the {@link * CacheStream} returned from the {@link CacheSet#stream()} method of the collection returned via {@link * AdvancedCache#cacheEntrySet()}. The use of this locked stream is that when an entry is being processed by the user * the entry is locked for the invocation preventing a different thread from modifying it. * <p> * Note that this stream is not supported when using a optimistic transactional or simple cache. Both non * transactional and pessimistic transactional caches are supported. * <p> * The stream will not share any ongoing transaction the user may have. Code executed by the stream should be treated * as completely independent. That is any operation performed via the stream will require the user to start their own * transaction or will be done intrinsically on the invocation. Note that if there is an ongoing transaction that has * a lock on a key from the cache, that it will cause a deadlock. * <p> * Currently simple cache, {@link org.infinispan.configuration.cache.ConfigurationBuilder#simpleCache(boolean)} was * set to true, and optimistic caches, {@link org.infinispan.configuration.cache.TransactionConfigurationBuilder#lockingMode(LockingMode)} * was set to {@link LockingMode#OPTIMISTIC}, do not support this method. In this case it will throw an {@link * UnsupportedOperationException}. This restriction may be removed in a future version. Also this method cannot be * used on a cache that has a lock owner already specified via {@link AdvancedCache#lockAs(Object)} as this could * lead to a deadlock or the release of locks early and will throw an {@link IllegalStateException}. * * @return the locked stream * @throws UnsupportedOperationException this is thrown if invoked from a cache that doesn't support this * @throws IllegalStateException if this cache has already explicitly set a lock owner * @since 9.1 */ LockedStream<K, V> lockedStream(); /** * Attempts to remove the entry if it is expired. Due to expired entries not being consistent across nodes, this * will still attempt to remove the value if it is not present. Note that this will raise an expired event even if * the entry is not present. Normally this method should never be invoked except by the {@link ExpirationManager}. * <p> * This command will only remove the value if the value and lifespan also match if provided. * <p> * This method will suspend any ongoing transaction and start a new one just for the invocation of this command. It * is automatically committed or rolled back after the command completes, either successfully or via an exception. * <p> * NOTE: This method may be removed at any point including in a minor release and is not supported for external * usage. * * @param key the key that is expiring * @param value the value that mapped to the given. Null means it will match any value * @param lifespan the lifespan that should match. If null is provided it will match any lifespan value * @return if the entry was removed */ CompletableFuture<Boolean> removeLifespanExpired(K key, V value, Long lifespan); /** * Attempts to remove the entry for the given key, if it has expired due to max idle. This command first locks * the key and then verifies that the entry has expired via maxIdle across all nodes. If it has this will then * remove the given key. * <p> * This method returns a boolean when it has determined if the entry has expired. This is useful for when a backup * node invokes this command for a get that found the entry expired. This way the node can return back to the caller * much faster when the entry is not expired and do any additional processing asynchronously if needed. * <p> * This method will suspend any ongoing transaction and start a new one just for the invocation of this command. It * is automatically committed or rolled back after the command completes, either successfully or via an exception. * <p> * NOTE: This method may be removed at any point including in a minor release and is not supported for external * usage. * @param key the key that expired via max idle for the given entry * @return if the entry was removed */ CompletableFuture<Boolean> removeMaxIdleExpired(K key, V value); /** * Performs any cache operations using the specified pair of {@link Encoder}. * * @param keyEncoder {@link Encoder} for the keys. * @param valueEncoder {@link Encoder} for the values. * @return an instance of {@link AdvancedCache} where all operations will use the supplied encoders. * @deprecated Since 12.1, to be removed in a future version. */ @Deprecated AdvancedCache<?, ?> withEncoding(Class<? extends Encoder> keyEncoder, Class<? extends Encoder> valueEncoder); /** * Performs any cache operations using the specified pair of {@link Wrapper}. * * @param keyWrapper {@link Wrapper} for the keys. * @param valueWrapper {@link Wrapper} for the values. * @return {@link AdvancedCache} where all operations will use the supplied wrappers. * @deprecated Since 11.0. To be removed in 14.0, with no replacement. */ AdvancedCache<K, V> withWrapping(Class<? extends Wrapper> keyWrapper, Class<? extends Wrapper> valueWrapper); /** * Performs any cache operations using the specified {@link Encoder}. * * @param encoder {@link Encoder} used for both keys and values. * @return an instance of {@link AdvancedCache} where all operations will use the supplied encoder. * @deprecated Since 12.1, to be removed in a future version. */ @Deprecated AdvancedCache<?, ?> withEncoding(Class<? extends Encoder> encoder); /** * Performs any cache operations using the specified {@link Wrapper}. * * @param wrapper {@link Wrapper} for the keys and values. * @return an instance of {@link AdvancedCache} where all operations will use the supplied wrapper. * @deprecated Since 11.0. To be removed in 14.0, with no replacement. */ AdvancedCache<K, V> withWrapping(Class<? extends Wrapper> wrapper); /** * Perform any cache operations using an alternate {@link org.infinispan.commons.dataconversion.MediaType}. * * @param keyMediaType {@link org.infinispan.commons.dataconversion.MediaType} for the keys. * @param valueMediaType {@link org.infinispan.commons.dataconversion} for the values. * @return an instance of {@link AdvancedCache} where all data will formatted according to the supplied {@link * org.infinispan.commons.dataconversion.MediaType}. * * @deprecated Use {@link #withMediaType(MediaType, MediaType)} instead. */ @Deprecated AdvancedCache<?, ?> withMediaType(String keyMediaType, String valueMediaType); /** * @see #withMediaType(String, String) */ <K1, V1> AdvancedCache<K1, V1> withMediaType(MediaType keyMediaType, MediaType valueMediaType); /** * Perform any cache operations using the same {@link org.infinispan.commons.dataconversion.MediaType} of the cache * storage. This is equivalent to disabling transcoding on the cache. * * @return an instance of {@link AdvancedCache} where no data conversion will take place. */ AdvancedCache<K, V> withStorageMediaType(); /** * @return The associated {@link DataConversion} for the keys. */ DataConversion getKeyDataConversion(); /** * @return The associated {@link DataConversion} for the cache's values. */ DataConversion getValueDataConversion(); /** * @deprecated Since 12.1, to be removed in a future version. */ @Deprecated AdvancedCache<?, ?> withKeyEncoding(Class<? extends Encoder> encoder); /** * An extension of {@link #removeAsync(Object)}, which returns a {@link CacheEntry} instead of only the value. * * @param key key to remove * @return a future containing the {@link CacheEntry} removed or <code>null</code> if not found. * @since 14.0 * @see #removeAsync(Object) * @see #remove(Object) */ CompletableFuture<CacheEntry<K, V>> removeAsyncEntry(Object key); }
45,874
47.39135
158
java
null
infinispan-main/core/src/main/java/org/infinispan/IllegalLifecycleStateException.java
package org.infinispan; /** * This exception is thrown when the cache or cache manager does not have the * right lifecycle state for operations to be called on it. Situations like * this include when the cache is stopping or is stopped, when the cache * manager is stopped...etc. * * @since 7.0 * @deprecated since 10.1 please use {@link org.infinispan.commons.IllegalLifecycleStateException} instead */ @Deprecated public class IllegalLifecycleStateException extends org.infinispan.commons.IllegalLifecycleStateException { public IllegalLifecycleStateException() { } public IllegalLifecycleStateException(String s) { super(s); } public IllegalLifecycleStateException(String message, Throwable cause) { super(message, cause); } public IllegalLifecycleStateException(Throwable cause) { super(cause); } }
857
28.586207
107
java
null
infinispan-main/core/src/main/java/org/infinispan/CacheStream.java
package org.infinispan; import static org.infinispan.util.Casting.toSerialSupplierCollect; import static org.infinispan.util.Casting.toSupplierCollect; import java.io.Serializable; import java.util.Comparator; import java.util.Iterator; import java.util.Optional; import java.util.Set; import java.util.Spliterator; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.function.ToDoubleFunction; import java.util.function.ToIntFunction; import java.util.function.ToLongFunction; import java.util.stream.Collector; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import org.infinispan.commons.util.IntSet; import org.infinispan.stream.CacheCollectors; import org.infinispan.util.function.SerializableBiConsumer; import org.infinispan.util.function.SerializableBiFunction; import org.infinispan.util.function.SerializableBinaryOperator; import org.infinispan.util.function.SerializableComparator; import org.infinispan.util.function.SerializableConsumer; import org.infinispan.util.function.SerializableFunction; import org.infinispan.util.function.SerializableIntFunction; import org.infinispan.util.function.SerializablePredicate; import org.infinispan.util.function.SerializableSupplier; import org.infinispan.util.function.SerializableToDoubleFunction; import org.infinispan.util.function.SerializableToIntFunction; import org.infinispan.util.function.SerializableToLongFunction; /** * A {@link Stream} that has additional operations to monitor or control behavior when used from a {@link Cache}. * * <p>Whenever the iterator or spliterator methods are used the user <b>must</b> close the {@link Stream} * that the method was invoked on after completion of its operation. Failure to do so may cause a thread leakage if * the iterator or spliterator are not fully consumed.</p> * * <p>When using stream that is backed by a distributed cache these operations will be performed using remote * distribution controlled by the segments that each key maps to. All intermediate operations are lazy, even the * special cases described in later paragraphs and are not evaluated until a final terminal operation is invoked on * the stream. Essentially each set of intermediate operations is shipped to each remote node where they are applied * to a local stream there and finally the terminal operation is completed. If this stream is parallel the processing * on remote nodes is also done using a parallel stream.</p> * * <p>Parallel distribution is enabled by default for all operations except for {@link CacheStream#iterator()} and * {@link CacheStream#spliterator()}. Please see {@link CacheStream#sequentialDistribution()} and * {@link CacheStream#parallelDistribution()}. With this disabled only a single node will process the operation * at a time (includes locally).</p> * * <p>Rehash aware is enabled by default for all operations. Any intermediate or terminal operation may be invoked * multiple times during a rehash and thus you should ensure the are idempotent. This can be problematic for * {@link CacheStream#forEach(Consumer)} as it may be difficult to implement with such requirements, please see it for * more information. If you wish to disable rehash aware operations you can disable them by calling * {@link CacheStream#disableRehashAware()} which should provide better performance for some operations. The * performance is most affected for the key aware operations {@link CacheStream#iterator()}, * {@link CacheStream#spliterator()}, {@link CacheStream#forEach(Consumer)}. Disabling rehash can cause * incorrect results if the terminal operation is invoked and a rehash occurs before the operation completes. If * incorrect results do occur it is guaranteed that it will only be that entries were missed and no entries are * duplicated.</p> * * <p>Any stateful intermediate operation requires pulling all information up to that point local to operate properly. * Each of these methods may have slightly different behavior, so make sure you check the method you are utilizing.</p> * * <p>An example of such an operation is using distinct intermediate operation. What will happen * is upon calling the terminal operation a remote retrieval operation will be ran using all of * the intermediate operations up to the distinct operation remotely. This retrieval is then used to fuel a local * stream where all of the remaining intermediate operations are performed and then finally the terminal operation is * applied as normal. Note in this case the intermediate iterator still obeys the * {@link CacheStream#distributedBatchSize(int)} setting irrespective of the terminal operator.</p> * * @param <R> The type of the stream * @since 8.0 */ public interface CacheStream<R> extends Stream<R>, BaseCacheStream<R, Stream<R>> { /** * {@inheritDoc} * @return a stream with parallel distribution disabled. */ CacheStream<R> sequentialDistribution(); /** * @inheritDoc * @return a stream with parallel distribution enabled. */ CacheStream<R> parallelDistribution(); /** * {@inheritDoc} * @return a stream with the segments filtered. * @deprecated This is to be replaced by {@link #filterKeySegments(IntSet)} */ CacheStream<R> filterKeySegments(Set<Integer> segments); /** * {@inheritDoc} * @return a stream with the segments filtered. */ CacheStream<R> filterKeySegments(IntSet segments); /** * {@inheritDoc} * @return a stream with the keys filtered. */ CacheStream<R> filterKeys(Set<?> keys); /** * {@inheritDoc} * @return a stream with the batch size updated */ CacheStream<R> distributedBatchSize(int batchSize); /** * {@inheritDoc} * @return a stream with the listener registered. */ CacheStream<R> segmentCompletionListener(SegmentCompletionListener listener); /** * {@inheritDoc} * @return a stream with rehash awareness disabled. */ CacheStream<R> disableRehashAware(); /** * {@inheritDoc} * @return a stream with the timeout set */ CacheStream<R> timeout(long timeout, TimeUnit unit); /** * {@inheritDoc} * <p>This operation is performed remotely on the node that is the primary owner for the key tied to the entry(s) * in this stream.</p> * <p>NOTE: This method while being rehash aware has the lowest consistency of all of the operators. This * operation will be performed on every entry at least once in the cluster, as long as the originator doesn't go * down while it is being performed. This is due to how the distributed action is performed. Essentially the * {@link CacheStream#distributedBatchSize} value controls how many elements are processed per node at a time * when rehash is enabled. After those are complete the keys are sent to the originator to confirm that those were * processed. If that node goes down during/before the response those keys will be processed a second time.</p> * <p>It is possible to have the cache local to each node injected into this instance if the provided * Consumer also implements the {@link org.infinispan.stream.CacheAware} interface. This method will be invoked * before the consumer <code>accept()</code> method is invoked.</p> * <p>This method is ran distributed by default with a distributed backing cache. However if you wish for this * operation to run locally you can use the {@code stream().iterator().forEachRemaining(action)} for a single * threaded variant. If you * wish to have a parallel variant you can use {@link java.util.stream.StreamSupport#stream(Spliterator, boolean)} * passing in the spliterator from the stream. In either case remember you <b>must</b> close the stream after * you are done processing the iterator or spliterator..</p> * @param action consumer to be ran for each element in the stream */ @Override void forEach(Consumer<? super R> action); /** * Same as {@link CacheStream#forEach(Consumer)} except that the Consumer must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param action consumer to be ran for each element in the stream */ default void forEach(SerializableConsumer<? super R> action) { forEach((Consumer<? super R>) action); } /** * Same as {@link CacheStream#forEach(Consumer)} except that it takes a {@link BiConsumer} that provides access * to the underlying {@link Cache} that is backing this stream. * <p> * Note that the <code>CacheAware</code> interface is not supported for injection using this method as the cache * is provided in the consumer directly. * @param action consumer to be ran for each element in the stream * @param <K> key type of the cache * @param <V> value type of the cache */ <K, V> void forEach(BiConsumer<Cache<K, V>, ? super R> action); /** * Same as {@link CacheStream#forEach(BiConsumer)} except that the <code>BiConsumer</code> must also implement * <code>Serializable</code> * @param action consumer to be ran for each element in the stream * @param <K> key type of the cache * @param <V> value type of the cache */ default <K, V> void forEach(SerializableBiConsumer<Cache<K, V>, ? super R> action) { forEach((BiConsumer<Cache<K, V>, ? super R>) action); } /** * {@inheritDoc} * <p>Usage of this operator requires closing this stream after you are done with the iterator. The preferred * usage is to use a try with resource block on the stream.</p> * <p>This method has special usage with the {@link org.infinispan.CacheStream.SegmentCompletionListener} in * that as entries are retrieved from the next method it will complete segments.</p> * <p>This method obeys the {@link CacheStream#distributedBatchSize(int)}. Note that when using methods such as * {@link CacheStream#flatMap(Function)} that you will have possibly more than 1 element mapped to a given key * so this doesn't guarantee that many number of entries are returned per batch.</p> * <p>Note that the {@link Iterator#remove()} method is only supported if no intermediate operations have been * applied to the stream and this is not a stream created from a {@link Cache#values()} collection.</p> * @return the element iterator for this stream */ @Override Iterator<R> iterator(); /** * {@inheritDoc} * <p>Usage of this operator requires closing this stream after you are done with the spliterator. The preferred * usage is to use a try with resource block on the stream.</p> * @return the element spliterator for this stream */ @Override Spliterator<R> spliterator(); /** * {@inheritDoc} * <p>This operation is performed entirely on the local node irrespective of the backing cache. This * operation will act as an intermediate iterator operation requiring data be brought locally for proper behavior. * Beware this means it will require having all entries of this cache into memory at one time. This is described in * more detail at {@link CacheStream}</p> * <p>Any subsequent intermediate operations and the terminal operation are also performed locally.</p> * @return the new stream */ @Override CacheStream<R> sorted(); /** * {@inheritDoc} * <p>This operation is performed entirely on the local node irrespective of the backing cache. This * operation will act as an intermediate iterator operation requiring data be brought locally for proper behavior. * Beware this means it will require having all entries of this cache into memory at one time. This is described in * more detail at {@link CacheStream}</p> * <p>Any subsequent intermediate operations and the terminal operation are then performed locally.</p> * @param comparator the comparator to be used for sorting the elements * @return the new stream */ @Override CacheStream<R> sorted(Comparator<? super R> comparator); /** * Same as {@link CacheStream#sorted(Comparator)} except that the Comparator must * also implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param comparator a non-interfering, stateless * {@code Comparator} to be used to compare stream elements * @return the new stream */ default CacheStream<R> sorted(SerializableComparator<? super R> comparator) { return sorted((Comparator<? super R>) comparator); } /** * {@inheritDoc} * <p>This intermediate operation will be performed both remotely and locally to reduce how many elements * are sent back from each node. More specifically this operation is applied remotely on each node to only return * up to the <b>maxSize</b> value and then the aggregated results are limited once again on the local node.</p> * <p>This operation will act as an intermediate iterator operation requiring data be brought locally for proper * behavior. This is described in more detail in the {@link CacheStream} documentation</p> * <p>Any subsequent intermediate operations and the terminal operation are then performed locally.</p> * @param maxSize how many elements to limit this stream to. * @return the new stream */ @Override CacheStream<R> limit(long maxSize); /** * {@inheritDoc} * <p>This operation is performed entirely on the local node irrespective of the backing cache. This * operation will act as an intermediate iterator operation requiring data be brought locally for proper behavior. * This is described in more detail in the {@link CacheStream} documentation</p> * <p>Depending on the terminal operator this may or may not require all entries or a subset after skip is applied * to be in memory all at once.</p> * <p>Any subsequent intermediate operations and the terminal operation are then performed locally.</p> * @param n how many elements to skip from this stream * @return the new stream */ @Override CacheStream<R> skip(long n); /** * {@inheritDoc} * @param action the action to perform on the stream * @return the new stream */ @Override CacheStream<R> peek(Consumer<? super R> action); /** * Same as {@link CacheStream#peek(Consumer)} except that the Consumer must also implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param action a non-interfering action to perform on the elements as * they are consumed from the stream * @return the new stream */ default CacheStream<R> peek(SerializableConsumer<? super R> action) { return peek((Consumer<? super R>) action); } /** * {@inheritDoc} * <p>This operation will be invoked both remotely and locally when used with a distributed cache backing this stream. * This operation will act as an intermediate iterator operation requiring data be brought locally for proper * behavior. This is described in more detail in the {@link CacheStream} documentation</p> * <p>This intermediate iterator operation will be performed locally and remotely requiring possibly a subset of * all elements to be in memory</p> * <p>Any subsequent intermediate operations and the terminal operation are then performed locally.</p> * @return the new stream */ @Override CacheStream<R> distinct(); /** * {@inheritDoc} * <p>Note when using a distributed backing cache for this stream the collector must be marshallable. This * prevents the usage of {@link java.util.stream.Collectors} class. However you can use the * {@link org.infinispan.stream.CacheCollectors} static factory methods to create a serializable wrapper, which then * creates the actual collector lazily after being deserialized. This is useful to use any method from the * {@link java.util.stream.Collectors} class as you would normally. * Alternatively, you can call {@link #collect(SerializableSupplier)} too.</p> * * <p>Note: The collector is applied on each node until all the local stream's values * are reduced into a single object. * Because of marshalling limitations, the final result of the collector on remote nodes * is limited to a size of 2GB. * If you need to process more than 2GB of data, you must force the collector to run on the * originator with {@link #spliterator()}: * <pre> * StreamSupport.stream(stream.filter(entry -> ...) * .map(entry -> ...) * .spliterator(), * false) * .collect(Collectors.toList()); * </pre> * </p> * * @param collector * @param <R1> collected type * @param <A> intermediate collected type if applicable * @return the collected value * @see org.infinispan.stream.CacheCollectors */ @Override <R1, A> R1 collect(Collector<? super R, A, R1> collector); /** * Performs a <a href="package-summary.html#MutableReduction">mutable * reduction</a> operation on the elements of this stream using a * {@code Collector} that is lazily created from the {@code SerializableSupplier} * provided. * * This method behaves exactly the same as {@link #collect(Collector)} with * the enhanced capability of working even when the mutable reduction * operation has to run in a remote node and the operation is not * {@link Serializable} or otherwise marshallable. * * So, this method is specially designed for situations when the user * wants to use a {@link Collector} instance that has been created by * {@link java.util.stream.Collectors} static factory methods. * * In this particular case, the function that instantiates the * {@link Collector} will be marshalled according to the * {@link Serializable} rules. * * <p>Note: The collector is applied on each node until all the local stream's values * are reduced into a single object. * Because of marshalling limitations, the final result of the collector on remote nodes * is limited to a size of 2GB. * If you need to process more than 2GB of data, you must force the collector to run on the * originator with {@link #spliterator()}: * <pre> * StreamSupport.stream(stream.filter(entry -> ...) * .map(entry -> ...) * .spliterator(), * false) * .collect(Collectors.toList()); * </pre> * </p> * * @param supplier The supplier to create the collector that is specifically serializable * @param <R1> The resulting type of the collector * @return the collected value * @since 9.2 */ default <R1> R1 collect(SerializableSupplier<Collector<? super R, ?, R1>> supplier) { return collect(CacheCollectors.serializableCollector(toSerialSupplierCollect(supplier))); } /** * Performs a <a href="package-summary.html#MutableReduction">mutable * reduction</a> operation on the elements of this stream using a * {@code Collector} that is lazily created from the {@code Supplier} * provided. * * This method behaves exactly the same as {@link #collect(Collector)} with * the enhanced capability of working even when the mutable reduction * operation has to run in a remote node and the operation is not * {@link Serializable} or otherwise marshallable. * * So, this method is specially designed for situations when the user * wants to use a {@link Collector} instance that has been created by * {@link java.util.stream.Collectors} static factory methods. * * In this particular case, the function that instantiates the * {@link Collector} will be marshalled using Infinispan * {@link org.infinispan.commons.marshall.Externalizer} class or one of its * subtypes. * * <p>Note: The collector is applied on each node until all the local stream's values * are reduced into a single object. * Because of marshalling limitations, the final result of the collector on remote nodes * is limited to a size of 2GB. * If you need to process more than 2GB of data, you must force the collector to run on the * originator with {@link #spliterator()}: * <pre> * StreamSupport.stream(stream.filter(entry -> ...) * .map(entry -> ...) * .spliterator(), * false) * .collect(Collectors.toList()); * </pre> * </p> * * @param supplier The supplier to create the collector * @param <R1> The resulting type of the collector * @return the collected value * @since 9.2 */ default <R1> R1 collect(Supplier<Collector<? super R, ?, R1>> supplier) { return collect(CacheCollectors.collector(toSupplierCollect(supplier))); } /** * Same as {@link CacheStream#collect(Supplier, BiConsumer, BiConsumer)} except that the various arguments must * also implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * * @param <R1> type of the result * @param supplier a function that creates a new result container. For a * parallel execution, this function may be called * multiple times and must return a fresh value each time. * Must be serializable * @param accumulator an associative, non-interfering, stateless * function for incorporating an additional element into a result and * must be serializable * @param combiner an associative, non-interfering, stateless * function for combining two values, which must be * compatible with the accumulator function and serializable * @return the result of the reduction */ default <R1> R1 collect(SerializableSupplier<R1> supplier, SerializableBiConsumer<R1, ? super R> accumulator, SerializableBiConsumer<R1, R1> combiner) { return collect((Supplier<R1>) supplier, accumulator, combiner); } /** * {@inheritDoc} * * <p>Note: The accumulator and combiner are applied on each node until all the local stream's values * are reduced into a single object. * Because of marshalling limitations, the final result of the collector on remote nodes * is limited to a size of 2GB. * If you need to process more than 2GB of data, you must force the collector to run on the * originator with {@link #spliterator()}: * <pre> * StreamSupport.stream(stream.filter(entry -> ...) * .map(entry -> ...) * .spliterator(), * false) * .collect(Collectors.toList()); * </pre> * </p> */ @Override <R1> R1 collect(Supplier<R1> supplier, BiConsumer<R1, ? super R> accumulator, BiConsumer<R1, R1> combiner); /** * Same as {@link CacheStream#allMatch(Predicate)} except that the Predicate must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param predicate a non-interfering, stateless * predicate to apply to elements of this stream that is serializable * @return {@code true} if either all elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} */ default boolean allMatch(SerializablePredicate<? super R> predicate) { return allMatch((Predicate<? super R>) predicate); } /** * Same as {@link CacheStream#noneMatch(Predicate)} except that the Predicate must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param predicate a non-interfering, stateless * predicate to apply to elements of this stream that is serializable * @return {@code true} if either no elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} */ default boolean noneMatch(SerializablePredicate<? super R> predicate) { return noneMatch((Predicate<? super R>) predicate); } /** * Same as {@link CacheStream#anyMatch(Predicate)} except that the Predicate must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param predicate a non-interfering, stateless * predicate to apply to elements of this stream that is serializable * @return {@code true} if any elements of the stream match the provided * predicate, otherwise {@code false} */ default boolean anyMatch(SerializablePredicate<? super R> predicate) { return anyMatch((Predicate<? super R>) predicate); } /** * Same as {@link CacheStream#max(Comparator)} except that the Comparator must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param comparator a non-interfering, stateless * {@code Comparator} to compare elements of this stream that is also serializable * @return an {@code Optional} describing the maximum element of this stream, * or an empty {@code Optional} if the stream is empty */ default Optional<R> max(SerializableComparator<? super R> comparator) { return max((Comparator<? super R>) comparator); } /** * Same as {@link CacheStream#min(Comparator)} except that the Comparator must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param comparator a non-interfering, stateless * {@code Comparator} to compare elements of this stream that is also serializable * @return an {@code Optional} describing the minimum element of this stream, * or an empty {@code Optional} if the stream is empty */ default Optional<R> min(SerializableComparator<? super R> comparator) { return min((Comparator<? super R>) comparator); } /** * Same as {@link CacheStream#reduce(BinaryOperator)} except that the BinaryOperator must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param accumulator an associative, non-interfering, stateless * function for combining two values that is also serializable * @return an {@link Optional} describing the result of the reduction */ default Optional<R> reduce(SerializableBinaryOperator<R> accumulator) { return reduce((BinaryOperator<R>) accumulator); } /** * Same as {@link CacheStream#reduce(Object, BinaryOperator)} except that the BinaryOperator must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param identity the identity value for the accumulating function * @param accumulator an associative, non-interfering, stateless * function for combining two values that is also serializable * @return the result of the reduction */ default R reduce(R identity, SerializableBinaryOperator<R> accumulator) { return reduce(identity, (BinaryOperator<R>) accumulator); } /** * Same as {@link CacheStream#reduce(Object, BiFunction, BinaryOperator)} except that the BinaryOperator must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * * <p>Just like in the cache, {@code null} values are not supported.</p> * * @param <U> The type of the result * @param identity the identity value for the combiner function * @param accumulator an associative, non-interfering, stateless * function for incorporating an additional element into a result that is also serializable * @param combiner an associative, non-interfering, stateless * function for combining two values, which must be * compatible with the accumulator function that is also serializable * @return the result of the reduction */ default <U> U reduce(U identity, SerializableBiFunction<U, ? super R, U> accumulator, SerializableBinaryOperator<U> combiner) { return reduce(identity, (BiFunction<U, ? super R, U>) accumulator, combiner); } /** * Same as {@link CacheStream#toArray(IntFunction)} except that the BinaryOperator must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param <A> the element type of the resulting array * @param generator a function which produces a new array of the desired * type and the provided length that is also serializable * @return an array containing the elements in this stream */ default <A> A[] toArray(SerializableIntFunction<A[]> generator) { return toArray((IntFunction<A[]>) generator); } /** * {@inheritDoc} * @return the new cache stream */ @Override CacheStream<R> filter(Predicate<? super R> predicate); /** * Same as {@link CacheStream#filter(Predicate)} except that the Predicate must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param predicate a non-interfering, stateless * predicate to apply to each element to determine if it * should be included * @return the new cache stream */ default CacheStream<R> filter(SerializablePredicate<? super R> predicate) { return filter((Predicate<? super R>) predicate); } /** * {@inheritDoc} * * <p>Just like in the cache, {@code null} values are not supported.</p> * * @return the new cache stream */ @Override <R1> CacheStream<R1> map(Function<? super R, ? extends R1> mapper); /** * Same as {@link CacheStream#map(Function)} except that the Function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param <R1> The element type of the new stream * @param mapper a non-interfering, stateless * function to apply to each element * @return the new cache stream */ default <R1> CacheStream<R1> map(SerializableFunction<? super R, ? extends R1> mapper) { return map((Function<? super R, ? extends R1>) mapper); } /** * {@inheritDoc} * @param mapper a non-interfering, stateless * function to apply to each element * @return the new double cache stream */ @Override DoubleCacheStream mapToDouble(ToDoubleFunction<? super R> mapper); /** * Same as {@link CacheStream#mapToDouble(ToDoubleFunction)} except that the ToDoubleFunction must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param mapper a non-interfering, stateless * function to apply to each element * @return the new stream */ default DoubleCacheStream mapToDouble(SerializableToDoubleFunction<? super R> mapper) { return mapToDouble((ToDoubleFunction<? super R>) mapper); } /** * {@inheritDoc} * @param mapper a non-interfering, stateless * function to apply to each element * @return the new int cache stream */ @Override IntCacheStream mapToInt(ToIntFunction<? super R> mapper); /** * Same as {@link CacheStream#mapToInt(ToIntFunction)} except that the ToIntFunction must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param mapper a non-interfering, stateless * function to apply to each element * @return the new stream */ default IntCacheStream mapToInt(SerializableToIntFunction<? super R> mapper) { return mapToInt((ToIntFunction<? super R>) mapper); } /** * {@inheritDoc} * @param mapper a non-interfering, stateless * function to apply to each element * @return the new long cache stream */ @Override LongCacheStream mapToLong(ToLongFunction<? super R> mapper); /** * Same as {@link CacheStream#mapToLong(ToLongFunction)} except that the ToLongFunction must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param mapper a non-interfering, stateless * function to apply to each element * @return the new stream */ default LongCacheStream mapToLong(SerializableToLongFunction<? super R> mapper) { return mapToLong((ToLongFunction<? super R>) mapper); } /** * {@inheritDoc} * @return the new cache stream */ @Override <R1> CacheStream<R1> flatMap(Function<? super R, ? extends Stream<? extends R1>> mapper); /** * Same as {@link CacheStream#flatMap(Function)} except that the Function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param <R1> The element type of the new stream * @param mapper a non-interfering, stateless * function to apply to each element which produces a stream * of new values * @return the new cache stream */ default <R1> CacheStream<R1> flatMap(SerializableFunction<? super R, ? extends Stream<? extends R1>> mapper) { return flatMap((Function<? super R, ? extends Stream<? extends R1>>) mapper); } /** * {@inheritDoc} * @return the new cache stream */ @Override DoubleCacheStream flatMapToDouble(Function<? super R, ? extends DoubleStream> mapper); /** * Same as {@link CacheStream#flatMapToDouble(Function)} except that the Function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param mapper a non-interfering, stateless * function to apply to each element which produces a stream * of new values * @return the new stream */ default DoubleCacheStream flatMapToDouble(SerializableFunction<? super R, ? extends DoubleStream> mapper) { return flatMapToDouble((Function<? super R, ? extends DoubleStream>) mapper); } /** * {@inheritDoc} * @return the new cache stream */ @Override IntCacheStream flatMapToInt(Function<? super R, ? extends IntStream> mapper); /** * Same as {@link CacheStream#flatMapToInt(Function)} except that the Function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param mapper a non-interfering, stateless * function to apply to each element which produces a stream * of new values * @return the new stream */ default IntCacheStream flatMapToInt(SerializableFunction<? super R, ? extends IntStream> mapper) { return flatMapToInt((Function<? super R, ? extends IntStream>) mapper); } /** * {@inheritDoc} * @return the new cache stream */ @Override LongCacheStream flatMapToLong(Function<? super R, ? extends LongStream> mapper); /** * Same as {@link CacheStream#flatMapToLong(Function)} except that the Function must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param mapper a non-interfering, stateless * function to apply to each element which produces a stream * of new values * @return the new stream */ default LongCacheStream flatMapToLong(SerializableFunction<? super R, ? extends LongStream> mapper) { return flatMapToLong((Function<? super R, ? extends LongStream>) mapper); } /** * {@inheritDoc} * @return a parallel cache stream */ @Override CacheStream<R> parallel(); /** * {@inheritDoc} * @return a sequential cache stream */ @Override CacheStream<R> sequential(); /** * {@inheritDoc} * @return an unordered cache stream */ @Override CacheStream<R> unordered(); /** * {@inheritDoc} * @param closeHandler * @return a cache stream with the handler applied */ @Override CacheStream<R> onClose(Runnable closeHandler); }
38,283
44.093051
121
java
null
infinispan-main/core/src/main/java/org/infinispan/Cache.java
package org.infinispan; import java.util.Collection; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; import java.util.function.Function; import org.infinispan.commons.api.BasicCache; import org.infinispan.commons.api.BatchingCache; import org.infinispan.commons.util.CloseableIteratorCollection; import org.infinispan.commons.util.CloseableIteratorSet; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.FilteringListenable; import org.infinispan.util.function.SerializableBiFunction; import org.infinispan.util.function.SerializableFunction; /** * The central interface of Infinispan. A Cache provides a highly concurrent, optionally distributed data structure * with additional features such as: * <p/> * <ul> <li>JTA transaction compatibility</li> <li>Eviction support for evicting entries from memory to prevent {@link * OutOfMemoryError}s</li> <li>Persisting entries to a {@link org.infinispan.persistence.spi.CacheLoader}, either when they are evicted as an overflow, * or all the time, to maintain persistent copies that would withstand server failure or restarts.</li> </ul> * <p/> * <p/> * <p/> * For convenience, Cache extends {@link ConcurrentMap} and implements all methods accordingly. Methods like * {@link #keySet()}, {@link #values()} and {@link #entrySet()} produce backing collections in that updates done to them * also update the original Cache instance. Certain methods on these maps can be expensive however (prohibitively so * when using a distributed cache). The {@link #size()} and {@link #containsValue(Object)} methods upon invocation can * also be expensive just as well. The reason these methods are expensive are that they take into account entries * stored in a configured {@link org.infinispan.persistence.spi.CacheLoader} and remote entries when using a distributed cache. * Frequent use of these methods is not recommended if used in this manner. These aforementioned methods do take into * account in-flight transactions, however key/value pairs read in using an iterator will not be placed into the transactional * context to prevent {@link OutOfMemoryError}s. Please note all of these methods behavior can be controlled using * a {@link org.infinispan.context.Flag} to disable certain things such as taking into account the loader. Please see * each method on this interface for more details. * <p /> * Also, like many {@link ConcurrentMap} implementations, Cache does not support the use of <tt>null</tt> keys or * values. * <p/> * <h3>Asynchronous operations</h3> Cache also supports the use of "async" remote operations. Note that these methods * only really make sense if you are using a clustered cache. I.e., when used in LOCAL mode, these "async" operations * offer no benefit whatsoever. These methods, such as {@link #putAsync(Object, Object)} offer the best of both worlds * between a fully synchronous and a fully asynchronous cache in that a {@link java.util.concurrent.CompletableFuture} is returned. The * <tt>CompletableFuture</tt> can then be ignored or thrown away for typical asynchronous behaviour, or queried for * synchronous behaviour, which would block until any remote calls complete. Note that all remote calls are, as far as * the transport is concerned, synchronous. This allows you the guarantees that remote calls succeed, while not * blocking your application thread unnecessarily. For example, usage such as the following could benefit from the * async operations: * <pre> * CompletableFuture f1 = cache.putAsync("key1", "value1"); * CompletableFuture f2 = cache.putAsync("key2", "value2"); * CompletableFuture f3 = cache.putAsync("key3", "value3"); * f1.get(); * f2.get(); * f3.get(); * </pre> * The net result is behavior similar to synchronous RPC calls in that at the end, you have guarantees that all calls * completed successfully, but you have the added benefit that the three calls could happen in parallel. This is * especially advantageous if the cache uses distribution and the three keys map to different cache instances in the * cluster. * <p/> * Also, the use of async operations when within a transaction return your local value only, as expected. A * CompletableFuture is still returned though for API consistency. * <p/> * <h3>Constructing a Cache</h3> An instance of the Cache is usually obtained by using a {@link org.infinispan.manager.CacheContainer}. * <pre> * CacheManager cm = new DefaultCacheManager(); // optionally pass in a default configuration * Cache c = cm.getCache(); * </pre> * See the {@link org.infinispan.manager.CacheContainer} interface for more details on providing specific configurations, using multiple caches * in the same JVM, etc. * <p/> * Please see the <a href="http://www.jboss.org/infinispan/docs">Infinispan documentation</a> and/or the <a * href="http://www.jboss.org/community/wiki/5minutetutorialonInfinispan">5 Minute Usage Tutorial</a> for more details. * <p/> * * @author Mircea.Markus@jboss.com * @author Manik Surtani * @author Galder Zamarreño * @see org.infinispan.manager.CacheContainer * @see DefaultCacheManager * @see <a href="http://www.jboss.org/infinispan/docs">Infinispan documentation</a> * @see <a href="http://www.jboss.org/community/wiki/5minutetutorialonInfinispan">5 Minute Usage Tutorial</a> * @since 4.0 */ public interface Cache<K, V> extends BasicCache<K, V>, BatchingCache, FilteringListenable<K, V> { /** * Under special operating behavior, associates the value with the specified key. <ul> <li> Only goes through if the * key specified does not exist; no-op otherwise (similar to {@link ConcurrentMap#putIfAbsent(Object, Object)})</i> * <li> Force asynchronous mode for replication to prevent any blocking.</li> <li> invalidation does not take place. * </li> <li> 0ms lock timeout to prevent any blocking here either. If the lock is not acquired, this method is a * no-op, and swallows the timeout exception.</li> <li> Ongoing transactions are suspended before this call, so * failures here will not affect any ongoing transactions.</li> <li> Errors and exceptions are 'silent' - logged at a * much lower level than normal, and this method does not throw exceptions</li> </ul> This method is for caching data * that has an external representation in storage, where, concurrent modification and transactions are not a * consideration, and failure to put the data in the cache should be treated as a 'suboptimal outcome' rather than a * 'failing outcome'. * <p/> * An example of when this method is useful is when data is read from, for example, a legacy datastore, and is cached * before returning the data to the caller. Subsequent calls would prefer to get the data from the cache and if the * data doesn't exist in the cache, fetch again from the legacy datastore. * <p/> * See <a href="http://jira.jboss.com/jira/browse/JBCACHE-848">JBCACHE-848</a> for details around this feature. * <p/> * * @param key key with which the specified value is to be associated. * @param value value to be associated with the specified key. * @throws IllegalStateException if {@link #getStatus()} would not return {@link ComponentStatus#RUNNING}. */ void putForExternalRead(K key, V value); /** * An overloaded form of {@link #putForExternalRead(K, V)}, which takes in lifespan parameters. * * @param key key to use * @param value value to store * @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan. * @param unit unit of measurement for the lifespan * * @since 7.0 */ void putForExternalRead(K key, V value, long lifespan, TimeUnit unit); /** * An overloaded form of {@link #putForExternalRead(K, V)}, which takes in lifespan parameters. * * @param key key to use * @param value value to store * @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan. * @param lifespanUnit time unit for lifespan * @param maxIdle the maximum amount of time this key is allowed to be idle for before it is considered as * expired * @param maxIdleUnit time unit for max idle time * @since 7.0 */ void putForExternalRead(K key, V value, long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit); /** * Evicts an entry from the memory of the cache. Note that the entry is <i>not</i> removed from any configured cache * stores or any other caches in the cluster (if used in a clustered mode). Use {@link #remove(Object)} to remove an * entry from the entire cache system. * <p/> * This method is designed to evict an entry from memory to free up memory used by the application. This method uses * a 0 lock acquisition timeout so it does not block in attempting to acquire locks. It behaves as a no-op if the * lock on the entry cannot be acquired <i>immediately</i>. * <p/> * Important: this method should not be called from within a transaction scope. * * @param key key to evict */ void evict(K key); org.infinispan.configuration.cache.Configuration getCacheConfiguration(); /** * Retrieves the cache manager responsible for creating this cache instance. * * @return a cache manager */ EmbeddedCacheManager getCacheManager(); AdvancedCache<K, V> getAdvancedCache(); ComponentStatus getStatus(); /** * Returns a count of all elements in this cache and cache loader across the entire cluster. * <p/> * Only a subset of entries is held in memory at a time when using a loader or remote entries, to prevent possible * memory issues, however the loading of said entries can still be vary slow. * <p/> * If there are performance concerns then the {@link org.infinispan.context.Flag#SKIP_CACHE_LOAD} flag should be used to * avoid hitting the cache loader in case if this is not needed in the size calculation. * <p/> * Also if you want the local contents only you can use the {@link org.infinispan.context.Flag#CACHE_MODE_LOCAL} flag so * that other remote nodes are not queried for data. However the loader will still be used unless the previously * mentioned {@link org.infinispan.context.Flag#SKIP_CACHE_LOAD} is also configured. * <p/> * If this method is used in a transactional context, note this method will not bring additional values into the * transaction context and thus objects that haven't yet been read will act in a * {@link org.infinispan.util.concurrent.IsolationLevel#READ_COMMITTED} behavior irrespective of the configured * isolation level. However values that have been previously modified or read that are in the context will be * adhered to. e.g. any write modification or any previous read when using * {@link org.infinispan.util.concurrent.IsolationLevel#REPEATABLE_READ} * <p/> * This method should only be used for debugging purposes such as to verify that the cache contains all the keys * entered. Any other use involving execution of this method on a production system is not recommended. * <p/> * * @return the number of key-value mappings in this cache and cache loader across the entire cluster. */ @Override int size(); /** * Returns a set view of the keys contained in this cache and cache loader across the entire cluster. * Modifications and changes to the cache will be reflected in the set and vice versa. When this method is called * nothing is actually queried as the backing set is just returned. Invocation on the set itself is when the * various operations are ran. * <p/> * <h3>Unsupported Operations</h3> * Care should be taken when invoking {@link java.util.Set#toArray()}, {@link Set#toArray(Object[])}, * {@link java.util.Set#size()}, {@link Set#retainAll(Collection)} and {@link java.util.Set#iterator()} * methods as they will traverse the entire contents of the cluster including a configured * {@link org.infinispan.persistence.spi.CacheLoader} and remote entries. The former 2 methods especially have a * very high likely hood of causing a {@link java.lang.OutOfMemoryError} due to storing all the keys in the entire * cluster in the array. * Use involving execution of this method on a production system is not recommended as they can be quite expensive * operations * <p/> * <h3>Supported Flags</h3> * Note any flag configured for the cache will also be passed along to the backing set when it was created. If * additional flags are configured on the cache they will not affect any existing backings sets. * <p/> * If there are performance concerns then the {@link org.infinispan.context.Flag#SKIP_CACHE_LOAD} flag should be used to * avoid hitting the cache store as this will cause all entries there to be read in (albeit in a batched form to * prevent {@link java.lang.OutOfMemoryError}) * <p/> * Also if you want the local contents only you can use the {@link org.infinispan.context.Flag#CACHE_MODE_LOCAL} flag so * that other remote nodes are not queried for data. However the loader will still be used unless the previously * mentioned {@link org.infinispan.context.Flag#SKIP_CACHE_LOAD} is also configured. * <p/> * <h3>Iterator Use</h3> * This class implements the {@link CloseableIteratorSet} interface which creates a * {@link org.infinispan.commons.util.CloseableIterator} instead of a regular one. This means this iterator must be * explicitly closed either through try with resource or calling the close method directly. Technically this iterator * will also close itself if you iterate fully over it, but it is safest to always make sure you close it explicitly. * <h3>Unsupported Operations</h3> * Due to not being able to add null values the following methods are not supported and will throw * {@link java.lang.UnsupportedOperationException} if invoked. * {@link Set#add(Object)} * {@link Set#addAll(java.util.Collection)} * @return a set view of the keys contained in this cache and cache loader across the entire cluster. */ @Override CacheSet<K> keySet(); /** * Returns a collection view of the values contained in this cache across the entire cluster. Modifications and * changes to the cache will be reflected in the set and vice versa. When this method is called nothing is actually * queried as the backing collection is just returned. Invocation on the collection itself is when the various * operations are ran. * <p/> * Care should be taken when invoking {@link Collection#toArray()}, {@link Collection#toArray(Object[])}, * {@link Collection#size()}, {@link Collection#retainAll(Collection)} and {@link Collection#iterator()} * methods as they will traverse the entire contents of the cluster including a configured * {@link org.infinispan.persistence.spi.CacheLoader} and remote entries. The former 2 methods especially have a * very high likely hood of causing a {@link java.lang.OutOfMemoryError} due to storing all the keys in the entire * cluster in the array. * Use involving execution of this method on a production system is not recommended as they can be quite expensive * operations * <p/> * * <h3>Supported Flags</h3> * Note any flag configured for the cache will also be passed along to the backing set when it was created. If * additional flags are configured on the cache they will not affect any existing backings sets. * <p/> * If there are performance concerns then the {@link org.infinispan.context.Flag#SKIP_CACHE_LOAD} flag should be used to * avoid hitting the cache store as this will cause all entries there to be read in (albeit in a batched form to * prevent {@link java.lang.OutOfMemoryError}) * <p/> * Also if you want the local contents only you can use the {@link org.infinispan.context.Flag#CACHE_MODE_LOCAL} flag so * that other remote nodes are not queried for data. However the loader will still be used unless the previously * mentioned {@link org.infinispan.context.Flag#SKIP_CACHE_LOAD} is also configured. * <p/> * <h3>Iterator Use</h3> * <p>This class implements the {@link CloseableIteratorCollection} interface which creates a * {@link org.infinispan.commons.util.CloseableIterator} instead of a regular one. This means this iterator must be * explicitly closed either through try with resource or calling the close method directly. Technically this iterator * will also close itself if you iterate fully over it, but it is safest to always make sure you close it explicitly.</p> * <p>The iterator retrieved using {@link CacheCollection#iterator()} supports the remove method, however the * iterator retrieved from {@link CacheStream#iterator()} will not support remove.</p> * <h3>Unsupported Operations</h3> * Due to not being able to add null values the following methods are not supported and will throw * {@link java.lang.UnsupportedOperationException} if invoked. * {@link Set#add(Object)} * {@link Set#addAll(java.util.Collection)} * * @return a collection view of the values contained in this cache and cache loader across the entire cluster. */ @Override CacheCollection<V> values(); /** * Returns a set view of the mappings contained in this cache and cache loader across the entire cluster. * Modifications and changes to the cache will be reflected in the set and vice versa. When this method is called * nothing is actually queried as the backing set is just returned. Invocation on the set itself is when the * various operations are ran. * <p/> * Care should be taken when invoking {@link java.util.Set#toArray()}, {@link Set#toArray(Object[])}, * {@link java.util.Set#size()}, {@link Set#retainAll(Collection)} and {@link java.util.Set#iterator()} * methods as they will traverse the entire contents of the cluster including a configured * {@link org.infinispan.persistence.spi.CacheLoader} and remote entries. The former 2 methods especially have a * very high likely hood of causing a {@link java.lang.OutOfMemoryError} due to storing all the keys in the entire * cluster in the array. * Use involving execution of this method on a production system is not recommended as they can be quite expensive * operations * <p/> * * <h3>Supported Flags</h3> * Note any flag configured for the cache will also be passed along to the backing set when it was created. If * additional flags are configured on the cache they will not affect any existing backings sets. * <p/> * If there are performance concerns then the {@link org.infinispan.context.Flag#SKIP_CACHE_LOAD} flag should be used to * avoid hitting the cache store as this will cause all entries there to be read in (albeit in a batched form to * prevent {@link java.lang.OutOfMemoryError}) * <p/> * Also if you want the local contents only you can use the {@link org.infinispan.context.Flag#CACHE_MODE_LOCAL} flag so * that other remote nodes are not queried for data. However the loader will still be used unless the previously * mentioned {@link org.infinispan.context.Flag#SKIP_CACHE_LOAD} is also configured. * <p/> * <h3>Modifying or Adding Entries</h3> * An entry's value is supported to be modified by using the {@link java.util.Map.Entry#setValue(Object)} and it will update * the cache as well. Also this backing set does allow addition of a new Map.Entry(s) via the * {@link Set#add(Object)} or {@link Set#addAll(java.util.Collection)} methods. * <h3>Iterator Use</h3> * This class implements the {@link CloseableIteratorSet} interface which creates a * {@link org.infinispan.commons.util.CloseableIterator} instead of a regular one. This means this iterator must be * explicitly closed either through try with resource or calling the close method directly. Technically this iterator * will also close itself if you iterate fully over it, but it is safest to always make sure you close it explicitly. * @return a set view of the mappings contained in this cache and cache loader across the entire cluster. */ @Override CacheSet<Entry<K, V>> entrySet(); /** * Removes all mappings from the cache. * <p/> * <b>Note:</b> This should never be invoked in production unless you can guarantee no other invocations are ran * concurrently. * <p/> * If the cache is transactional, it will not interact with the transaction. */ @Override void clear(); /** * Stops a cache. If the cache is clustered, this only stops the cache on the node where it is being invoked. If you * need to stop the cache across a cluster, use the {@link #shutdown()} method. */ @Override void stop(); /** * Performs a controlled, clustered shutdown of the cache. When invoked, the following operations are performed: * <ul> * <li>rebalancing for the cache is disabled</li> * <li>in-memory data is flushed/passivated to any persistent stores</li> * <li>state is persisted to the location defined in {@link org.infinispan.configuration.global.GlobalStateConfigurationBuilder#persistentLocation(String)}</li> * </ul> * * This method differs from {@link #stop()} only in clustered modes, * and only when {@link org.infinispan.configuration.global.GlobalStateConfiguration#enabled()} is true, otherwise it * just behaves like {@link #stop()}. */ default void shutdown() { stop(); } /** * {@inheritDoc} * <p> * When this method is used on a clustered cache, either replicated or distributed, the function will be serialized * to owning nodes to perform the operation in the most performant way. However this means the function must * have an appropriate {@link org.infinispan.commons.marshall.Externalizer} or be {@link java.io.Serializable} itself. * <p> * For transactional caches, whenever the values of the caches are collections, and the mapping function modifies the collection, the collection * must be copied and not directly modified, otherwise whenever rollback is called it won't work. * This limitation could disappear in following releases if technically possible. */ @Override V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction); /** * Overloaded {@link Cache#computeIfAbsent(Object, Function)} with Infinispan {@link SerializableFunction}. * * The compiler will pick this overload for lambda parameters, making them {@link java.io.Serializable} * @param key, the key to be computed * @param mappingFunction, mapping function to be appliyed to the key * @return computed value or null if nothing is computed or computation value is null */ default V computeIfAbsent(K key, SerializableFunction<? super K, ? extends V> mappingFunction) { return computeIfAbsent(key, (Function<? super K, ? extends V>) mappingFunction); } /** * Overloaded {@link Cache#computeIfAbsent(Object, Function, long, TimeUnit)} with Infinispan {@link SerializableFunction}. * * The compiler will pick this overload for lambda parameters, making them {@link java.io.Serializable} * @param key, the key to be computed * @param mappingFunction, mapping function to be appliyed to the key * @return computed value or null if nothing is computed or computation value is null */ default V computeIfAbsent(K key, SerializableFunction<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit) { return computeIfAbsent(key, (Function<? super K, ? extends V>) mappingFunction, lifespan, lifespanUnit); } /** * Overloaded {@link Cache#computeIfAbsent(Object, Function, long, TimeUnit, long, TimeUnit)} with Infinispan {@link SerializableFunction}. * * The compiler will pick this overload for lambda parameters, making them {@link java.io.Serializable} * @param key, the key to be computed * @param mappingFunction, mapping function to be appliyed to the key * @return computed value or null if nothing is computed or computation value is null */ default V computeIfAbsent(K key, SerializableFunction<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { return computeIfAbsent(key, (Function<? super K, ? extends V>) mappingFunction, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit); } /** * Overloaded {@link Cache#computeIfAbsentAsync(Object, Function)} with Infinispan {@link SerializableFunction}. * * The compiler will pick this overload for lambda parameters, making them {@link java.io.Serializable} * @param key, the key to be computed * @param mappingFunction, mapping function to be appliyed to the key * @return computed value or null if nothing is computed or computation value is null */ default CompletableFuture<V> computeIfAbsentAsync(K key, SerializableFunction<? super K, ? extends V> mappingFunction) { return computeIfAbsentAsync(key, (Function<? super K, ? extends V>) mappingFunction); } /** * Overloaded {@link Cache#computeIfAbsentAsync(Object, Function, long, TimeUnit)} with Infinispan {@link SerializableFunction}. * * The compiler will pick this overload for lambda parameters, making them {@link java.io.Serializable} * @param key, the key to be computed * @param mappingFunction, mapping function to be appliyed to the key * @return computed value or null if nothing is computed or computation value is null */ default CompletableFuture<V> computeIfAbsentAsync(K key, SerializableFunction<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit) { return computeIfAbsentAsync(key, (Function<? super K, ? extends V>) mappingFunction, lifespan, lifespanUnit); } /** * Overloaded {@link Cache#computeIfAbsentAsync(Object, Function, long, TimeUnit, long, TimeUnit)} with Infinispan {@link SerializableFunction}. * * The compiler will pick this overload for lambda parameters, making them {@link java.io.Serializable} * @param key, the key to be computed * @param mappingFunction, mapping function to be appliyed to the key * @return computed value or null if nothing is computed or computation value is null */ default CompletableFuture<V> computeIfAbsentAsync(K key, SerializableFunction<? super K, ? extends V> mappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { return computeIfAbsentAsync(key, (Function<? super K, ? extends V>) mappingFunction, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit); } /** * {@inheritDoc} * <p> * When this method is used on a clustered cache, either replicated or distributed, the bifunction will be serialized * to owning nodes to perform the operation in the most performant way. However this means the bifunction must * have an appropriate {@link org.infinispan.commons.marshall.Externalizer} or be {@link java.io.Serializable} itself. * <p> * For transactional caches, whenever the values of the caches are collections, and the mapping function modifies the collection, the collection * must be copied and not directly modified, otherwise whenever rollback is called it won't work. * This limitation could disappear in following releases if technically possible. */ @Override V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction); /** * Overloaded {@link Cache#computeIfPresent(Object, BiFunction)} with Infinispan {@link SerializableBiFunction} * * The compiler will pick this overload for lambda parameters, making them {@link java.io.Serializable} * * @param key, the key to be computed * @param remappingFunction, mapping function to be appliyed to the key * @return computed value or null if nothing is computed or computation result is null */ default V computeIfPresent(K key, SerializableBiFunction<? super K, ? super V, ? extends V> remappingFunction) { return computeIfPresent(key, (BiFunction<? super K, ? super V, ? extends V>) remappingFunction); } /** * Overloaded {@link Cache#computeIfPresentAsync(Object, BiFunction)} with Infinispan {@link SerializableBiFunction} * * The compiler will pick this overload for lambda parameters, making them {@link java.io.Serializable} * * @param key, the key to be computed * @param remappingFunction, mapping function to be appliyed to the key * @return computed value or null if nothing is computed or computation result is null */ default CompletableFuture<V> computeIfPresentAsync(K key, SerializableBiFunction<? super K, ? super V, ? extends V> remappingFunction) { return computeIfPresentAsync(key, (BiFunction<? super K, ? super V, ? extends V>) remappingFunction); } /** * {@inheritDoc} * <p> * When this method is used on a clustered cache, either replicated or distributed, the bifunction will be serialized * to owning nodes to perform the operation in the most performant way. However this means the bifunction must * have an appropriate {@link org.infinispan.commons.marshall.Externalizer} or be {@link java.io.Serializable} itself. * <p> * For transactional caches, whenever the values of the caches are collections, and the mapping function modifies the collection, the collection * must be copied and not directly modified, otherwise whenever rollback is called it won't work. * This limitation could disappear in following releases if technically possible. */ @Override V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction); /** * Overloaded {@link Cache#compute(Object, BiFunction)} with Infinispan {@link SerializableBiFunction}. * * The compiler will pick this overload for lambda parameters, making them {@link java.io.Serializable} * * @param key, the key to be computed * @param remappingFunction, mapping function to be appliyed to the key * @return computation result (can be null) */ default V compute(K key, SerializableBiFunction<? super K, ? super V, ? extends V> remappingFunction) { return compute(key, (BiFunction<? super K, ? super V, ? extends V>) remappingFunction); } /** * Overloaded {@link Cache#compute(Object, BiFunction, long, TimeUnit)} with Infinispan {@link SerializableBiFunction}. * * The compiler will pick this overload for lambda parameters, making them {@link java.io.Serializable} * * @param key, the key to be computed * @param remappingFunction, mapping function to be appliyed to the key * @return computation result (can be null) */ default V compute(K key, SerializableBiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) { return compute(key, (BiFunction<? super K, ? super V, ? extends V>) remappingFunction, lifespan, lifespanUnit); } /** * Overloaded {@link Cache#compute(Object, BiFunction, long, TimeUnit, long, TimeUnit)} with Infinispan {@link SerializableBiFunction}. * * The compiler will pick this overload for lambda parameters, making them {@link java.io.Serializable} * * @param key, the key to be computed * @param remappingFunction, mapping function to be appliyed to the key * @return computation result (can be null) */ default V compute(K key, SerializableBiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { return compute(key, (BiFunction<? super K, ? super V, ? extends V>) remappingFunction, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit); } /** * Overloaded {@link Cache#computeAsync(Object, BiFunction)} with Infinispan {@link SerializableBiFunction}. * * The compiler will pick this overload for lambda parameters, making them {@link java.io.Serializable} * * @param key, the key to be computed * @param remappingFunction, mapping function to be appliyed to the key * @return computation result (can be null) */ default CompletableFuture<V> computeAsync(K key, SerializableBiFunction<? super K, ? super V, ? extends V> remappingFunction) { return computeAsync(key, (BiFunction<? super K, ? super V, ? extends V>) remappingFunction); } /** * Overloaded {@link Cache#computeAsync(Object, BiFunction, long, TimeUnit)} with Infinispan {@link SerializableBiFunction}. * * The compiler will pick this overload for lambda parameters, making them {@link java.io.Serializable} * * @param key, the key to be computed * @param remappingFunction, mapping function to be appliyed to the key * @return computation result (can be null) */ default CompletableFuture<V> computeAsync(K key, SerializableBiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) { return computeAsync(key, (BiFunction<? super K, ? super V, ? extends V>) remappingFunction, lifespan, lifespanUnit); } /** * Overloaded {@link Cache#computeAsync(Object, BiFunction, long, TimeUnit, long, TimeUnit)} with Infinispan {@link SerializableBiFunction}. * * The compiler will pick this overload for lambda parameters, making them {@link java.io.Serializable} * * @param key, the key to be computed * @param remappingFunction, mapping function to be appliyed to the key * @return computation result (can be null) */ default CompletableFuture<V> computeAsync(K key, SerializableBiFunction<? super K, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { return computeAsync(key, (BiFunction<? super K, ? super V, ? extends V>) remappingFunction, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit); } /** * {@inheritDoc} * <p> * When this method is used on a clustered cache, either replicated or distributed, the bifunction will be serialized * to owning nodes to perform the operation in the most performant way. However this means the bifunction must * have an appropriate {@link org.infinispan.commons.marshall.Externalizer} or be {@link java.io.Serializable} itself. * <p> * For transactional caches, whenever the values of the caches are collections, and the mapping function modifies the collection, the collection * must be copied and not directly modified, otherwise whenever rollback is called it won't work. * This limitation could disappear in following releases if technically possible. */ @Override V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction); /** * Overloaded {@link Cache#merge(Object, Object, BiFunction)} with Infinispan {@link SerializableBiFunction}. * <p> * The compiler will pick this overload for lambda parameters, making them {@link java.io.Serializable}. * * @param key key with which the resulting value is to be associated * @param value the non-null value to be merged with the existing value associated with the key or, if no * existing value or a null value is associated with the key, to be associated with the key * @param remappingFunction the function to recompute a value if present */ default V merge(K key, V value, SerializableBiFunction<? super V, ? super V, ? extends V> remappingFunction) { return merge(key, value, (BiFunction<? super V, ? super V, ? extends V>) remappingFunction); } /** * Overloaded {@link #merge(Object, Object, BiFunction, long, TimeUnit)} with Infinispan {@link SerializableBiFunction}. * * @param key key to use * @param value new value to merge with existing value * @param remappingFunction function to use to merge new and existing values into a merged value to store under key * @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan. * @param lifespanUnit time unit for lifespan * @return the merged value that was stored under key * @since 9.4 */ default V merge(K key, V value, SerializableBiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) { return merge(key, value, (BiFunction<? super V, ? super V, ? extends V>) remappingFunction, lifespan, lifespanUnit); } /** * Overloaded {@link #merge(Object, Object, BiFunction, long, TimeUnit, long, TimeUnit)} with Infinispan {@link SerializableBiFunction}. * * @param key key to use * @param value new value to merge with existing value * @param remappingFunction function to use to merge new and existing values into a merged value to store under key * @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan. * @param lifespanUnit time unit for lifespan * @param maxIdleTime the maximum amount of time this key is allowed to be idle for before it is considered as * expired * @param maxIdleTimeUnit time unit for max idle time * @return the merged value that was stored under key * @since 9.4 */ default V merge(K key, V value, SerializableBiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { return merge(key, value, (BiFunction<? super V, ? super V, ? extends V>) remappingFunction, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit); } /** * Overloaded {@link #mergeAsync(Object, Object, BiFunction)} with Infinispan {@link SerializableBiFunction}. * * @param key key to use * @param value new value to merge with existing value * @param remappingFunction function to use to merge new and existing values into a merged value to store under key * @return the merged value that was stored under key * @since 10.0 */ default CompletableFuture<V> mergeAsync(K key, V value, SerializableBiFunction<? super V, ? super V, ? extends V> remappingFunction) { return mergeAsync(key, value, (BiFunction<? super V, ? super V, ? extends V>) remappingFunction); } /** * Overloaded {@link #mergeAsync(Object, Object, BiFunction, long, TimeUnit)} with Infinispan {@link SerializableBiFunction}. * * @param key key to use * @param value new value to merge with existing value * @param remappingFunction function to use to merge new and existing values into a merged value to store under key * @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan. * @param lifespanUnit time unit for lifespan * @return the merged value that was stored under key * @since 10.0 */ default CompletableFuture<V> mergeAsync(K key, V value, SerializableBiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit) { return mergeAsync(key, value, (BiFunction<? super V, ? super V, ? extends V>) remappingFunction, lifespan, lifespanUnit); } /** * Overloaded {@link #mergeAsync(Object, Object, BiFunction, long, TimeUnit, long, TimeUnit)} with Infinispan {@link SerializableBiFunction}. * * @param key key to use * @param value new value to merge with existing value * @param remappingFunction function to use to merge new and existing values into a merged value to store under key * @param lifespan lifespan of the entry. Negative values are interpreted as unlimited lifespan. * @param lifespanUnit time unit for lifespan * @param maxIdleTime the maximum amount of time this key is allowed to be idle for before it is considered as * expired * @param maxIdleTimeUnit time unit for max idle time * @return the merged value that was stored under key * @since 10.0 */ default CompletableFuture<V> mergeAsync(K key, V value, SerializableBiFunction<? super V, ? super V, ? extends V> remappingFunction, long lifespan, TimeUnit lifespanUnit, long maxIdleTime, TimeUnit maxIdleTimeUnit) { return mergeAsync(key, value, (BiFunction<? super V, ? super V, ? extends V>) remappingFunction, lifespan, lifespanUnit, maxIdleTime, maxIdleTimeUnit); } }
41,476
58.679137
219
java
null
infinispan-main/core/src/main/java/org/infinispan/InternalCacheSet.java
package org.infinispan; import java.util.Collection; import java.util.function.Consumer; import java.util.function.Predicate; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.CloseableSpliterator; import org.infinispan.commons.util.IntSet; import org.reactivestreams.Publisher; /** * Base class for internal classes used in cache collections. * * <p>It extends {@link CacheSet} because that's what interceptors used return for * {@link org.infinispan.commands.read.KeySetCommand} and {@link org.infinispan.commands.read.EntrySetCommand}, * but because these classes are only used internally, we can avoid implementing most of the methods.</p> * * <p>Subclasses only need to implement {@link #localPublisher(IntSet)} and {@link #localPublisher(int)}, * and a facade class like {@link org.infinispan.cache.impl.CacheBackedKeySet} implements the rest of the * {@link CacheSet} methods.</p> * * @param <E> The element type * @since 14.0 * @author Dan Berindei */ public abstract class InternalCacheSet<E> implements CacheSet<E> { @Override public abstract Publisher<E> localPublisher(int segment); @Override public abstract Publisher<E> localPublisher(IntSet segments); @Override public final boolean removeIf(Predicate<? super E> filter) { throw new UnsupportedOperationException(); } @Override public final void forEach(Consumer<? super E> action) { throw new UnsupportedOperationException(); } @Override public final CloseableIterator<E> iterator() { throw new UnsupportedOperationException(); } @Override public final CloseableSpliterator<E> spliterator() { throw new UnsupportedOperationException(); } @Override public final CacheStream<E> stream() { throw new UnsupportedOperationException(); } @Override public final CacheStream<E> parallelStream() { throw new UnsupportedOperationException(); } @Override public final int size() { throw new UnsupportedOperationException(); } @Override public final boolean isEmpty() { throw new UnsupportedOperationException(); } @Override public final boolean contains(Object o) { throw new UnsupportedOperationException(); } @Override public final Object[] toArray() { throw new UnsupportedOperationException(); } @Override public final <T> T[] toArray(T[] a) { throw new UnsupportedOperationException(); } @Override public final boolean add(E e) { throw new UnsupportedOperationException(); } @Override public final boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public final boolean containsAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public final boolean addAll(Collection<? extends E> c) { throw new UnsupportedOperationException(); } @Override public final boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public final boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public final void clear() { throw new UnsupportedOperationException(); } }
3,301
25.629032
111
java
null
infinispan-main/core/src/main/java/org/infinispan/CoreModule.java
package org.infinispan; import org.infinispan.factories.annotations.InfinispanModule; import org.infinispan.lifecycle.ModuleLifecycle; /** * @api.private */ @InfinispanModule(name = "core") public class CoreModule implements ModuleLifecycle { }
249
19.833333
61
java
null
infinispan-main/core/src/main/java/org/infinispan/IntCacheStream.java
package org.infinispan; import java.util.OptionalInt; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.IntBinaryOperator; import java.util.function.IntConsumer; import java.util.function.IntFunction; import java.util.function.IntPredicate; import java.util.function.IntToDoubleFunction; import java.util.function.IntToLongFunction; import java.util.function.IntUnaryOperator; import java.util.function.ObjIntConsumer; import java.util.function.Supplier; import java.util.stream.IntStream; import org.infinispan.util.function.SerializableBiConsumer; import org.infinispan.util.function.SerializableIntBinaryOperator; import org.infinispan.util.function.SerializableIntConsumer; import org.infinispan.util.function.SerializableIntFunction; import org.infinispan.util.function.SerializableIntPredicate; import org.infinispan.util.function.SerializableIntToDoubleFunction; import org.infinispan.util.function.SerializableIntToLongFunction; import org.infinispan.util.function.SerializableIntUnaryOperator; import org.infinispan.util.function.SerializableObjIntConsumer; import org.infinispan.util.function.SerializableSupplier; /** * A {@link IntStream} that has additional methods to allow for Serializable instances. Please see * {@link CacheStream} for additional details about various methods. * * @author wburns * @since 9.0 */ public interface IntCacheStream extends IntStream, BaseCacheStream<Integer, IntStream> { /** * {@inheritDoc} * @return a stream with parallel distribution disabled. */ IntCacheStream sequentialDistribution(); /** * @inheritDoc * @return a stream with parallel distribution enabled. */ IntCacheStream parallelDistribution(); /** * {@inheritDoc} * @return a stream with the segments filtered. */ IntCacheStream filterKeySegments(Set<Integer> segments); /** * {@inheritDoc} * @return a stream with the keys filtered. */ IntCacheStream filterKeys(Set<?> keys); /** * {@inheritDoc} * @return a stream with the batch size updated */ IntCacheStream distributedBatchSize(int batchSize); /** * {@inheritDoc} * @return a stream with the listener registered. */ IntCacheStream segmentCompletionListener(SegmentCompletionListener listener); /** * {@inheritDoc} * @return a stream with rehash awareness disabled. */ IntCacheStream disableRehashAware(); /** * {@inheritDoc} * @return a stream with the timeout set */ IntCacheStream timeout(long timeout, TimeUnit unit); /** * {@inheritDoc} * @return the new cache int stream */ @Override IntCacheStream filter(IntPredicate predicate); /** * Same as {@link IntCacheStream#filter(IntPredicate)} except that the IntPredicate must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param predicate a non-interfering, stateless * predicate to apply to each element to determine if it * should be included * @return the new cache int stream */ default IntCacheStream filter(SerializableIntPredicate predicate) { return filter((IntPredicate) predicate); } /** * {@inheritDoc} * @return the new cache int stream */ @Override IntCacheStream map(IntUnaryOperator mapper); /** * Same as {@link IntCacheStream#map(IntUnaryOperator)} except that the IntUnaryOperator must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param mapper a non-interfering, stateless * function to apply to each element * @return the new cache int stream */ default IntCacheStream map(SerializableIntUnaryOperator mapper) { return map((IntUnaryOperator) mapper); } /** * {@inheritDoc} * @return the new cache stream */ @Override <U> CacheStream<U> mapToObj(IntFunction<? extends U> mapper); /** * Same as {@link IntCacheStream#mapToObj(IntFunction)} except that the IntFunction must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param <U> the element type of the new stream * @param mapper a non-interfering, stateless * function to apply to each element * @return the new cache stream */ default <U> CacheStream<U> mapToObj(SerializableIntFunction<? extends U> mapper) { return mapToObj((IntFunction<? extends U>) mapper); } /** * {@inheritDoc} * @return the new cache double stream */ @Override DoubleCacheStream mapToDouble(IntToDoubleFunction mapper); /** * Same as {@link IntCacheStream#mapToDouble(IntToDoubleFunction)} except that the IntToIntFunction must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param mapper a non-interfering, stateless * function to apply to each element * @return the new cache double stream */ default DoubleCacheStream mapToDouble(SerializableIntToDoubleFunction mapper) { return mapToDouble((IntToDoubleFunction) mapper); } /** * {@inheritDoc} * @return the new cache long stream */ @Override LongCacheStream mapToLong(IntToLongFunction mapper); /** * Same as {@link IntCacheStream#mapToLong(IntToLongFunction)} except that the IntToLongFunction must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param mapper a non-interfering, stateless * function to apply to each element * @return the new cache long stream */ default LongCacheStream mapToLong(SerializableIntToLongFunction mapper) { return mapToLong((IntToLongFunction) mapper); } /** * {@inheritDoc} * @return the new cache int stream */ @Override IntCacheStream flatMap(IntFunction<? extends IntStream> mapper); /** * Same as {@link IntCacheStream#flatMap(IntFunction)} except that the IntFunction must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param mapper a non-interfering, stateless * function to apply to each element which produces a * {@code IntStream} of new values * @return the new cache int stream */ default IntCacheStream flatMap(SerializableIntFunction<? extends IntStream> mapper) { return flatMap((IntFunction<? extends IntStream>) mapper); } /** * {@inheritDoc} * @return the new cache int stream */ @Override IntCacheStream distinct(); /** * {@inheritDoc} * @return the new cache int stream */ @Override IntCacheStream sorted(); /** * {@inheritDoc} * @return the new cache int stream */ @Override IntCacheStream peek(IntConsumer action); /** * Same as {@link IntCacheStream#flatMap(IntFunction)} except that the IntFunction must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param action a non-interfering action to perform on the elements as * they are consumed from the stream * @return the new cache int stream */ default IntCacheStream peek(SerializableIntConsumer action) { return peek((IntConsumer) action); } /** * {@inheritDoc} * @return the new cache int stream */ @Override IntCacheStream limit(long maxSize); /** * {@inheritDoc} * @return the new cache int stream */ @Override IntCacheStream skip(long n); /** * Same as {@link IntCacheStream#forEach(IntConsumer)} except that the IntConsumer must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param action a non-interfering action to perform on the elements */ default void forEach(SerializableIntConsumer action) { forEach((IntConsumer) action); } /** * Same as {@link IntCacheStream#forEach(IntConsumer)} except that it takes an {@link ObjIntConsumer} that * provides access to the underlying {@link Cache} that is backing this stream. * <p> * Note that the <code>CacheAware</code> interface is not supported for injection using this method as the cache * is provided in the consumer directly. * @param action consumer to be ran for each element in the stream * @param <K> key type of the cache * @param <V> value type of the cache */ <K, V> void forEach(ObjIntConsumer<Cache<K, V>> action); /** * Same as {@link IntCacheStream#forEach(ObjIntConsumer)} except that the <code>BiConsumer</code> must also implement * <code>Serializable</code> * @param action consumer to be ran for each element in the stream * @param <K> key type of the cache * @param <V> value type of the cache */ default <K, V> void forEach(SerializableObjIntConsumer<Cache<K, V>> action) { forEach((ObjIntConsumer<Cache<K, V>>) action); } /** * Same as {@link IntCacheStream#reduce(int, IntBinaryOperator)} except that the IntBinaryOperator * must also implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param identity the identity value for the accumulating function * @param op an associative, non-interfering, stateless * function for combining two values * @return the result of the reduction */ default int reduce(int identity, SerializableIntBinaryOperator op) { return reduce(identity, (IntBinaryOperator) op); } /** * Same as {@link IntCacheStream#reduce(IntBinaryOperator)} except that the IntBinaryOperator must * also implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param op an associative, non-interfering, stateless * function for combining two values * @return the result of the reduction */ default OptionalInt reduce(SerializableIntBinaryOperator op) { return reduce((IntBinaryOperator) op); } /** * Same as {@link IntCacheStream#collect(Supplier, ObjIntConsumer, BiConsumer)} except that the arguments must also * implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param <R> type of the result * @param supplier a function that creates a new result container. For a * parallel execution, this function may be called * multiple times and must return a fresh value each time. * @param accumulator an associative, non-interfering, stateless * function for incorporating an additional element into a result * @param combiner an associative, non-interfering, stateless * function for combining two values, which must be * compatible with the accumulator function * @return the result of the reduction */ default <R> R collect(SerializableSupplier<R> supplier, SerializableObjIntConsumer<R> accumulator, SerializableBiConsumer<R, R> combiner) { return collect((Supplier<R>) supplier, accumulator, combiner); } /** * Same as {@link IntCacheStream#anyMatch(IntPredicate)} except that the IntPredicate must * also implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param predicate a non-interfering, stateless * predicate to apply to elements of this stream * @return {@code true} if any elements of the stream match the provided * predicate, otherwise {@code false} */ default boolean anyMatch(SerializableIntPredicate predicate) { return anyMatch((IntPredicate) predicate); } /** * Same as {@link IntCacheStream#allMatch(IntPredicate)} except that the IntPredicate must * also implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param predicate a non-interfering, stateless * predicate to apply to elements of this stream * @return {@code true} if either all elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} */ default boolean allMatch(SerializableIntPredicate predicate) { return allMatch((IntPredicate) predicate); } /** * Same as {@link IntCacheStream#noneMatch(IntPredicate)} except that the IntPredicate must * also implement <code>Serializable</code> * <p> * The compiler will pick this overload for lambda parameters, making them <code>Serializable</code> * @param predicate a non-interfering, stateless * predicate to apply to elements of this stream * @return {@code true} if either no elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} */ default boolean noneMatch(SerializableIntPredicate predicate) { return noneMatch((IntPredicate) predicate); } /** * {@inheritDoc} * @return the new cache stream containing integers */ @Override CacheStream<Integer> boxed(); /** * {@inheritDoc} * @return the cache double stream */ @Override DoubleCacheStream asDoubleStream(); /** * {@inheritDoc} * @return the cache long stream */ @Override LongCacheStream asLongStream(); /** * {@inheritDoc} * @return a sequential cache int stream */ @Override IntCacheStream sequential(); /** * {@inheritDoc} * @return a parallel cache int stream */ @Override IntCacheStream parallel(); /** * {@inheritDoc} * @return an unordered cache int stream */ @Override IntCacheStream unordered(); /** * {@inheritDoc} * @return a cache int stream with the handler applied */ @Override IntCacheStream onClose(Runnable closeHandler); }
14,855
33.548837
120
java
null
infinispan-main/core/src/main/java/org/infinispan/CacheCollection.java
package org.infinispan; import org.infinispan.commons.util.CloseableIteratorCollection; import org.infinispan.commons.util.Experimental; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; import org.reactivestreams.Publisher; import io.reactivex.rxjava3.core.Flowable; /** * A collection type that returns special Cache based streams that have additional options to tweak behavior. * @param <E> The type of the collection * @since 8.0 */ public interface CacheCollection<E> extends CloseableIteratorCollection<E> { @Override CacheStream<E> stream(); @Override CacheStream<E> parallelStream(); /** * Returns a publisher that will publish all elements that map to the given segment. Note this publisher may * require going remotely to retrieve elements depending on the underlying configuration and flags applied * to the original Cache used to create this CacheCollection. * @param segment the segment that all published elements belong to * @return Publisher that will publish the elements for the given segment * @implSpec Default implementation just does: * <pre> {@code * return localPublisher(org.infinispan.commons.util.IntSets.immutableSet(segment)); * }</pre> */ @Experimental default Publisher<E> localPublisher(int segment) { return localPublisher(IntSets.immutableSet(segment)); } /** * Returns a publisher that will publish all elements that map to the given segment. Note this publisher may * require going remotely to retrieve elements depending on the underlying configuration and flags applied * to the original Cache used to create this CacheCollection. * @param segments the segments that all published elements belong to * @return Publisher that will publish the elements for the given segments * @implSpec Default implementation falls back to stream filtering out the given segments * <pre> {@code * return io.reactivex.Flowable.fromIterable(() -> stream().filterKeySegments(segments).iterator()); * }</pre> */ @Experimental default Publisher<E> localPublisher(IntSet segments) { return Flowable.fromStream(stream().filterKeySegments(segments)); } }
2,243
39.8
111
java
null
infinispan-main/core/src/main/java/org/infinispan/LongCacheStream.java
package org.infinispan; import java.util.OptionalLong; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.LongBinaryOperator; import java.util.function.LongConsumer; import java.util.function.LongFunction; import java.util.function.LongPredicate; import java.util.function.LongToDoubleFunction; import java.util.function.LongToIntFunction; import java.util.function.LongUnaryOperator; import java.util.function.ObjLongConsumer; import java.util.function.Supplier; import java.util.stream.LongStream; import org.infinispan.util.function.SerializableBiConsumer; import org.infinispan.util.function.SerializableLongBinaryOperator; import org.infinispan.util.function.SerializableLongConsumer; import org.infinispan.util.function.SerializableLongFunction; import org.infinispan.util.function.SerializableLongPredicate; import org.infinispan.util.function.SerializableLongToDoubleFunction; import org.infinispan.util.function.SerializableLongToIntFunction; import org.infinispan.util.function.SerializableLongUnaryOperator; import org.infinispan.util.function.SerializableObjLongConsumer; import org.infinispan.util.function.SerializableSupplier; /** * A {@link LongStream} that has additional methods to allow for Serializable instances. Please see * {@link CacheStream} for additional details about various methods. * * @author wburns * @since 9.0 */ public interface LongCacheStream extends LongStream, BaseCacheStream<Long, LongStream> { /** * {@inheritDoc} * @return a stream with parallel distribution disabled. */ LongCacheStream sequentialDistribution(); /** * @inheritDoc * @return a stream with parallel distribution enabled. */ LongCacheStream parallelDistribution(); /** * {@inheritDoc} * @return a stream with the segments filtered. */ LongCacheStream filterKeySegments(Set<Integer> segments); /** * {@inheritDoc} * @return a stream with the keys filtered. */ LongCacheStream filterKeys(Set<?> keys); /** * {@inheritDoc} * @return a stream with the batch size updated */ LongCacheStream distributedBatchSize(int batchSize); /** * {@inheritDoc} * @return a stream with the listener registered. */ LongCacheStream segmentCompletionListener(SegmentCompletionListener listener); /** * {@inheritDoc} * @return a stream with rehash awareness disabled. */ LongCacheStream disableRehashAware(); /** * {@inheritDoc} * @return a stream with the timeout set */ LongCacheStream timeout(long timeout, TimeUnit unit); /** * {@inheritDoc} * @return the new cache long stream */ @Override LongCacheStream filter(LongPredicate predicate); /** * Same as {@link LongCacheStream#filter(LongPredicate)} except that the LongPredicate must also * implement Serializable. * <p> * This method will be used automatically by lambdas, which prevents users from having to manually cast to * a Serializable lambda. * @param predicate a non-interfering, stateless * predicate to apply to each element to determine if it * should be included * @return the new cache long stream */ default LongCacheStream filter(SerializableLongPredicate predicate) { return filter((LongPredicate) predicate); } /** * {@inheritDoc} * @return the new cache long stream */ @Override LongCacheStream map(LongUnaryOperator mapper); /** * Same as {@link LongCacheStream#map(LongUnaryOperator)} except that the LongUnaryOperator must also * implement Serializable. * <p> * This method will be used automatically by lambdas, which prevents users from having to manually cast to * a Serializable lambda. * @param mapper a non-interfering, stateless * function to apply to each element * @return the new cache long stream */ default LongCacheStream map(SerializableLongUnaryOperator mapper) { return map((LongUnaryOperator) mapper); } /** * {@inheritDoc} * @return the new cache stream */ @Override <U> CacheStream<U> mapToObj(LongFunction<? extends U> mapper); /** * Same as {@link LongCacheStream#mapToObj(LongFunction)} except that the LongFunction must also * implement Serializable. * <p> * This method will be used automatically by lambdas, which prevents users from having to manually cast to * a Serializable lambda. * @param <U> the element type of the new stream * @param mapper a non-interfering, stateless * function to apply to each element * @return the new cache stream */ default <U> CacheStream<U> mapToObj(SerializableLongFunction<? extends U> mapper) { return mapToObj((LongFunction<? extends U>) mapper); } /** * {@inheritDoc} * @return the new cache int stream */ @Override IntCacheStream mapToInt(LongToIntFunction mapper); /** * Same as {@link LongCacheStream#mapToInt(LongToIntFunction)} except that the LongToIntFunction must also * implement Serializable. * <p> * This method will be used automatically by lambdas, which prevents users from having to manually cast to * a Serializable lambda. * @param mapper a non-interfering, stateless * function to apply to each element * @return the new cache int stream */ default IntCacheStream mapToInt(SerializableLongToIntFunction mapper) { return mapToInt((LongToIntFunction) mapper); } /** * {@inheritDoc} * @return the new cache double stream */ @Override DoubleCacheStream mapToDouble(LongToDoubleFunction mapper); /** * Same as {@link LongCacheStream#mapToDouble(LongToDoubleFunction)} except that the LongToLongFunction must also * implement Serializable. * <p> * This method will be used automatically by lambdas, which prevents users from having to manually cast to * a Serializable lambda. * @param mapper a non-interfering, stateless * function to apply to each element * @return the new cache double stream */ default DoubleCacheStream mapToDouble(SerializableLongToDoubleFunction mapper) { return mapToDouble((LongToDoubleFunction) mapper); } /** * {@inheritDoc} * @return the new cache long stream */ @Override LongCacheStream flatMap(LongFunction<? extends LongStream> mapper); /** * Same as {@link LongCacheStream#flatMap(LongFunction)} except that the LongFunction must also * implement Serializable. * <p> * This method will be used automatically by lambdas, which prevents users from having to manually cast to * a Serializable lambda. * @param mapper a non-interfering, stateless * function to apply to each element which produces a * {@code LongStream} of new values * @return the new cache long stream */ default LongCacheStream flatMap(SerializableLongFunction<? extends LongStream> mapper) { return flatMap((LongFunction<? extends LongStream>) mapper); } /** * {@inheritDoc} * @return the new cache long stream */ @Override LongCacheStream distinct(); /** * {@inheritDoc} * @return the new cache long stream */ @Override LongCacheStream sorted(); /** * {@inheritDoc} * @return the new cache long stream */ @Override LongCacheStream peek(LongConsumer action); /** * Same as {@link LongCacheStream#flatMap(LongFunction)} except that the LongFunction must also * implement Serializable. * <p> * This method will be used automatically by lambdas, which prevents users from having to manually cast to * a Serializable lambda. * @param action a non-interfering action to perform on the elements as * they are consumed from the stream * @return the new cache long stream */ default LongCacheStream peek(SerializableLongConsumer action) { return peek((LongConsumer) action); } /** * {@inheritDoc} * @return the new cache long stream */ @Override LongCacheStream limit(long maxSize); /** * {@inheritDoc} * @return the new cache long stream */ @Override LongCacheStream skip(long n); /** * Same as {@link LongCacheStream#forEach(LongConsumer)} except that the LongConsumer must also * implement Serializable. * <p> * This method will be used automatically by lambdas, which prevents users from having to manually cast to * a Serializable lambda. * @param action a non-interfering action to perform on the elements */ default void forEach(SerializableLongConsumer action) { forEach((LongConsumer) action); } /** * Same as {@link LongCacheStream#forEach(LongConsumer)} except that it takes an {@link ObjLongConsumer} that * provides access to the underlying {@link Cache} that is backing this stream. * <p> * Note that the <code>CacheAware</code> interface is not supported for injection using this method as the cache * is provided in the consumer directly. * @param action consumer to be ran for each element in the stream * @param <K> key type of the cache * @param <V> value type of the cache */ <K, V> void forEach(ObjLongConsumer<Cache<K, V>> action); /** * Same as {@link LongCacheStream#forEach(ObjLongConsumer)} except that the <code>BiConsumer</code> must also implement * <code>Serializable</code> * @param action consumer to be ran for each element in the stream * @param <K> key type of the cache * @param <V> value type of the cache */ default <K, V> void forEach(SerializableObjLongConsumer<Cache<K, V>> action) { forEach((ObjLongConsumer<Cache<K, V>>) action); } /** * Same as {@link LongCacheStream#reduce(long, LongBinaryOperator)} except that the LongBinaryOperator must * also implement Serializable. * <p> * This method will be used automatically by lambdas, which prevents users from having to manually cast to * a Serializable lambda. * @param identity the identity value for the accumulating function * @param op an associative, non-interfering, stateless * function for combining two values * @return the result of the reduction */ default long reduce(long identity, SerializableLongBinaryOperator op) { return reduce(identity, (LongBinaryOperator) op); } /** * Same as {@link LongCacheStream#reduce(LongBinaryOperator)} except that the LongBinaryOperator must * also implement Serializable. * <p> * This method will be used automatically by lambdas, which prevents users from having to manually cast to * a Serializable lambda. * @param op an associative, non-interfering, stateless * function for combining two values * @return the result of the reduction */ default OptionalLong reduce(SerializableLongBinaryOperator op) { return reduce((LongBinaryOperator) op); } /** * Same as {@link LongCacheStream#collect(Supplier, ObjLongConsumer, BiConsumer)} except that the arguments must * also implement Serializable. * <p> * This method will be used automatically by lambdas, which prevents users from having to manually cast to * a Serializable lambda. * @param <R> type of the result * @param supplier a function that creates a new result container. For a * parallel execution, this function may be called * multiple times and must return a fresh value each time. * @param accumulator an associative, non-interfering, stateless * function for incorporating an additional element into a result * @param combiner an associative, non-interfering, stateless * function for combining two values, which must be * compatible with the accumulator function * @return the result of the reduction */ default <R> R collect(SerializableSupplier<R> supplier, SerializableObjLongConsumer<R> accumulator, SerializableBiConsumer<R, R> combiner) { return collect((Supplier<R>) supplier, accumulator, combiner); } /** * Same as {@link LongCacheStream#anyMatch(LongPredicate)} except that the LongPredicate must * also implement Serializable. * <p> * This method will be used automatically by lambdas, which prevents users from having to manually cast to * a Serializable lambda. * @param predicate a non-interfering, stateless * predicate to apply to elements of this stream * @return {@code true} if any elements of the stream match the provided * predicate, otherwise {@code false} */ default boolean anyMatch(SerializableLongPredicate predicate) { return anyMatch((LongPredicate) predicate); } /** * Same as {@link LongCacheStream#allMatch(LongPredicate)} except that the LongPredicate must * also implement Serializable. * <p> * This method will be used automatically by lambdas, which prevents users from having to manually cast to * a Serializable lambda. * @param predicate a non-interfering, stateless * predicate to apply to elements of this stream * @return {@code true} if either all elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} */ default boolean allMatch(SerializableLongPredicate predicate) { return allMatch((LongPredicate) predicate); } /** * Same as {@link LongCacheStream#noneMatch(LongPredicate)} except that the LongPredicate must * also implement Serializable. * <p> * This method will be used automatically by lambdas, which prevents users from having to manually cast to * a Serializable lambda. * @param predicate a non-interfering, stateless * predicate to apply to elements of this stream * @return {@code true} if either no elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} */ default boolean noneMatch(SerializableLongPredicate predicate) { return noneMatch((LongPredicate) predicate); } /** * {@inheritDoc} * @return the new cache stream containing longs */ @Override CacheStream<Long> boxed(); /** * {@inheritDoc} * @return the cache double stream */ @Override DoubleCacheStream asDoubleStream(); /** * {@inheritDoc} * @return a sequential cache long stream */ @Override LongCacheStream sequential(); /** * {@inheritDoc} * @return a parallel cache long stream */ @Override LongCacheStream parallel(); /** * {@inheritDoc} * @return an unordered cache long stream */ @Override LongCacheStream unordered(); /** * {@inheritDoc} * @return a cache long stream with the handler applied */ @Override LongCacheStream onClose(Runnable closeHandler); }
15,188
33.757437
122
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/ConfigurationManager.java
package org.infinispan.configuration; import static org.infinispan.util.logging.Log.CONFIG; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Collectors; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.util.GlobUtils; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; /** * It manages all the configuration for a specific container. * <p> * It manages the {@link GlobalConfiguration}, the default {@link Configuration} and all the defined named caches {@link * Configuration}. * * @author Pedro Ruivo * @since 8.1 */ public class ConfigurationManager { private final GlobalConfiguration globalConfiguration; private final ConcurrentMap<String, Configuration> namedConfiguration; public ConfigurationManager(GlobalConfiguration globalConfiguration) { this.globalConfiguration = globalConfiguration; this.namedConfiguration = new ConcurrentHashMap<>(); } public ConfigurationManager(ConfigurationBuilderHolder holder) { this(holder.getGlobalConfigurationBuilder().build()); holder.getNamedConfigurationBuilders() .forEach((name, builder) -> namedConfiguration.put(name, builder.build(globalConfiguration))); } public GlobalConfiguration getGlobalConfiguration() { return globalConfiguration; } public Configuration getConfiguration(String cacheName, boolean includeWildcards) { if (includeWildcards) return findConfiguration(cacheName); else return namedConfiguration.get(cacheName); } public Configuration getConfiguration(String cacheName) { Configuration configuration = findConfiguration(cacheName); if (configuration != null) { return configuration; } else { throw CONFIG.noSuchCacheConfiguration(cacheName); } } private Configuration findConfiguration(String name) { if (namedConfiguration.containsKey(name)) { return namedConfiguration.get(name); } else { // Attempt wildcard matching Configuration match = null; for (Map.Entry<String, Configuration> c : namedConfiguration.entrySet()) { String key = c.getKey(); if (GlobUtils.isGlob(key)) { if (name.matches(GlobUtils.globToRegex(key))) { if (match == null) { match = c.getValue(); // If this is a template, turn it into a concrete configuration if (match.isTemplate()) { ConfigurationBuilder builder = new ConfigurationBuilder().read(match).template(false); match = builder.build(); } } else throw CONFIG.configurationNameMatchesMultipleWildcards(name); } } } return match; } } public Configuration putConfiguration(String cacheName, Configuration configuration) { namedConfiguration.put(cacheName, configuration); return configuration; } public Configuration putConfiguration(String cacheName, ConfigurationBuilder builder) { return putConfiguration(cacheName, builder.build(globalConfiguration)); } public void removeConfiguration(String cacheName) { namedConfiguration.remove(cacheName); } public Collection<String> getDefinedCaches() { return namedConfiguration.entrySet().stream() .filter(entry -> !entry.getValue().isTemplate()) .map(Map.Entry::getKey).collect(Collectors.toUnmodifiableList()); } public Collection<String> getDefinedConfigurations() { return Collections.unmodifiableCollection(namedConfiguration.keySet()); } public ConfigurationBuilderHolder toBuilderHolder() { ConfigurationBuilderHolder holder = new ConfigurationBuilderHolder(); holder.getGlobalConfigurationBuilder().read(globalConfiguration); for (Map.Entry<String, Configuration> entry : namedConfiguration.entrySet()) { holder.newConfigurationBuilder(entry.getKey()).read(entry.getValue(), Combine.DEFAULT); } return holder; } }
4,498
35.577236
120
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/serializing/CoreConfigurationSerializer.java
package org.infinispan.configuration.serializing; import static org.infinispan.configuration.parsing.Attribute.CLUSTER; import static org.infinispan.configuration.parsing.Attribute.DEFAULT_STACK; import static org.infinispan.configuration.parsing.Attribute.EXTENDS; import static org.infinispan.configuration.parsing.Attribute.NAME; import static org.infinispan.configuration.parsing.Attribute.PATH; import static org.infinispan.configuration.parsing.Attribute.RAFT_MEMBERS; import static org.infinispan.configuration.parsing.Attribute.STACK; import static org.infinispan.configuration.serializing.SerializeUtils.writeOptional; import static org.infinispan.util.logging.Log.CONFIG; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ThreadFactory; import java.util.stream.Collectors; import org.infinispan.commons.configuration.ConfigurationFor; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.commons.executors.BlockingThreadPoolExecutorFactory; import org.infinispan.commons.executors.CachedThreadPoolExecutorFactory; import org.infinispan.commons.executors.ScheduledThreadPoolExecutorFactory; import org.infinispan.commons.executors.ThreadPoolExecutorFactory; import org.infinispan.commons.util.Util; import org.infinispan.commons.util.Version; import org.infinispan.configuration.cache.AbstractStoreConfiguration; import org.infinispan.configuration.cache.AuthorizationConfiguration; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.ClusterLoaderConfiguration; import org.infinispan.configuration.cache.ClusteringConfiguration; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.CustomInterceptorsConfiguration; import org.infinispan.configuration.cache.CustomStoreConfiguration; import org.infinispan.configuration.cache.GroupsConfiguration; import org.infinispan.configuration.cache.HashConfiguration; import org.infinispan.configuration.cache.IndexMergeConfiguration; import org.infinispan.configuration.cache.IndexWriterConfiguration; import org.infinispan.configuration.cache.IndexingConfiguration; import org.infinispan.configuration.cache.InterceptorConfiguration; import org.infinispan.configuration.cache.MemoryConfiguration; import org.infinispan.configuration.cache.PartitionHandlingConfiguration; import org.infinispan.configuration.cache.PersistenceConfiguration; import org.infinispan.configuration.cache.QueryConfiguration; import org.infinispan.configuration.cache.RecoveryConfiguration; import org.infinispan.configuration.cache.SingleFileStoreConfiguration; import org.infinispan.configuration.cache.SitesConfiguration; import org.infinispan.configuration.cache.StatisticsConfiguration; import org.infinispan.configuration.cache.StoreConfiguration; import org.infinispan.configuration.cache.TransactionConfiguration; import org.infinispan.configuration.global.AllowListConfiguration; import org.infinispan.configuration.global.GlobalAuthorizationConfiguration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.global.GlobalJmxConfiguration; import org.infinispan.configuration.global.GlobalMetricsConfiguration; import org.infinispan.configuration.global.GlobalStateConfiguration; import org.infinispan.configuration.global.GlobalStatePathConfiguration; import org.infinispan.configuration.global.SerializationConfiguration; import org.infinispan.configuration.global.ShutdownHookBehavior; import org.infinispan.configuration.global.StackConfiguration; import org.infinispan.configuration.global.StackFileConfiguration; import org.infinispan.configuration.global.TemporaryGlobalStatePathConfiguration; import org.infinispan.configuration.global.ThreadPoolConfiguration; import org.infinispan.configuration.global.TransportConfiguration; import org.infinispan.configuration.parsing.Attribute; import org.infinispan.configuration.parsing.CacheParser; import org.infinispan.configuration.parsing.Element; import org.infinispan.configuration.parsing.Parser; import org.infinispan.configuration.parsing.ParserScope; import org.infinispan.conflict.EntryMergePolicy; import org.infinispan.conflict.MergePolicy; import org.infinispan.factories.threads.DefaultThreadFactory; import org.infinispan.factories.threads.EnhancedQueueExecutorFactory; import org.infinispan.factories.threads.NonBlockingThreadPoolExecutorFactory; import org.infinispan.persistence.sifs.configuration.DataConfiguration; import org.infinispan.persistence.sifs.configuration.IndexConfiguration; import org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfiguration; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.remoting.transport.jgroups.EmbeddedJGroupsChannelConfigurator; import org.infinispan.security.PrincipalRoleMapper; import org.infinispan.security.Role; import org.infinispan.security.mappers.ClusterRoleMapper; import org.infinispan.security.mappers.CommonNameRoleMapper; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.security.mappers.NameRewriter; import org.infinispan.security.mappers.RegexNameRewriter; import org.jgroups.conf.ProtocolConfiguration; /** * Serializes an Infinispan configuration to an {@link ConfigurationWriter} * * @author Tristan Tarrant * @since 9.0 */ public class CoreConfigurationSerializer extends AbstractStoreSerializer implements ConfigurationSerializer<ConfigurationHolder> { private static final Map<String, Element> THREAD_POOL_FACTORIES; static { THREAD_POOL_FACTORIES = new ConcurrentHashMap<>(); THREAD_POOL_FACTORIES.put(CachedThreadPoolExecutorFactory.class.getName(), Element.CACHED_THREAD_POOL); THREAD_POOL_FACTORIES.put(NonBlockingThreadPoolExecutorFactory.class.getName(), Element.BLOCKING_BOUNDED_QUEUE_THREAD_POOL); THREAD_POOL_FACTORIES.put(EnhancedQueueExecutorFactory.class.getName(), Element.BLOCKING_BOUNDED_QUEUE_THREAD_POOL); THREAD_POOL_FACTORIES.put(ScheduledThreadPoolExecutorFactory.class.getName(), Element.SCHEDULED_THREAD_POOL); } @Override public void serialize(ConfigurationWriter writer, ConfigurationHolder holder) { writer.writeStartElement("infinispan"); writer.writeDefaultNamespace(Parser.NAMESPACE + Version.getMajorMinor()); GlobalConfiguration globalConfiguration = holder.getGlobalConfiguration(); if (globalConfiguration != null) { // Full configuration writeJGroups(writer, globalConfiguration); writeThreads(writer, globalConfiguration); } writeCacheContainer(writer, holder); if (globalConfiguration != null) { writeExtraConfiguration(writer, globalConfiguration.modules(), ParserScope.GLOBAL); } writer.writeEndElement(); } private void writeJGroups(ConfigurationWriter writer, GlobalConfiguration globalConfiguration) { if (globalConfiguration.isClustered()) { writer.writeStartElement(Element.JGROUPS); writer.writeAttribute(Attribute.TRANSPORT, globalConfiguration.transport().transport().getClass().getName()); List<StackFileConfiguration> stackFiles = globalConfiguration.transport().jgroups().stackFiles(); List<StackConfiguration> stacks = globalConfiguration.transport().jgroups().stacks(); if ((stackFiles.stream().filter(s -> !s.builtIn()).count() + stacks.size()) > 0) { writer.writeStartMap(Element.STACKS); for (StackFileConfiguration stack : stackFiles) { if (!stack.builtIn()) { writer.writeMapItem(Element.STACK_FILE, NAME, stack.name()); writer.writeAttribute(PATH, stack.path()); writer.writeEndMapItem(); } } for (StackConfiguration stack : stacks) { writer.writeMapItem(Element.STACK, NAME, stack.name()); writeOptional(writer, EXTENDS, stack.extend()); for (ProtocolConfiguration protocol : stack.configurator().getUncombinedProtocolStack()) { if (protocol.getProperties().isEmpty()) { writer.writeEmptyElement(protocol.getProtocolName()); } else { writer.writeStartElement(protocol.getProtocolName()); for (Entry<String, String> attr : protocol.getProperties().entrySet()) { writer.writeAttribute(attr.getKey(), attr.getValue()); } writer.writeEndElement(); } } EmbeddedJGroupsChannelConfigurator.RemoteSites remoteSites = stack.configurator().getUncombinedRemoteSites(); if (remoteSites != null) { writer.writeStartElement(Element.REMOTE_SITES); writer.writeAttribute(DEFAULT_STACK, remoteSites.getDefaultStack()); writeOptional(writer, CLUSTER, remoteSites.getDefaultCluster()); Map<String, EmbeddedJGroupsChannelConfigurator.RemoteSite> sites = remoteSites.getRemoteSites(); for (Entry<String, EmbeddedJGroupsChannelConfigurator.RemoteSite> remote : sites.entrySet()) { writer.writeStartElement(Element.REMOTE_SITE); writer.writeAttribute(NAME, remote.getKey()); writeOptional(writer, CLUSTER, remote.getValue().getCluster()); writer.writeAttribute(STACK, remote.getValue().getStack()); writer.writeEndElement(); // REMOTE_SITE } writer.writeEndElement(); // REMOTE_SITES } writer.writeEndMapItem(); // STACK } writer.writeEndMap(); } writer.writeEndElement(); // JGROUPS } } private void writeThreads(ConfigurationWriter writer, GlobalConfiguration globalConfiguration) { ConcurrentMap<String, DefaultThreadFactory> threadFactories = new ConcurrentHashMap<>(); for (ThreadPoolConfiguration threadPoolConfiguration : Arrays.asList( globalConfiguration.expirationThreadPool(), globalConfiguration.listenerThreadPool(), globalConfiguration.nonBlockingThreadPool(), globalConfiguration.blockingThreadPool(), globalConfiguration.transport().remoteCommandThreadPool(), globalConfiguration.transport().transportThreadPool())) { ThreadFactory threadFactory = threadPoolConfiguration.threadFactory(); if (threadFactory instanceof DefaultThreadFactory) { DefaultThreadFactory tf = (DefaultThreadFactory) threadFactory; threadFactories.putIfAbsent(tf.getName(), tf); } } if (threadFactories.size() > 0) { writer.writeStartElement(Element.THREADS); writer.writeStartMap(Element.THREAD_FACTORIES); for (DefaultThreadFactory threadFactory : threadFactories.values()) { writeThreadFactory(writer, threadFactory); } writer.writeEndMap(); writer.writeStartMap(Element.THREAD_POOLS); writeThreadPool(writer, globalConfiguration.nonBlockingThreadPoolName(), globalConfiguration.nonBlockingThreadPool()); writeThreadPool(writer, globalConfiguration.expirationThreadPoolName(), globalConfiguration.expirationThreadPool()); writeThreadPool(writer, globalConfiguration.listenerThreadPoolName(), globalConfiguration.listenerThreadPool()); writeThreadPool(writer, globalConfiguration.blockingThreadPoolName(), globalConfiguration.blockingThreadPool()); writeThreadPool(writer, globalConfiguration.transport().remoteThreadPoolName(), globalConfiguration.transport().remoteCommandThreadPool()); writer.writeEndMap(); writer.writeEndElement(); } } private void writeThreadFactory(ConfigurationWriter writer, DefaultThreadFactory threadFactory) { writer.writeMapItem(Element.THREAD_FACTORY, Attribute.NAME, threadFactory.getName()); writeOptional(writer, Attribute.GROUP_NAME, threadFactory.threadGroup().getName()); writeOptional(writer, Attribute.THREAD_NAME_PATTERN, threadFactory.threadNamePattern()); writer.writeAttribute(Attribute.PRIORITY, Integer.toString(threadFactory.initialPriority())); writer.writeEndMapItem(); } private void writeThreadPool(ConfigurationWriter writer, String name, ThreadPoolConfiguration threadPoolConfiguration) { ThreadPoolExecutorFactory<?> threadPoolFactory = threadPoolConfiguration.threadPoolFactory(); if (threadPoolFactory != null) { Element element = THREAD_POOL_FACTORIES.get(threadPoolFactory.getClass().getName()); if (element == Element.BLOCKING_BOUNDED_QUEUE_THREAD_POOL && threadPoolFactory.createsNonBlockingThreads()) { element = Element.NON_BLOCKING_BOUNDED_QUEUE_THREAD_POOL; } writer.writeMapItem(element, Attribute.NAME, name); ThreadFactory threadFactory = threadPoolConfiguration.threadFactory(); if (threadFactory instanceof DefaultThreadFactory) { DefaultThreadFactory tf = (DefaultThreadFactory) threadFactory; writer.writeAttribute(Attribute.THREAD_FACTORY, tf.getName()); } if (threadPoolFactory instanceof BlockingThreadPoolExecutorFactory) { BlockingThreadPoolExecutorFactory pool = (BlockingThreadPoolExecutorFactory) threadPoolFactory; writer.writeAttribute(Attribute.MAX_THREADS, Integer.toString(pool.maxThreads())); writer.writeAttribute(Attribute.CORE_THREADS, Integer.toString(pool.coreThreads())); writer.writeAttribute(Attribute.QUEUE_LENGTH, Integer.toString(pool.queueLength())); writer.writeAttribute(Attribute.KEEP_ALIVE_TIME, Long.toString(pool.keepAlive())); } writer.writeEndMapItem(); } } private void writeCacheContainer(ConfigurationWriter writer, ConfigurationHolder holder) { writer.writeStartElement(Element.CACHE_CONTAINER); GlobalConfiguration globalConfiguration = holder.getGlobalConfiguration(); if (globalConfiguration != null) { writer.writeAttribute(Attribute.NAME, globalConfiguration.cacheManagerName()); if (globalConfiguration.shutdown().hookBehavior() != ShutdownHookBehavior.DEFAULT) { writer.writeAttribute(Attribute.SHUTDOWN_HOOK, globalConfiguration.shutdown().hookBehavior().name()); } writer.writeAttribute(Attribute.STATISTICS, String.valueOf(globalConfiguration.statistics())); if (globalConfiguration.nonBlockingThreadPool().threadFactory() != null) { writer.writeAttribute(Attribute.NON_BLOCKING_EXECUTOR, globalConfiguration.nonBlockingThreadPoolName()); } if (globalConfiguration.expirationThreadPool().threadFactory() != null) { writer.writeAttribute(Attribute.EXPIRATION_EXECUTOR, globalConfiguration.expirationThreadPoolName()); } if (globalConfiguration.listenerThreadPool().threadFactory() != null) { writer.writeAttribute(Attribute.LISTENER_EXECUTOR, globalConfiguration.listenerThreadPoolName()); } if (globalConfiguration.blockingThreadPool().threadFactory() != null) { writer.writeAttribute(Attribute.BLOCKING_EXECUTOR, globalConfiguration.blockingThreadPoolName()); } writeTransport(writer, globalConfiguration); writeSecurity(writer, globalConfiguration); writeSerialization(writer, globalConfiguration); writeMetrics(writer, globalConfiguration); writeJMX(writer, globalConfiguration); writeGlobalState(writer, globalConfiguration); writeExtraConfiguration(writer, globalConfiguration.modules(), ParserScope.CACHE_CONTAINER); } writer.writeStartMap(Element.CACHES); for (Entry<String, Configuration> configuration : holder.getConfigurations().entrySet()) { Configuration config = configuration.getValue(); writeCache(writer, configuration.getKey(), config); } writer.writeEndMap(); // CACHES writer.writeEndElement(); // CACHE-CONTAINER } public void writeCache(ConfigurationWriter writer, String name, Configuration config) { boolean unnamed = (name == null || name.isBlank()); switch (config.clustering().cacheMode()) { case LOCAL: writeLocalCache(writer, name, config, unnamed); break; case DIST_ASYNC: case DIST_SYNC: writeDistributedCache(writer, name, config, unnamed); break; case INVALIDATION_ASYNC: case INVALIDATION_SYNC: writeInvalidationCache(writer, name, config, unnamed); break; case REPL_ASYNC: case REPL_SYNC: writeReplicatedCache(writer, name, config, unnamed); break; default: break; } } private void writeExtraConfiguration(ConfigurationWriter writer, Map<Class<?>, ?> modules) { writeExtraConfiguration(writer, modules, null); } private void writeExtraConfiguration(ConfigurationWriter writer, Map<Class<?>, ?> modules, ParserScope scope) { for (Entry<Class<?>, ?> entry : modules.entrySet()) { SerializedWith serializedWith = entry.getKey().getAnnotation(SerializedWith.class); if (serializedWith == null || (scope != null && scope != serializedWith.scope())) { continue; } try { ConfigurationSerializer<Object> serializer = Util.getInstanceStrict(serializedWith.value()); serializer.serialize(writer, entry.getValue()); } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { throw CONFIG.unableToInstantiateSerializer(serializedWith.value()); } } } private void writeGlobalState(ConfigurationWriter writer, GlobalConfiguration globalConfiguration) { GlobalStateConfiguration configuration = globalConfiguration.globalState(); if (configuration.enabled()) { writer.writeStartElement(Element.GLOBAL_STATE); configuration.attributes().write(writer); if (configuration.persistenceConfiguration().attributes().attribute(GlobalStatePathConfiguration.PATH).isModified()) { writer.writeStartElement(Element.PERSISTENT_LOCATION); writer.writeAttribute(Attribute.PATH, configuration.persistentLocation()); writer.writeEndElement(); } if (configuration.sharedPersistenceConfiguration().attributes().attribute(GlobalStatePathConfiguration.PATH).isModified()) { writer.writeStartElement(Element.SHARED_PERSISTENT_LOCATION); writer.writeAttribute(Attribute.PATH, configuration.sharedPersistentLocation()); writer.writeEndElement(); } if (configuration.temporaryLocationConfiguration().attributes().attribute(TemporaryGlobalStatePathConfiguration.PATH).isModified()) { writer.writeStartElement(Element.TEMPORARY_LOCATION); writer.writeAttribute(Attribute.PATH, configuration.temporaryLocation()); writer.writeEndElement(); } switch (configuration.configurationStorage()) { case IMMUTABLE: writer.writeEmptyElement(Element.IMMUTABLE_CONFIGURATION_STORAGE); break; case VOLATILE: writer.writeEmptyElement(Element.VOLATILE_CONFIGURATION_STORAGE); break; case OVERLAY: writer.writeEmptyElement(Element.OVERLAY_CONFIGURATION_STORAGE); break; case MANAGED: writer.writeEmptyElement(Element.MANAGED_CONFIGURATION_STORAGE); break; case CUSTOM: writer.writeStartElement(Element.CUSTOM_CONFIGURATION_STORAGE); writer.writeAttribute(Attribute.CLASS, configuration.configurationStorageClass().get().getClass().getName()); writer.writeEndElement(); break; } writer.writeEndElement(); } } private void writeSecurity(ConfigurationWriter writer, GlobalConfiguration configuration) { GlobalAuthorizationConfiguration authorization = configuration.security().authorization(); AttributeSet attributes = authorization.attributes(); if (attributes.isModified() && authorization.enabled()) { writer.writeStartElement(Element.SECURITY); writer.writeStartElement(Element.AUTHORIZATION); attributes.write(writer, GlobalAuthorizationConfiguration.GROUP_ONLY_MAPPING, Attribute.GROUP_ONLY_MAPPING); attributes.write(writer, GlobalAuthorizationConfiguration.AUDIT_LOGGER, Attribute.AUDIT_LOGGER); PrincipalRoleMapper mapper = authorization.principalRoleMapper(); if (mapper != null) { if (mapper instanceof IdentityRoleMapper) { writer.writeEmptyElement(Element.IDENTITY_ROLE_MAPPER); } else if (mapper instanceof CommonNameRoleMapper) { writer.writeEmptyElement(Element.COMMON_NAME_ROLE_MAPPER); } else if (mapper instanceof ClusterRoleMapper) { ClusterRoleMapper clusterRoleMapper = (ClusterRoleMapper) mapper; NameRewriter rewriter = clusterRoleMapper.nameRewriter(); if (rewriter instanceof RegexNameRewriter) { RegexNameRewriter regexNameRewriter = (RegexNameRewriter) rewriter; writer.writeStartElement(Element.CLUSTER_ROLE_MAPPER); writer.writeStartElement(Element.NAME_REWRITER); writer.writeStartElement(Element.REGEX_PRINCIPAL_TRANSFORMER); writer.writeAttribute(Attribute.PATTERN, regexNameRewriter.getPattern().pattern()); writer.writeAttribute(Attribute.REPLACEMENT, regexNameRewriter.getReplacement()); writer.writeAttribute(Attribute.REPLACE_ALL, regexNameRewriter.isReplaceAll()); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); } else { writer.writeEmptyElement(Element.CLUSTER_ROLE_MAPPER); } } else { writer.writeStartElement(Element.CUSTOM_ROLE_MAPPER); writer.writeAttribute(Attribute.CLASS, mapper.getClass().getName()); writer.writeEndElement(); } } if (!authorization.isDefaultRoles()) { writer.writeStartMap(Element.ROLES); for (Role role : authorization.roles().values()) { writer.writeMapItem(Element.ROLE, Attribute.NAME, role.getName()); writer.writeAttribute(Attribute.PERMISSIONS, role.getPermissions().stream().map(Enum::name).collect(Collectors.toList())); writer.writeEndMapItem(); } writer.writeEndMap(); } writer.writeEndElement(); writer.writeEndElement(); } } private void writeReplicatedCache(ConfigurationWriter writer, String name, Configuration configuration, boolean unnamed) { if (unnamed) { writer.writeStartElement(configuration.isTemplate() ? Element.REPLICATED_CACHE_CONFIGURATION : Element.REPLICATED_CACHE); } else { writer.writeMapItem(configuration.isTemplate() ? Element.REPLICATED_CACHE_CONFIGURATION : Element.REPLICATED_CACHE, Attribute.NAME, name); } configuration.attributes().write(writer); AttributeSet hashAttributes = configuration.clustering().hash().attributes(); hashAttributes.write(writer, HashConfiguration.NUM_SEGMENTS); hashAttributes.write(writer, HashConfiguration.CONSISTENT_HASH_FACTORY); hashAttributes.write(writer, HashConfiguration.KEY_PARTITIONER); writeCommonClusteredCacheAttributes(writer, configuration); writeCommonCacheAttributesElements(writer, name, configuration); writeExtraConfiguration(writer, configuration.modules()); if (unnamed) { writer.writeEndElement(); } else { writer.writeEndMapItem(); } } private void writeDistributedCache(ConfigurationWriter writer, String name, Configuration configuration, boolean unnamed) { if (unnamed) { writer.writeStartElement(configuration.isTemplate() ? Element.DISTRIBUTED_CACHE_CONFIGURATION : Element.DISTRIBUTED_CACHE); } else { writer.writeMapItem(configuration.isTemplate() ? Element.DISTRIBUTED_CACHE_CONFIGURATION : Element.DISTRIBUTED_CACHE, Attribute.NAME, name); } configuration.attributes().write(writer); configuration.clustering().hash().attributes().write(writer); configuration.clustering().l1().attributes().write(writer); writeCommonClusteredCacheAttributes(writer, configuration); writeCommonCacheAttributesElements(writer, name, configuration); GroupsConfiguration groups = configuration.clustering().hash().groups(); if (groups.attributes().isModified()) { writer.writeStartElement(Element.GROUPS); groups.attributes().write(writer, GroupsConfiguration.ENABLED); if (!groups.groupers().isEmpty()) { writer.writeArrayElement(Element.GROUPER, Element.GROUPER, Attribute.CLASS, groups.groupers().stream().map(g -> g.getClass().getName()).collect(Collectors.toList())); } writer.writeEndElement(); } writeExtraConfiguration(writer, configuration.modules()); if (unnamed) { writer.writeEndElement(); } else { writer.writeEndMapItem(); } } private void writeInvalidationCache(ConfigurationWriter writer, String name, Configuration configuration, boolean unnamed) { if (unnamed) { writer.writeStartElement(configuration.isTemplate() ? Element.INVALIDATION_CACHE_CONFIGURATION : Element.INVALIDATION_CACHE); } else { writer.writeMapItem(configuration.isTemplate() ? Element.INVALIDATION_CACHE_CONFIGURATION : Element.INVALIDATION_CACHE, Attribute.NAME, name); } configuration.attributes().write(writer); writeCommonClusteredCacheAttributes(writer, configuration); writeCommonCacheAttributesElements(writer, name, configuration); writeExtraConfiguration(writer, configuration.modules()); if (unnamed) { writer.writeEndElement(); } else { writer.writeEndMapItem(); } } private void writeLocalCache(ConfigurationWriter writer, String name, Configuration configuration, boolean unnamed) { if (unnamed) { writer.writeStartElement(configuration.isTemplate() ? Element.LOCAL_CACHE_CONFIGURATION : Element.LOCAL_CACHE); } else { writer.writeMapItem(configuration.isTemplate() ? Element.LOCAL_CACHE_CONFIGURATION : Element.LOCAL_CACHE, Attribute.NAME, name); } configuration.attributes().write(writer); writeCommonCacheAttributesElements(writer, name, configuration); writeExtraConfiguration(writer, configuration.modules()); if (unnamed) { writer.writeEndElement(); } else { writer.writeEndMapItem(); } } private void writeTransport(ConfigurationWriter writer, GlobalConfiguration globalConfiguration) { TransportConfiguration transport = globalConfiguration.transport(); AttributeSet attributes = transport.attributes(); if (attributes.isModified()) { writer.writeStartElement(Element.TRANSPORT); attributes.write(writer, TransportConfiguration.CLUSTER_NAME, Attribute.CLUSTER); attributes.write(writer, TransportConfiguration.MACHINE_ID, Attribute.MACHINE_ID); attributes.write(writer, TransportConfiguration.RACK_ID, Attribute.RACK_ID); if (transport.siteId() != null) { attributes.write(writer, TransportConfiguration.SITE_ID, Attribute.SITE); } attributes.write(writer, TransportConfiguration.NODE_NAME, Attribute.NODE_NAME); attributes.write(writer, TransportConfiguration.STACK); if (transport.remoteCommandThreadPool().threadPoolFactory() != null) { writer.writeAttribute(Attribute.REMOTE_COMMAND_EXECUTOR, transport.remoteThreadPoolName()); } attributes.write(writer, TransportConfiguration.DISTRIBUTED_SYNC_TIMEOUT, Attribute.LOCK_TIMEOUT); attributes.write(writer, TransportConfiguration.INITIAL_CLUSTER_SIZE, Attribute.INITIAL_CLUSTER_SIZE); attributes.write(writer, TransportConfiguration.INITIAL_CLUSTER_TIMEOUT, Attribute.INITIAL_CLUSTER_TIMEOUT); if (!transport.raftMembers().isEmpty()) { attributes.write(writer, TransportConfiguration.RAFT_MEMBERS, RAFT_MEMBERS); } writer.writeEndElement(); } } private void writeSerialization(ConfigurationWriter writer, GlobalConfiguration globalConfiguration) { SerializationConfiguration serialization = globalConfiguration.serialization(); AttributeSet attributes = serialization.attributes(); if (attributes.isModified()) { writer.writeStartElement(Element.SERIALIZATION); attributes.write(writer, SerializationConfiguration.MARSHALLER, Attribute.MARSHALLER); SerializationConfiguration config = globalConfiguration.serialization(); writeSerializationContextInitializers(writer, config); writeClassAllowList(writer, config.allowList()); writer.writeEndElement(); } } private void writeSerializationContextInitializers(ConfigurationWriter writer, SerializationConfiguration config) { List<SerializationContextInitializer> scis = config.contextInitializers(); if (scis != null && !scis.isEmpty()) { List<String> classes = scis.stream().map(s -> s.getClass().getName()).collect(Collectors.toList()); writer.writeArrayElement(Element.SERIALIZATION_CONTEXT_INITIALIZERS, Element.SERIALIZATION_CONTEXT_INITIALIZER, Attribute.CLASS, classes); } } private void writeClassAllowList(ConfigurationWriter writer, AllowListConfiguration config) { if (!config.getClasses().isEmpty() || !config.getRegexps().isEmpty()) { writer.writeStartElement(Element.ALLOW_LIST); writer.writeArrayElement(Element.CLASS, Element.CLASS, null, config.getClasses()); writer.writeArrayElement(Element.REGEX, Element.REGEX, null, config.getRegexps()); writer.writeEndElement(); } } private void writeMetrics(ConfigurationWriter writer, GlobalConfiguration globalConfiguration) { GlobalMetricsConfiguration metrics = globalConfiguration.metrics(); AttributeSet attributes = metrics.attributes(); if (attributes.isModified()) { writer.writeStartElement(Element.METRICS); attributes.write(writer, GlobalMetricsConfiguration.GAUGES, Attribute.GAUGES); attributes.write(writer, GlobalMetricsConfiguration.HISTOGRAMS, Attribute.HISTOGRAMS); attributes.write(writer, GlobalMetricsConfiguration.PREFIX, Attribute.PREFIX); attributes.write(writer, GlobalMetricsConfiguration.NAMES_AS_TAGS, Attribute.NAMES_AS_TAGS); writer.writeEndElement(); } } private void writeJMX(ConfigurationWriter writer, GlobalConfiguration globalConfiguration) { GlobalJmxConfiguration jmx = globalConfiguration.jmx(); AttributeSet attributes = jmx.attributes(); if (attributes.isModified()) { writer.writeStartElement(Element.JMX); attributes.write(writer, GlobalJmxConfiguration.ENABLED, Attribute.ENABLED); attributes.write(writer, GlobalJmxConfiguration.DOMAIN, Attribute.DOMAIN); attributes.write(writer, GlobalJmxConfiguration.MBEAN_SERVER_LOOKUP, Attribute.MBEAN_SERVER_LOOKUP); attributes.write(writer, GlobalJmxConfiguration.PROPERTIES); writer.writeEndElement(); } } private void writeTransaction(ConfigurationWriter writer, Configuration configuration) { TransactionConfiguration transaction = configuration.transaction(); AttributeSet attributes = transaction.attributes(); if (attributes.isModified()) { writer.writeStartElement(Element.TRANSACTION); CacheParser.TransactionMode mode = CacheParser.TransactionMode.fromConfiguration(transaction, configuration.invocationBatching().enabled()); writer.writeAttribute(Attribute.MODE, mode.toString()); attributes.write(writer); if (mode != CacheParser.TransactionMode.NONE) { attributes.write(writer, TransactionConfiguration.TRANSACTION_MANAGER_LOOKUP); } if (transaction.recovery().enabled()) transaction.recovery().attributes().write(writer, RecoveryConfiguration.RECOVERY_INFO_CACHE_NAME, Attribute.RECOVERY_INFO_CACHE_NAME); writer.writeEndElement(); } } private void writeSecurity(ConfigurationWriter writer, Configuration configuration) { AuthorizationConfiguration authorization = configuration.security().authorization(); AttributeSet attributes = authorization.attributes(); if (attributes.isModified()) { writer.writeStartElement(Element.SECURITY); writer.writeStartElement(Element.AUTHORIZATION); attributes.write(writer, AuthorizationConfiguration.ENABLED, Attribute.ENABLED); if (!authorization.roles().isEmpty()) { writer.writeAttribute(Attribute.ROLES, authorization.roles()); } writer.writeEndElement(); writer.writeEndElement(); } } private void writeCommonClusteredCacheAttributes(ConfigurationWriter writer, Configuration configuration) { ClusteringConfiguration clustering = configuration.clustering(); writer.writeAttribute(Attribute.MODE, clustering.cacheMode().isSynchronous() ? "SYNC" : "ASYNC"); clustering.attributes().write(writer, ClusteringConfiguration.REMOTE_TIMEOUT, Attribute.REMOTE_TIMEOUT); } private void writeCommonCacheAttributesElements(ConfigurationWriter writer, String name, Configuration configuration) { configuration.statistics().attributes().write(writer, StatisticsConfiguration.ENABLED, Attribute.STATISTICS); configuration.unsafe().attributes().write(writer); writeBackup(writer, configuration); writeEncoding(writer, configuration); configuration.sites().backupFor().attributes().write(writer, Element.BACKUP_FOR.getLocalName()); configuration.locking().attributes().write(writer, Element.LOCKING.getLocalName()); writeTransaction(writer, configuration); configuration.expiration().attributes().write(writer, Element.EXPIRATION.getLocalName()); writeMemory(writer, configuration); writePersistence(writer, configuration); writeQuery(writer, configuration); writeIndexing(writer, configuration); writeCustomInterceptors(writer, configuration); writeSecurity(writer, configuration); if (configuration.clustering().cacheMode().needsStateTransfer()) { configuration.clustering().stateTransfer().attributes().write(writer, Element.STATE_TRANSFER.getLocalName()); } writePartitionHandling(writer, configuration); } private void writeEncoding(ConfigurationWriter writer, Configuration configuration) { configuration.encoding().write(writer); } private void writePartitionHandling(ConfigurationWriter writer, Configuration configuration) { PartitionHandlingConfiguration partitionHandling = configuration.clustering().partitionHandling(); AttributeSet attributes = partitionHandling.attributes(); if (attributes.isModified()) { writer.writeStartElement(Element.PARTITION_HANDLING); attributes.write(writer, PartitionHandlingConfiguration.WHEN_SPLIT, Attribute.WHEN_SPLIT); EntryMergePolicy policyImpl = partitionHandling.mergePolicy(); MergePolicy policy = MergePolicy.fromConfiguration(policyImpl); String output = policy == MergePolicy.CUSTOM ? policyImpl.getClass().getName() : policy.toString(); writer.writeAttribute(Attribute.MERGE_POLICY, output); writer.writeEndElement(); } } private void writeCustomInterceptors(ConfigurationWriter writer, Configuration configuration) { CustomInterceptorsConfiguration customInterceptors = configuration.customInterceptors(); if (customInterceptors.interceptors().size() > 0) { writer.writeStartMap(Element.CUSTOM_INTERCEPTORS); for (InterceptorConfiguration interceptor : customInterceptors.interceptors()) { AttributeSet attributes = interceptor.attributes(); if (!attributes.attribute(InterceptorConfiguration.INTERCEPTOR_CLASS).isNull()) { writer.writeMapItem(Element.INTERCEPTOR, Attribute.CLASS, attributes.attribute(InterceptorConfiguration.INTERCEPTOR_CLASS).get().getName()); attributes.write(writer, InterceptorConfiguration.AFTER, Attribute.AFTER); attributes.write(writer, InterceptorConfiguration.BEFORE, Attribute.BEFORE); attributes.write(writer, InterceptorConfiguration.INDEX, Attribute.INDEX); attributes.write(writer, InterceptorConfiguration.POSITION, Attribute.POSITION); attributes.write(writer, InterceptorConfiguration.PROPERTIES); writer.writeEndMapItem(); } } writer.writeEndMap(); } } private void writeMemory(ConfigurationWriter writer, Configuration configuration) { MemoryConfiguration memory = configuration.memory(); AttributeSet attributes = memory.attributes(); if (attributes.isModified()) { writer.writeStartElement(Element.MEMORY); attributes.write(writer, MemoryConfiguration.STORAGE, Attribute.STORAGE); if (attributes.attribute(MemoryConfiguration.MAX_COUNT).get() > 0) { attributes.write(writer, MemoryConfiguration.MAX_COUNT, Attribute.MAX_COUNT); } else if (attributes.attribute(MemoryConfiguration.MAX_SIZE).get() != null) { attributes.write(writer, MemoryConfiguration.MAX_SIZE, Attribute.MAX_SIZE); } attributes.write(writer, MemoryConfiguration.WHEN_FULL, Attribute.WHEN_FULL); writer.writeEndElement(); } } private void writeQuery(ConfigurationWriter writer, Configuration configuration) { QueryConfiguration query = configuration.query(); AttributeSet attributes = query.attributes(); if (attributes.isModified()) { writer.writeStartElement(Element.QUERY); attributes.write(writer, QueryConfiguration.DEFAULT_MAX_RESULTS, Attribute.DEFAULT_MAX_RESULTS); attributes.write(writer, QueryConfiguration.HIT_COUNT_ACCURACY, Attribute.HIT_COUNT_ACCURACY); writer.writeEndElement(); } } private void writeIndexing(ConfigurationWriter writer, Configuration configuration) { IndexingConfiguration indexing = configuration.indexing(); AttributeSet attributes = indexing.attributes(); if (attributes.isModified()) { writer.writeStartElement(Element.INDEXING); attributes.write(writer, IndexingConfiguration.ENABLED, Attribute.ENABLED); attributes.write(writer, IndexingConfiguration.STORAGE, Attribute.STORAGE); attributes.write(writer, IndexingConfiguration.STARTUP_MODE, Attribute.STARTUP_MODE); attributes.write(writer, IndexingConfiguration.PATH, Attribute.PATH); attributes.write(writer, IndexingConfiguration.INDEXING_MODE, Attribute.INDEXING_MODE); long refreshInterval = indexing.reader().getRefreshInterval(); if (refreshInterval != 0) { writer.writeStartElement(Element.INDEX_READER); writer.writeAttribute(Attribute.REFRESH_INTERVAL, Long.toString(refreshInterval)); writer.writeEndElement(); } Integer shards = indexing.sharding().getShards(); if (shards > 1) { writer.writeStartElement(Element.INDEX_SHARDING); writer.writeAttribute(Attribute.SHARDS, Integer.toString(shards)); writer.writeEndElement(); } IndexWriterConfiguration indexWriter = indexing.writer(); IndexMergeConfiguration indexMerge = indexWriter.merge(); AttributeSet writerAttributes = indexWriter.attributes(); AttributeSet mergeAttributes = indexMerge.attributes(); boolean indexWriterModified = writerAttributes.isModified(); boolean indexMergeModified = mergeAttributes.isModified(); if (indexWriterModified || indexMergeModified) { writer.writeStartElement(Element.INDEX_WRITER); writerAttributes.write(writer, IndexWriterConfiguration.INDEX_COMMIT_INTERVAL, Attribute.COMMIT_INTERVAL); writerAttributes.write(writer, IndexWriterConfiguration.INDEX_LOW_LEVEL_TRACE, Attribute.LOW_LEVEL_TRACE); writerAttributes.write(writer, IndexWriterConfiguration.INDEX_MAX_BUFFERED_ENTRIES, Attribute.MAX_BUFFERED_ENTRIES); writerAttributes.write(writer, IndexWriterConfiguration.INDEX_QUEUE_COUNT, Attribute.QUEUE_COUNT); writerAttributes.write(writer, IndexWriterConfiguration.INDEX_QUEUE_SIZE, Attribute.QUEUE_SIZE); writerAttributes.write(writer, IndexWriterConfiguration.INDEX_THREAD_POOL_SIZE, Attribute.THREAD_POOL_SIZE); writerAttributes.write(writer, IndexWriterConfiguration.INDEX_RAM_BUFFER_SIZE, Attribute.RAM_BUFFER_SIZE); if (indexMergeModified) { writer.writeStartElement(Element.INDEX_MERGE); mergeAttributes.write(writer, IndexMergeConfiguration.CALIBRATE_BY_DELETES, Attribute.CALIBRATE_BY_DELETES); mergeAttributes.write(writer, IndexMergeConfiguration.FACTOR, Attribute.FACTOR); mergeAttributes.write(writer, IndexMergeConfiguration.MAX_ENTRIES, Attribute.MAX_ENTRIES); mergeAttributes.write(writer, IndexMergeConfiguration.MIN_SIZE, Attribute.MIN_SIZE); mergeAttributes.write(writer, IndexMergeConfiguration.MAX_SIZE, Attribute.MAX_SIZE); mergeAttributes.write(writer, IndexMergeConfiguration.MAX_FORCED_SIZE, Attribute.MAX_FORCED_SIZE); writer.writeEndElement(); } writer.writeEndElement(); } writer.writeArrayElement(Element.INDEXED_ENTITIES, Element.INDEXED_ENTITY, null, indexing.indexedEntityTypes()); if (!indexing.keyTransformers().isEmpty()) { writer.writeStartListElement(Element.KEY_TRANSFORMERS, true); for (Map.Entry<Class<?>, Class<?>> e : indexing.keyTransformers().entrySet()) { writer.writeStartElement(Element.KEY_TRANSFORMER); writer.writeAttribute(Attribute.KEY, e.getKey().getName()); writer.writeAttribute(Attribute.TRANSFORMER, e.getValue().getName()); writer.writeEndElement(); } writer.writeEndListElement(); } attributes.write(writer, GlobalJmxConfiguration.PROPERTIES); writer.writeEndElement(); } } private void writePersistence(ConfigurationWriter writer, Configuration configuration) { PersistenceConfiguration persistence = configuration.persistence(); AttributeSet attributes = persistence.attributes(); if (attributes.isModified() || !persistence.stores().isEmpty()) { writer.writeStartElement(Element.PERSISTENCE); attributes.write(writer, PersistenceConfiguration.PASSIVATION, Attribute.PASSIVATION); attributes.write(writer, PersistenceConfiguration.AVAILABILITY_INTERVAL, Attribute.AVAILABILITY_INTERVAL); attributes.write(writer, PersistenceConfiguration.CONNECTION_ATTEMPTS, Attribute.CONNECTION_ATTEMPTS); attributes.write(writer, PersistenceConfiguration.CONNECTION_INTERVAL, Attribute.CONNECTION_INTERVAL); for (StoreConfiguration store : persistence.stores()) { writeStore(writer, store); } writer.writeEndElement(); } } private void writeStore(ConfigurationWriter writer, StoreConfiguration configuration) { if (configuration instanceof SoftIndexFileStoreConfiguration) { writeFileStore(writer, (SoftIndexFileStoreConfiguration) configuration); } else if (configuration instanceof SingleFileStoreConfiguration) { writeSingleFileStore(writer, (SingleFileStoreConfiguration) configuration); } else if (configuration instanceof ClusterLoaderConfiguration) { writeClusterLoader(writer, (ClusterLoaderConfiguration) configuration); } else if (configuration instanceof CustomStoreConfiguration) { writeCustomStore(writer, (CustomStoreConfiguration) configuration); } else { SerializedWith serializedWith = configuration.getClass().getAnnotation(SerializedWith.class); if (serializedWith == null) { ConfigurationFor configurationFor = configuration.getClass().getAnnotation(ConfigurationFor.class); if (configuration instanceof AbstractStoreConfiguration && configurationFor != null) { writer.writeComment("A serializer for the store configuration class " + configuration.getClass().getName() + " was not found. Using custom store mode"); AbstractStoreConfiguration asc = (AbstractStoreConfiguration) configuration; writeGenericStore(writer, configurationFor.value().getName(), asc); } else throw new UnsupportedOperationException("Cannot serialize store configuration " + configuration.getClass().getName()); } else { ConfigurationSerializer<StoreConfiguration> serializer; try { serializer = Util.getInstanceStrict(serializedWith.value()); serializer.serialize(writer, configuration); } catch (InstantiationException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { throw CONFIG.unableToInstantiateSerializer(serializedWith.value()); } } } } private void writeBackup(ConfigurationWriter writer, Configuration configuration) { SitesConfiguration sites = configuration.sites(); if (sites.allBackups().isEmpty()) { return; } writer.writeStartMap(Element.BACKUPS); sites.attributes().write(writer); for (BackupConfiguration backup : sites.allBackups()) { writer.writeMapItem(Element.BACKUP, Attribute.SITE, backup.site()); backup.attributes().write(writer); AttributeSet stateTransfer = backup.stateTransfer().attributes(); if (stateTransfer.isModified()) { writer.writeStartElement(Element.STATE_TRANSFER); stateTransfer.write(writer); writer.writeEndElement(); } AttributeSet takeOffline = backup.takeOffline().attributes(); if (takeOffline.isModified()) { writer.writeStartElement(Element.TAKE_OFFLINE); takeOffline.write(writer); writer.writeEndElement(); } writer.writeEndMapItem(); } writer.writeEndMap(); } private void writeFileStore(ConfigurationWriter writer, SoftIndexFileStoreConfiguration configuration) { writer.writeStartElement(Element.FILE_STORE); configuration.attributes().write(writer); writeCommonStoreSubAttributes(writer, configuration); writeDataElement(writer, configuration); writeIndexElement(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); } private void writeDataElement(ConfigurationWriter writer, SoftIndexFileStoreConfiguration configuration) { configuration.data().attributes().write(writer, Element.DATA.getLocalName(), DataConfiguration.DATA_LOCATION, DataConfiguration.MAX_FILE_SIZE, DataConfiguration.SYNC_WRITES); } private void writeIndexElement(ConfigurationWriter writer, SoftIndexFileStoreConfiguration configuration) { configuration.index().attributes().write(writer, Element.INDEX.getLocalName(), IndexConfiguration.INDEX_LOCATION, IndexConfiguration.INDEX_QUEUE_LENGTH, IndexConfiguration.INDEX_SEGMENTS, IndexConfiguration.MIN_NODE_SIZE, IndexConfiguration.MAX_NODE_SIZE); } private void writeSingleFileStore(ConfigurationWriter writer, SingleFileStoreConfiguration configuration) { writer.writeStartElement(Element.SINGLE_FILE_STORE); configuration.attributes().write(writer); writeCommonStoreSubAttributes(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); } private void writeClusterLoader(ConfigurationWriter writer, ClusterLoaderConfiguration configuration) { writer.writeStartElement(Element.CLUSTER_LOADER); configuration.attributes().write(writer); writeCommonStoreSubAttributes(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); } private void writeCustomStore(ConfigurationWriter writer, CustomStoreConfiguration configuration) { writer.writeStartElement(Element.STORE); configuration.attributes().write(writer); writeCommonStoreSubAttributes(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); } private void writeGenericStore(ConfigurationWriter writer, String storeClassName, AbstractStoreConfiguration configuration) { writer.writeStartElement(Element.STORE); writer.writeAttribute(Attribute.CLASS.getLocalName(), storeClassName); configuration.attributes().write(writer); writeCommonStoreSubAttributes(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); } }
50,582
54.70815
178
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/serializing/ConfigurationSerializer.java
package org.infinispan.configuration.serializing; import org.infinispan.commons.configuration.io.ConfigurationWriter; /** * @author Tristan Tarrant * @since 9.0 */ public interface ConfigurationSerializer<T> { void serialize(ConfigurationWriter writer, T configuration); }
281
22.5
67
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/serializing/ConfigurationHolder.java
package org.infinispan.configuration.serializing; import java.util.Map; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.global.GlobalConfiguration; /** * ConfigurationHolder. * * @author Tristan Tarrant * @since 9.0 */ public class ConfigurationHolder { final private GlobalConfiguration globalConfiguration; final private Map<String, Configuration> configurations; public ConfigurationHolder(GlobalConfiguration globalConfiguration, Map<String, Configuration> configurations) { this.globalConfiguration = globalConfiguration; this.configurations = configurations; } public GlobalConfiguration getGlobalConfiguration() { return globalConfiguration; } public Map<String, Configuration> getConfigurations() { return configurations; } }
839
25.25
115
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/serializing/SerializedWith.java
package org.infinispan.configuration.serializing; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.infinispan.configuration.parsing.ParserScope; /** * SerializedWith, specifies the {@link ConfigurationSerializer} to use to serialize the annotated class * * @author Tristan Tarrant * @since 9.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface SerializedWith { Class<? extends ConfigurationSerializer> value(); ParserScope scope() default ParserScope.CACHE_CONTAINER; }
641
26.913043
104
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/serializing/AbstractStoreSerializer.java
package org.infinispan.configuration.serializing; import static org.infinispan.configuration.serializing.SerializeUtils.writeTypedProperties; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.commons.util.TypedProperties; import org.infinispan.configuration.cache.AbstractStoreConfiguration; import org.infinispan.configuration.cache.AsyncStoreConfiguration; import org.infinispan.configuration.cache.StoreConfiguration; import org.infinispan.configuration.parsing.Attribute; import org.infinispan.configuration.parsing.Element; /** * AbstractStoreSerializer. * * @author Tristan Tarrant * @since 9.0 */ public abstract class AbstractStoreSerializer { protected void writeCommonStoreSubAttributes(ConfigurationWriter writer, AbstractStoreConfiguration configuration) { } protected void writeCommonStoreElements(ConfigurationWriter writer, StoreConfiguration configuration) { if (configuration.async().enabled()) { writeStoreWriteBehind(writer, configuration); } writeTypedProperties(writer, TypedProperties.toTypedProperties(configuration.properties())); } private void writeStoreWriteBehind(ConfigurationWriter writer, StoreConfiguration configuration) { AttributeSet writeBehind = configuration.async().attributes(); if (writeBehind.isModified()) { writer.writeStartElement(Element.WRITE_BEHIND); writeBehind.write(writer, AsyncStoreConfiguration.MODIFICATION_QUEUE_SIZE, Attribute.MODIFICATION_QUEUE_SIZE); writeBehind.write(writer, AsyncStoreConfiguration.FAIL_SILENTLY, Attribute.FAIL_SILENTLY); writer.writeEndElement(); } } }
1,751
41.731707
119
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/serializing/SerializeUtils.java
package org.infinispan.configuration.serializing; import org.infinispan.commons.configuration.io.ConfigurationFormatFeature; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.commons.util.TypedProperties; import org.infinispan.configuration.parsing.Attribute; import org.infinispan.configuration.parsing.Element; public class SerializeUtils { private SerializeUtils() {} public static void writeOptional(ConfigurationWriter writer, Enum<?> attribute, String value) { if (value != null) { writer.writeAttribute(attribute, value); } } public static void writeTypedProperties(ConfigurationWriter writer, TypedProperties properties) { writeTypedProperties(writer, properties, Element.PROPERTIES, Element.PROPERTY); } public static void writeTypedProperties(ConfigurationWriter writer, TypedProperties properties, Enum<?> collectionElement, Enum<?> itemElement) { if (!properties.isEmpty()) { if (writer.hasFeature(ConfigurationFormatFeature.BARE_COLLECTIONS)) { for(String property : properties.stringPropertyNames()) { writer.writeStartElement(itemElement); writer.writeAttribute(Attribute.NAME, property); writer.writeCharacters(properties.getProperty(property)); writer.writeEndElement(); } } else { writer.writeStartMap(collectionElement); for (String property : properties.stringPropertyNames()) { writer.writeMapItem(itemElement, Attribute.NAME, property, properties.getProperty(property)); } writer.writeEndMap(); } } } }
1,704
40.585366
148
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/InvocationBatchingConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.InvocationBatchingConfiguration.ENABLED; import static org.infinispan.configuration.cache.TransactionConfiguration.TRANSACTION_MODE; import static org.infinispan.transaction.TransactionMode.TRANSACTIONAL; import static org.infinispan.util.logging.Log.CONFIG; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.transaction.TransactionMode; public class InvocationBatchingConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<InvocationBatchingConfiguration> { private final AttributeSet attributes; InvocationBatchingConfigurationBuilder(ConfigurationBuilder builder) { super(builder); attributes = InvocationBatchingConfiguration.attributeDefinitionSet(); } @Override public AttributeSet attributes() { return attributes; } public InvocationBatchingConfigurationBuilder enable() { attributes.attribute(ENABLED).set(true); enableTransactions(); return this; } public InvocationBatchingConfigurationBuilder disable() { attributes.attribute(ENABLED).set(false); return this; } public InvocationBatchingConfigurationBuilder enable(boolean enable) { attributes.attribute(ENABLED).set(enable); if (enable) { enableTransactions(); } return this; } private void enableTransactions() { Attribute<TransactionMode> transactionModeAttribute = getBuilder().transaction().attributes.attribute(TRANSACTION_MODE); if (!transactionModeAttribute.isModified()) { getBuilder().transaction().transactionMode(TRANSACTIONAL); } } boolean isEnabled() { return attributes.attribute(ENABLED).get(); } @Override public void validate() { if (isEnabled() && !getBuilder().transaction().transactionMode().isTransactional()) throw CONFIG.invocationBatchingNeedsTransactionalCache(); if (isEnabled() && getBuilder().transaction().recovery().isEnabled() && !getBuilder().transaction().useSynchronization()) throw CONFIG.invocationBatchingCannotBeRecoverable(); } @Override public void validate(GlobalConfiguration globalConfig) { } @Override public InvocationBatchingConfiguration create() { return new InvocationBatchingConfiguration(attributes.protect()); } @Override public InvocationBatchingConfigurationBuilder read(InvocationBatchingConfiguration template, Combine combine) { attributes.read(template.attributes(), combine); return this; } @Override public String toString() { return "InvocationBatchingConfigurationBuilder [attributes=" + attributes + "]"; } }
3,032
32.7
147
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/IndexWriterConfiguration.java
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Attribute; import org.infinispan.configuration.parsing.Element; /** * @since 12.0 */ public class IndexWriterConfiguration extends ConfigurationElement<IndexWriterConfiguration> { public static final AttributeDefinition<Integer> INDEX_THREAD_POOL_SIZE = AttributeDefinition.builder(Attribute.THREAD_POOL_SIZE, 1, Integer.class).immutable().build(); public static final AttributeDefinition<Integer> INDEX_QUEUE_COUNT = AttributeDefinition.builder(Attribute.QUEUE_COUNT, 1, Integer.class).immutable().build(); public static final AttributeDefinition<Integer> INDEX_QUEUE_SIZE = AttributeDefinition.builder(Attribute.QUEUE_SIZE, null, Integer.class).immutable().build(); public static final AttributeDefinition<Integer> INDEX_COMMIT_INTERVAL = AttributeDefinition.builder(Attribute.COMMIT_INTERVAL, null, Integer.class).immutable().build(); public static final AttributeDefinition<Integer> INDEX_RAM_BUFFER_SIZE = AttributeDefinition.builder(Attribute.RAM_BUFFER_SIZE, null, Integer.class).immutable().build(); public static final AttributeDefinition<Integer> INDEX_MAX_BUFFERED_ENTRIES = AttributeDefinition.builder(Attribute.MAX_BUFFERED_ENTRIES, null, Integer.class).immutable().build(); public static final AttributeDefinition<Boolean> INDEX_LOW_LEVEL_TRACE = AttributeDefinition.builder(Attribute.LOW_LEVEL_TRACE, false, Boolean.class).immutable().build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(IndexWriterConfiguration.class, INDEX_THREAD_POOL_SIZE, INDEX_QUEUE_COUNT, INDEX_QUEUE_SIZE, INDEX_COMMIT_INTERVAL, INDEX_RAM_BUFFER_SIZE, INDEX_MAX_BUFFERED_ENTRIES, INDEX_LOW_LEVEL_TRACE); } private final IndexMergeConfiguration indexMergeConfiguration; IndexWriterConfiguration(AttributeSet attributes, IndexMergeConfiguration indexMergeConfiguration) { super(Element.INDEX_WRITER, attributes, indexMergeConfiguration); this.indexMergeConfiguration = indexMergeConfiguration; } public IndexMergeConfiguration merge() { return indexMergeConfiguration; } public Integer getThreadPoolSize() { return attributes.attribute(INDEX_THREAD_POOL_SIZE).get(); } public Integer getQueueCount() { return attributes.attribute(INDEX_QUEUE_COUNT).get(); } public Integer getQueueSize() { return attributes.attribute(INDEX_QUEUE_SIZE).get(); } public Integer getCommitInterval() { return attributes.attribute(INDEX_COMMIT_INTERVAL).get(); } public Integer getRamBufferSize() { return attributes.attribute(INDEX_RAM_BUFFER_SIZE).get(); } public Integer getMaxBufferedEntries() { return attributes.attribute(INDEX_MAX_BUFFERED_ENTRIES).get(); } public Boolean isLowLevelTrace() { return attributes.attribute(INDEX_LOW_LEVEL_TRACE).get(); } }
3,207
42.945205
122
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/AbstractModuleConfigurationBuilder.java
package org.infinispan.configuration.cache; /** * AbstractModuleConfigurationBuilder. * * @author Tristan Tarrant * @since 5.2 */ public abstract class AbstractModuleConfigurationBuilder extends AbstractConfigurationChildBuilder { protected AbstractModuleConfigurationBuilder(ConfigurationBuilder builder) { super(builder); } }
348
20.8125
100
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/StatisticsConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.StatisticsConfiguration.AVAILABLE; import static org.infinispan.configuration.cache.StatisticsConfiguration.ENABLED; import static org.infinispan.util.logging.Log.CONFIG; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; /** * Determines whether cache statistics are gathered. * * @since 10.1.3 */ public class StatisticsConfigurationBuilder extends JMXStatisticsConfigurationBuilder implements Builder<StatisticsConfiguration> { private final AttributeSet attributes; StatisticsConfigurationBuilder(ConfigurationBuilder builder) { super(builder); this.attributes = StatisticsConfiguration.attributeDefinitionSet(); } @Override public AttributeSet attributes() { return attributes; } /** * Enable statistics gathering. */ public StatisticsConfigurationBuilder enable() { attributes.attribute(ENABLED).set(true); return this; } /** * Disable statistics gathering. */ public StatisticsConfigurationBuilder disable() { attributes.attribute(ENABLED).set(false); return this; } /** * Enable or disable statistics gathering. */ public StatisticsConfigurationBuilder enabled(boolean enabled) { attributes.attribute(ENABLED).set(enabled); return this; } /** * If set to false, statistics gathering cannot be enabled during runtime. Performance optimization. * @deprecated since 10.1.3. This method will be removed in a future version. */ @Deprecated public StatisticsConfigurationBuilder available(boolean available) { attributes.attribute(AVAILABLE).set(available); return this; } @Override public void validate() { Attribute<Boolean> enabled = attributes.attribute(ENABLED); Attribute<Boolean> available = attributes.attribute(AVAILABLE); if (enabled.isModified() && available.isModified()) { if (enabled.get() && !available.get()) { throw CONFIG.statisticsEnabledNotAvailable(); } } } @Override public void validate(GlobalConfiguration globalConfig) { } @Override public StatisticsConfiguration create() { return new StatisticsConfiguration(attributes.protect()); } @Override public StatisticsConfigurationBuilder read(StatisticsConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); return this; } @Override public String toString() { return "StatisticsConfigurationBuilder [attributes=" + attributes + "]"; } }
2,899
28.896907
131
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/BackupConfiguration.java
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Attribute; import org.infinispan.configuration.parsing.Element; /** * @author Mircea.Markus@jboss.com * @since 5.2 */ public class BackupConfiguration extends ConfigurationElement<BackupConfiguration> { public static final AttributeDefinition<String> SITE = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.SITE, null, String.class).autoPersist(false).immutable().build(); public static final AttributeDefinition<BackupConfiguration.BackupStrategy> STRATEGY = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.STRATEGY, BackupConfiguration.BackupStrategy.ASYNC).immutable().build(); public static final AttributeDefinition<Long> REPLICATION_TIMEOUT = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.TIMEOUT, 15000L).build(); public static final AttributeDefinition<BackupFailurePolicy> FAILURE_POLICY = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.BACKUP_FAILURE_POLICY, BackupFailurePolicy.WARN).build(); public static final AttributeDefinition<String> FAILURE_POLICY_CLASS = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.FAILURE_POLICY_CLASS, null, String.class).immutable().build(); public static final AttributeDefinition<Boolean> USE_TWO_PHASE_COMMIT = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.USE_TWO_PHASE_COMMIT, false).immutable().build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(BackupConfiguration.class, Element.BACKUP.toString(), null, new AttributeDefinition[]{SITE, STRATEGY, REPLICATION_TIMEOUT, FAILURE_POLICY, FAILURE_POLICY_CLASS, USE_TWO_PHASE_COMMIT}, new AttributeSet.RemovedAttribute[]{new AttributeSet.RemovedAttribute(Attribute.ENABLED, 15, 0)}); } private final TakeOfflineConfiguration takeOfflineConfiguration; private final XSiteStateTransferConfiguration xSiteStateTransferConfiguration; public BackupConfiguration(AttributeSet attributes, TakeOfflineConfiguration takeOfflineConfiguration, XSiteStateTransferConfiguration xSiteStateTransferConfiguration) { super(Element.BACKUP, attributes, takeOfflineConfiguration, xSiteStateTransferConfiguration); this.takeOfflineConfiguration = takeOfflineConfiguration; this.xSiteStateTransferConfiguration = xSiteStateTransferConfiguration; } /** * Returns the name of the site where this cache backups its data. */ public String site() { return attributes.attribute(SITE).get(); } /** * How does the backup happen: sync or async. */ public BackupStrategy strategy() { return attributes.attribute(STRATEGY).get(); } public TakeOfflineConfiguration takeOffline() { return takeOfflineConfiguration; } /** * If the failure policy is set to {@link BackupFailurePolicy#CUSTOM} then the failurePolicyClass is required and * should return the fully qualified name of a class implementing {@link CustomFailurePolicy} */ public String failurePolicyClass() { return attributes.attribute(FAILURE_POLICY_CLASS).get(); } public boolean isAsyncBackup() { return strategy() == BackupStrategy.ASYNC; } public boolean isSyncBackup() { return strategy() == BackupStrategy.SYNC; } public long replicationTimeout() { return attributes.attribute(REPLICATION_TIMEOUT).get(); } /** * @deprecated Since 14.0. To be removed without replacement */ @Deprecated public BackupConfiguration replicationTimeout(long timeout) { return this; } public BackupFailurePolicy backupFailurePolicy() { return attributes.attribute(FAILURE_POLICY).get(); } public enum BackupStrategy { SYNC, ASYNC } public boolean isTwoPhaseCommit() { return attributes.attribute(USE_TWO_PHASE_COMMIT).get(); } /** * @see BackupConfigurationBuilder#enabled(boolean). * @deprecated Since 14.0. To be removed without replacement. */ @Deprecated public boolean enabled() { return true; } public XSiteStateTransferConfiguration stateTransfer() { return xSiteStateTransferConfiguration; } }
4,541
41.448598
237
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/StateTransferConfiguration.java
package org.infinispan.configuration.cache; import java.util.concurrent.TimeUnit; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Element; /** * Configures how state is retrieved when a new cache joins the cluster. * Used with distribution and replication clustered modes. * * @since 5.1 */ public class StateTransferConfiguration extends ConfigurationElement<StateTransferConfiguration> { public static final AttributeDefinition<Boolean> AWAIT_INITIAL_TRANSFER = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.AWAIT_INITIAL_TRANSFER, true).immutable().build(); public static final AttributeDefinition<Boolean> FETCH_IN_MEMORY_STATE = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.ENABLED, true).immutable().build(); public static final AttributeDefinition<Long> TIMEOUT = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.TIMEOUT, TimeUnit.MINUTES.toMillis(4)).immutable().build(); public static final AttributeDefinition<Integer> CHUNK_SIZE = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.CHUNK_SIZE, 512).immutable().build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(StateTransferConfiguration.class, FETCH_IN_MEMORY_STATE, TIMEOUT, CHUNK_SIZE, AWAIT_INITIAL_TRANSFER); } private final Attribute<Boolean> awaitInitialTransfer; private final Attribute<Boolean> fetchInMemoryState; private final Attribute<Long> timeout; private final Attribute<Integer> chunkSize; StateTransferConfiguration(AttributeSet attributes) { super(Element.STATE_TRANSFER, attributes); awaitInitialTransfer = attributes.attribute(AWAIT_INITIAL_TRANSFER); fetchInMemoryState = attributes.attribute(FETCH_IN_MEMORY_STATE); timeout = attributes.attribute(TIMEOUT); chunkSize = attributes.attribute(CHUNK_SIZE); } /** * If {@code true}, the cache will fetch data from the neighboring caches when it starts up, so * the cache starts 'warm', although it will impact startup time. * <p/> * In distributed mode, state is transferred between running caches as well, as the ownership of * keys changes (e.g. because a cache left the cluster). Disabling this setting means a key will * sometimes have less than {@code numOwner} owners. */ public boolean fetchInMemoryState() { return fetchInMemoryState.get(); } /** * This is the maximum amount of time - in milliseconds - to wait for state from neighboring * caches, before throwing an exception and aborting startup. */ public long timeout() { return timeout.get(); } /** * This is the maximum amount of time - in milliseconds - to wait for state from neighboring * caches, before throwing an exception and aborting startup. * * @deprecated Since 12.1, the attribute was never writable */ @Deprecated public StateTransferConfiguration timeout(long l) { timeout.set(l); return this; } /** * The state will be transferred in batches of {@code chunkSize} cache entries. * If chunkSize is equal to Integer.MAX_VALUE, the state will be transferred in all at once. Not recommended. */ public int chunkSize() { return chunkSize.get(); } /** * If {@code true}, this will cause the first call to method {@code CacheManager.getCache()} on the joiner node to * block and wait until the joining is complete and the cache has finished receiving state from neighboring caches * (if fetchInMemoryState is enabled). This option applies to distributed and replicated caches only and is enabled * by default. Please note that setting this to {@code false} will make the cache object available immediately but * any access to keys that should be available locally but are not yet transferred will actually cause a (transparent) * remote access. While this will not have any impact on the logic of your application it might impact performance. */ public boolean awaitInitialTransfer() { return awaitInitialTransfer.get(); } /** * We want to remember if the user didn't configure awaitInitialTransfer for the default cache. */ private boolean originalAwaitInitialTransfer() { return !awaitInitialTransfer.isModified(); } }
4,641
45.888889
202
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/package-info.java
/** * {@link org.infinispan.Cache} configuration * * @api.public */ package org.infinispan.configuration.cache;
116
15.714286
45
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/AsyncStoreConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.AsyncStoreConfiguration.ENABLED; import static org.infinispan.configuration.cache.AsyncStoreConfiguration.FAIL_SILENTLY; import static org.infinispan.configuration.cache.AsyncStoreConfiguration.MODIFICATION_QUEUE_SIZE; import static org.infinispan.configuration.cache.AsyncStoreConfiguration.THREAD_POOL_SIZE; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; /** * Configuration for the async cache store. If enabled, this configuration provides * asynchronous writes to the cache store or 'write-behind' caching. * * @author pmuir * */ public class AsyncStoreConfigurationBuilder<S> extends AbstractStoreConfigurationChildBuilder<S> implements Builder<AsyncStoreConfiguration> { private final AttributeSet attributes; AsyncStoreConfigurationBuilder(AbstractStoreConfigurationBuilder<? extends AbstractStoreConfiguration, ?> builder) { this(builder, AsyncStoreConfiguration.attributeDefinitionSet()); } AsyncStoreConfigurationBuilder(AbstractStoreConfigurationBuilder<? extends AbstractStoreConfiguration, ?> builder, AttributeSet attributeSet) { super(builder); this.attributes = attributeSet; } @Override public AttributeSet attributes() { return attributes; } /** * If true, all modifications to this cache store happen asynchronously on a separate thread. */ public AsyncStoreConfigurationBuilder<S> enable() { attributes.attribute(ENABLED).set(true); return this; } public AsyncStoreConfigurationBuilder<S> disable() { attributes.attribute(ENABLED).set(false); return this; } public AsyncStoreConfigurationBuilder<S> enabled(boolean enabled) { attributes.attribute(ENABLED).set(enabled); return this; } /** * Sets the size of the modification queue for the async store. If updates are made at a rate * that is faster than the underlying cache store can process this queue, then the async store * behaves like a synchronous store for that period, blocking until the queue can accept more * elements. */ public AsyncStoreConfigurationBuilder<S> modificationQueueSize(int i) { attributes.attribute(MODIFICATION_QUEUE_SIZE).set(i); return this; } /** * Configures the number of threads in the thread pool that is responsible for applying modifications. * @deprecated since 11.0 with no replacement as the thread pool is no longer used */ @Deprecated public AsyncStoreConfigurationBuilder<S> threadPoolSize(int i) { attributes.attribute(THREAD_POOL_SIZE).set(i); return this; } /** * @param failSilently If true, the async store attempts to perform write operations only * as many times as configured with `connection-attempts` in the PersistenceConfiguration. * If all attempts fail, the errors are ignored and the write operations are not executed * on the store. * If false, write operations that fail are attempted again when the underlying store * becomes available. If the modification queue becomes full before the underlying * store becomes available, an error is thrown on all future write operations to the store * until the modification queue is flushed. The modification queue is not persisted. If the * underlying store does not become available before the Async store is stopped, queued * modifications are lost. */ public AsyncStoreConfigurationBuilder<S> failSilently(boolean failSilently) { attributes.attribute(FAIL_SILENTLY).set(failSilently); return this; } @Override public void validate() { } @Override public void validate(GlobalConfiguration globalConfig) { } @Override public AsyncStoreConfiguration create() { return new AsyncStoreConfiguration(attributes.protect()); } @Override public AsyncStoreConfigurationBuilder<S> read(AsyncStoreConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); return this; } @Override public String toString() { return "AsyncStoreConfigurationBuilder [attributes=" + attributes + "]"; } }
4,520
36.991597
142
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/ClusteringConfigurationChildBuilder.java
package org.infinispan.configuration.cache; public interface ClusteringConfigurationChildBuilder extends ConfigurationChildBuilder { /** * Allows fine-tuning of rehashing characteristics. Must only used with 'distributed' cache mode. */ HashConfigurationBuilder hash(); /** * Configures the L1 cache behavior in 'distributed' caches instances. In any other cache modes, * this element is ignored. */ L1ConfigurationBuilder l1(); /** * Configures how state is transferred when a new cache joins the cluster. * Used with distribution and replication clustered modes. */ StateTransferConfigurationBuilder stateTransfer(); /** * Configures how the cache will react to cluster partitions. */ PartitionHandlingConfigurationBuilder partitionHandling(); }
817
29.296296
100
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/IndexStorage.java
package org.infinispan.configuration.cache; import java.util.Arrays; import org.infinispan.util.logging.Log; /** * @since 12.0 */ public enum IndexStorage { FILESYSTEM("filesystem"), LOCAL_HEAP("local-heap"); private final String token; IndexStorage(String token) { this.token = token; } public static IndexStorage requireValid(String token, Log logger) { return Arrays.stream(IndexStorage.values()) .filter(i -> i.token.equals(token)).findFirst().orElseThrow(logger::invalidIndexStorage); } @Override public String toString() { return token; } }
617
18.935484
101
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/SecurityConfigurationBuilder.java
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; /** * SecurityConfigurationBuilder. * * @author Tristan Tarrant * @since 7.0 */ public class SecurityConfigurationBuilder extends AbstractConfigurationChildBuilder implements SecurityConfigurationChildBuilder, Builder<SecurityConfiguration> { private final AuthorizationConfigurationBuilder authorizationBuilder; public SecurityConfigurationBuilder(ConfigurationBuilder builder) { super(builder); authorizationBuilder = new AuthorizationConfigurationBuilder(this); } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } @Override public void validate(GlobalConfiguration globalConfig) { authorizationBuilder.validate(globalConfig); } @Override public SecurityConfiguration create() { return new SecurityConfiguration(authorizationBuilder.create()); } @Override public SecurityConfigurationBuilder read(SecurityConfiguration template, Combine combine) { this.authorizationBuilder.read(template.authorization(), combine); return this; } @Override public AuthorizationConfigurationBuilder authorization() { return authorizationBuilder; } }
1,457
28.755102
162
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/ClusterLoaderConfiguration.java
package org.infinispan.configuration.cache; import java.util.concurrent.TimeUnit; import org.infinispan.commons.configuration.BuiltBy; import org.infinispan.commons.configuration.ConfigurationFor; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.parsing.Element; import org.infinispan.persistence.cluster.ClusterLoader; /** * ClusterLoaderConfiguration. * * @author Tristan Tarrant * @since 5.2 * @deprecated since 11.0. To be removed in 14.0 ISPN-11864 with no direct replacement. */ @BuiltBy(ClusterLoaderConfigurationBuilder.class) @ConfigurationFor(ClusterLoader.class) @Deprecated public class ClusterLoaderConfiguration extends AbstractStoreConfiguration<ClusterLoaderConfiguration> { static final AttributeDefinition<Long> REMOTE_CALL_TIMEOUT = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.REMOTE_TIMEOUT, TimeUnit.SECONDS.toMillis(15)).immutable().build(); public static AttributeSet attributeDefinitionSet() { return new AttributeSet(ClusterLoaderConfiguration.class, AbstractStoreConfiguration.attributeDefinitionSet(), REMOTE_CALL_TIMEOUT); } private final Attribute<Long> remoteCallTimeout; ClusterLoaderConfiguration(AttributeSet attributes, AsyncStoreConfiguration async) { super(Element.CLUSTER_LOADER, attributes, async); remoteCallTimeout = attributes.attribute(REMOTE_CALL_TIMEOUT); } public long remoteCallTimeout() { return remoteCallTimeout.get(); } }
1,663
38.619048
206
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/CustomInterceptorsConfigurationBuilder.java
package org.infinispan.configuration.cache; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; /** * Configures custom interceptors to be added to the cache. * * @author pmuir * @deprecated Since 10.0, custom interceptors support will be removed and only modules will be able to define interceptors */ @Deprecated public class CustomInterceptorsConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<CustomInterceptorsConfiguration> { private List<InterceptorConfigurationBuilder> interceptorBuilders = new LinkedList<>(); CustomInterceptorsConfigurationBuilder(ConfigurationBuilder builder) { super(builder); } @Override public AttributeSet attributes() { return AttributeSet.EMPTY; } /** * Adds a new custom interceptor definition, to be added to the cache when the cache is started. * @deprecated Since 10.0, custom interceptors support will be removed and only modules will be able to define interceptors */ @Deprecated public InterceptorConfigurationBuilder addInterceptor() { InterceptorConfigurationBuilder builder = new InterceptorConfigurationBuilder(this); this.interceptorBuilders.add(builder); return builder; } @Override public void validate() { for (InterceptorConfigurationBuilder builder : interceptorBuilders) builder.validate(); } @Override public void validate(GlobalConfiguration globalConfig) { for (InterceptorConfigurationBuilder builder : interceptorBuilders) builder.validate(globalConfig); } @Override public CustomInterceptorsConfiguration create() { if (interceptorBuilders.isEmpty()) { return new CustomInterceptorsConfiguration(); } else { List<InterceptorConfiguration> interceptors = new ArrayList<>(interceptorBuilders.size()); for (InterceptorConfigurationBuilder builder : interceptorBuilders) interceptors.add(builder.create()); return new CustomInterceptorsConfiguration(interceptors); } } @Override public CustomInterceptorsConfigurationBuilder read(CustomInterceptorsConfiguration template, Combine combine) { this.interceptorBuilders = new LinkedList<>(); for (InterceptorConfiguration c : template.interceptors()) { this.interceptorBuilders.add(new InterceptorConfigurationBuilder(this).read(c, combine)); } return this; } @Override public String toString() { return "CustomInterceptorsConfigurationBuilder{" + "interceptors=" + interceptorBuilders + '}'; } }
2,859
34.75
147
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/UnsafeConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.UnsafeConfiguration.UNRELIABLE_RETURN_VALUES; import java.util.Map; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; /** * Controls certain tuning parameters that may break some of Infinispan's public API contracts in exchange for better * performance in some cases. * <p /> * Use with care, only after thoroughly reading and understanding the documentation about a specific feature. * <p /> */ public class UnsafeConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<UnsafeConfiguration> { private final AttributeSet attributes; protected UnsafeConfigurationBuilder(ConfigurationBuilder builder) { super(builder); attributes = UnsafeConfiguration.attributeDefinitionSet(); } @Override public AttributeSet attributes() { return attributes; } /** * Specify whether Infinispan is allowed to disregard the {@link Map} contract when providing return values for * {@link org.infinispan.Cache#put(Object, Object)} and {@link org.infinispan.Cache#remove(Object)} methods. * <p /> * Providing return values can be expensive as they may entail a read from disk or across a network, and if the usage * of these methods never make use of these return values, allowing unreliable return values helps Infinispan * optimize away these remote calls or disk reads. * <p /> * @param allowUnreliableReturnValues if true, return values for the methods described above should not be relied on. */ public UnsafeConfigurationBuilder unreliableReturnValues(boolean allowUnreliableReturnValues) { attributes.attribute(UNRELIABLE_RETURN_VALUES).set(allowUnreliableReturnValues); return this; } @Override public void validate() { // Nothing to validate } @Override public void validate(GlobalConfiguration globalConfig) { } @Override public UnsafeConfiguration create() { return new UnsafeConfiguration(attributes.protect()); } @Override public UnsafeConfigurationBuilder read(UnsafeConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); return this; } @Override public String toString() { return this.getClass().getSimpleName() + attributes; } }
2,561
34.09589
123
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/IndexWriterConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.IndexWriterConfiguration.INDEX_COMMIT_INTERVAL; import static org.infinispan.configuration.cache.IndexWriterConfiguration.INDEX_LOW_LEVEL_TRACE; import static org.infinispan.configuration.cache.IndexWriterConfiguration.INDEX_MAX_BUFFERED_ENTRIES; import static org.infinispan.configuration.cache.IndexWriterConfiguration.INDEX_QUEUE_COUNT; import static org.infinispan.configuration.cache.IndexWriterConfiguration.INDEX_QUEUE_SIZE; import static org.infinispan.configuration.cache.IndexWriterConfiguration.INDEX_RAM_BUFFER_SIZE; import static org.infinispan.configuration.cache.IndexWriterConfiguration.INDEX_THREAD_POOL_SIZE; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; /** * @since 12.0 */ public class IndexWriterConfigurationBuilder extends AbstractIndexingConfigurationChildBuilder implements Builder<IndexWriterConfiguration> { private final AttributeSet attributes; private final IndexMergeConfigurationBuilder indexMergeConfigurationBuilder; IndexWriterConfigurationBuilder(IndexingConfigurationBuilder builder) { super(builder); this.attributes = IndexWriterConfiguration.attributeDefinitionSet(); this.indexMergeConfigurationBuilder = new IndexMergeConfigurationBuilder(builder); } @Override public AttributeSet attributes() { return attributes; } public IndexMergeConfigurationBuilder merge() { return indexMergeConfigurationBuilder; } public IndexWriterConfigurationBuilder threadPoolSize(int value) { attributes.attribute(INDEX_THREAD_POOL_SIZE).set(value); return this; } public IndexWriterConfigurationBuilder queueCount(int value) { attributes.attribute(INDEX_QUEUE_COUNT).set(value); return this; } public IndexWriterConfigurationBuilder queueSize(int value) { attributes.attribute(INDEX_QUEUE_SIZE).set(value); return this; } public IndexWriterConfigurationBuilder commitInterval(int value) { attributes.attribute(INDEX_COMMIT_INTERVAL).set(value); return this; } public IndexWriterConfigurationBuilder ramBufferSize(int value) { attributes.attribute(INDEX_RAM_BUFFER_SIZE).set(value); return this; } public IndexWriterConfigurationBuilder maxBufferedEntries(int value) { attributes.attribute(INDEX_MAX_BUFFERED_ENTRIES).set(value); return this; } public IndexWriterConfigurationBuilder setLowLevelTrace(boolean value) { attributes.attribute(INDEX_LOW_LEVEL_TRACE).set(value); return this; } @Override public IndexWriterConfiguration create() { return new IndexWriterConfiguration(attributes.protect(), indexMergeConfigurationBuilder.create()); } @Override public IndexWriterConfigurationBuilder read(IndexWriterConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); this.indexMergeConfigurationBuilder.read(template.merge(), combine); return this; } @Override public String toString() { return "IndexWriterConfigurationBuilder{" + "attributes=" + attributes + ", indexMergeConfigurationBuilder=" + indexMergeConfigurationBuilder + '}'; } }
3,426
35.457447
105
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/JMXStatisticsConfiguration.java
package org.infinispan.configuration.cache; /** * Determines whether cache statistics are gathered. * * @author pmuir * @deprecated since 10.1.3. Use {@link StatisticsConfiguration} instead. This will be removed in next major version. */ @Deprecated public interface JMXStatisticsConfiguration { boolean enabled(); /** * If set to false, statistics gathering cannot be enabled during runtime. Performance optimization. * * @deprecated since 10.1.3. This method will be removed in a future version. */ @Deprecated boolean available(); }
572
25.045455
117
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/AbstractTransportConfigurationChildBuilder.java
package org.infinispan.configuration.cache; public abstract class AbstractTransportConfigurationChildBuilder extends AbstractConfigurationChildBuilder implements TransactionConfigurationChildBuilder { private final TransactionConfigurationBuilder transactionConfigurationBuilder; protected AbstractTransportConfigurationChildBuilder(TransactionConfigurationBuilder builder) { super(builder.getBuilder()); this.transactionConfigurationBuilder = builder; } @Override public RecoveryConfigurationBuilder recovery() { return transactionConfigurationBuilder.recovery(); } }
610
32.944444
156
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/AsyncStoreConfiguration.java
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Element; /** * Configuration for the async cache store. If enabled, this provides you with asynchronous writes * to the cache store, giving you 'write-behind' caching. * * @author pmuir * */ public class AsyncStoreConfiguration extends ConfigurationElement<AsyncStoreConfiguration> { public static final AttributeDefinition<Boolean> ENABLED = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.ENABLED, false).immutable().build(); public static final AttributeDefinition<Integer> MODIFICATION_QUEUE_SIZE = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.MODIFICATION_QUEUE_SIZE, 1024).immutable().build(); @Deprecated public static final AttributeDefinition<Integer> THREAD_POOL_SIZE = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.THREAD_POOL_SIZE, 1).immutable().build(); public static final AttributeDefinition<Boolean> FAIL_SILENTLY = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.FAIL_SILENTLY, false).immutable().build(); public static AttributeSet attributeDefinitionSet() { return new AttributeSet(AsyncStoreConfiguration.class, ENABLED, MODIFICATION_QUEUE_SIZE, THREAD_POOL_SIZE, FAIL_SILENTLY); } private final Attribute<Boolean> failSilently; public AsyncStoreConfiguration(AttributeSet attributes) { super(Element.WRITE_BEHIND, attributes); this.failSilently = attributes.attribute(FAIL_SILENTLY); } /** * If true, all modifications to this cache store happen asynchronously, on a separate thread. */ public boolean enabled() { return attributes.attribute(ENABLED).get(); } /** * Sets the size of the modification queue for the async store. If updates are made at a rate * that is faster than the underlying cache store can process this queue, then the async store * behaves like a synchronous store for that period, blocking until the queue can accept more * elements. */ public int modificationQueueSize() { return attributes.attribute(MODIFICATION_QUEUE_SIZE).get(); } /** * Size of the thread pool whose threads are responsible for applying the modifications. * @deprecated since 11.0 with no replacement as the thread pool is no longer used */ @Deprecated public int threadPoolSize() { return attributes.attribute(THREAD_POOL_SIZE).get(); } public boolean failSilently() { return failSilently.get(); } }
2,870
43.859375
205
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/L1Configuration.java
package org.infinispan.configuration.cache; import java.util.concurrent.TimeUnit; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Element; /** * Configures the L1 cache behavior in 'distributed' caches instances. In any other cache modes, this element is * ignored. */ public class L1Configuration extends ConfigurationElement<L1Configuration> { public static final AttributeDefinition<Boolean> ENABLED = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.ENABLED, false).immutable().autoPersist(false).build(); public static final AttributeDefinition<Integer> INVALIDATION_THRESHOLD = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.INVALIDATION_THRESHOLD, 0).immutable().autoPersist(false).build(); public static final AttributeDefinition<Long> LIFESPAN = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.L1_LIFESPAN, TimeUnit.MINUTES.toMillis(10)).immutable().build(); public static final AttributeDefinition<Long> CLEANUP_TASK_FREQUENCY = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.INVALIDATION_CLEANUP_TASK_FREQUENCY, TimeUnit.MINUTES.toMillis(1)).immutable().build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(L1Configuration.class, ENABLED, INVALIDATION_THRESHOLD, LIFESPAN, CLEANUP_TASK_FREQUENCY); } private final Attribute<Boolean> enabled; private final Attribute<Integer> invalidationThreshold; private final Attribute<Long> lifespan; private final Attribute<Long> cleanupTaskFrequency; L1Configuration(AttributeSet attributes) { super(Element.L1, attributes); enabled = attributes.attribute(ENABLED); invalidationThreshold = attributes.attribute(INVALIDATION_THRESHOLD); lifespan = attributes.attribute(LIFESPAN); cleanupTaskFrequency = attributes.attribute(CLEANUP_TASK_FREQUENCY); } public boolean enabled() { return enabled.get(); } /** * <p> * Determines whether a multicast or a web of unicasts are used when performing L1 invalidations. * </p> * * <p> * By default multicast will be used. * </p> * * <p> * If the threshold is set to -1, then unicasts will always be used. If the threshold is set to 0, then multicast * will be always be used. * </p> */ public int invalidationThreshold() { return invalidationThreshold.get(); } /** * Determines how often a cleanup thread runs to clean up an internal log of requestors for a specific key */ public long cleanupTaskFrequency() { return cleanupTaskFrequency.get(); } /** * Maximum lifespan of an entry placed in the L1 cache. Default 10 minutes. */ public long lifespan() { return lifespan.get(); } }
3,103
39.311688
236
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/CustomStoreConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.CustomStoreConfiguration.CUSTOM_STORE_CLASS; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; /** * StoreConfigurationBuilder used for stores/loaders that don't have a configuration builder * * @author wburns * @since 7.0 */ public class CustomStoreConfigurationBuilder extends AbstractStoreConfigurationBuilder<CustomStoreConfiguration, CustomStoreConfigurationBuilder> { public CustomStoreConfigurationBuilder(PersistenceConfigurationBuilder builder) { super(builder, CustomStoreConfiguration.attributeDefinitionSet()); } @Override public CustomStoreConfiguration create() { return new CustomStoreConfiguration(attributes.protect(), async.create()); } public CustomStoreConfigurationBuilder customStoreClass(Class<?> customStoreClass) { attributes.attribute(CUSTOM_STORE_CLASS).set(customStoreClass); return this; } @Override public Builder<?> read(CustomStoreConfiguration template, Combine combine) { super.read(template, combine); return this; } @Override public CustomStoreConfigurationBuilder self() { return this; } }
1,277
28.72093
100
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/EncodingConfiguration.java
package org.infinispan.configuration.cache; import java.util.Objects; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.parsing.Attribute; import org.infinispan.configuration.parsing.Element; /** * Controls encoding configuration for keys and values in the cache. * * @since 9.2 */ public final class EncodingConfiguration extends ConfigurationElement<EncodingConfiguration> { static final AttributeDefinition<MediaType> MEDIA_TYPE = AttributeDefinition.builder(Attribute.MEDIA_TYPE, null, MediaType.class).immutable().build(); private final ContentTypeConfiguration keyDataType, valueDataType; static AttributeSet attributeDefinitionSet() { return new AttributeSet(EncodingConfiguration.class, MEDIA_TYPE); } public EncodingConfiguration(AttributeSet attributes, ContentTypeConfiguration keyDataType, ContentTypeConfiguration valueDataType) { super(Element.ENCODING, attributes, keyDataType, valueDataType); this.keyDataType = keyDataType; this.valueDataType = valueDataType; } public ContentTypeConfiguration keyDataType() { return keyDataType; } public ContentTypeConfiguration valueDataType() { return valueDataType; } @Override public boolean matches(EncodingConfiguration other) { return Objects.equals(this.keyDataType.mediaType(), other.keyDataType.mediaType()) && Objects.equals(this.valueDataType.mediaType(), other.valueDataType.mediaType()); } }
1,727
37.4
153
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/ClusterLoaderConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.ClusterLoaderConfiguration.REMOTE_CALL_TIMEOUT; import java.util.concurrent.TimeUnit; import org.infinispan.commons.configuration.Combine; /** * @deprecated since 11.0. To be removed in 14.0 ISPN-11864 with no direct replacement. */ @Deprecated public class ClusterLoaderConfigurationBuilder extends AbstractStoreConfigurationBuilder<ClusterLoaderConfiguration, ClusterLoaderConfigurationBuilder> { public ClusterLoaderConfigurationBuilder(PersistenceConfigurationBuilder builder) { super(builder, ClusterLoaderConfiguration.attributeDefinitionSet()); } @Override public ClusterLoaderConfigurationBuilder self() { return this; } public ClusterLoaderConfigurationBuilder remoteCallTimeout(long remoteCallTimeout) { attributes.attribute(REMOTE_CALL_TIMEOUT).set(remoteCallTimeout); return this; } public ClusterLoaderConfigurationBuilder remoteCallTimeout(long remoteCallTimeout, TimeUnit unit) { remoteCallTimeout(unit.toMillis(remoteCallTimeout)); return this; } @Override public ClusterLoaderConfiguration create() { return new ClusterLoaderConfiguration(attributes.protect(), async.create()); } @Override public ClusterLoaderConfigurationBuilder read(ClusterLoaderConfiguration template, Combine combine) { super.read(template, combine); return this; } }
1,461
31.488889
153
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/VersioningScheme.java
package org.infinispan.configuration.cache; /** * The various versioning schemes supported * * @author Manik Surtani * @since 5.1 */ public enum VersioningScheme { SIMPLE, NONE }
188
14.75
43
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/InterceptorConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.commons.configuration.AbstractTypedPropertiesConfiguration.PROPERTIES; import static org.infinispan.configuration.cache.InterceptorConfiguration.AFTER; import static org.infinispan.configuration.cache.InterceptorConfiguration.BEFORE; import static org.infinispan.configuration.cache.InterceptorConfiguration.INDEX; import static org.infinispan.configuration.cache.InterceptorConfiguration.INTERCEPTOR; import static org.infinispan.configuration.cache.InterceptorConfiguration.INTERCEPTOR_CLASS; import static org.infinispan.configuration.cache.InterceptorConfiguration.POSITION; import static org.infinispan.util.logging.Log.CONFIG; import java.util.Properties; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.util.TypedProperties; import org.infinispan.configuration.cache.InterceptorConfiguration.Position; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.interceptors.AsyncInterceptor; import org.infinispan.interceptors.BaseCustomAsyncInterceptor; /** * This builder defines details of a specific custom interceptor. * * @deprecated Since 10.0, custom interceptors support will be removed and only modules will be able to define interceptors */ @Deprecated public class InterceptorConfigurationBuilder extends AbstractCustomInterceptorsConfigurationChildBuilder implements Builder<InterceptorConfiguration> { private final AttributeSet attributes; InterceptorConfigurationBuilder(CustomInterceptorsConfigurationBuilder builder) { super(builder); attributes = InterceptorConfiguration.attributeDefinitionSet(); } @Override public AttributeSet attributes() { return attributes; } /** * Dictates that the custom interceptor appears immediately <i>after</i> the specified interceptor. If the specified * interceptor is not found in the interceptor chain, a {@link CacheConfigurationException} will be thrown when the * cache starts. * * @param after the class of the interceptor to look for */ public InterceptorConfigurationBuilder after(Class<? extends AsyncInterceptor> after) { attributes.attribute(AFTER).set(after); return this; } /** * Dictates that the custom interceptor appears immediately <i>before</i> the specified interceptor. If the specified * interceptor is not found in the interceptor chain, a {@link CacheConfigurationException} will be thrown when the * cache starts. * * @param before the class of the interceptor to look for */ public InterceptorConfigurationBuilder before(Class<? extends AsyncInterceptor> before) { attributes.attribute(BEFORE).set(before); return this; } /** * Class of the new custom interceptor to add to the configuration. * @param interceptorClass an instance of {@link AsyncInterceptor} */ public InterceptorConfigurationBuilder interceptorClass(Class<? extends AsyncInterceptor> interceptorClass) { attributes.attribute(INTERCEPTOR_CLASS).set(interceptorClass); return this; } /** * An instance of the new custom interceptor to add to the configuration. * Warning: if you use this configuration for multiple caches, the interceptor instance will * be shared, which will corrupt interceptor stack. Use {@link #interceptorClass} instead. * * @param interceptor an instance of {@link AsyncInterceptor} */ public InterceptorConfigurationBuilder interceptor(AsyncInterceptor interceptor) { attributes.attribute(INTERCEPTOR).set(interceptor); return this; } /** * Specifies a position in the interceptor chain to place the new interceptor. The index starts at 0 and goes up to * the number of interceptors in a given configuration. An {@link IllegalArgumentException} is thrown if the index is * less than 0 or greater than the maximum number of interceptors in the chain. * * @param i positional index in the interceptor chain to place the new interceptor. */ public InterceptorConfigurationBuilder index(int i) { if (i < 0) throw new IllegalArgumentException("Index cannot be negative"); attributes.attribute(INDEX).set(i); return this; } /** * Specifies a position, denoted by the {@link Position} enumeration, where to place the new interceptor. * * @param p position to place the new interceptor */ public InterceptorConfigurationBuilder position(Position p) { attributes.attribute(POSITION).set(p); return this; } /** * Sets interceptor properties * * @return this InterceptorConfigurationBuilder */ public InterceptorConfigurationBuilder withProperties(Properties properties) { attributes.attribute(PROPERTIES).set(TypedProperties.toTypedProperties(properties)); return this; } /** * Clears the interceptor properties * * @return this InterceptorConfigurationBuilder */ public InterceptorConfigurationBuilder clearProperties() { TypedProperties properties = attributes.attribute(PROPERTIES).get(); properties.clear(); attributes.attribute(PROPERTIES).set(TypedProperties.toTypedProperties(properties)); return this; } public InterceptorConfigurationBuilder addProperty(String key, String value) { TypedProperties properties = attributes.attribute(PROPERTIES).get(); properties.put(key, value); attributes.attribute(PROPERTIES).set(TypedProperties.toTypedProperties(properties)); return this; } public InterceptorConfigurationBuilder removeProperty(String key) { TypedProperties properties = attributes.attribute(PROPERTIES).get(); properties.remove(key); attributes.attribute(PROPERTIES).set(TypedProperties.toTypedProperties(properties)); return this; } @Override public void validate() { Attribute<Class> interceptorClassAttribute = attributes.attribute(INTERCEPTOR_CLASS); Attribute<AsyncInterceptor> interceptorAttribute = attributes.attribute(INTERCEPTOR); if (!interceptorClassAttribute.isNull() && !interceptorAttribute.isNull()) { throw CONFIG.interceptorClassAndInstanceDefined(interceptorClassAttribute.get().getName(), interceptorAttribute.get().toString()); } else if (interceptorClassAttribute.isNull() && interceptorAttribute.isNull()) { throw CONFIG.customInterceptorMissingClass(); } Class<? extends AsyncInterceptor> interceptorClass = interceptorClassAttribute.get(); if (interceptorClass == null) { interceptorClass = interceptorAttribute.get().getClass(); } if (!BaseCustomAsyncInterceptor.class.isAssignableFrom(interceptorClass)) { final String className = interceptorClass.getName(); //Suppress noisy warnings if the interceptor is one of our own (like one of those from Query): if (! className.startsWith("org.infinispan.")) { CONFIG.suggestCustomInterceptorInheritance(className); } } // Make sure more than one 'position' isn't picked. int positions = 0; if (!attributes.attribute(BEFORE).isNull()) positions++; if (!attributes.attribute(AFTER).isNull()) positions++; if (attributes.attribute(INDEX).get() > -1) positions++; if (attributes.attribute(POSITION).isModified()) positions++; switch (positions) { case 0: throw CONFIG.missingCustomInterceptorPosition(interceptorClass.getName()); case 1: break; default: throw CONFIG.multipleCustomInterceptorPositions(interceptorClass.getName()); } } @Override public void validate(GlobalConfiguration globalConfig) { } @Override public InterceptorConfiguration create() { return new InterceptorConfiguration(attributes.protect()); } @Override public InterceptorConfigurationBuilder read(InterceptorConfiguration template, Combine combine) { attributes.read(template.attributes(), combine); return this; } @Override public String toString() { return "InterceptorConfigurationBuilder [attributes=" + attributes + "]"; } }
8,520
39.57619
151
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/IndexShardingConfiguration.java
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Element; public class IndexShardingConfiguration extends ConfigurationElement<IndexShardingConfiguration> { public static final AttributeDefinition<Integer> SHARDS = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.SHARDS, 1, Integer.class).immutable().build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(IndexShardingConfiguration.class, SHARDS); } private final Attribute<Integer> shards; IndexShardingConfiguration(AttributeSet attributes) { super(Element.INDEX_SHARDING, attributes); this.shards = attributes.attribute(SHARDS); } public Integer getShards() { return shards.get(); } }
1,082
36.344828
130
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/ConfigurationChildBuilder.java
package org.infinispan.configuration.cache; import org.infinispan.configuration.global.GlobalConfiguration; public interface ConfigurationChildBuilder { ConfigurationChildBuilder simpleCache(boolean simpleCache); boolean simpleCache(); ClusteringConfigurationBuilder clustering(); /** * @deprecated Since 10.0, custom interceptors support will be removed and only modules will be able to define interceptors */ @Deprecated CustomInterceptorsConfigurationBuilder customInterceptors(); EncodingConfigurationBuilder encoding(); ExpirationConfigurationBuilder expiration(); QueryConfigurationBuilder query(); IndexingConfigurationBuilder indexing(); InvocationBatchingConfigurationBuilder invocationBatching(); StatisticsConfigurationBuilder statistics(); /** * @deprecated since 10.1.3 use {@link #statistics} instead. This will be removed in next major version. */ @Deprecated default JMXStatisticsConfigurationBuilder jmxStatistics() { return statistics(); } PersistenceConfigurationBuilder persistence(); LockingConfigurationBuilder locking(); SecurityConfigurationBuilder security(); TransactionConfigurationBuilder transaction(); UnsafeConfigurationBuilder unsafe(); SitesConfigurationBuilder sites(); MemoryConfigurationBuilder memory(); default ConfigurationChildBuilder template(boolean template) { return this; } default void validate(GlobalConfiguration globalConfig) {} Configuration build(); }
1,535
24.180328
126
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/GroupsConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.GroupsConfiguration.ENABLED; import static org.infinispan.configuration.cache.GroupsConfiguration.GROUPERS; import java.util.List; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.distribution.group.Group; import org.infinispan.distribution.group.Grouper; /** * Configuration for various grouper definitions. See the user guide for more information. * * @author pmuir * */ public class GroupsConfigurationBuilder extends AbstractClusteringConfigurationChildBuilder implements Builder<GroupsConfiguration> { private final AttributeSet attributes; protected GroupsConfigurationBuilder(ClusteringConfigurationBuilder builder) { super(builder); attributes = GroupsConfiguration.attributeDefinitionSet(); } @Override public AttributeSet attributes() { return attributes; } public boolean isEnabled() { return attributes.attribute(ENABLED).get(); } /** * Enable grouping support so that {@link Group} annotations are honored and any configured * groupers will be invoked */ public GroupsConfigurationBuilder enabled() { attributes.attribute(ENABLED).set(true); return this; } /** * Enable grouping support so that {@link Group} annotations are honored and any configured * groupers will be invoked */ public GroupsConfigurationBuilder enabled(boolean enabled) { attributes.attribute(ENABLED).set(enabled); return this; } /** * Disable grouping support so that {@link Group} annotations are not used and any configured * groupers will not be be invoked */ public GroupsConfigurationBuilder disabled() { attributes.attribute(ENABLED).set(false); return this; } /** * Set the groupers to use */ public GroupsConfigurationBuilder withGroupers(List<Grouper<?>> groupers) { attributes.attribute(GROUPERS).set(groupers); return this; } /** * Clear the groupers */ public GroupsConfigurationBuilder clearGroupers() { List<Grouper<?>> groupers = attributes.attribute(GROUPERS).get(); groupers.clear(); attributes.attribute(GROUPERS).set(groupers); return this; } /** * Add a grouper */ public GroupsConfigurationBuilder addGrouper(Grouper<?> grouper) { List<Grouper<?>> groupers = attributes.attribute(GROUPERS).get(); groupers.add(grouper); attributes.attribute(GROUPERS).set(groupers); return this; } @Override public GroupsConfiguration create() { return new GroupsConfiguration(attributes.protect()); } @Override public GroupsConfigurationBuilder read(GroupsConfiguration template, Combine combine) { attributes.read(template.attributes(), combine); return this; } @Override public String toString() { return "GroupsConfigurationBuilder [attributes=" + attributes + "]"; } }
3,135
28.037037
133
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/MemoryStorageConfigurationBuilder.java
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; /** * @since 10.0 * @deprecated since 11.0, use {@link MemoryConfigurationBuilder} instead. */ @Deprecated public class MemoryStorageConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<MemoryStorageConfiguration> { AttributeSet attributes; MemoryStorageConfigurationBuilder(ConfigurationBuilder builder) { super(builder); attributes = MemoryStorageConfiguration.attributeDefinitionSet(); } @Override public AttributeSet attributes() { return attributes; } @Override public MemoryStorageConfiguration create() { return new MemoryStorageConfiguration(attributes.protect()); } @Override public MemoryStorageConfigurationBuilder read(MemoryStorageConfiguration template, Combine combine) { return this; } @Override public String toString() { return "MemoryStorageConfigurationBuilder [attributes=" + attributes + "]"; } }
1,158
27.975
137
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/AbstractSecurityConfigurationChildBuilder.java
package org.infinispan.configuration.cache; abstract class AbstractSecurityConfigurationChildBuilder extends AbstractConfigurationChildBuilder implements SecurityConfigurationChildBuilder { private final SecurityConfigurationBuilder securityBuilder; protected AbstractSecurityConfigurationChildBuilder(SecurityConfigurationBuilder builder) { super(builder.getBuilder()); this.securityBuilder = builder; } protected SecurityConfigurationBuilder getSecurityBuilder() { return securityBuilder; } @Override public AuthorizationConfigurationBuilder authorization() { return securityBuilder.authorization(); } }
660
29.045455
145
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/IndexingConfigurationChildBuilder.java
package org.infinispan.configuration.cache; /** * @since 12.0 */ public interface IndexingConfigurationChildBuilder extends ConfigurationChildBuilder { IndexReaderConfigurationBuilder reader(); IndexWriterConfigurationBuilder writer(); IndexShardingConfigurationBuilder sharding(); IndexingConfigurationBuilder addKeyTransformer(Class<?> keyClass, Class<?> keyTransformerClass); IndexingConfigurationBuilder addIndexedEntity(String indexedEntity); IndexingConfigurationBuilder addIndexedEntities(String... indexedEntities); IndexingConfigurationBuilder addIndexedEntity(Class<?> indexedEntity); IndexingConfigurationBuilder addIndexedEntities(Class<?>... indexedEntities); IndexingConfigurationBuilder disable(); IndexingConfigurationBuilder enable(); IndexingConfigurationBuilder path(String path); IndexingConfigurationBuilder storage(IndexStorage storage); IndexingConfigurationBuilder startupMode(IndexStartupMode startupMode); IndexingConfigurationBuilder indexingMode(IndexingMode indexingMode); }
1,064
27.783784
99
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/PersistenceConfiguration.java
package org.infinispan.configuration.cache; import java.util.List; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Attribute; import org.infinispan.configuration.parsing.Element; /** * Configuration for stores. */ public class PersistenceConfiguration extends ConfigurationElement<PersistenceConfiguration> { public static final AttributeDefinition<Boolean> PASSIVATION = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.PASSIVATION, false).immutable().build(); public static final AttributeDefinition<Integer> AVAILABILITY_INTERVAL = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.AVAILABILITY_INTERVAL, 1000).immutable().build(); public static final AttributeDefinition<Integer> CONNECTION_ATTEMPTS = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.CONNECTION_ATTEMPTS, 10).build(); @Deprecated public static final AttributeDefinition<Integer> CONNECTION_INTERVAL = AttributeDefinition.builder(Attribute.CONNECTION_INTERVAL, 50).immutable().deprecatedSince(15, 0).build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(PersistenceConfiguration.class, PASSIVATION, AVAILABILITY_INTERVAL, CONNECTION_ATTEMPTS, CONNECTION_INTERVAL); } private final List<StoreConfiguration> stores; PersistenceConfiguration(AttributeSet attributes, List<StoreConfiguration> stores) { super(Element.PERSISTENCE, attributes, asChildren(stores)); this.stores = stores; } private static ConfigurationElement<?>[] asChildren(List<StoreConfiguration> stores) { return stores.stream().filter(store -> store instanceof ConfigurationElement).toArray(ConfigurationElement[]::new); } /** * If true, data is only written to the cache store when it is evicted from memory, a phenomenon known as * 'passivation'. Next time the data is requested, it will be 'activated' which means that data will be brought back * to memory and removed from the persistent store. This gives you the ability to 'overflow' to disk, similar to * swapping in an operating system. <br /> <br /> If false, the cache store contains a copy of the contents in * memory, so writes to cache result in cache store writes. This essentially gives you a 'write-through' * configuration. */ public boolean passivation() { return attributes.attribute(PASSIVATION).get(); } public int availabilityInterval() { return attributes.attribute(AVAILABILITY_INTERVAL).get(); } public int connectionAttempts() { return attributes.attribute(CONNECTION_ATTEMPTS).get(); } @Deprecated public int connectionInterval() { return -1; } public List<StoreConfiguration> stores() { return stores; } /** * Loops through all individual cache loader configs and checks if fetchPersistentState is set on any of them * * @deprecated since 14.0. This will always return false */ @Deprecated public Boolean fetchPersistentState() { return false; } /** * Loops through all individual cache loader configs and checks if preload is set on any of them */ public Boolean preload() { for (StoreConfiguration c : stores) { if (c.preload()) return true; } return false; } public boolean usingStores() { return !stores.isEmpty(); } public boolean usingAsyncStore() { for (StoreConfiguration c : stores) { if (c.async().enabled()) return true; } return false; } /** * Returns if any store is {@link StoreConfiguration#segmented()} * * @return true if any configured store is segmented, otherwise false */ public boolean usingSegmentedStore() { for (StoreConfiguration c : stores) { if (c.segmented()) return true; } return false; } }
4,141
35.982143
200
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/SingleFileStoreConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.AbstractStoreConfiguration.SEGMENTED; import static org.infinispan.configuration.cache.SingleFileStoreConfiguration.FRAGMENTATION_FACTOR; import static org.infinispan.configuration.cache.SingleFileStoreConfiguration.LOCATION; import static org.infinispan.configuration.cache.SingleFileStoreConfiguration.MAX_ENTRIES; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.persistence.PersistenceUtil; import org.infinispan.persistence.file.SingleFileStore; import org.infinispan.util.logging.Log; /** * Single file cache store configuration builder. * * @author Galder Zamarreño * @since 6.0 */ public class SingleFileStoreConfigurationBuilder extends AbstractStoreConfigurationBuilder<SingleFileStoreConfiguration, SingleFileStoreConfigurationBuilder> { public SingleFileStoreConfigurationBuilder(PersistenceConfigurationBuilder builder) { this(builder, SingleFileStoreConfiguration.attributeDefinitionSet()); } public SingleFileStoreConfigurationBuilder(PersistenceConfigurationBuilder builder, AttributeSet attributeSet) { super(builder, attributeSet); } @Override public SingleFileStoreConfigurationBuilder self() { return this; } /** * Sets a location on disk where the store can write. */ public SingleFileStoreConfigurationBuilder location(String location) { attributes.attribute(LOCATION).set(location); return this; } /** * In order to speed up lookups, the single file cache store keeps an index * of keys and their corresponding position in the file. To avoid this * index resulting in memory consumption problems, this cache store can * bounded by a maximum number of entries that it stores. If this limit is * exceeded, entries are removed permanently using the LRU algorithm both * from the in-memory index and the underlying file based cache store. * * So, setting a maximum limit only makes sense when Infinispan is used as * a cache, whose contents can be recomputed or they can be retrieved from * the authoritative data store. * * If this maximum limit is set when the Infinispan is used as an * authoritative data store, it could lead to data loss, and hence it's * not recommended for this use case. * * @deprecated Since 13.0, will be removed in 16.0 */ @Deprecated public SingleFileStoreConfigurationBuilder maxEntries(int maxEntries) { attributes.attribute(MAX_ENTRIES).set(maxEntries); return this; } /** * The store tries to fit in a new entry into an existing entry from a free entry pool (if one is available) * However, this existing free entry may be quite bigger than what is required to contain the new entry * It may then make sense to split the free entry into two parts: * 1. That is required to contain the new entry requested * 2. the remaining part to be returned to the pool of free entries. * The fragmentationFactor decides when to split the free entry. * So, if this value is set as 0.75, then the free entry will be split if the new entry is equal to or less than 0.75 times the size of free entry */ public SingleFileStoreConfigurationBuilder fragmentationFactor(float fragmentationFactor) { attributes.attribute(FRAGMENTATION_FACTOR).set(fragmentationFactor); return this; } @Override public void validate() { Attribute<Boolean> segmentedAttribute = attributes.attribute(SEGMENTED); Attribute<Integer> maxEntriesAttribute = attributes.attribute(MAX_ENTRIES); if (segmentedAttribute.get() && maxEntriesAttribute.get() > 0) { throw Log.CONFIG.segmentedSingleFileStoreDoesNotSupportMaxEntries(); } super.validate(); } @Override public void validate(GlobalConfiguration globalConfig) { PersistenceUtil.validateGlobalStateStoreLocation(globalConfig, SingleFileStore.class.getSimpleName(), attributes.attribute(LOCATION)); super.validate(globalConfig); } @Override public SingleFileStoreConfiguration create() { return new SingleFileStoreConfiguration(attributes.protect(), async.create()); } @Override public Builder<?> read(SingleFileStoreConfiguration template, Combine combine) { super.read(template, combine); return this; } }
4,679
40.415929
149
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/TransactionConfiguration.java
package org.infinispan.configuration.cache; import static org.infinispan.commons.configuration.attributes.IdentityAttributeCopier.identityCopier; import java.util.concurrent.TimeUnit; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSerializer; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; import org.infinispan.configuration.parsing.Element; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.TransactionMode; import org.infinispan.transaction.lookup.GenericTransactionManagerLookup; import org.infinispan.transaction.lookup.TransactionSynchronizationRegistryLookup; /** * Defines transactional (JTA) characteristics of the cache. * * @author pmuir * @author Pedro Ruivo */ public class TransactionConfiguration extends ConfigurationElement<TransactionConfiguration> { public static final AttributeDefinition<Boolean> AUTO_COMMIT = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.AUTO_COMMIT, true).immutable().build(); public static final AttributeDefinition<Long> CACHE_STOP_TIMEOUT = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.STOP_TIMEOUT, TimeUnit.SECONDS.toMillis(30)).build(); public static final AttributeDefinition<LockingMode> LOCKING_MODE = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.LOCKING, LockingMode.OPTIMISTIC) .immutable().build(); public static final AttributeDefinition<TransactionManagerLookup> TRANSACTION_MANAGER_LOOKUP = AttributeDefinition.<TransactionManagerLookup>builder(org.infinispan.configuration.parsing.Attribute.TRANSACTION_MANAGER_LOOKUP_CLASS, GenericTransactionManagerLookup.INSTANCE) .serializer(AttributeSerializer.INSTANCE_CLASS_NAME) .autoPersist(false).global(false).immutable().build(); public static final AttributeDefinition<TransactionSynchronizationRegistryLookup> TRANSACTION_SYNCHRONIZATION_REGISTRY_LOOKUP = AttributeDefinition.builder("transaction-synchronization-registry-lookup", null, TransactionSynchronizationRegistryLookup.class) .copier(identityCopier()).autoPersist(false).immutable().build(); public static final AttributeDefinition<TransactionMode> TRANSACTION_MODE = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.MODE, TransactionMode.NON_TRANSACTIONAL).immutable() .autoPersist(false).build(); public static final AttributeDefinition<Boolean> USE_SYNCHRONIZATION = AttributeDefinition.builder("synchronization", false).immutable().autoPersist(false).build(); public static final AttributeDefinition<Boolean> USE_1_PC_FOR_AUTO_COMMIT_TRANSACTIONS = AttributeDefinition.builder("single-phase-auto-commit", false).build(); public static final AttributeDefinition<Long> REAPER_WAKE_UP_INTERVAL = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.REAPER_WAKE_UP_INTERVAL, 30000L).immutable().build(); public static final AttributeDefinition<Long> COMPLETED_TX_TIMEOUT = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.COMPLETED_TX_TIMEOUT, 60000L).immutable().build(); public static final AttributeDefinition<Boolean> NOTIFICATIONS = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.NOTIFICATIONS, true).immutable().build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(TransactionConfiguration.class, Element.TRANSACTION.toString(), null, new AttributeDefinition[]{ AUTO_COMMIT, CACHE_STOP_TIMEOUT, LOCKING_MODE, TRANSACTION_MANAGER_LOOKUP, TRANSACTION_SYNCHRONIZATION_REGISTRY_LOOKUP, TRANSACTION_MODE, USE_SYNCHRONIZATION, USE_1_PC_FOR_AUTO_COMMIT_TRANSACTIONS, REAPER_WAKE_UP_INTERVAL, COMPLETED_TX_TIMEOUT, NOTIFICATIONS }, new AttributeSet.RemovedAttribute[]{new AttributeSet.RemovedAttribute(org.infinispan.configuration.parsing.Attribute.TRANSACTION_PROTOCOL, 11, 0)}); } private final Attribute<Boolean> autoCommit; private final Attribute<Long> cacheStopTimeout; private final Attribute<LockingMode> lockingMode; private final Attribute<TransactionManagerLookup> transactionManagerLookup; private final Attribute<TransactionSynchronizationRegistryLookup> transactionSynchronizationRegistryLookup; private final Attribute<TransactionMode> transactionMode; private final Attribute<Boolean> useSynchronization; private final Attribute<Boolean> use1PcForAutoCommitTransactions; private final Attribute<Long> reaperWakeUpInterval; private final Attribute<Long> completedTxTimeout; private final Attribute<Boolean> notifications; private final RecoveryConfiguration recovery; private final boolean invocationBatching; TransactionConfiguration(AttributeSet attributes, RecoveryConfiguration recovery, boolean invocationBatching) { super(Element.TRANSACTION, attributes, recovery); autoCommit = attributes.attribute(AUTO_COMMIT); cacheStopTimeout = attributes.attribute(CACHE_STOP_TIMEOUT); lockingMode = attributes.attribute(LOCKING_MODE); transactionManagerLookup = attributes.attribute(TRANSACTION_MANAGER_LOOKUP); transactionSynchronizationRegistryLookup = attributes.attribute(TRANSACTION_SYNCHRONIZATION_REGISTRY_LOOKUP); transactionMode = attributes.attribute(TRANSACTION_MODE); useSynchronization = attributes.attribute(USE_SYNCHRONIZATION); use1PcForAutoCommitTransactions = attributes.attribute(USE_1_PC_FOR_AUTO_COMMIT_TRANSACTIONS); reaperWakeUpInterval = attributes.attribute(REAPER_WAKE_UP_INTERVAL); completedTxTimeout = attributes.attribute(COMPLETED_TX_TIMEOUT); notifications = attributes.attribute(NOTIFICATIONS); this.recovery = recovery; this.invocationBatching = invocationBatching; } /** * If the cache is transactional (i.e. {@link #transactionMode()} == TransactionMode.TRANSACTIONAL) and * transactionAutoCommit is enabled then for single operation transactions the user doesn't need to manually start a * transaction, but a transactions is injected by the system. Defaults to true. */ public boolean autoCommit() { return autoCommit.get(); } /** * If there are any ongoing transactions when a cache is stopped, Infinispan waits for ongoing remote and local * transactions to finish. The amount of time to wait for is defined by the cache stop timeout. It is recommended * that this value does not exceed the transaction timeout because even if a new transaction was started just before * the cache was stopped, this could only last as long as the transaction timeout allows it. */ public TransactionConfiguration cacheStopTimeout(long l) { cacheStopTimeout.set(l); return this; } /** * If there are any ongoing transactions when a cache is stopped, Infinispan waits for ongoing remote and local * transactions to finish. The amount of time to wait for is defined by the cache stop timeout. It is recommended * that this value does not exceed the transaction timeout because even if a new transaction was started just before * the cache was stopped, this could only last as long as the transaction timeout allows it. */ public long cacheStopTimeout() { return cacheStopTimeout.get(); } /** * Configures whether the cache uses optimistic or pessimistic locking. If the cache is not transactional then the * locking mode is ignored. * * @see TransactionConfiguration#transactionMode() */ public LockingMode lockingMode() { return lockingMode.get(); } /** * Configures whether the cache uses optimistic or pessimistic locking. If the cache is not transactional then the * locking mode is ignored. * * @see TransactionConfiguration#transactionMode() */ public TransactionConfiguration lockingMode(LockingMode lockingMode) { this.lockingMode.set(lockingMode); return this; } /** * Configure Transaction manager lookup directly using an instance of TransactionManagerLookup. Calling this method * marks the cache as transactional. */ public TransactionManagerLookup transactionManagerLookup() { return transactionManagerLookup.get(); } /** * Configure Transaction Synchronization Registry lookup directly using an instance of TransactionManagerLookup. * Calling this method marks the cache as transactional. */ public TransactionSynchronizationRegistryLookup transactionSynchronizationRegistryLookup() { return transactionSynchronizationRegistryLookup.get(); } public TransactionMode transactionMode() { return transactionMode.get(); } public boolean useSynchronization() { return useSynchronization.get(); } /** * This method allows configuration of the transaction recovery cache. When this method is called, it automatically * enables recovery. So, if you want it to be disabled, make sure you call * {@link RecoveryConfigurationBuilder#enabled(boolean)} with false as parameter */ public RecoveryConfiguration recovery() { return recovery; } /** * @see TransactionConfigurationBuilder#reaperWakeUpInterval(long) */ public long reaperWakeUpInterval() { return reaperWakeUpInterval.get(); } /** * @see TransactionConfigurationBuilder#completedTxTimeout(long) */ public long completedTxTimeout() { return completedTxTimeout.get(); } /** * Before Infinispan 5.1 you could access the cache both transactionally and non-transactionally. Naturally the * non-transactional access is faster and offers less consistency guarantees. From Infinispan 5.1 onwards, mixed * access is no longer supported, so if you wanna speed up transactional caches and you're ready to trade some * consistency guarantees, you can enable use1PcForAutoCommitTransactions. <p/> * <p> * What this configuration option does is force an induced transaction, that has been started by Infinispan as a * result of enabling autoCommit, to commit in a single phase. So only 1 RPC instead of 2RPCs as in the case of a * full 2 Phase Commit (2PC). * <p/> * <b>N.B.</b> this option should NOT be used when modifying the * same key from multiple transactions as 1PC does not offer any consistency guarantees under concurrent access. */ public boolean use1PcForAutoCommitTransactions() { return use1PcForAutoCommitTransactions.get(); } /** * @return are transactional notifications ( * {@link org.infinispan.notifications.cachelistener.annotation.TransactionRegistered} and * {@link org.infinispan.notifications.cachelistener.annotation.TransactionCompleted}) triggered? */ public boolean notifications() { return notifications.get(); } }
11,225
52.712919
274
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/ConfigurationBuilder.java
package org.infinispan.configuration.cache; import static java.util.Arrays.asList; import static org.infinispan.configuration.cache.Configuration.CONFIGURATION; import static org.infinispan.configuration.cache.Configuration.SIMPLE_CACHE; import static org.infinispan.util.logging.Log.CONFIG; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.ConfigurationUtils; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; public class ConfigurationBuilder implements ConfigurationChildBuilder { private final ClusteringConfigurationBuilder clustering; private final CustomInterceptorsConfigurationBuilder customInterceptors; private final EncodingConfigurationBuilder encoding; private final ExpirationConfigurationBuilder expiration; private final QueryConfigurationBuilder query; private final IndexingConfigurationBuilder indexing; private final InvocationBatchingConfigurationBuilder invocationBatching; private final StatisticsConfigurationBuilder statistics; private final PersistenceConfigurationBuilder persistence; private final LockingConfigurationBuilder locking; private final SecurityConfigurationBuilder security; private final TransactionConfigurationBuilder transaction; private final UnsafeConfigurationBuilder unsafe; private final List<Builder<?>> modules = new ArrayList<>(); private final SitesConfigurationBuilder sites; private final MemoryConfigurationBuilder memory; private final AttributeSet attributes; private boolean template = false; public ConfigurationBuilder() { this.attributes = Configuration.attributeDefinitionSet(); this.clustering = new ClusteringConfigurationBuilder(this); this.customInterceptors = new CustomInterceptorsConfigurationBuilder(this); this.encoding = new EncodingConfigurationBuilder(this); this.expiration = new ExpirationConfigurationBuilder(this); this.query = new QueryConfigurationBuilder(this); this.indexing = new IndexingConfigurationBuilder(this); this.invocationBatching = new InvocationBatchingConfigurationBuilder(this); this.statistics = new StatisticsConfigurationBuilder(this); this.persistence = new PersistenceConfigurationBuilder(this); this.locking = new LockingConfigurationBuilder(this); this.security = new SecurityConfigurationBuilder(this); this.transaction = new TransactionConfigurationBuilder(this); this.unsafe = new UnsafeConfigurationBuilder(this); this.sites = new SitesConfigurationBuilder(this); this.memory = new MemoryConfigurationBuilder(this); } @Override public ConfigurationBuilder simpleCache(boolean simpleCache) { attributes.attribute(SIMPLE_CACHE).set(simpleCache); return this; } @Override public boolean simpleCache() { return attributes.attribute(SIMPLE_CACHE).get(); } @Override public ClusteringConfigurationBuilder clustering() { return clustering; } /** * @deprecated Since 10.0, custom interceptors support will be removed and only modules will be able to define interceptors */ @Deprecated @Override public CustomInterceptorsConfigurationBuilder customInterceptors() { return customInterceptors; } @Override public EncodingConfigurationBuilder encoding() { return encoding; } @Override public ExpirationConfigurationBuilder expiration() { return expiration; } @Override public QueryConfigurationBuilder query() { return query; } @Override public IndexingConfigurationBuilder indexing() { return indexing; } @Override public InvocationBatchingConfigurationBuilder invocationBatching() { return invocationBatching; } @Override public StatisticsConfigurationBuilder statistics() { return statistics; } @Override public PersistenceConfigurationBuilder persistence() { return persistence; } @Override public LockingConfigurationBuilder locking() { return locking; } @Override public SecurityConfigurationBuilder security() { return security; } @Override public TransactionConfigurationBuilder transaction() { return transaction; } @Override public UnsafeConfigurationBuilder unsafe() { return unsafe; } @Override public SitesConfigurationBuilder sites() { return sites; } @Override public MemoryConfigurationBuilder memory() { return memory; } public List<Builder<?>> modules() { return Collections.unmodifiableList(modules); } public ConfigurationBuilder clearModules() { modules.clear(); return this; } public <T extends Builder<?>> T addModule(Class<T> klass) { try { Constructor<T> constructor = klass.getDeclaredConstructor(ConfigurationBuilder.class); T builder = constructor.newInstance(this); this.modules.add(builder); return builder; } catch (Exception e) { throw new CacheConfigurationException("Could not instantiate module configuration builder '" + klass.getName() + "'", e); } } @Override public ConfigurationBuilder template(boolean template) { this.template = template; return this; } public boolean template() { return template; } public ConfigurationBuilder configuration(String baseConfigurationName) { attributes.attribute(CONFIGURATION).set(baseConfigurationName); return this; } public String configuration() { return attributes.attribute(CONFIGURATION).get(); } public void validate() { if (attributes.attribute(SIMPLE_CACHE).get()) { validateSimpleCacheConfiguration(); } List<RuntimeException> validationExceptions = new ArrayList<>(); for (Builder<?> validatable: asList(clustering, customInterceptors, expiration, indexing, encoding, invocationBatching, statistics, persistence, locking, transaction, unsafe, sites, memory)) { try { validatable.validate(); } catch (RuntimeException e) { validationExceptions.add(e); } } for (Builder<?> m : modules) { try { m.validate(); } catch (RuntimeException e) { validationExceptions.add(e); } } CacheConfigurationException.fromMultipleRuntimeExceptions(validationExceptions).ifPresent(e -> { throw e; }); } private void validateSimpleCacheConfiguration() { if (clustering().cacheMode().isClustered() || (transaction.transactionMode() != null && transaction.transactionMode().isTransactional()) || !customInterceptors.create().interceptors().isEmpty() || !persistence.stores().isEmpty() || invocationBatching.isEnabled() || indexing.enabled() || memory.create().storage() == StorageType.BINARY) { throw CONFIG.notSupportedInSimpleCache(); } } @Override public void validate(GlobalConfiguration globalConfig) { List<RuntimeException> validationExceptions = new ArrayList<>(); for (ConfigurationChildBuilder validatable: asList(clustering, customInterceptors, expiration, indexing, invocationBatching, statistics, persistence, locking, transaction, unsafe, sites, security, memory)) { try { validatable.validate(globalConfig); } catch (RuntimeException e) { validationExceptions.add(e); } } // Modules cannot be checked with GlobalConfiguration CacheConfigurationException.fromMultipleRuntimeExceptions(validationExceptions).ifPresent(e -> { throw e; }); } @Override public Configuration build() { return build(true); } public Configuration build(GlobalConfiguration globalConfiguration) { validate(globalConfiguration); return build(true); } public Configuration build(boolean validate) { if (validate) { validate(); } List<Object> modulesConfig = new LinkedList<>(); for (Builder<?> module : modules) modulesConfig.add(module.create()); return new Configuration(template, attributes.protect(), clustering.create(), customInterceptors.create(), expiration.create(), encoding.create(), query.create(), indexing.create(), invocationBatching.create(), statistics.create(), persistence.create(), locking.create(), security.create(), transaction.create(), unsafe.create(), sites.create(), memory.create(), modulesConfig); } public ConfigurationBuilder read(Configuration template) { return read(template, Combine.DEFAULT); } public ConfigurationBuilder read(Configuration template, Combine combine) { this.attributes.read(template.attributes(), combine); this.clustering.read(template.clustering(), combine); this.customInterceptors.read(template.customInterceptors(), combine); this.expiration.read(template.expiration(), combine); this.query.read(template.query(), combine); this.indexing.read(template.indexing(), combine); this.invocationBatching.read(template.invocationBatching(), combine); this.statistics.read(template.statistics(), combine); this.persistence.read(template.persistence(), combine); this.locking.read(template.locking(), combine); this.security.read(template.security(), combine); this.transaction.read(template.transaction(), combine); this.unsafe.read(template.unsafe(), combine); this.sites.read(template.sites(), combine); this.memory.read(template.memory(), combine); this.encoding.read(template.encoding(), combine); this.template = template.isTemplate(); for (Object c : template.modules().values()) { Builder<Object> builder = this.addModule(ConfigurationUtils.builderFor(c)); builder.read(c, combine); } return this; } @Override public String toString() { return "ConfigurationBuilder{" + "clustering=" + clustering + ", customInterceptors=" + customInterceptors + ", expiration=" + expiration + ", query=" + query + ", indexing=" + indexing + ", invocationBatching=" + invocationBatching + ", statistics=" + statistics + ", persistence=" + persistence + ", locking=" + locking + ", modules=" + modules + ", security=" + security + ", transaction=" + transaction + ", unsafe=" + unsafe + ", sites=" + sites + '}'; } }
11,206
34.46519
134
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/PartitionHandlingConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.PartitionHandlingConfiguration.MERGE_POLICY; import static org.infinispan.configuration.cache.PartitionHandlingConfiguration.WHEN_SPLIT; import static org.infinispan.util.logging.Log.CONFIG; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.conflict.EntryMergePolicy; import org.infinispan.partitionhandling.PartitionHandling; /** * Controls how the cache handles partitioning and/or multiple node failures. * * @author Mircea Markus * @since 7.0 */ public class PartitionHandlingConfigurationBuilder extends AbstractClusteringConfigurationChildBuilder implements Builder<PartitionHandlingConfiguration> { private final AttributeSet attributes; public PartitionHandlingConfigurationBuilder(ClusteringConfigurationBuilder builder) { super(builder); attributes = PartitionHandlingConfiguration.attributeDefinitionSet(); } PartitionHandling whenSplit() { return attributes.attribute(WHEN_SPLIT).get(); } public PartitionHandlingConfigurationBuilder whenSplit(PartitionHandling partitionHandling) { attributes.attribute(WHEN_SPLIT).set(partitionHandling); return this; } public PartitionHandlingConfigurationBuilder mergePolicy(EntryMergePolicy mergePolicy) { attributes.attribute(MERGE_POLICY).set(mergePolicy); return this; } @Override public void validate() { if (attributes.attribute(WHEN_SPLIT).get() != PartitionHandling.ALLOW_READ_WRITES && clustering().cacheMode().isInvalidation()) throw CONFIG.invalidationPartitionHandlingNotSuported(); } @Override public void validate(GlobalConfiguration globalConfig) { } @Override public PartitionHandlingConfiguration create() { return new PartitionHandlingConfiguration(attributes.protect()); } @Override public Builder<?> read(PartitionHandlingConfiguration template, Combine combine) { attributes.read(template.attributes(), combine); return this; } public AttributeSet attributes() { return attributes; } }
2,327
33.746269
155
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/MemoryStorageConfiguration.java
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.parsing.Attribute; import org.infinispan.configuration.parsing.Element; import org.infinispan.eviction.EvictionStrategy; import org.infinispan.eviction.EvictionType; /** * @deprecated Since 11.0, {@link MemoryConfiguration} is used to defined the data container memory * eviction and sizing. */ @Deprecated public class MemoryStorageConfiguration { public static final AttributeDefinition<Long> SIZE = AttributeDefinition.builder(Attribute.SIZE, -1L).build(); public static final AttributeDefinition<EvictionType> EVICTION_TYPE = AttributeDefinition.builder(Element.EVICTION, EvictionType.COUNT).immutable().build(); public static final AttributeDefinition<EvictionStrategy> EVICTION_STRATEGY = AttributeDefinition.builder(Attribute.STRATEGY, EvictionStrategy.NONE).immutable().build(); public static final AttributeDefinition<StorageType> STORAGE_TYPE = AttributeDefinition.builder(Attribute.TYPE, StorageType.HEAP).immutable().build(); private final AttributeSet attributes; static public AttributeSet attributeDefinitionSet() { return new AttributeSet(MemoryStorageConfiguration.class, SIZE, EVICTION_TYPE, EVICTION_STRATEGY, STORAGE_TYPE); } public MemoryStorageConfiguration(AttributeSet attributes) { this.attributes = attributes; } public AttributeSet attributes() { return attributes; } public StorageType storageType() { return attributes.attribute(STORAGE_TYPE).get(); } public long size() { return attributes.attribute(SIZE).get(); } public EvictionType evictionType() { return attributes.attribute(EVICTION_TYPE).get(); } public EvictionStrategy evictionStrategy() { return attributes.attribute(EVICTION_STRATEGY).get(); } public void size(long newSize) { attributes.attribute(SIZE).set(newSize); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MemoryStorageConfiguration that = (MemoryStorageConfiguration) o; return attributes.equals(that.attributes); } @Override public int hashCode() { return attributes.hashCode(); } @Override public String toString() { return "MemoryStorageConfiguration{" + "attributes=" + attributes + '}'; } }
2,576
32.038462
172
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/BackupForConfiguration.java
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Element; /** * Defines the remote caches for which this cache acts as a backup. * * @author Mircea Markus * @since 5.2 */ public class BackupForConfiguration extends ConfigurationElement<BackupForConfiguration> { public static final AttributeDefinition<String> REMOTE_CACHE = AttributeDefinition.<String>builder(org.infinispan.configuration.parsing.Attribute.REMOTE_CACHE, null, String.class).immutable().build(); public static final AttributeDefinition<String> REMOTE_SITE = AttributeDefinition.<String>builder(org.infinispan.configuration.parsing.Attribute.REMOTE_SITE, null, String.class).immutable().build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(BackupForConfiguration.class, REMOTE_CACHE, REMOTE_SITE); } private final Attribute<String> remoteCache; private final Attribute<String> remoteSite; public BackupForConfiguration(AttributeSet attributes) { super(Element.BACKUP_FOR, attributes); this.remoteCache = attributes.attribute(REMOTE_CACHE); this.remoteSite = attributes.attribute(REMOTE_SITE); } /** * @return the name of the remote site that backups data into this cache. */ public String remoteCache() { return remoteCache.get(); } /** * @return the name of the remote cache that backups data into this cache. */ public String remoteSite() { return remoteSite.get(); } public boolean isBackupFor(String remoteSite, String remoteCache) { boolean remoteSiteMatches = remoteSite() != null && remoteSite().equals(remoteSite); boolean remoteCacheMatches = remoteCache() != null && this.remoteCache().equals(remoteCache); return remoteSiteMatches && remoteCacheMatches; } }
2,119
40.568627
203
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/IndexReaderConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.IndexReaderConfiguration.REFRESH_INTERVAL; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeSet; /** * @since 12.0 */ public class IndexReaderConfigurationBuilder extends AbstractIndexingConfigurationChildBuilder implements Builder<IndexReaderConfiguration> { private final AttributeSet attributes; private final Attribute<Long> refreshInterval; IndexReaderConfigurationBuilder(IndexingConfigurationBuilder builder) { super(builder); this.attributes = IndexReaderConfiguration.attributeDefinitionSet(); this.refreshInterval = attributes.attribute(REFRESH_INTERVAL); } @Override public AttributeSet attributes() { return attributes; } public IndexReaderConfigurationBuilder refreshInterval(long valueMillis) { refreshInterval.set(valueMillis); return this; } @Override public IndexReaderConfiguration create() { return new IndexReaderConfiguration(attributes.protect()); } @Override public IndexReaderConfigurationBuilder read(IndexReaderConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); return this; } @Override public String toString() { return "IndexReaderConfigurationBuilder{" + "attributes=" + attributes + '}'; } }
1,604
29.283019
100
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/SecurityConfiguration.java
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Element; /** * SecurityConfiguration. * * @author Tristan Tarrant * @since 7.0 */ public class SecurityConfiguration extends ConfigurationElement<SecurityConfiguration> { private final AuthorizationConfiguration authorization; SecurityConfiguration(AuthorizationConfiguration authorization) { super(Element.SECURITY, AttributeSet.EMPTY, authorization); this.authorization = authorization; } public AuthorizationConfiguration authorization() { return authorization; } }
746
27.730769
88
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/LockingConfiguration.java
package org.infinispan.configuration.cache; import java.util.concurrent.TimeUnit; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Element; import org.infinispan.util.concurrent.IsolationLevel; /** * Defines the local, in-VM locking and concurrency characteristics of the cache. * * @author pmuir * */ public class LockingConfiguration extends ConfigurationElement<LockingConfiguration> { public static final AttributeDefinition<Integer> CONCURRENCY_LEVEL = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.CONCURRENCY_LEVEL, 32).immutable().build(); public static final AttributeDefinition<IsolationLevel> ISOLATION_LEVEL = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.ISOLATION, IsolationLevel.REPEATABLE_READ).immutable().build(); public static final AttributeDefinition<Long> LOCK_ACQUISITION_TIMEOUT = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.ACQUIRE_TIMEOUT, TimeUnit.SECONDS.toMillis(10)).build(); public static final AttributeDefinition<Boolean> USE_LOCK_STRIPING = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.STRIPING, false).immutable().build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(LockingConfiguration.class, Element.LOCKING.toString(), null, new AttributeDefinition[]{ CONCURRENCY_LEVEL, ISOLATION_LEVEL, LOCK_ACQUISITION_TIMEOUT, USE_LOCK_STRIPING }, new AttributeSet.RemovedAttribute[] { new AttributeSet.RemovedAttribute(org.infinispan.configuration.parsing.Attribute.WRITE_SKEW_CHECK, 10, 0)} ); } private final Attribute<Integer> concurrencyLevel; private final Attribute<IsolationLevel> isolationLevel; private final Attribute<Long> lockAcquisitionTimeout; private final Attribute<Boolean> useLockStriping; LockingConfiguration(AttributeSet attributes) { super(Element.LOCKING, attributes); concurrencyLevel = attributes.attribute(CONCURRENCY_LEVEL); isolationLevel = attributes.attribute(ISOLATION_LEVEL); lockAcquisitionTimeout = attributes.attribute(LOCK_ACQUISITION_TIMEOUT); useLockStriping = attributes.attribute(USE_LOCK_STRIPING); } /** * Concurrency level for lock containers. Adjust this value according to the number of concurrent * threads interacting with Infinispan. Similar to the concurrencyLevel tuning parameter seen in * the JDK's ConcurrentHashMap. */ public int concurrencyLevel() { return concurrencyLevel.get(); } /** * Cache isolation level. Infinispan only supports READ_COMMITTED or REPEATABLE_READ isolation * levels. See <a href= * 'http://en.wikipedia.org/wiki/Isolation_level'>http://en.wikipedia.org/wiki/Isolation_level</a * > for a discussion on isolation levels. */ public IsolationLevel isolationLevel() { return isolationLevel.get(); } /** * Maximum time to attempt a particular lock acquisition */ public long lockAcquisitionTimeout() { return lockAcquisitionTimeout.get(); } public LockingConfiguration lockAcquisitionTimeout(long timeout) { lockAcquisitionTimeout.set(timeout); return this; } /** * If true, a pool of shared locks is maintained for all entries that need to be locked. * Otherwise, a lock is created per entry in the cache. Lock striping helps control memory * footprint but may reduce concurrency in the system. */ public boolean useLockStriping() { return useLockStriping.get(); } }
3,885
44.186047
216
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/L1ConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.L1Configuration.CLEANUP_TASK_FREQUENCY; import static org.infinispan.configuration.cache.L1Configuration.ENABLED; import static org.infinispan.configuration.cache.L1Configuration.INVALIDATION_THRESHOLD; import static org.infinispan.configuration.cache.L1Configuration.LIFESPAN; import static org.infinispan.util.logging.Log.CONFIG; import java.util.concurrent.TimeUnit; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.eviction.EvictionStrategy; /** * Configures the L1 cache behavior in 'distributed' caches instances. In any other cache modes, * this element is ignored. */ public class L1ConfigurationBuilder extends AbstractClusteringConfigurationChildBuilder implements Builder<L1Configuration> { private final AttributeSet attributes; L1ConfigurationBuilder(ClusteringConfigurationBuilder builder) { super(builder); attributes = L1Configuration.attributeDefinitionSet(); } @Override public AttributeSet attributes() { return attributes; } /** * <p> * Determines whether a multicast or a web of unicasts are used when performing L1 invalidations. * </p> * * <p> * By default multicast will be used. * </p> * * <p> * If the threshold is set to -1, then unicasts will always be used. If the threshold is set to * 0, then multicast will be always be used. * </p> * * @param invalidationThreshold the threshold over which to use a multicast * */ public L1ConfigurationBuilder invalidationThreshold(int invalidationThreshold) { attributes.attribute(INVALIDATION_THRESHOLD).set(invalidationThreshold); return this; } /** * Maximum lifespan of an entry placed in the L1 cache. */ public L1ConfigurationBuilder lifespan(long lifespan) { attributes.attribute(LIFESPAN).set(lifespan); return this; } /** * Maximum lifespan of an entry placed in the L1 cache. */ public L1ConfigurationBuilder lifespan(long lifespan, TimeUnit unit) { return lifespan(unit.toMillis(lifespan)); } /** * How often the L1 requestors map is cleaned up of stale items */ public L1ConfigurationBuilder cleanupTaskFrequency(long frequencyMillis) { attributes.attribute(CLEANUP_TASK_FREQUENCY).set(frequencyMillis); return this; } /** * How often the L1 requestors map is cleaned up of stale items */ public L1ConfigurationBuilder cleanupTaskFrequency(long frequencyMillis, TimeUnit unit) { return cleanupTaskFrequency(unit.toMillis(frequencyMillis)); } public L1ConfigurationBuilder enable() { attributes.attribute(ENABLED).set(true); return this; } public L1ConfigurationBuilder disable() { attributes.attribute(ENABLED).set(false); return this; } public L1ConfigurationBuilder enabled(boolean enabled) { attributes.attribute(ENABLED).set(enabled); return this; } @Override public void validate() { if (attributes.attribute(ENABLED).get()) { if (!clustering().cacheMode().isDistributed()) throw CONFIG.l1OnlyForDistributedCache(clustering().cacheMode().friendlyCacheModeString()); if (attributes.attribute(LIFESPAN).get() < 1) throw CONFIG.l1InvalidLifespan(); MemoryConfigurationBuilder memoryConfigurationBuilder = getClusteringBuilder().memory(); if (memoryConfigurationBuilder.evictionStrategy() == EvictionStrategy.EXCEPTION) { throw CONFIG.l1NotValidWithExpirationEviction(); } } } @Override public void validate(GlobalConfiguration globalConfig) { } @Override public L1Configuration create() { return new L1Configuration(attributes.protect()); } @Override public L1ConfigurationBuilder read(L1Configuration template, Combine combine) { attributes.read(template.attributes(), combine); return this; } @Override public String toString() { return "L1ConfigurationBuilder [attributes=" + attributes + "]"; } }
4,354
30.557971
125
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/XSiteStateTransferConfiguration.java
package org.infinispan.configuration.cache; import java.util.concurrent.TimeUnit; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Element; /** * Configuration needed for State Transfer between different sites. * * @author Pedro Ruivo * @since 7.0 */ public class XSiteStateTransferConfiguration extends ConfigurationElement<XSiteStateTransferConfiguration> { public static final int DEFAULT_CHUNK_SIZE = 512; public static final long DEFAULT_TIMEOUT = TimeUnit.MINUTES.toMillis(20); public static final int DEFAULT_MAX_RETRIES = 30; public static final long DEFAULT_WAIT_TIME = TimeUnit.SECONDS.toMillis(2); public static final AttributeDefinition<Integer> CHUNK_SIZE = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.CHUNK_SIZE, DEFAULT_CHUNK_SIZE).immutable().build(); public static final AttributeDefinition<Long> TIMEOUT = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.TIMEOUT, DEFAULT_TIMEOUT).build(); public static final AttributeDefinition<Integer> MAX_RETRIES = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.MAX_RETRIES, DEFAULT_MAX_RETRIES).build(); public static final AttributeDefinition<Long> WAIT_TIME = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.WAIT_TIME, DEFAULT_WAIT_TIME).build(); public static final AttributeDefinition<XSiteStateTransferMode> MODE = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.MODE, XSiteStateTransferMode.MANUAL).build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(XSiteStateTransferConfiguration.class, CHUNK_SIZE, TIMEOUT, MAX_RETRIES, WAIT_TIME, MODE); } public XSiteStateTransferConfiguration(AttributeSet attributes) { super(Element.STATE_TRANSFER, attributes); } public int chunkSize() { return attributes.attribute(CHUNK_SIZE).get(); } public long timeout() { return attributes.attribute(TIMEOUT).get(); } public int maxRetries() { return attributes.attribute(MAX_RETRIES).get(); } public long waitTime() { return attributes.attribute(WAIT_TIME).get(); } public XSiteStateTransferMode mode() { return attributes.attribute(MODE).get(); } }
2,506
43.767857
194
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/ContentTypeConfiguration.java
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.parsing.Attribute; /** * @since 9.2 */ public class ContentTypeConfiguration extends ConfigurationElement<ContentTypeConfiguration> { public static final AttributeDefinition<MediaType> MEDIA_TYPE = AttributeDefinition.builder(Attribute.MEDIA_TYPE, null, MediaType.class).immutable().build(); private final MediaType mediaType; ContentTypeConfiguration(Enum<?> element, AttributeSet attributes, MediaType parentType) { super(element, attributes); // parent type has precedence this.mediaType = parentType != null ? parentType : attributes.attribute(MEDIA_TYPE).get(); } public static AttributeSet attributeDefinitionSet() { return new AttributeSet(ContentTypeConfiguration.class, MEDIA_TYPE); } public MediaType mediaType() { return mediaType; } public boolean isMediaTypeChanged() { return mediaType != null; } public boolean isObjectStorage() { return MediaType.APPLICATION_OBJECT.match(mediaType); } public boolean isProtoBufStorage() { return MediaType.APPLICATION_PROTOSTREAM.match(mediaType); } }
1,470
32.431818
102
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/IndexingConfiguration.java
package org.infinispan.configuration.cache; import static org.infinispan.commons.configuration.attributes.CollectionAttributeCopier.collectionCopier; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.infinispan.commons.configuration.AbstractTypedPropertiesConfiguration; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Element; /** * Configures indexing of entries in the cache for searching. */ public class IndexingConfiguration extends ConfigurationElement<IndexingConfiguration> { public static final AttributeDefinition<Boolean> ENABLED = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.ENABLED, false).immutable().build(); public static final AttributeDefinition<Map<Class<?>, Class<?>>> KEY_TRANSFORMERS = AttributeDefinition.builder(Element.KEY_TRANSFORMERS, null, (Class<Map<Class<?>, Class<?>>>) (Class<?>) Map.class) .copier(collectionCopier()) .initializer(HashMap::new).immutable().build(); public static final AttributeDefinition<Set<String>> INDEXED_ENTITIES = AttributeDefinition.builder(Element.INDEXED_ENTITIES, null, (Class<Set<String>>) (Class<?>) Set.class) .copier(collectionCopier()) .initializer(HashSet::new).build(); public static final AttributeDefinition<IndexStorage> STORAGE = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.STORAGE, IndexStorage.FILESYSTEM) .immutable().build(); public static final AttributeDefinition<IndexStartupMode> STARTUP_MODE = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.STARTUP_MODE, IndexStartupMode.NONE) .immutable().build(); public static final AttributeDefinition<String> PATH = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.PATH, null, String.class).immutable().build(); public static final AttributeDefinition<IndexingMode> INDEXING_MODE = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.INDEXING_MODE, IndexingMode.AUTO) .immutable().build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(IndexingConfiguration.class, AbstractTypedPropertiesConfiguration.attributeSet(), KEY_TRANSFORMERS, INDEXED_ENTITIES, ENABLED, STORAGE, STARTUP_MODE, PATH, INDEXING_MODE); } private final IndexReaderConfiguration readerConfiguration; private final IndexWriterConfiguration writerConfiguration; private final IndexShardingConfiguration shardingConfiguration; IndexingConfiguration(AttributeSet attributes, IndexReaderConfiguration readerConfiguration, IndexWriterConfiguration writerConfiguration, IndexShardingConfiguration shardingConfiguration) { super(Element.INDEXING, attributes); this.readerConfiguration = readerConfiguration; this.writerConfiguration = writerConfiguration; this.shardingConfiguration = shardingConfiguration; } /** * Determines if indexing is enabled for this cache configuration. */ public boolean enabled() { return attributes.attribute(ENABLED).get(); } public IndexStorage storage() { return attributes.attribute(STORAGE).get(); } public IndexStartupMode startupMode() { return attributes.attribute(STARTUP_MODE).get(); } public String path() { return attributes.attribute(PATH).get(); } /** * Affects how cache operations will be propagated to the indexes. * By default, {@link IndexingMode#AUTO}. * * @see IndexingMode * * @return If the auto-indexing is enabled */ public IndexingMode indexingMode() { return attributes.attribute(INDEXING_MODE).get(); } /** * The currently configured key transformers. * * @return a {@link Map} in which the map key is the key class and the value is the Transformer class. */ public Map<Class<?>, Class<?>> keyTransformers() { return attributes.attribute(KEY_TRANSFORMERS).get(); } /** * The set of fully qualified names of indexed entity types, either Java classes or protobuf type names. This * configuration corresponds to the {@code <indexed-entities>} XML configuration element. */ public Set<String> indexedEntityTypes() { return attributes.attribute(INDEXED_ENTITIES).get(); } /** * Check if the indexes can be shared. Currently no index can be shared, so it always returns false. sharing. * * @return always false, starting with version 11.0 * @deprecated Since 11.0 with no replacement; to be removed in next major version. */ @Deprecated public final boolean indexShareable() { return false; } public IndexReaderConfiguration reader() { return readerConfiguration; } public IndexWriterConfiguration writer() { return writerConfiguration; } public IndexShardingConfiguration sharding() { return shardingConfiguration; } /** * Does the index use a provider that does not persist upon restart? */ public boolean isVolatile() { return attributes.attribute(STORAGE).get().equals(IndexStorage.LOCAL_HEAP); } @Override public String toString() { return attributes.toString(null) + ", reader=" + readerConfiguration + ", writer=" + writerConfiguration + ", sharding=" + shardingConfiguration; } }
5,628
39.789855
201
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/ContentTypeConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.ContentTypeConfiguration.MEDIA_TYPE; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.global.GlobalConfiguration; /** * @since 9.2 */ public class ContentTypeConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<ContentTypeConfiguration> { private final AttributeSet attributes; private final Enum<?> element; protected ContentTypeConfigurationBuilder(Enum<?> element, EncodingConfigurationBuilder builder) { super(builder.getBuilder()); this.element = element; attributes = ContentTypeConfiguration.attributeDefinitionSet(); } @Override public AttributeSet attributes() { return attributes; } public boolean isObjectStorage() { return MediaType.APPLICATION_OBJECT.match(mediaType()); } public boolean isProtobufStorage() { return MediaType.APPLICATION_PROTOSTREAM.match(mediaType()); } public ContentTypeConfigurationBuilder mediaType(String mediaType) { attributes.attribute(MEDIA_TYPE).set(MediaType.fromString(mediaType)); return this; } public ContentTypeConfigurationBuilder mediaType(MediaType mediaType) { attributes.attribute(MEDIA_TYPE).set(mediaType); return this; } public MediaType mediaType() { return attributes.attribute(MEDIA_TYPE).get(); } @Override public ContentTypeConfiguration create() { throw new UnsupportedOperationException(); } ContentTypeConfiguration create(MediaType globalType) { return new ContentTypeConfiguration(element, attributes.protect(), globalType); } @Override public ContentTypeConfigurationBuilder read(ContentTypeConfiguration template, Combine combine) { attributes.read(template.attributes(), combine); return this; } @Override public void validate(GlobalConfiguration globalConfig) { } }
2,167
29.535211
133
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/XSiteStateTransferConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.XSiteStateTransferConfiguration.CHUNK_SIZE; import static org.infinispan.configuration.cache.XSiteStateTransferConfiguration.MAX_RETRIES; import static org.infinispan.configuration.cache.XSiteStateTransferConfiguration.MODE; import static org.infinispan.configuration.cache.XSiteStateTransferConfiguration.TIMEOUT; import static org.infinispan.configuration.cache.XSiteStateTransferConfiguration.WAIT_TIME; import static org.infinispan.util.logging.Log.CONFIG; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; /** * Configuration Builder to configure the state transfer between sites. * * @author Pedro Ruivo * @since 7.0 */ public class XSiteStateTransferConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<XSiteStateTransferConfiguration> { private final BackupConfigurationBuilder backupConfigurationBuilder; private final AttributeSet attributes; public XSiteStateTransferConfigurationBuilder(ConfigurationBuilder builder, BackupConfigurationBuilder backupConfigurationBuilder) { super(builder); attributes = XSiteStateTransferConfiguration.attributeDefinitionSet(); this.backupConfigurationBuilder = backupConfigurationBuilder; } @Override public AttributeSet attributes() { return attributes; } @Override public void validate() { int chunkSize = attributes.attribute(StateTransferConfiguration.CHUNK_SIZE).get(); if (chunkSize <= 0) { throw CONFIG.invalidChunkSize(chunkSize); } if (attributes.attribute(TIMEOUT).get() <= 0) { throw CONFIG.invalidXSiteStateTransferTimeout(); } if (attributes.attribute(WAIT_TIME).get() <= 0) { throw CONFIG.invalidXSiteStateTransferWaitTime(); } XSiteStateTransferMode mode = attributes.attribute(MODE).get(); if (mode == null) { throw CONFIG.invalidXSiteStateTransferMode(); } if (mode == XSiteStateTransferMode.AUTO && backupConfigurationBuilder.strategy() == BackupConfiguration.BackupStrategy.SYNC) { throw CONFIG.autoXSiteStateTransferModeNotAvailableInSync(); } } @Override public void validate(GlobalConfiguration globalConfig) { validate(); } /** * If &gt; 0, the state will be transferred in batches of {@code chunkSize} cache entries. If &lt;= 0, the state will * be transferred in all at once. Not recommended. Defaults to 512. */ public final XSiteStateTransferConfigurationBuilder chunkSize(int chunkSize) { attributes.attribute(CHUNK_SIZE).set(chunkSize); return this; } /** * The time (in milliseconds) to wait for the backup site acknowledge the state chunk received and applied. Default * value is 20 min. */ public final XSiteStateTransferConfigurationBuilder timeout(long timeout) { attributes.attribute(TIMEOUT).set(timeout); return this; } /** * The maximum number of retries when a push state command fails. A value &le; 0 (zero) means that the command does * not retry. Default value is 30. */ public final XSiteStateTransferConfigurationBuilder maxRetries(int maxRetries) { attributes.attribute(MAX_RETRIES).set(maxRetries); return this; } /** * The wait time, in milliseconds, between each retry. The value should be &gt; 0 (zero). Default value is 2 * seconds. */ public final XSiteStateTransferConfigurationBuilder waitTime(long waitingTimeBetweenRetries) { attributes.attribute(WAIT_TIME).set(waitingTimeBetweenRetries); return this; } /** * The cross-site state transfer mode. * <p> * If set to {@link XSiteStateTransferMode#AUTO}, Infinispan automatically starts state transfer when it detects * a new view for a backup location that was previously offline. */ public final XSiteStateTransferConfigurationBuilder mode(XSiteStateTransferMode mode) { attributes.attribute(MODE).set(mode); return this; } public final BackupConfigurationBuilder backup() { return backupConfigurationBuilder; } @Override public XSiteStateTransferConfiguration create() { return new XSiteStateTransferConfiguration(attributes.protect()); } @Override public Builder<XSiteStateTransferConfiguration> read(XSiteStateTransferConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); return this; } public String toString() { return "XSiteStateTransferConfigurationBuilder [attributes=" + attributes + "]"; } }
4,902
36.427481
132
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/StateTransferConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.StateTransferConfiguration.AWAIT_INITIAL_TRANSFER; import static org.infinispan.configuration.cache.StateTransferConfiguration.CHUNK_SIZE; import static org.infinispan.configuration.cache.StateTransferConfiguration.FETCH_IN_MEMORY_STATE; import static org.infinispan.configuration.cache.StateTransferConfiguration.TIMEOUT; import static org.infinispan.util.logging.Log.CONFIG; import java.util.concurrent.TimeUnit; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; /** * Configures how state is transferred when a cache joins or leaves the cluster. Used in distributed and * replication clustered modes. * * @since 5.1 */ public class StateTransferConfigurationBuilder extends AbstractClusteringConfigurationChildBuilder implements Builder<StateTransferConfiguration> { private final AttributeSet attributes; StateTransferConfigurationBuilder(ClusteringConfigurationBuilder builder) { super(builder); attributes = StateTransferConfiguration.attributeDefinitionSet(); } /** * If {@code true}, the cache will fetch data from the neighboring caches when it starts up, so * the cache starts 'warm', although it will impact startup time. * <p/> * In distributed mode, state is transferred between running caches as well, as the ownership of * keys changes (e.g. because a cache left the cluster). Disabling this setting means a key will * sometimes have less than {@code numOwner} owners. */ public StateTransferConfigurationBuilder fetchInMemoryState(boolean b) { attributes.attribute(FETCH_IN_MEMORY_STATE).set(b); return this; } /** * If {@code true}, this will cause the first call to method {@code CacheManager.getCache()} on the joiner node to * block and wait until the joining is complete and the cache has finished receiving state from neighboring caches * (if fetchInMemoryState is enabled). This option applies to distributed and replicated caches only and is enabled * by default. Please note that setting this to {@code false} will make the cache object available immediately but * any access to keys that should be available locally but are not yet transferred will actually cause a (transparent) * remote access. While this will not have any impact on the logic of your application it might impact performance. */ public StateTransferConfigurationBuilder awaitInitialTransfer(boolean b) { attributes.attribute(AWAIT_INITIAL_TRANSFER).set(b); return this; } /** * The state will be transferred in batches of {@code chunkSize} cache entries. * If chunkSize is equal to Integer.MAX_VALUE, the state will be transferred in all at once. Not recommended. */ public StateTransferConfigurationBuilder chunkSize(int i) { attributes.attribute(CHUNK_SIZE).set(i); return this; } /** * This is the maximum amount of time - in milliseconds - to wait for state from neighboring * caches, before throwing an exception and aborting startup. * * Must be greater than or equal to 'remote-timeout' in the clustering configuration. */ public StateTransferConfigurationBuilder timeout(long l) { attributes.attribute(TIMEOUT).set(l); return this; } /** * This is the maximum amount of time - in milliseconds - to wait for state from neighboring * caches, before throwing an exception and aborting startup. * * Must be greater than or equal to 'remote-timeout' in the clustering configuration. */ public StateTransferConfigurationBuilder timeout(long l, TimeUnit unit) { return timeout(unit.toMillis(l)); } @Override public void validate() { int chunkSize = attributes.attribute(CHUNK_SIZE).get(); if (chunkSize <= 0) { throw CONFIG.invalidChunkSize(chunkSize); } if (clustering().cacheMode().isInvalidation()) { Attribute<Boolean> fetchAttribute = attributes.attribute(FETCH_IN_MEMORY_STATE); if (fetchAttribute.isModified() && fetchAttribute.get()) { throw CONFIG.attributeNotAllowedInInvalidationMode(FETCH_IN_MEMORY_STATE.name()); } } Attribute<Boolean> awaitInitialTransfer = attributes.attribute(AWAIT_INITIAL_TRANSFER); if (awaitInitialTransfer.isModified() && awaitInitialTransfer.get() && !getClusteringBuilder().cacheMode().needsStateTransfer()) throw CONFIG.awaitInitialTransferOnlyForDistOrRepl(); Attribute<Long> timeoutAttribute = attributes.attribute(TIMEOUT); Attribute<Long> remoteTimeoutAttribute = clustering().attributes.attribute(ClusteringConfiguration.REMOTE_TIMEOUT); if (timeoutAttribute.get() < remoteTimeoutAttribute.get()) { throw CONFIG.invalidStateTransferTimeout(timeoutAttribute.get(), remoteTimeoutAttribute.get()); } } @Override public void validate(GlobalConfiguration globalConfig) { } @Override public StateTransferConfiguration create() { return new StateTransferConfiguration(attributes.protect()); } @Override public StateTransferConfigurationBuilder read(StateTransferConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); return this; } @Override public String toString() { return "StateTransferConfigurationBuilder [attributes=" + attributes + "]"; } public AttributeSet attributes() { return attributes; } }
5,813
41.130435
121
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/SitesConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.SitesConfiguration.MERGE_POLICY; import static org.infinispan.util.logging.Log.CONFIG; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.xsite.spi.XSiteEntryMergePolicy; import org.infinispan.xsite.spi.XSiteMergePolicy; /** * @author Mircea.Markus@jboss.com * @since 5.2 */ public class SitesConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<SitesConfiguration> { private final AttributeSet attributes; private final List<BackupConfigurationBuilder> backups = new ArrayList<>(2); private final BackupForBuilder backupForBuilder; public SitesConfigurationBuilder(ConfigurationBuilder builder) { super(builder); attributes = SitesConfiguration.attributeDefinitionSet(); backupForBuilder = new BackupForBuilder(builder); } public BackupConfigurationBuilder addBackup() { BackupConfigurationBuilder bcb = new BackupConfigurationBuilder(getBuilder()); backups.add(bcb); return bcb; } public List<BackupConfigurationBuilder> backups() { return backups; } /** * Returns true if this cache won't backup its data remotely. * It would still accept other sites backing up data on this site. * @deprecated Since 14.0. To be removed without replacement. */ @Deprecated public SitesConfigurationBuilder disableBackups(boolean disable) { //no-op return this; } /** * Defines the site names, from the list of sites names defined within 'backups' element, to * which this cache backups its data. * @deprecated Since 14.0. To be removed without replacement. */ @Deprecated public SitesConfigurationBuilder addInUseBackupSite(String site) { return this; } public BackupForBuilder backupFor() { return backupForBuilder; } /** * Configures the {@link XSiteEntryMergePolicy} to be used. * <p> * {@link XSiteEntryMergePolicy} is invoked when a conflicts is detected between 2 sites. A conflict happens when a * key is updated concurrently in 2 sites. * <p> * {@link XSiteMergePolicy} enum contains implementation available to be used. * * @param mergePolicy The {@link XSiteEntryMergePolicy} implementation to use. * @return {@code this}. * @see XSiteEntryMergePolicy * @see XSiteMergePolicy */ public SitesConfigurationBuilder mergePolicy(XSiteEntryMergePolicy<?, ?> mergePolicy) { attributes.attribute(MERGE_POLICY).set(mergePolicy); return this; } /** * Sets the maximum delay, in milliseconds, between which the tombstone cleanup task runs. * * @param value The maximum delay in milliseconds. * @return {@code this}. */ public SitesConfigurationBuilder maxTombstoneCleanupDelay(long value) { attributes.attribute(SitesConfiguration.MAX_CLEANUP_DELAY).set(value); return this; } /** * Sets the target tombstone map size. * <p> * The cleanup task checks the current size of the tombstone map before starting, and increases the delay of the next * run if the size is less than the target size, or reduces the delay if the size is greater than the target size. * * @param value The target tombstone map size. * @return {@code this}. */ public SitesConfigurationBuilder tombstoneMapSize(int value) { attributes.attribute(SitesConfiguration.TOMBSTONE_MAP_SIZE).set(value); return this; } @Override public void validate() { backupForBuilder.validate(); attributes.validate(); //don't allow two backups with the same name Set<String> backupNames = new HashSet<>(backups.size()); for (BackupConfigurationBuilder bcb : backups) { if (!backupNames.add(bcb.site())) { throw CONFIG.multipleSitesWithSameName(bcb.site()); } bcb.validate(); } //we have backups configured. check if we have a clustered cache if (!backupNames.isEmpty() && !builder.clustering().cacheMode().isClustered()) { throw CONFIG.xsiteInLocalCache(); } if (attributes.attribute(MERGE_POLICY).get() == null) { throw CONFIG.missingXSiteEntryMergePolicy(); } } @Override public void validate(GlobalConfiguration globalConfig) { backupForBuilder.validate(globalConfig); attributes.validate(); for (BackupConfigurationBuilder bcb : backups) { bcb.validate(globalConfig); } } @Override public SitesConfiguration create() { List<BackupConfiguration> backupConfigurations = new ArrayList<>(backups.size()); for (BackupConfigurationBuilder bcb : this.backups) { backupConfigurations.add(bcb.create()); } return new SitesConfiguration(attributes.protect(), backupConfigurations, backupForBuilder.create()); } @Override public SitesConfigurationBuilder read(SitesConfiguration template, Combine combine) { attributes.read(template.attributes(), combine); backupForBuilder.read(template.backupFor(), combine); if (combine.repeatedAttributes() == Combine.RepeatedAttributes.OVERRIDE && template.attributes().isTouched()) { backups.clear(); } for (BackupConfiguration bc : template.allBackups()) { BackupConfigurationBuilder bcb = new BackupConfigurationBuilder(getBuilder()); bcb.read(bc, combine); backups.removeIf(b -> b.site().equals(bcb.site())); // no-op in case of Combine.Children.OVERRIDE backups.add(bcb); } return this; } @Override public AttributeSet attributes() { return attributes; } }
6,033
32.898876
121
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/PersistenceConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.PersistenceConfiguration.AVAILABILITY_INTERVAL; import static org.infinispan.configuration.cache.PersistenceConfiguration.CONNECTION_ATTEMPTS; import static org.infinispan.configuration.cache.PersistenceConfiguration.PASSIVATION; import static org.infinispan.util.logging.Log.CONFIG; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.ConfigurationUtils; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfigurationBuilder; /** * Configuration for cache stores. * */ public class PersistenceConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<PersistenceConfiguration> { private final List<StoreConfigurationBuilder<?, ?>> stores = new ArrayList<>(2); private final AttributeSet attributes; protected PersistenceConfigurationBuilder(ConfigurationBuilder builder) { super(builder); attributes = PersistenceConfiguration.attributeDefinitionSet(); } @Override public AttributeSet attributes() { return attributes; } public PersistenceConfigurationBuilder passivation(boolean b) { attributes.attribute(PASSIVATION).set(b); return this; } /** * @param interval The time, in milliseconds, between availability checks to determine if the PersistenceManager * is available. In other words, this interval sets how often stores/loaders are polled via their * `org.infinispan.persistence.spi.CacheWriter#isAvailable` or * `org.infinispan.persistence.spi.CacheLoader#isAvailable` implementation. If a single store/loader is * not available, an exception is thrown during cache operations. */ public PersistenceConfigurationBuilder availabilityInterval(int interval) { attributes.attribute(AVAILABILITY_INTERVAL).set(interval); return this; } /** * @param attempts The maximum number of unsuccessful attempts to start each of the configured CacheWriter/CacheLoader * before an exception is thrown and the cache fails to start. */ public PersistenceConfigurationBuilder connectionAttempts(int attempts) { attributes.attribute(CONNECTION_ATTEMPTS).set(attempts); return this; } /** * @param interval The time, in milliseconds, to wait between subsequent connection attempts on startup. A negative * or zero value means no wait between connection attempts. */ @Deprecated public PersistenceConfigurationBuilder connectionInterval(int interval) { // Ignore return this; } /** * If true, data is written to the cache store only when it is evicted from memory, which is known as 'passivation'. * When the data is requested again it is activated, which returns the data to memory and removes it from the * persistent store. As a result, you can overflow data to disk, similarly to swapping in an operating system. <br /> * <br /> * If false, the cache store contains a copy of the contents in memory. Write operations to the cache result in * writes to the cache store, which is equivalent to a 'write-through' configuration. */ boolean passivation() { return attributes.attribute(PASSIVATION).get(); } /** * Adds a cache loader that uses the specified builder class to build its configuration. */ public <T extends StoreConfigurationBuilder<?, ?>> T addStore(Class<T> klass) { T builder = getBuilderFromClass(klass); this.stores.add(builder); return builder; } private <T extends StoreConfigurationBuilder<?, ?>> T getBuilderFromClass(Class<T> klass) { try { Constructor<T> constructor = klass.getDeclaredConstructor(PersistenceConfigurationBuilder.class); return constructor.newInstance(this); } catch (Exception e) { throw new CacheConfigurationException("Could not instantiate loader configuration builder '" + klass.getName() + "'", e); } } /** * Adds a cache loader that uses the specified builder instance to build its configuration. * * @param builder is an instance of {@link StoreConfigurationBuilder}. */ public StoreConfigurationBuilder<?, ?> addStore(StoreConfigurationBuilder<?, ?> builder) { this.stores.add(builder); return builder; } /** * Adds a cluster cache loader. * @deprecated since 11.0. To be removed in 14.0 ISPN-11864 with no direct replacement. */ @Deprecated public ClusterLoaderConfigurationBuilder addClusterLoader() { ClusterLoaderConfigurationBuilder builder = new ClusterLoaderConfigurationBuilder(this); this.stores.add(builder); return builder; } /** * Adds a single file cache store. * @deprecated since 13.0. To be removed in 14.0 has been replaced by {@link #addSoftIndexFileStore()} */ @Deprecated public SingleFileStoreConfigurationBuilder addSingleFileStore() { SingleFileStoreConfigurationBuilder builder = new SingleFileStoreConfigurationBuilder(this); this.stores.add(builder); return builder; } /** * Adds a soft index file cache store. * @return the configuration for a soft index file store */ public SoftIndexFileStoreConfigurationBuilder addSoftIndexFileStore() { SoftIndexFileStoreConfigurationBuilder builder = new SoftIndexFileStoreConfigurationBuilder(this); this.stores.add(builder); return builder; } /** * Removes any configured stores from this builder. */ public PersistenceConfigurationBuilder clearStores() { this.stores.clear(); return this; } @Override public void validate() { boolean isLocalCache = builder.clustering().create().cacheMode().equals(CacheMode.LOCAL); int numPreload = 0; for (StoreConfigurationBuilder<?, ?> b : stores) { b.validate(); StoreConfiguration storeConfiguration = b.create(); if (storeConfiguration.shared()) { if (b.persistence().passivation()) { throw CONFIG.passivationStoreCannotBeShared(storeConfiguration.getClass().getSimpleName()); } if (storeConfiguration.purgeOnStartup()) { throw CONFIG.sharedStoreShouldNotBePurged(storeConfiguration.getClass().getSimpleName()); } } else if (storeConfiguration.transactional() && !isLocalCache) { throw CONFIG.clusteredTransactionalStoreMustBeShared(storeConfiguration.getClass().getSimpleName()); } if (storeConfiguration.async().enabled() && storeConfiguration.transactional()) { throw CONFIG.transactionalStoreCannotBeAsync(storeConfiguration.getClass().getSimpleName()); } if (storeConfiguration.preload()) { numPreload++; } } if (numPreload > 1) { throw CONFIG.onlyOnePreloadStoreAllowed(); } // If a store is present, the reaper expiration thread must be enabled. if (!stores.isEmpty()) { boolean reaperEnabled = builder.expiration().reaperEnabled(); long wakeupInterval = builder.expiration().wakeupInterval(); if (!reaperEnabled || wakeupInterval < 0) { builder.expiration().enableReaper(); if (wakeupInterval < 0) { CONFIG.debug("Store present and expiration reaper wakeup was less than 0 - explicitly enabling and setting " + "wakeup interval to 1 minute."); builder.expiration().wakeUpInterval(1, TimeUnit.MINUTES); } else { CONFIG.debug("Store present however expiration reaper was not enabled - explicitly enabling."); } } } } @Override public void validate(GlobalConfiguration globalConfig) { for (StoreConfigurationBuilder<?, ?> b : stores) { b.validate(globalConfig); } } @Override public PersistenceConfiguration create() { List<StoreConfiguration> stores = new ArrayList<>(this.stores.size()); for (StoreConfigurationBuilder<?, ?> loader : this.stores) stores.add(loader.create()); return new PersistenceConfiguration(attributes.protect(), stores); } @SuppressWarnings("unchecked") @Override public PersistenceConfigurationBuilder read(PersistenceConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); if (combine.repeatedAttributes() == Combine.RepeatedAttributes.OVERRIDE && template.attributes().isTouched()) { clearStores(); } for (StoreConfiguration c : template.stores()) { Class<? extends StoreConfigurationBuilder<?, ?>> builderClass = getBuilderClass(c); StoreConfigurationBuilder builder = this.getBuilderFromClass(builderClass); stores.add((StoreConfigurationBuilder) builder.read(c, combine)); } return this; } private Class<? extends StoreConfigurationBuilder<?, ?>> getBuilderClass(StoreConfiguration c) { Class<? extends StoreConfigurationBuilder<?, ?>> builderClass = (Class<? extends StoreConfigurationBuilder<?, ?>>) ConfigurationUtils.builderForNonStrict(c); if (builderClass == null) { builderClass = CustomStoreConfigurationBuilder.class; } return builderClass; } public List<StoreConfigurationBuilder<?, ?>> stores() { return stores; } @Override public String toString() { return "PersistenceConfigurationBuilder [stores=" + stores + ", attributes=" + attributes + "]"; } }
10,080
39.649194
163
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/PersistenceConfigurationChildBuilder.java
package org.infinispan.configuration.cache; public interface PersistenceConfigurationChildBuilder extends ConfigurationChildBuilder { @Override PersistenceConfigurationBuilder persistence(); }
202
21.555556
89
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/TransactionMode.java
package org.infinispan.configuration.cache; /** * Transaction mode * * @author Galder Zamarreño * @version 7.0 */ public enum TransactionMode { NONE, NON_XA, NON_DURABLE_XA, FULL_XA; public org.infinispan.transaction.TransactionMode getMode() { return this == NONE ? org.infinispan.transaction.TransactionMode.NON_TRANSACTIONAL : org.infinispan.transaction.TransactionMode.TRANSACTIONAL; } public boolean isXAEnabled() { return this == FULL_XA || this == NON_DURABLE_XA; } public boolean isRecoveryEnabled() { return this == FULL_XA; } }
612
20.892857
74
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/IndexMergeConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.IndexMergeConfiguration.CALIBRATE_BY_DELETES; import static org.infinispan.configuration.cache.IndexMergeConfiguration.FACTOR; import static org.infinispan.configuration.cache.IndexMergeConfiguration.MAX_ENTRIES; import static org.infinispan.configuration.cache.IndexMergeConfiguration.MAX_FORCED_SIZE; import static org.infinispan.configuration.cache.IndexMergeConfiguration.MAX_SIZE; import static org.infinispan.configuration.cache.IndexMergeConfiguration.MIN_SIZE; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeSet; /** * @since 12.0 */ public class IndexMergeConfigurationBuilder extends AbstractIndexingConfigurationChildBuilder implements Builder<IndexMergeConfiguration> { private final AttributeSet attributes; private final Attribute<Integer> maxEntries; private final Attribute<Integer> factor; private final Attribute<Integer> minSize; private final Attribute<Integer> maxSize; private final Attribute<Integer> maxForceSize; private final Attribute<Boolean> calibrateByDeletes; IndexMergeConfigurationBuilder(IndexingConfigurationBuilder builder) { super(builder); this.attributes = IndexMergeConfiguration.attributeDefinitionSet(); this.maxEntries = attributes.attribute(MAX_ENTRIES); this.factor = attributes.attribute(FACTOR); this.minSize = attributes.attribute(MIN_SIZE); this.maxSize = attributes.attribute(MAX_SIZE); this.maxForceSize = attributes.attribute(MAX_FORCED_SIZE); this.calibrateByDeletes = attributes.attribute(CALIBRATE_BY_DELETES); } @Override public AttributeSet attributes() { return attributes; } public IndexMergeConfigurationBuilder maxEntries(int value) { maxEntries.set(value); return this; } public IndexMergeConfigurationBuilder factor(int value) { factor.set(value); return this; } public Integer factor() { return factor.get(); } public IndexMergeConfigurationBuilder minSize(int value) { minSize.set(value); return this; } public Integer minSize() { return minSize.get(); } public IndexMergeConfigurationBuilder maxSize(int value) { maxSize.set(value); return this; } public IndexMergeConfigurationBuilder maxForcedSize(int value) { maxForceSize.set(value); return this; } public IndexMergeConfigurationBuilder calibrateByDeletes(boolean value) { calibrateByDeletes.set(value); return this; } @Override public IndexMergeConfiguration create() { return new IndexMergeConfiguration(attributes.protect()); } @Override public IndexMergeConfigurationBuilder read(IndexMergeConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); return this; } }
3,092
31.904255
98
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/AbstractConfigurationChildBuilder.java
package org.infinispan.configuration.cache; abstract class AbstractConfigurationChildBuilder implements ConfigurationChildBuilder { protected final ConfigurationBuilder builder; protected AbstractConfigurationChildBuilder(ConfigurationBuilder builder) { this.builder = builder; } @Override public ConfigurationChildBuilder template(boolean template) { return builder.template(template); } public ConfigurationChildBuilder simpleCache(boolean simpleCache) { return builder.simpleCache(simpleCache); } @Override public boolean simpleCache() { return builder.simpleCache(); } @Override public ClusteringConfigurationBuilder clustering() { return builder.clustering(); } /** * @deprecated Since 10.0, custom interceptors support will be removed and only modules will be able to define interceptors */ @Deprecated @Override public CustomInterceptorsConfigurationBuilder customInterceptors() { return builder.customInterceptors(); } @Override public EncodingConfigurationBuilder encoding() { return builder.encoding(); } @Override public ExpirationConfigurationBuilder expiration() { return builder.expiration(); } @Override public QueryConfigurationBuilder query() { return builder.query(); } @Override public IndexingConfigurationBuilder indexing() { return builder.indexing(); } @Override public InvocationBatchingConfigurationBuilder invocationBatching() { return builder.invocationBatching(); } @Override public StatisticsConfigurationBuilder statistics() { return builder.statistics(); } @Override public PersistenceConfigurationBuilder persistence() { return builder.persistence(); } @Override public LockingConfigurationBuilder locking() { return builder.locking(); } @Override public SecurityConfigurationBuilder security() { return builder.security(); } @Override public TransactionConfigurationBuilder transaction() { return builder.transaction(); } @Override public UnsafeConfigurationBuilder unsafe() { return builder.unsafe(); } @Override public SitesConfigurationBuilder sites() { return builder.sites(); } @Override public MemoryConfigurationBuilder memory() { return builder.memory(); } protected ConfigurationBuilder getBuilder() { return builder; } @Override public Configuration build() { return builder.build(); } }
2,578
21.622807
126
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/IndexReaderConfiguration.java
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Element; /** * @since 12.0 */ public class IndexReaderConfiguration extends ConfigurationElement<IndexReaderConfiguration> { public static final AttributeDefinition<Long> REFRESH_INTERVAL = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.REFRESH_INTERVAL, 0L, Long.class).immutable().build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(IndexReaderConfiguration.class, REFRESH_INTERVAL); } private final Attribute<Long> refreshInternal; IndexReaderConfiguration(AttributeSet attributes) { super(Element.INDEX_READER, attributes); this.refreshInternal = attributes.attribute(REFRESH_INTERVAL); } public long getRefreshInterval() { return refreshInternal.get(); } }
1,160
35.28125
138
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/CustomStoreConfiguration.java
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSerializer; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.parsing.Element; public class CustomStoreConfiguration extends AbstractStoreConfiguration<CustomStoreConfiguration> { public static final AttributeDefinition<Class> CUSTOM_STORE_CLASS = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.CLASS, null, Class.class).serializer(AttributeSerializer.CLASS_NAME).immutable().build(); public static AttributeSet attributeDefinitionSet() { return new AttributeSet(CustomStoreConfiguration.class, AbstractStoreConfiguration.attributeDefinitionSet(), CUSTOM_STORE_CLASS); } private final Attribute<Class> customStoreClass; public CustomStoreConfiguration(AttributeSet attributes, AsyncStoreConfiguration async) { super(Element.STORE, attributes, async); this.customStoreClass = attributes.attribute(CUSTOM_STORE_CLASS); } public Class<?> customStoreClass() { return customStoreClass.get(); } }
1,278
46.37037
235
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/InterceptorConfiguration.java
package org.infinispan.configuration.cache; import static org.infinispan.commons.configuration.attributes.IdentityAttributeCopier.identityCopier; import org.infinispan.commons.configuration.AbstractTypedPropertiesConfiguration; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSerializer; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.util.Util; import org.infinispan.configuration.parsing.Element; import org.infinispan.interceptors.AsyncInterceptor; /** * Describes a custom interceptor */ public class InterceptorConfiguration extends AbstractTypedPropertiesConfiguration { /** * Positional placing of a new custom interceptor */ public enum Position { /** * Specifies that the new interceptor is placed first in the chain. */ FIRST, /** * Specifies that the new interceptor is placed last in the chain. The new interceptor is added right before the * last interceptor in the chain. The very last interceptor is owned by Infinispan and cannot be replaced. */ LAST, /** * Specifies that the new interceptor can be placed anywhere, except first or last. */ OTHER_THAN_FIRST_OR_LAST } public static final AttributeDefinition<Position> POSITION = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.POSITION, Position.OTHER_THAN_FIRST_OR_LAST).immutable().build(); public static final AttributeDefinition<Class> AFTER = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.AFTER, null, Class.class) .serializer(AttributeSerializer.INSTANCE_CLASS_NAME).immutable().build(); public static final AttributeDefinition<Class> BEFORE = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.BEFORE, null, Class.class) .serializer(AttributeSerializer.INSTANCE_CLASS_NAME).immutable().build(); public static final AttributeDefinition<AsyncInterceptor> INTERCEPTOR = AttributeDefinition.builder(Element.INTERCEPTOR, null, AsyncInterceptor.class) .copier(identityCopier()).immutable().build(); public static final AttributeDefinition<Class> INTERCEPTOR_CLASS = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.CLASS, null, Class.class) .serializer(AttributeSerializer.INSTANCE_CLASS_NAME).immutable().build(); public static final AttributeDefinition<Integer> INDEX = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.INDEX, -1).immutable().build(); public static AttributeSet attributeDefinitionSet() { return new AttributeSet(InterceptorConfiguration.class, AbstractTypedPropertiesConfiguration.attributeSet(), POSITION, AFTER, BEFORE, INTERCEPTOR, INTERCEPTOR_CLASS, INDEX); } private final Attribute<Position> position; private final Attribute<Class> after; private final Attribute<Class> before; private final Attribute<AsyncInterceptor> interceptor; private final Attribute<Class> interceptorClass; private final Attribute<Integer> index; InterceptorConfiguration(AttributeSet attributes) { super(attributes); position = attributes.attribute(POSITION); after = attributes.attribute(AFTER); before = attributes.attribute(BEFORE); interceptor = attributes.attribute(INTERCEPTOR); interceptorClass = attributes.attribute(INTERCEPTOR_CLASS); index = attributes.attribute(INDEX); } @SuppressWarnings("unchecked") public Class<? extends AsyncInterceptor> after() { return after.get(); } @SuppressWarnings("unchecked") public Class<? extends AsyncInterceptor> before() { return before.get(); } public AsyncInterceptor asyncInterceptor() { if (interceptor.isNull()) { return (AsyncInterceptor) Util.getInstance(interceptorClass.get()); } else { return interceptor.get(); } } public Class<? extends AsyncInterceptor> sequentialInterceptorClass() { return interceptorClass.get(); } public int index() { return index.get(); } public Position position() { return position.get(); } public boolean first() { return position() == Position.FIRST; } public boolean last() { return position() == Position.LAST; } public AttributeSet attributes() { return attributes; } @Override public String toString() { return "InterceptorConfiguration [attributes=" + attributes + "]"; } }
4,690
39.439655
204
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/LockingConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.LockingConfiguration.CONCURRENCY_LEVEL; import static org.infinispan.configuration.cache.LockingConfiguration.ISOLATION_LEVEL; import static org.infinispan.configuration.cache.LockingConfiguration.LOCK_ACQUISITION_TIMEOUT; import static org.infinispan.configuration.cache.LockingConfiguration.USE_LOCK_STRIPING; import java.util.concurrent.TimeUnit; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.util.concurrent.IsolationLevel; /** * Defines the local, in-VM locking and concurrency characteristics of the cache. * * @author pmuir * */ public class LockingConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<LockingConfiguration> { private final AttributeSet attributes; protected LockingConfigurationBuilder(ConfigurationBuilder builder) { super(builder); attributes = LockingConfiguration.attributeDefinitionSet(); } @Override public AttributeSet attributes() { return attributes; } /** * Concurrency level for lock containers. Adjust this value according to the number of concurrent * threads interacting with Infinispan. Similar to the concurrencyLevel tuning parameter seen in * the JDK's ConcurrentHashMap. */ public LockingConfigurationBuilder concurrencyLevel(int i) { attributes.attribute(CONCURRENCY_LEVEL).set(i); return this; } /** * Cache isolation level. Infinispan only supports READ_COMMITTED or REPEATABLE_READ isolation * levels. See <a href= * 'http://en.wikipedia.org/wiki/Isolation_level'>http://en.wikipedia.org/wiki/Isolation_level</a * > for a discussion on isolation levels. */ public LockingConfigurationBuilder isolationLevel(IsolationLevel isolationLevel) { attributes.attribute(ISOLATION_LEVEL).set(isolationLevel); return this; } public IsolationLevel isolationLevel() { return attributes.attribute(ISOLATION_LEVEL).get(); } /** * Maximum time to attempt a particular lock acquisition */ public LockingConfigurationBuilder lockAcquisitionTimeout(long l) { attributes.attribute(LOCK_ACQUISITION_TIMEOUT).set(l); return this; } /** * Maximum time to attempt a particular lock acquisition */ public LockingConfigurationBuilder lockAcquisitionTimeout(long l, TimeUnit unit) { return lockAcquisitionTimeout(unit.toMillis(l)); } /** * If true, a pool of shared locks is maintained for all entries that need to be locked. * Otherwise, a lock is created per entry in the cache. Lock striping helps control memory * footprint but may reduce concurrency in the system. */ public LockingConfigurationBuilder useLockStriping(boolean b) { attributes.attribute(USE_LOCK_STRIPING).set(b); return this; } @Override public void validate() { Attribute<IsolationLevel> isolationLevel = attributes.attribute(ISOLATION_LEVEL); if (getBuilder().clustering().cacheMode().isClustered() && isolationLevel.get() == IsolationLevel.NONE) isolationLevel.set(IsolationLevel.READ_COMMITTED); if (isolationLevel.get() == IsolationLevel.READ_UNCOMMITTED) isolationLevel.set(IsolationLevel.READ_COMMITTED); if (isolationLevel.get() == IsolationLevel.SERIALIZABLE) isolationLevel.set(IsolationLevel.REPEATABLE_READ); } @Override public void validate(GlobalConfiguration globalConfig) { } @Override public LockingConfiguration create() { return new LockingConfiguration(attributes.protect()); } @Override public LockingConfigurationBuilder read(LockingConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); return this; } @Override public String toString() { return this.getClass().getSimpleName() + "[" + attributes + "]"; } }
4,228
34.241667
125
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/IndexMergeConfiguration.java
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Attribute; import org.infinispan.configuration.parsing.Element; /** * @since 12.0 */ public class IndexMergeConfiguration extends ConfigurationElement<IndexMergeConfiguration> { public static final AttributeDefinition<Integer> MAX_ENTRIES = AttributeDefinition.builder(Attribute.MAX_ENTRIES, null, Integer.class).immutable().build(); public static final AttributeDefinition<Integer> FACTOR = AttributeDefinition.builder(Attribute.FACTOR, null, Integer.class).immutable().build(); public static final AttributeDefinition<Integer> MIN_SIZE = AttributeDefinition.builder(Attribute.MIN_SIZE, null, Integer.class).immutable().build(); public static final AttributeDefinition<Integer> MAX_SIZE = AttributeDefinition.builder(Attribute.MAX_SIZE, null, Integer.class).immutable().build(); public static final AttributeDefinition<Integer> MAX_FORCED_SIZE = AttributeDefinition.builder(Attribute.MAX_FORCED_SIZE, null, Integer.class).immutable().build(); public static final AttributeDefinition<Boolean> CALIBRATE_BY_DELETES = AttributeDefinition.builder(Attribute.CALIBRATE_BY_DELETES, null, Boolean.class).immutable().build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(IndexMergeConfiguration.class, MAX_ENTRIES, FACTOR, MIN_SIZE, MAX_SIZE, MAX_FORCED_SIZE, CALIBRATE_BY_DELETES); } IndexMergeConfiguration(AttributeSet attributes) { super(Element.INDEX_MERGE, attributes); } public Integer maxEntries() { return attributes.attribute(MAX_ENTRIES).get(); } public Integer factor() { return attributes.attribute(FACTOR).get(); } public Integer minSize() { return attributes.attribute(MIN_SIZE).get(); } public Integer maxSize() { return attributes.attribute(MAX_SIZE).get(); } public Integer maxForcedSize() { return attributes.attribute(MAX_FORCED_SIZE).get(); } public Boolean calibrateByDeletes() { return attributes.attribute(CALIBRATE_BY_DELETES).get(); } }
2,384
38.75
118
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/CacheMode.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.parsing.Element.DISTRIBUTED_CACHE; import static org.infinispan.configuration.parsing.Element.DISTRIBUTED_CACHE_CONFIGURATION; import static org.infinispan.configuration.parsing.Element.INVALIDATION_CACHE; import static org.infinispan.configuration.parsing.Element.INVALIDATION_CACHE_CONFIGURATION; import static org.infinispan.configuration.parsing.Element.LOCAL_CACHE; import static org.infinispan.configuration.parsing.Element.LOCAL_CACHE_CONFIGURATION; import static org.infinispan.configuration.parsing.Element.REPLICATED_CACHE; import static org.infinispan.configuration.parsing.Element.REPLICATED_CACHE_CONFIGURATION; import org.infinispan.configuration.parsing.Element; import org.infinispan.protostream.annotations.ProtoEnumValue; /** * Cache replication mode. */ public enum CacheMode { /** * Data is not replicated. */ @ProtoEnumValue(number = 0) LOCAL, /** * Data replicated synchronously. */ @ProtoEnumValue(number = 1) REPL_SYNC, /** * Data replicated asynchronously. */ @ProtoEnumValue(number = 2) REPL_ASYNC, /** * Data invalidated synchronously. */ @ProtoEnumValue(number = 3) INVALIDATION_SYNC, /** * Data invalidated asynchronously. */ @ProtoEnumValue(number = 4) INVALIDATION_ASYNC, /** * Synchronous DIST */ @ProtoEnumValue(number = 5) DIST_SYNC, /** * Async DIST */ @ProtoEnumValue(number = 6) DIST_ASYNC; private static final CacheMode[] cachedValues = values(); public static CacheMode valueOf(int order) { return cachedValues[order]; } public static CacheMode of(CacheType cacheType, boolean sync) { switch (cacheType) { case REPLICATION: return sync ? REPL_SYNC : REPL_ASYNC; case DISTRIBUTION: return sync ? DIST_SYNC : DIST_ASYNC; case INVALIDATION: return sync ? INVALIDATION_SYNC : INVALIDATION_ASYNC; case LOCAL: default: return LOCAL; } } /** * Returns true if the mode is invalidation, either sync or async. */ public boolean isInvalidation() { return this == INVALIDATION_SYNC || this == INVALIDATION_ASYNC; } public boolean isSynchronous() { return this == REPL_SYNC || this == DIST_SYNC || this == INVALIDATION_SYNC || this == LOCAL; } public boolean isClustered() { return this != LOCAL; } public boolean isDistributed() { return this == DIST_SYNC || this == DIST_ASYNC; } public boolean isReplicated() { return this == REPL_SYNC || this == REPL_ASYNC; } public boolean needsStateTransfer() { return isReplicated() || isDistributed(); } public CacheMode toSync() { switch (this) { case REPL_ASYNC: return REPL_SYNC; case INVALIDATION_ASYNC: return INVALIDATION_SYNC; case DIST_ASYNC: return DIST_SYNC; default: return this; } } public CacheMode toSync(boolean sync) { return sync ? toSync() : toAsync(); } public CacheMode toAsync() { switch (this) { case REPL_SYNC: return REPL_ASYNC; case INVALIDATION_SYNC: return INVALIDATION_ASYNC; case DIST_SYNC: return DIST_ASYNC; default: return this; } } public String friendlyCacheModeString() { switch (this) { case REPL_SYNC: case REPL_ASYNC: return "REPLICATED"; case INVALIDATION_SYNC: case INVALIDATION_ASYNC: return "INVALIDATED"; case DIST_SYNC: case DIST_ASYNC: return "DISTRIBUTED"; case LOCAL: return "LOCAL"; } throw new IllegalArgumentException("Unknown cache mode " + this); } public String toCacheType() { switch (this) { case DIST_SYNC: case DIST_ASYNC: return DISTRIBUTED_CACHE.getLocalName(); case REPL_SYNC: case REPL_ASYNC: return REPLICATED_CACHE.getLocalName(); case INVALIDATION_SYNC: case INVALIDATION_ASYNC: return INVALIDATION_CACHE.getLocalName(); default: return LOCAL_CACHE.getLocalName(); } } public Element toElement(boolean template) { switch (this) { case DIST_SYNC: case DIST_ASYNC: return template ? DISTRIBUTED_CACHE_CONFIGURATION : DISTRIBUTED_CACHE; case REPL_SYNC: case REPL_ASYNC: return template ? REPLICATED_CACHE_CONFIGURATION : REPLICATED_CACHE; case INVALIDATION_SYNC: case INVALIDATION_ASYNC: return template ? INVALIDATION_CACHE_CONFIGURATION : INVALIDATION_CACHE; default: return template ? LOCAL_CACHE_CONFIGURATION : LOCAL_CACHE; } } public CacheType cacheType() { switch (this) { case DIST_ASYNC: case DIST_SYNC: return CacheType.DISTRIBUTION; case REPL_ASYNC: case REPL_SYNC: return CacheType.REPLICATION; case INVALIDATION_ASYNC: case INVALIDATION_SYNC: return CacheType.INVALIDATION; case LOCAL: default: return CacheType.LOCAL; } } }
5,459
25.634146
98
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/StoreConfigurationChildBuilder.java
package org.infinispan.configuration.cache; import java.util.Properties; import org.infinispan.persistence.spi.MarshallableEntry; public interface StoreConfigurationChildBuilder<S> extends ConfigurationChildBuilder { /** * Configuration for the async cache store. If enabled, this provides you with asynchronous * writes to the cache store, giving you 'write-behind' caching. */ AsyncStoreConfigurationBuilder<S> async(); /** * If true, fetch persistent state when joining a cluster. If multiple cache stores are chained, * only one of them can have this property enabled. Persistent state transfer with a shared cache * store does not make sense, as the same persistent store that provides the data will just end * up receiving it. Therefore, if a shared cache store is used, the cache will not allow a * persistent state transfer even if a cache store has this property set to true. Finally, * setting it to true only makes sense if in a clustered environment. * * @deprecated since 14.0. This method does nothing. Only the first non shared store that supports publishEntries is used for state transfer. */ @Deprecated S fetchPersistentState(boolean b); /** * If true, any operation that modifies the cache (put, remove, clear, store...etc) won't be * applied to the cache store. This means that the cache store could become out of sync with the * cache. */ S ignoreModifications(boolean b); /** * If true, purges this cache store when it starts up. */ S purgeOnStartup(boolean b); /** * If true, this cache store will be only used to write entries. */ S writeOnly(boolean b); /** * If true, when the cache starts, data stored in the cache store will be pre-loaded into memory. * If multiple cache stores are chained, only one of them can have this property enabled. * This is particularly useful when data in the cache store will be needed immediately after * startup and you want to avoid cache operations being delayed as a result of loading this data * lazily. Can be used to provide a 'warm-cache' on startup, however there is a performance * penalty as startup time is affected by this process. */ S preload(boolean b); /** * This setting should be set to true when multiple cache instances share the same cache store * (e.g., multiple nodes in a cluster using a JDBC-based CacheStore pointing to the same, shared * database.) Setting this to true avoids multiple cache instances writing the same modification * multiple times. If enabled, only the node where the modification originated will write to the * cache store. * <p/> * If disabled, each individual cache reacts to a potential remote update by storing the data to * the cache store. Note that this could be useful if each individual node has its own cache * store - perhaps local on-disk. */ S shared(boolean b); /** * This setting should be set to true when the underlying cache store supports transactions and it is desirable for * the underlying store and the cache to remain synchronized. With this enabled any Exceptions thrown whilst writing * to the underlying store will result in both the store's and the cache's transaction rollingback. * <p/> * If enabled and this store is shared, then writes to this store will be performed at prepare time of the Infinispan Tx. * If an exception is encountered by the store during prepare time, then this will result in the global Tx being * rolledback along with this stores writes, otherwise writes to this store will be committed during the commit * phase of 2PC. If this is not enabled, then writes to the cache store are performed during the commit phase of a Tx. *<p/> * Note that this requires {@link #shared(boolean)} to be set to true. */ S transactional(boolean b); /** * The maximum size of a batch to be inserted/deleted from the store. If the value is less than one, then no upper limit is placed on the number of operations in a batch. */ S maxBatchSize(int maxBatchSize); /** * If true this store should either be non shared (segmenting can be done automatically for non shared stores) or * the shared store must implement the {@link org.infinispan.persistence.spi.SegmentedAdvancedLoadWriteStore} interface. * Segmented stores help performance for things that require viewing the entire contents of the store (eg. iteration, * stream processing, state transfer, mass indexer). If the store doesn't provide constant time operations for methods * such as {@link org.infinispan.persistence.spi.CacheLoader#loadEntry(Object)} or * {@link org.infinispan.persistence.spi.CacheWriter#write(MarshallableEntry)} than segmenting this store could also * improve performance of those operations. * @param b whether this store should be segmented * @return this */ S segmented(boolean b); /** * <p> * Defines a single property. Can be used multiple times to define all needed properties, but the * full set is overridden by {@link #withProperties(java.util.Properties)}. * </p> * <p> * These properties are passed directly to the cache store. * </p> */ S addProperty(String key, String value); /** * Properties passed to the cache store or loader */ S withProperties(Properties p); }
5,472
46.181034
173
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/IndexingMode.java
package org.infinispan.configuration.cache; import java.util.EnumSet; import org.infinispan.commons.logging.Log; /** * Affects how cache operations will be propagated to the indexes. * By default, {@link #AUTO}. * * @author Fabio Massimo Ercoli &lt;fabiomassimo.ercoli@gmail.com&gt; * @since 15.0 */ public enum IndexingMode { /** * All the changes to the cache will be immediately applied to the indexes. */ AUTO, /** * Indexes will be only updated when a reindex is explicitly invoked. */ MANUAL; public static IndexingMode requireValid(String value) { try { return IndexingMode.valueOf(value.toUpperCase()); } catch (IllegalArgumentException e) { throw Log.CONFIG.illegalEnumValue(value, EnumSet.allOf(IndexingMode.class)); } } }
815
23
85
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/TransactionConfigurationChildBuilder.java
package org.infinispan.configuration.cache; public interface TransactionConfigurationChildBuilder extends ConfigurationChildBuilder { RecoveryConfigurationBuilder recovery(); }
183
22
89
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/RecoveryConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.RecoveryConfiguration.ENABLED; import static org.infinispan.configuration.cache.RecoveryConfiguration.RECOVERY_INFO_CACHE_NAME; import static org.infinispan.util.logging.Log.CONFIG; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.transaction.TransactionMode; /** * Defines recovery configuration for the cache. * * @author pmuir * */ public class RecoveryConfigurationBuilder extends AbstractTransportConfigurationChildBuilder implements Builder<RecoveryConfiguration> { private final AttributeSet attributes; RecoveryConfigurationBuilder(TransactionConfigurationBuilder builder) { super(builder); attributes = RecoveryConfiguration.attributeDefinitionSet(); } @Override public AttributeSet attributes() { return attributes; } /** * Enable recovery for this cache */ public RecoveryConfigurationBuilder enable() { attributes.attribute(ENABLED).set(true); return this; } /** * Disable recovery for this cache */ public RecoveryConfigurationBuilder disable() { attributes.attribute(ENABLED).set(false); return this; } /** * Enable recovery for this cache */ public RecoveryConfigurationBuilder enabled(boolean enabled) { attributes.attribute(ENABLED).set(enabled); return this; } boolean isEnabled() { return attributes.attribute(ENABLED).get(); } /** * Sets the name of the cache where recovery related information is held. If not specified * defaults to a cache named {@link RecoveryConfiguration#DEFAULT_RECOVERY_INFO_CACHE} */ public RecoveryConfigurationBuilder recoveryInfoCacheName(String recoveryInfoName) { attributes.attribute(RECOVERY_INFO_CACHE_NAME).set(recoveryInfoName); return this; } @Override public void validate() { if (!attributes.attribute(ENABLED).get()) { return; //nothing to validate } if (transaction().transactionMode() == TransactionMode.NON_TRANSACTIONAL) { throw CONFIG.recoveryNotSupportedWithNonTxCache(); } if (transaction().useSynchronization()) { throw CONFIG.recoveryNotSupportedWithSynchronization(); } } @Override public void validate(GlobalConfiguration globalConfig) { validate(); } @Override public RecoveryConfiguration create() { return new RecoveryConfiguration(attributes.protect()); } @Override public RecoveryConfigurationBuilder read(RecoveryConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); return this; } @Override public String toString() { return "RecoveryConfigurationBuilder [attributes=" + attributes + "]"; } }
3,048
27.764151
136
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/BackupConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.BackupConfiguration.FAILURE_POLICY; import static org.infinispan.configuration.cache.BackupConfiguration.FAILURE_POLICY_CLASS; import static org.infinispan.configuration.cache.BackupConfiguration.REPLICATION_TIMEOUT; import static org.infinispan.configuration.cache.BackupConfiguration.SITE; import static org.infinispan.configuration.cache.BackupConfiguration.STRATEGY; import static org.infinispan.configuration.cache.BackupConfiguration.USE_TWO_PHASE_COMMIT; import static org.infinispan.util.logging.Log.CONFIG; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.xsite.XSiteNamedCache; /** * @author Mircea.Markus@jboss.com * @since 5.2 */ public class BackupConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<BackupConfiguration> { private final AttributeSet attributes; private final XSiteStateTransferConfigurationBuilder stateTransferBuilder; private final TakeOfflineConfigurationBuilder takeOfflineBuilder; public BackupConfigurationBuilder(ConfigurationBuilder builder) { super(builder); attributes = BackupConfiguration.attributeDefinitionSet(); takeOfflineBuilder = new TakeOfflineConfigurationBuilder(builder, this); stateTransferBuilder = new XSiteStateTransferConfigurationBuilder(builder, this); } @Override public AttributeSet attributes() { return attributes; } /** * @param site Specifies the name of the backup location for this cache. The name must match a site defined in the * global configuration. */ public BackupConfigurationBuilder site(String site) { attributes.attribute(SITE).set(XSiteNamedCache.cachedString(site)); return this; } /** * @see #site(String) */ public String site() { return attributes.attribute(SITE).get(); } /** * If the failure policy is set to {@link BackupFailurePolicy#CUSTOM} then the failurePolicyClass is required and * should return the fully qualified name of a class implementing {@link CustomFailurePolicy} */ public String failurePolicyClass() { return attributes.attribute(FAILURE_POLICY_CLASS).get(); } /** * @see #failurePolicyClass() */ public BackupConfigurationBuilder failurePolicyClass(String failurePolicy) { attributes.attribute(FAILURE_POLICY_CLASS).set(failurePolicy); return this; } /** * Timeout(millis) used for replicating calls to other sites. */ public BackupConfigurationBuilder replicationTimeout(long replicationTimeout) { attributes.attribute(REPLICATION_TIMEOUT).set(replicationTimeout); return this; } /** * Sets the strategy used for backing up data: sync or async. Defaults to {@link * org.infinispan.configuration.cache.BackupConfiguration.BackupStrategy#ASYNC}. */ public BackupConfigurationBuilder strategy(BackupConfiguration.BackupStrategy strategy) { attributes.attribute(STRATEGY).set(strategy); return this; } /** * @see #strategy() */ public BackupConfiguration.BackupStrategy strategy() { return attributes.attribute(STRATEGY).get(); } public TakeOfflineConfigurationBuilder takeOffline() { return takeOfflineBuilder; } /** * Configures the policy for handling failed requests. Defaults to {@link BackupFailurePolicy#WARN} */ public BackupConfigurationBuilder backupFailurePolicy(BackupFailurePolicy backupFailurePolicy) { attributes.attribute(FAILURE_POLICY).set(backupFailurePolicy); return this; } /** * Controls if replication happens in a two phase commit (2PC) for synchronous backups. The default value is {@code * false}, which means replication happens in a one phase commit (1PC). */ public BackupConfigurationBuilder useTwoPhaseCommit(boolean useTwoPhaseCommit) { attributes.attribute(USE_TWO_PHASE_COMMIT).set(useTwoPhaseCommit); return this; } /** * Configures whether this site is used for backing up data or not (defaults to true). * @deprecated Since 14.0. To be removed without replacement. */ @Deprecated public BackupConfigurationBuilder enabled(boolean isEnabled) { return this; } public XSiteStateTransferConfigurationBuilder stateTransfer() { return this.stateTransferBuilder; } @Override public void validate() { takeOfflineBuilder.validate(); stateTransferBuilder.validate(); String siteName = attributes.attribute(SITE).get(); if (siteName == null) throw CONFIG.backupMissingSite(); BackupFailurePolicy policy = attributes.attribute(FAILURE_POLICY).get(); boolean asyncStrategy = strategy() == BackupConfiguration.BackupStrategy.ASYNC; boolean hasFailurePolicyClass = failurePolicyClass() != null; switch (policy) { case CUSTOM: if (!hasFailurePolicyClass) { throw CONFIG.missingBackupFailurePolicyClass(siteName); } if (asyncStrategy) { throw CONFIG.invalidPolicyWithAsyncStrategy(siteName, policy); } break; case WARN: case IGNORE: if (hasFailurePolicyClass) { throw CONFIG.failurePolicyClassNotCompatibleWith(siteName, policy); } break; case FAIL: if (hasFailurePolicyClass) { throw CONFIG.failurePolicyClassNotCompatibleWith(siteName, policy); } if (asyncStrategy) { throw CONFIG.invalidPolicyWithAsyncStrategy(siteName, policy); } break; default: throw new IllegalStateException("Unexpected backup policy " + policy + " for backup " + siteName); } if (attributes.attribute(USE_TWO_PHASE_COMMIT).get() && asyncStrategy) { throw CONFIG.twoPhaseCommitAsyncBackup(); } } @Override public void validate(GlobalConfiguration globalConfig) { takeOfflineBuilder.validate(globalConfig); stateTransferBuilder.validate(globalConfig); } @Override public BackupConfiguration create() { return new BackupConfiguration(attributes.protect(), takeOfflineBuilder.create(), stateTransferBuilder.create()); } @Override public BackupConfigurationBuilder read(BackupConfiguration template, Combine combine) { attributes.read(template.attributes(), combine); takeOfflineBuilder.read(template.takeOffline(), combine); stateTransferBuilder.read(template.stateTransfer(), combine); return this; } @Override public String toString() { return this.getClass().getSimpleName() + attributes; } }
6,997
34.704082
123
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/AuthorizationConfiguration.java
package org.infinispan.configuration.cache; import java.util.HashSet; import java.util.Set; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Element; /** * AuthorizationConfiguration. * * @author Tristan Tarrant * @since 7.0 */ public class AuthorizationConfiguration extends ConfigurationElement<AuthorizationConfiguration> { public static final AttributeDefinition<Boolean> ENABLED = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.ENABLED, false).immutable().build(); public static final AttributeDefinition<Set> ROLES = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.ROLES, null, Set.class).initializer(HashSet::new).build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(AuthorizationConfiguration.class, ENABLED, ROLES); } private final Attribute<Boolean> enabled; private final Attribute<Set> roles; AuthorizationConfiguration(AttributeSet attributes) { super(Element.AUTHORIZATION, attributes); enabled = attributes.attribute(ENABLED); roles = attributes.attribute(ROLES); } public boolean enabled() { return enabled.get(); } public Set<String> roles() { return roles.get(); } }
1,535
34.72093
189
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/CacheType.java
package org.infinispan.configuration.cache; /** * Cache replication mode. */ public enum CacheType { LOCAL, REPLICATION, INVALIDATION, DISTRIBUTION; private static final CacheType[] cachedValues = values(); public static CacheType valueOf(int order) { return cachedValues[order]; } }
317
15.736842
60
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/LoaderConfigurationChildBuilder.java
package org.infinispan.configuration.cache; /** * LoaderConfigurationBuilder is an interface which should be implemented by all cache loader builders * * @author Tristan Tarrant * @since 5.2 */ public interface LoaderConfigurationChildBuilder<S> extends PersistenceConfigurationChildBuilder { }
304
20.785714
102
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/AbstractStoreConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.AbstractStoreConfiguration.MAX_BATCH_SIZE; import static org.infinispan.configuration.cache.AbstractStoreConfiguration.PRELOAD; import static org.infinispan.configuration.cache.AbstractStoreConfiguration.PROPERTIES; import static org.infinispan.configuration.cache.AbstractStoreConfiguration.PURGE_ON_STARTUP; import static org.infinispan.configuration.cache.AbstractStoreConfiguration.READ_ONLY; import static org.infinispan.configuration.cache.AbstractStoreConfiguration.SEGMENTED; import static org.infinispan.configuration.cache.AbstractStoreConfiguration.SHARED; import static org.infinispan.configuration.cache.AbstractStoreConfiguration.TRANSACTIONAL; import static org.infinispan.configuration.cache.AbstractStoreConfiguration.WRITE_ONLY; import static org.infinispan.util.logging.Log.CONFIG; import java.util.Properties; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.ConfigurationFor; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.persistence.Store; import org.infinispan.commons.util.TypedProperties; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.persistence.spi.NonBlockingStore; import org.infinispan.persistence.spi.SegmentedAdvancedLoadWriteStore; public abstract class AbstractStoreConfigurationBuilder<T extends StoreConfiguration, S extends AbstractStoreConfigurationBuilder<T, S>> extends AbstractPersistenceConfigurationChildBuilder implements StoreConfigurationBuilder<T, S> { protected final AttributeSet attributes; protected final AsyncStoreConfigurationBuilder<S> async; public AbstractStoreConfigurationBuilder(PersistenceConfigurationBuilder builder, AttributeSet attributes) { super(builder); this.attributes = attributes; this.async = new AsyncStoreConfigurationBuilder(this); } public AbstractStoreConfigurationBuilder(PersistenceConfigurationBuilder builder, AttributeSet attributes, AttributeSet asyncAttributeSet) { super(builder); this.attributes = attributes; this.async = new AsyncStoreConfigurationBuilder(this, asyncAttributeSet); } /** * {@inheritDoc} */ @Override public AsyncStoreConfigurationBuilder<S> async() { return async; } /** * {@inheritDoc} * * @deprecated Deprecated since 14.0. There is no replacement. First non shared store is picked instead. */ @Deprecated @Override public S fetchPersistentState(boolean b) { return self(); } /** * {@inheritDoc} */ @Override public S ignoreModifications(boolean b) { attributes.attribute(READ_ONLY).set(b); return self(); } /** * If true, purges this cache store when it starts up. */ @Override public S purgeOnStartup(boolean b) { attributes.attribute(PURGE_ON_STARTUP).set(b); return self(); } @Override public S writeOnly(boolean b) { attributes.attribute(WRITE_ONLY).set(b); return self(); } public S properties(Properties properties) { attributes.attribute(PROPERTIES).set(new TypedProperties(properties)); return self(); } /** * {@inheritDoc} */ @Override public S addProperty(String key, String value) { TypedProperties properties = attributes.attribute(PROPERTIES).get(); properties.put(key, value); attributes.attribute(PROPERTIES).set(properties); return self(); } /** * {@inheritDoc} */ @Override public S withProperties(Properties props) { attributes.attribute(PROPERTIES).set(TypedProperties.toTypedProperties(props)); return self(); } /** * {@inheritDoc} */ @Override public S preload(boolean b) { attributes.attribute(PRELOAD).set(b); return self(); } /** * {@inheritDoc} */ @Override public S shared(boolean b) { attributes.attribute(SHARED).set(b); return self(); } /** * {@inheritDoc} */ @Override public S transactional(boolean b) { attributes.attribute(TRANSACTIONAL).set(b); return self(); } @Override public S maxBatchSize(int maxBatchSize) { attributes.attribute(MAX_BATCH_SIZE).set(maxBatchSize); return self(); } @Override public S segmented(boolean b) { attributes.attribute(SEGMENTED).set(b); return self(); } public AttributeSet attributes() { return attributes; } @Override public void validate() { validate(false); } protected void validate(boolean skipClassChecks) { if (!skipClassChecks) validateStoreWithAnnotations(); validateStoreAttributes(); } private void validateStoreAttributes() { async.validate(); boolean shared = attributes.attribute(SHARED).get(); boolean preload = attributes.attribute(PRELOAD).get(); boolean purgeOnStartup = attributes.attribute(PURGE_ON_STARTUP).get(); boolean transactional = attributes.attribute(TRANSACTIONAL).get(); boolean readOnly = attributes.attribute(READ_ONLY).get(); boolean writeOnly = attributes.attribute(WRITE_ONLY).get(); ConfigurationBuilder builder = getBuilder(); if (purgeOnStartup && preload) { throw CONFIG.preloadAndPurgeOnStartupConflict(); } if (readOnly && writeOnly) { throw CONFIG.storeBothReadAndWriteOnly(); } if (readOnly && (purgeOnStartup || shared || persistence().passivation())) { throw CONFIG.storeReadOnlyExceptions(); } if (writeOnly && preload) { throw CONFIG.storeWriteOnlyExceptions(); } if (shared && !builder.clustering().cacheMode().isClustered()) { throw CONFIG.sharedStoreWithLocalCache(); } if (transactional && !builder.transaction().transactionMode().isTransactional()) throw CONFIG.transactionalStoreInNonTransactionalCache(); if (transactional && builder.persistence().passivation()) throw CONFIG.transactionalStoreInPassivatedCache(); } private void validateStoreWithAnnotations() { Class configKlass = attributes.getKlass(); if (configKlass != null && configKlass.isAnnotationPresent(ConfigurationFor.class)) { Class storeKlass = ((ConfigurationFor) configKlass.getAnnotation(ConfigurationFor.class)).value(); if (storeKlass.isAnnotationPresent(Store.class)) { Store storeProps = (Store) storeKlass.getAnnotation(Store.class); boolean segmented = attributes.attribute(SEGMENTED).get(); if (segmented && !AbstractSegmentedStoreConfiguration.class.isAssignableFrom(configKlass) && !(SegmentedAdvancedLoadWriteStore.class.isAssignableFrom(storeKlass) || NonBlockingStore.class.isAssignableFrom(storeKlass))) { throw CONFIG.storeNotSegmented(storeKlass); } if (!storeProps.shared() && attributes.attribute(SHARED).get()) { throw CONFIG.nonSharedStoreConfiguredAsShared(storeKlass.getSimpleName()); } } } else { CONFIG.warnConfigurationForAnnotationMissing(attributes.getName()); } } @Override public void validate(GlobalConfiguration globalConfig) { } @Override public Builder<?> read(T template, Combine combine) { attributes.read(template.attributes(), combine); async.read(template.async(), combine); return this; } @Override public String toString() { return "AbstractStoreConfigurationBuilder [attributes=" + attributes + ", async=" + async + "]"; } }
7,816
31.570833
148
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/SecurityConfigurationChildBuilder.java
package org.infinispan.configuration.cache; public interface SecurityConfigurationChildBuilder extends ConfigurationChildBuilder { AuthorizationConfigurationBuilder authorization(); }
188
30.5
86
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/StoreConfigurationBuilder.java
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Self; /** * LoaderConfigurationBuilder is an interface which should be implemented by all cache loader builders * * @author Tristan Tarrant * @since 5.2 */ public interface StoreConfigurationBuilder<T extends StoreConfiguration, S extends StoreConfigurationBuilder<T, S>> extends Builder<T>, StoreConfigurationChildBuilder<S>, Self<S> { }
487
33.857143
180
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/JMXStatisticsConfigurationBuilder.java
package org.infinispan.configuration.cache; /** * Determines whether cache statistics are gathered. * * @author pmuir * @deprecated since 10.1.3. Use {@link StatisticsConfigurationBuilder} instead. This will be removed in next major * version. */ @Deprecated public abstract class JMXStatisticsConfigurationBuilder extends AbstractConfigurationChildBuilder { JMXStatisticsConfigurationBuilder(ConfigurationBuilder builder) { super(builder); } /** * Enable statistics gathering and reporting */ public abstract JMXStatisticsConfigurationBuilder enable(); /** * Disable statistics gathering and reporting */ public abstract JMXStatisticsConfigurationBuilder disable(); /** * Enable or disable statistics gathering and reporting */ public abstract JMXStatisticsConfigurationBuilder enabled(boolean enabled); /** * If set to false, statistics gathering cannot be enabled during runtime. Performance optimization. * * @deprecated since 10.1.3. This method will be removed in a future version. */ @Deprecated public abstract JMXStatisticsConfigurationBuilder available(boolean available); }
1,176
28.425
115
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/AuthorizationConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.AuthorizationConfiguration.ENABLED; import static org.infinispan.configuration.cache.AuthorizationConfiguration.ROLES; import static org.infinispan.util.logging.Log.CONFIG; import java.util.HashSet; import java.util.Set; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalAuthorizationConfiguration; import org.infinispan.configuration.global.GlobalConfiguration; /** * AuthorizationConfigurationBuilder. * * @author Tristan Tarrant * @since 7.0 */ public class AuthorizationConfigurationBuilder extends AbstractSecurityConfigurationChildBuilder implements Builder<AuthorizationConfiguration> { private final AttributeSet attributes; public AuthorizationConfigurationBuilder(SecurityConfigurationBuilder securityBuilder) { super(securityBuilder); attributes = AuthorizationConfiguration.attributeDefinitionSet(); } @Override public AttributeSet attributes() { return attributes; } /** * Disables authorization for this cache */ public AuthorizationConfigurationBuilder disable() { attributes.attribute(ENABLED).set(false); return this; } /** * Enables authorization for this cache. If no explicit {@link #role(String)} are specified, all of the global roles apply. */ public AuthorizationConfigurationBuilder enable() { attributes.attribute(ENABLED).set(true); return this; } /** * Enables/disables authorization for this cache. If enabled and no explicit {@link #role(String)} are specified, all of the global roles apply. */ public AuthorizationConfigurationBuilder enabled(boolean enabled) { this.attributes.attribute(ENABLED).set(enabled); return this; } /** * Adds a role that can work with this cache. Roles must be declared in the {@link org.infinispan.configuration.global.GlobalAuthorizationConfigurationBuilder}. * @param name the name of the role */ public AuthorizationConfigurationBuilder role(String name) { Set<String> roles = attributes.attribute(ROLES).get(); roles.add(name); attributes.attribute(ROLES).set(roles); return this; } /** * Adds roles that can work with this cache. Roles must be declared in the {@link org.infinispan.configuration.global.GlobalAuthorizationConfigurationBuilder}. * @param names the names of the roles */ public AuthorizationConfigurationBuilder roles(String... names) { for (String name : names) { this.role(name); } return this; } @Override public void validate(GlobalConfiguration globalConfig) { GlobalAuthorizationConfiguration authorization = globalConfig.security().authorization(); if (attributes.attribute(ENABLED).get() && !authorization.enabled()) { throw CONFIG.globalSecurityAuthShouldBeEnabled(); } Set<String> cacheRoles = attributes.attribute(ROLES).get(); Set<String> missingRoles = new HashSet<>(); for(String role : cacheRoles) { if (!authorization.hasRole(role)) { missingRoles.add(role); } } if (!missingRoles.isEmpty()) { throw CONFIG.noSuchGlobalRoles(missingRoles); } } @Override public AuthorizationConfiguration create() { return new AuthorizationConfiguration(attributes.protect()); } @Override public Builder<?> read(AuthorizationConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); return this; } @Override public String toString() { return "AuthorizationConfigurationBuilder [attributes=" + attributes + "]"; } }
3,899
32.913043
163
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/TakeOfflineConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.TakeOfflineConfiguration.AFTER_FAILURES; import static org.infinispan.configuration.cache.TakeOfflineConfiguration.MIN_TIME_TO_WAIT; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; /** * @author Mircea Markus * @see <a href="https://infinispan.org/docs/stable/titles/xsite/xsite.html#taking_a_site_offline">Infinispan Cross-Site documentation</a> * @since 5.2 */ public class TakeOfflineConfigurationBuilder extends AbstractConfigurationChildBuilder implements Builder<TakeOfflineConfiguration> { public final AttributeSet attributes; private final BackupConfigurationBuilder backupConfigurationBuilder; public TakeOfflineConfigurationBuilder(ConfigurationBuilder builder, BackupConfigurationBuilder backupConfigurationBuilder) { super(builder); attributes = TakeOfflineConfiguration.attributeDefinitionSet(); this.backupConfigurationBuilder = backupConfigurationBuilder; } @Override public AttributeSet attributes() { return attributes; } /** * The minimal number of milliseconds to wait before taking this site offline. It defaults to 0 (zero). * <p> * A zero or negative value will disable any waiting time and use only {@link #afterFailures(int)}. * <p> * The switch to offline status happens after a failed request (times-out or network failure) and {@code * minTimeToWait} is already elapsed. * <p> * When a request fails (after a successful request) the timer is set and it is stopped and reset after a successful * request. * <p> * Check the <a href="https://infinispan.org/docs/stable/titles/xsite/xsite.html#taking_a_site_offline">Infinispan * Cross-Site documentation</a> for more information about {@link #minTimeToWait(long)} and {@link * #afterFailures(int)}. */ public TakeOfflineConfigurationBuilder minTimeToWait(long minTimeToWait) { attributes.attribute(MIN_TIME_TO_WAIT).set(minTimeToWait); return this; } /** * The number of consecutive failed request operations after which this site should be taken offline. It default to 0 * (zero). * <p> * A zero or negative value will ignore the number of failures and use only {@link #minTimeToWait(long)}. * <p> * Check the <a href="https://infinispan.org/docs/stable/titles/xsite/xsite.html#taking_a_site_offline">Infinispan * Cross-Site documentation</a> for more information about {@link #minTimeToWait(long)} and {@link * #afterFailures(int)}. */ public TakeOfflineConfigurationBuilder afterFailures(int afterFailures) { attributes.attribute(AFTER_FAILURES).set(afterFailures); return this; } public BackupConfigurationBuilder backup() { return backupConfigurationBuilder; } @Override public TakeOfflineConfiguration create() { return new TakeOfflineConfiguration(attributes.protect()); } @Override public TakeOfflineConfigurationBuilder read(TakeOfflineConfiguration template, Combine combine) { attributes.read(template.attributes(), combine); return this; } }
3,291
39.641975
138
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/HashConfigurationBuilder.java
package org.infinispan.configuration.cache; import static org.infinispan.configuration.cache.HashConfiguration.CAPACITY_FACTOR; import static org.infinispan.configuration.cache.HashConfiguration.CONSISTENT_HASH_FACTORY; import static org.infinispan.configuration.cache.HashConfiguration.KEY_PARTITIONER; import static org.infinispan.configuration.cache.HashConfiguration.NUM_OWNERS; import static org.infinispan.configuration.cache.HashConfiguration.NUM_SEGMENTS; import org.infinispan.commons.configuration.Builder; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.distribution.ch.ConsistentHashFactory; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.util.logging.Log; /** * Allows fine-tuning of rehashing characteristics. Must only used with 'distributed' cache mode. * * @author pmuir */ public class HashConfigurationBuilder extends AbstractClusteringConfigurationChildBuilder implements Builder<HashConfiguration> { private final AttributeSet attributes; private final GroupsConfigurationBuilder groupsConfigurationBuilder; HashConfigurationBuilder(ClusteringConfigurationBuilder builder) { super(builder); this.attributes = HashConfiguration.attributeDefinitionSet(); this.groupsConfigurationBuilder = new GroupsConfigurationBuilder(builder); } @Override public AttributeSet attributes() { return attributes; } /** * The consistent hash factory in use. * @deprecated Since 11.0. Will be removed in 14.0, the segment allocation will no longer be customizable. */ @Deprecated public HashConfigurationBuilder consistentHashFactory(ConsistentHashFactory<? extends ConsistentHash> consistentHashFactory) { attributes.attribute(CONSISTENT_HASH_FACTORY).set(consistentHashFactory); return this; } /** * Number of cluster-wide replicas for each cache entry. */ public HashConfigurationBuilder numOwners(int numOwners) { if (numOwners < 1) throw new IllegalArgumentException("numOwners cannot be less than 1"); attributes.attribute(NUM_OWNERS).set(numOwners); return this; } boolean isNumOwnersSet() { return attributes.attribute(NUM_OWNERS).isModified(); } int numOwners() { return attributes.attribute(NUM_OWNERS).get(); } /** * Controls the total number of hash space segments (per cluster). * * <p>A hash space segment is the granularity for key distribution in the cluster: a node can own * (or primary-own) one or more full segments, but not a fraction of a segment. * As such, very small {@code numSegments} values (&lt; 10 segments per node) will make * the distribution of keys between nodes more uneven.</p> * <p>The recommended value is 20 * the expected cluster size.</p> * <p>Note: The value returned by {@link ConsistentHash#getNumSegments()} may be different, * e.g. rounded up to a power of 2.</p> * * @param numSegments the number of hash space segments. Must be strictly positive. */ public HashConfigurationBuilder numSegments(int numSegments) { if (numSegments < 1) throw new IllegalArgumentException("numSegments cannot be less than 1"); attributes.attribute(NUM_SEGMENTS).set(numSegments); return this; } /** * Controls the proportion of entries that will reside on the local node, compared to the other nodes in the * cluster. This is just a suggestion, there is no guarantee that a node with a capacity factor of {@code 2} will * have twice as many entries as a node with a capacity factor of {@code 1}. * @param capacityFactor the capacity factor for the local node. Must be positive. */ public HashConfigurationBuilder capacityFactor(float capacityFactor) { if (capacityFactor < 0) throw Log.CONFIG.illegalCapacityFactor(); attributes.attribute(CAPACITY_FACTOR).set(capacityFactor); return this; } /** * Key partitioner, controlling the mapping of keys to hash segments. * <p> * The default implementation is {@code org.infinispan.distribution.ch.impl.HashFunctionPartitioner}, * uses {@link org.infinispan.commons.hash.MurmurHash3}. * * @since 8.2 */ public HashConfigurationBuilder keyPartitioner(KeyPartitioner keyPartitioner) { attributes.attribute(KEY_PARTITIONER).set(keyPartitioner); return this; } public KeyPartitioner keyPartitioner() { return attributes.attribute(KEY_PARTITIONER).get(); } public GroupsConfigurationBuilder groups() { return groupsConfigurationBuilder; } @Override public void validate() { groupsConfigurationBuilder.validate(); } @Override public void validate(GlobalConfiguration globalConfig) { groupsConfigurationBuilder.validate(globalConfig); } @Override public HashConfiguration create() { return new HashConfiguration(attributes.protect(), groupsConfigurationBuilder.create()); } @Override public HashConfigurationBuilder read(HashConfiguration template, Combine combine) { this.attributes.read(template.attributes(), combine); this.groupsConfigurationBuilder.read(template.groups(), combine); return this; } @Override public String toString() { return "HashConfigurationBuilder [attributes=" + attributes + ", groupsConfigurationBuilder=" + groupsConfigurationBuilder + "]"; } }
5,640
37.636986
129
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/BackupFailurePolicy.java
package org.infinispan.configuration.cache; /** * Defines the possible behaviour in case of failure during x-site. * * @author Mircea Markus * @since 5.2 */ public enum BackupFailurePolicy { IGNORE, WARN, FAIL, CUSTOM }
229
18.166667
67
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/QueryConfiguration.java
package org.infinispan.configuration.cache; import org.infinispan.commons.configuration.AbstractTypedPropertiesConfiguration; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Element; /** * Configures query options and defaults */ public class QueryConfiguration extends ConfigurationElement<QueryConfiguration> { public static final AttributeDefinition<Integer> DEFAULT_MAX_RESULTS = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.DEFAULT_MAX_RESULTS, 100).immutable().build(); public static final AttributeDefinition<Integer> HIT_COUNT_ACCURACY = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.HIT_COUNT_ACCURACY, 10_000).immutable().build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(QueryConfiguration.class, AbstractTypedPropertiesConfiguration.attributeSet(), DEFAULT_MAX_RESULTS, HIT_COUNT_ACCURACY); } protected QueryConfiguration(AttributeSet attributes) { super(Element.QUERY, attributes); } /** * Limits the number of results returned by a query. Applies to indexed, non-indexed, and hybrid queries. * Setting the default-max-results significantly improves the performance of queries that don't have an explicit limit set. */ public int defaultMaxResults() { return attributes.attribute(DEFAULT_MAX_RESULTS).get(); } /** * Limit the required accuracy of the hit count for the indexed queries to an upper-bound. * Setting the hit-count-accuracy could improve the performance of queries targeting large data sets. * For optimal performances set this value not much above the expected hit count. * If you do not require accurate hit counts, set it to a low value. */ public int hitCountAccuracy() { return attributes.attribute(HIT_COUNT_ACCURACY).get(); } }
2,069
47.139535
196
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/UnsafeConfiguration.java
package org.infinispan.configuration.cache; import java.util.Map; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Element; /** * * Controls certain tuning parameters that may break some of Infinispan's public API contracts in * exchange for better performance in some cases. * <p /> * Use with care, only after thoroughly reading and understanding the documentation about a specific * feature. * <p /> * * @see UnsafeConfigurationBuilder */ public class UnsafeConfiguration extends ConfigurationElement<UnsafeConfiguration> { public static final AttributeDefinition<Boolean> UNRELIABLE_RETURN_VALUES = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.UNRELIABLE_RETURN_VALUES, false).immutable().build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(UnsafeConfiguration.class, UNRELIABLE_RETURN_VALUES); } private final Attribute<Boolean> unreliableReturnValues; UnsafeConfiguration(AttributeSet attributes) { super(Element.UNSAFE, attributes); unreliableReturnValues = attributes.attribute(UNRELIABLE_RETURN_VALUES); } /** * Specifies whether Infinispan is allowed to disregard the {@link Map} contract when providing * return values for {@link org.infinispan.Cache#put(Object, Object)} and * {@link org.infinispan.Cache#remove(Object)} methods. */ public boolean unreliableReturnValues() { return unreliableReturnValues.get(); } }
1,751
39.744186
207
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/SitesConfiguration.java
package org.infinispan.configuration.cache; import static org.infinispan.commons.configuration.attributes.AttributeValidator.greaterThanZero; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.infinispan.commons.configuration.attributes.AttributeCopier; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeParser; import org.infinispan.commons.configuration.attributes.AttributeSerializer; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.commons.util.Util; import org.infinispan.configuration.parsing.Element; import org.infinispan.xsite.spi.XSiteEntryMergePolicy; import org.infinispan.xsite.spi.XSiteMergePolicy; /** * @author Mircea.Markus@jboss.com * @since 5.2 */ public class SitesConfiguration extends ConfigurationElement<SitesConfiguration> { @SuppressWarnings("rawtypes") public static final AttributeDefinition<XSiteEntryMergePolicy> MERGE_POLICY = AttributeDefinition .builder(org.infinispan.configuration.parsing.Attribute.MERGE_POLICY, XSiteMergePolicy.DEFAULT, XSiteEntryMergePolicy.class) .copier(MergePolicyAttributeUtil.INSTANCE) .parser(MergePolicyAttributeUtil.INSTANCE) .serializer(MergePolicyAttributeUtil.INSTANCE) .immutable() .build(); public static final AttributeDefinition<Long> MAX_CLEANUP_DELAY = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.MAX_CLEANUP_DELAY, 30000L) .validator(greaterThanZero(org.infinispan.configuration.parsing.Attribute.MAX_CLEANUP_DELAY)) .immutable() .build(); public static final AttributeDefinition<Integer> TOMBSTONE_MAP_SIZE = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.TOMBSTONE_MAP_SIZE, 512000) .validator(greaterThanZero(org.infinispan.configuration.parsing.Attribute.TOMBSTONE_MAP_SIZE)) .immutable() .build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(SitesConfiguration.class, MERGE_POLICY, MAX_CLEANUP_DELAY, TOMBSTONE_MAP_SIZE); } private final BackupForConfiguration backupFor; private final List<BackupConfiguration> allBackups; public SitesConfiguration(AttributeSet attributes, List<BackupConfiguration> allBackups, BackupForConfiguration backupFor) { super(Element.SITES, attributes, ConfigurationElement.list(Element.BACKUPS, allBackups), backupFor); this.allBackups = Collections.unmodifiableList(allBackups); this.backupFor = backupFor; } /** * Returns true if this cache won't backup its data remotely. It would still accept other sites backing up data on * this site. * * @deprecated since 14.0. To be removed without replacement. */ @Deprecated public boolean disableBackups() { return false; } /** * Returns the list of all sites where this cache might back up its data. The list of actual sites is defined by * {@link #inUseBackupSites}. */ public List<BackupConfiguration> allBackups() { return allBackups; } public Stream<BackupConfiguration> allBackupsStream() { return allBackups.stream(); } /** * Returns the list of {@link BackupConfiguration} that have {@link org.infinispan.configuration.cache.BackupConfiguration#enabled()} == true. * * @deprecated Since 14.0. To be removed without replacement. Use {@link #allBackups()} or {@link #allBackupsStream()}. */ @Deprecated public List<BackupConfiguration> enabledBackups() { return allBackups(); } /** * @deprecated Since 14.0. To be removed without replacement. Use {@link #allBackups()} or {@link #allBackupsStream()}. */ @Deprecated public Stream<BackupConfiguration> enabledBackupStream() { return allBackupsStream(); } /** * @return information about caches that backup data into this cache. */ public BackupForConfiguration backupFor() { return backupFor; } public BackupFailurePolicy getFailurePolicy(String siteName) { for (BackupConfiguration bc : allBackups) { if (bc.site().equals(siteName)) { return bc.backupFailurePolicy(); } } throw new IllegalStateException("There must be a site configured for " + siteName); } /** * @deprecated since 14.0. To be removed without replacement */ @Deprecated public boolean hasInUseBackup(String siteName) { return allBackups.stream().anyMatch(bc -> bc.site().equals(siteName)); } /** * @deprecated since 14.0. To be removed without replacement. Use {@link #hasBackups()} instead. */ @Deprecated public boolean hasEnabledBackups() { return hasBackups(); } public boolean hasBackups() { return !allBackups.isEmpty(); } public boolean hasSyncEnabledBackups() { return allBackupsStream().anyMatch(BackupConfiguration::isSyncBackup); } public Stream<BackupConfiguration> syncBackupsStream() { return allBackupsStream().filter(BackupConfiguration::isSyncBackup); } public boolean hasAsyncEnabledBackups() { return allBackupsStream().anyMatch(BackupConfiguration::isAsyncBackup); } public Stream<BackupConfiguration> asyncBackupsStream() { return allBackupsStream().filter(BackupConfiguration::isAsyncBackup); } /** * @deprecated since 14.0. To be removed without replacement. */ @Deprecated public Set<String> inUseBackupSites() { return allBackups.stream().map(BackupConfiguration::site).collect(Collectors.toSet()); } /** * @return The {@link XSiteEntryMergePolicy} to resolve conflicts when asynchronous cross-site replication is * enabled. * @see SitesConfigurationBuilder#mergePolicy(XSiteEntryMergePolicy) */ public XSiteEntryMergePolicy<?, ?> mergePolicy() { return attributes.attribute(MERGE_POLICY).get(); } /** * @return The maximum delay, in milliseconds, between which tombstone cleanup tasks run. */ public long maxTombstoneCleanupDelay() { return attributes.attribute(MAX_CLEANUP_DELAY).get(); } /** * @return The target tombstone map size. */ public int tombstoneMapSize() { return attributes.attribute(TOMBSTONE_MAP_SIZE).get(); } @SuppressWarnings("rawtypes") private enum MergePolicyAttributeUtil implements AttributeCopier<XSiteEntryMergePolicy>, AttributeSerializer<XSiteEntryMergePolicy>, AttributeParser<XSiteEntryMergePolicy> { INSTANCE; @Override public XSiteEntryMergePolicy copyAttribute(XSiteEntryMergePolicy value) { if (value == null) { return null; } if (value instanceof XSiteMergePolicy) { //the default implementations are immutable and can be reused. return ((XSiteMergePolicy) value).getInstance(); } else { //noinspection unchecked XSiteMergePolicy enumPolicy = XSiteMergePolicy.fromInstance(value); return enumPolicy == null ? Util.getInstance(value.getClass()) : enumPolicy.getInstance(); } } @Override public void serialize(ConfigurationWriter writer, String name, XSiteEntryMergePolicy value) { //noinspection unchecked XSiteMergePolicy enumPolicy = XSiteMergePolicy.fromInstance(value); if (enumPolicy != null) { writer.writeAttribute(name, enumPolicy.name()); } else { INSTANCE_CLASS_NAME.serialize(writer, name, value); } } @Override public XSiteEntryMergePolicy parse(Class klass, String value) { return XSiteMergePolicy.instanceFromString(value, null); } } }
8,094
35.463964
175
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/Configuration.java
package org.infinispan.configuration.cache; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.infinispan.commons.configuration.BasicConfiguration; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.commons.configuration.attributes.Matchable; import org.infinispan.configuration.parsing.ParserRegistry; public class Configuration extends ConfigurationElement<Configuration> implements BasicConfiguration { public static final AttributeDefinition<String> CONFIGURATION = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.CONFIGURATION, null, String.class).immutable().build(); public static final AttributeDefinition<Boolean> SIMPLE_CACHE = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.SIMPLE_CACHE, false).immutable().build(); public static AttributeSet attributeDefinitionSet() { return new AttributeSet(Configuration.class, CONFIGURATION, SIMPLE_CACHE); } private final Attribute<Boolean> simpleCache; private final ClusteringConfiguration clusteringConfiguration; private final CustomInterceptorsConfiguration customInterceptorsConfiguration; private final EncodingConfiguration encodingConfiguration; private final ExpirationConfiguration expirationConfiguration; private final IndexingConfiguration indexingConfiguration; private final InvocationBatchingConfiguration invocationBatchingConfiguration; private final LockingConfiguration lockingConfiguration; private final MemoryConfiguration memoryConfiguration; private final Map<Class<?>, ?> moduleConfiguration; private final PersistenceConfiguration persistenceConfiguration; private final QueryConfiguration queryConfiguration; private final SecurityConfiguration securityConfiguration; private final SitesConfiguration sitesConfiguration; private final StatisticsConfiguration statisticsConfiguration; private final TransactionConfiguration transactionConfiguration; private final UnsafeConfiguration unsafeConfiguration; private final boolean template; Configuration(boolean template, AttributeSet attributes, ClusteringConfiguration clusteringConfiguration, CustomInterceptorsConfiguration customInterceptorsConfiguration, ExpirationConfiguration expirationConfiguration, EncodingConfiguration encodingConfiguration, QueryConfiguration queryConfiguration, IndexingConfiguration indexingConfiguration, InvocationBatchingConfiguration invocationBatchingConfiguration, StatisticsConfiguration statisticsConfiguration, PersistenceConfiguration persistenceConfiguration, LockingConfiguration lockingConfiguration, SecurityConfiguration securityConfiguration, TransactionConfiguration transactionConfiguration, UnsafeConfiguration unsafeConfiguration, SitesConfiguration sitesConfiguration, MemoryConfiguration memoryConfiguration, List<?> modules) { super(clusteringConfiguration.cacheMode().toElement(template), attributes, clusteringConfiguration, expirationConfiguration, encodingConfiguration, queryConfiguration, indexingConfiguration, statisticsConfiguration, persistenceConfiguration, lockingConfiguration, securityConfiguration, transactionConfiguration, unsafeConfiguration, sitesConfiguration, memoryConfiguration); this.template = template; this.simpleCache = attributes.attribute(SIMPLE_CACHE); this.clusteringConfiguration = clusteringConfiguration; this.customInterceptorsConfiguration = customInterceptorsConfiguration; this.encodingConfiguration = encodingConfiguration; this.expirationConfiguration = expirationConfiguration; this.queryConfiguration = queryConfiguration; this.indexingConfiguration = indexingConfiguration; this.invocationBatchingConfiguration = invocationBatchingConfiguration; this.statisticsConfiguration = statisticsConfiguration; this.persistenceConfiguration = persistenceConfiguration; this.lockingConfiguration = lockingConfiguration; this.transactionConfiguration = transactionConfiguration; this.unsafeConfiguration = unsafeConfiguration; this.securityConfiguration = securityConfiguration; this.sitesConfiguration = sitesConfiguration; this.memoryConfiguration = memoryConfiguration; Map<Class<?>, Object> modulesMap = new HashMap<>(); for(Object module : modules) { modulesMap.put(module.getClass(), module); } this.moduleConfiguration = Collections.unmodifiableMap(modulesMap); } public boolean simpleCache() { return simpleCache.get(); } public ClusteringConfiguration clustering() { return clusteringConfiguration; } /** * @deprecated Since 10.0, custom interceptors support will be removed and only modules will be able to define interceptors */ @Deprecated public CustomInterceptorsConfiguration customInterceptors() { return customInterceptorsConfiguration; } public EncodingConfiguration encoding() { return encodingConfiguration; } public ExpirationConfiguration expiration() { return expirationConfiguration; } public QueryConfiguration query() { return queryConfiguration; } public IndexingConfiguration indexing() { return indexingConfiguration; } public InvocationBatchingConfiguration invocationBatching() { return invocationBatchingConfiguration; } public StatisticsConfiguration statistics() { return statisticsConfiguration; } /** * @deprecated since 10.1.3 use {@link #statistics} instead. This will be removed in next major version. */ @Deprecated public JMXStatisticsConfiguration jmxStatistics() { return statistics(); } public PersistenceConfiguration persistence() { return persistenceConfiguration; } public LockingConfiguration locking() { return lockingConfiguration; } public MemoryConfiguration memory() { return memoryConfiguration; } @SuppressWarnings("unchecked") public <T> T module(Class<T> moduleClass) { return (T)moduleConfiguration.get(moduleClass); } public Map<Class<?>, ?> modules() { return moduleConfiguration; } public TransactionConfiguration transaction() { return transactionConfiguration; } public UnsafeConfiguration unsafe() { return unsafeConfiguration; } public SecurityConfiguration security() { return securityConfiguration; } public SitesConfiguration sites() { return sitesConfiguration; } public boolean isTemplate() { return template; } @Override public String toString() { return "Configuration{" + "simpleCache=" + simpleCache.get() + ", clustering=" + clusteringConfiguration + ", customInterceptors=" + customInterceptorsConfiguration + ", encoding=" + encodingConfiguration + ", expiration=" + expirationConfiguration + ", query=" + queryConfiguration + ", indexing=" + indexingConfiguration + ", invocationBatching=" + invocationBatchingConfiguration + ", locking=" + lockingConfiguration + ", memory=" + memoryConfiguration + ", modules=" + moduleConfiguration + ", persistence=" + persistenceConfiguration + ", security=" + securityConfiguration + ", sites=" + sitesConfiguration + ", statistics=" + statisticsConfiguration + ", transaction=" + transactionConfiguration + ", unsafe=" + unsafeConfiguration + ", template=" + template + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Configuration that = (Configuration) o; return template == that.template && Objects.equals(simpleCache.get(), that.simpleCache.get()) && Objects.equals(clusteringConfiguration, that.clusteringConfiguration) && Objects.equals(customInterceptorsConfiguration, that.customInterceptorsConfiguration) && Objects.equals(encodingConfiguration, that.encodingConfiguration) && Objects.equals(expirationConfiguration, that.expirationConfiguration) && Objects.equals(indexingConfiguration, that.indexingConfiguration) && Objects.equals(invocationBatchingConfiguration, that.invocationBatchingConfiguration) && Objects.equals(lockingConfiguration, that.lockingConfiguration) && Objects.equals(memoryConfiguration, that.memoryConfiguration) && Objects.equals(moduleConfiguration, that.moduleConfiguration) && Objects.equals(persistenceConfiguration, that.persistenceConfiguration) && Objects.equals(queryConfiguration, that.queryConfiguration) && Objects.equals(securityConfiguration, that.securityConfiguration) && Objects.equals(sitesConfiguration, that.sitesConfiguration) && Objects.equals(statisticsConfiguration, that.statisticsConfiguration) && Objects.equals(transactionConfiguration, that.transactionConfiguration) && Objects.equals(unsafeConfiguration, that.unsafeConfiguration); } @Override public int hashCode() { return Objects.hash(super.hashCode(), simpleCache.get(), clusteringConfiguration, customInterceptorsConfiguration, encodingConfiguration, expirationConfiguration, indexingConfiguration, invocationBatchingConfiguration, lockingConfiguration, memoryConfiguration, moduleConfiguration, persistenceConfiguration, queryConfiguration, securityConfiguration, sitesConfiguration, statisticsConfiguration, transactionConfiguration, unsafeConfiguration, template ); } @Override public boolean matches(Configuration other) { if (!simpleCache.get().equals(other.simpleCache.get())) return false; if (!clusteringConfiguration.matches(other.clusteringConfiguration)) return false; if (!customInterceptorsConfiguration.matches(other.customInterceptorsConfiguration)) return false; if (!encodingConfiguration.matches(other.encodingConfiguration)) return false; if (!expirationConfiguration.matches(other.expirationConfiguration)) return false; if (!indexingConfiguration.matches(other.indexingConfiguration)) return false; if (!invocationBatchingConfiguration.matches(other.invocationBatchingConfiguration)) return false; if (!lockingConfiguration.matches(other.lockingConfiguration)) return false; if (!memoryConfiguration.matches(other.memoryConfiguration)) return false; if (!persistenceConfiguration.matches(other.persistenceConfiguration)) return false; if (!queryConfiguration.matches(other.queryConfiguration)) return false; if (!securityConfiguration.matches(other.securityConfiguration)) return false; if (!sitesConfiguration.matches(other.sitesConfiguration)) return false; if (!statisticsConfiguration.matches(other.statisticsConfiguration)) return false; if (!transactionConfiguration.matches(other.transactionConfiguration)) return false; if (!unsafeConfiguration.matches(other.unsafeConfiguration)) return false; for(Map.Entry<Class<?>, ?> module : moduleConfiguration.entrySet()) { if (!other.moduleConfiguration.containsKey(module.getKey())) return false; Object thisModule = module.getValue(); Object thatModule = other.moduleConfiguration.get(module.getKey()); if (thisModule instanceof Matchable && (!((Matchable)thisModule).matches(thatModule))) return false; if (!thisModule.equals(thatModule)) return false; } return attributes.matches(other.attributes); } @Override public String toStringConfiguration(String name) { ParserRegistry reg = new ParserRegistry(); return reg.serialize(name, this); } }
13,116
41.041667
197
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/AbstractCustomInterceptorsConfigurationChildBuilder.java
package org.infinispan.configuration.cache; /** * @deprecated Since 10.0, custom interceptors support will be removed and only modules will be able to define interceptors */ @Deprecated public abstract class AbstractCustomInterceptorsConfigurationChildBuilder extends AbstractConfigurationChildBuilder { private final CustomInterceptorsConfigurationBuilder customInterceptorsBuilder; protected AbstractCustomInterceptorsConfigurationChildBuilder(CustomInterceptorsConfigurationBuilder builder) { super(builder.getBuilder()); this.customInterceptorsBuilder = builder; } protected CustomInterceptorsConfigurationBuilder getCustomInterceptorsBuilder() { return customInterceptorsBuilder; } }
729
33.761905
123
java
null
infinispan-main/core/src/main/java/org/infinispan/configuration/cache/GroupsConfiguration.java
package org.infinispan.configuration.cache; import java.util.ArrayList; import java.util.List; import org.infinispan.commons.configuration.attributes.Attribute; import org.infinispan.commons.configuration.attributes.AttributeDefinition; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.configuration.attributes.ConfigurationElement; import org.infinispan.configuration.parsing.Element; import org.infinispan.distribution.group.Group; import org.infinispan.distribution.group.Grouper; /** * Configuration for various grouper definitions. See the user guide for more information. * * @author pmuir * */ public class GroupsConfiguration extends ConfigurationElement<GroupsConfiguration> { public final static AttributeDefinition<Boolean> ENABLED = AttributeDefinition.builder(org.infinispan.configuration.parsing.Attribute.ENABLED, false).immutable().build(); public final static AttributeDefinition<List<Grouper<?>>> GROUPERS = AttributeDefinition.builder(Element.GROUPER, null, (Class<List<Grouper<?>>>) (Class<?>) List.class).initializer(ArrayList::new) .immutable().build(); static AttributeSet attributeDefinitionSet() { return new AttributeSet(GroupsConfiguration.class, ENABLED, GROUPERS); } private final Attribute<Boolean> enabled; private final Attribute<List<Grouper<?>>> groupers; GroupsConfiguration(AttributeSet attributes) { super(Element.GROUPS, attributes); enabled = attributes.attribute(ENABLED); groupers = attributes.attribute(GROUPERS); } /** * If grouping support is enabled, then {@link Group} annotations are honored and any configured * groupers will be invoked * * @return */ public boolean enabled() { return enabled.get(); } /** * Get the current groupers in use */ public List<Grouper<?>> groupers() { return groupers.get(); } }
1,934
34.181818
199
java