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/commons/all/src/main/java/org/infinispan/commons/internal/CommonsBlockHoundIntegration.java
package org.infinispan.commons.internal; import java.lang.reflect.Method; import java.security.SecureRandom; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; import org.apache.logging.log4j.spi.AbstractLogger; import org.infinispan.commons.dataconversion.MediaTypeResolver; import org.infinispan.commons.executors.NonBlockingResource; import org.infinispan.commons.util.ServiceFinder; import org.infinispan.commons.util.SslContextFactory; import org.infinispan.commons.util.concurrent.NonBlockingRejectedExecutionHandler; import org.kohsuke.MetaInfServices; import reactor.blockhound.BlockHound; import reactor.blockhound.integration.BlockHoundIntegration; @MetaInfServices public class CommonsBlockHoundIntegration implements BlockHoundIntegration { @Override public void applyTo(BlockHound.Builder builder) { builder.nonBlockingThreadPredicate(current -> current.or(thread -> thread.getThreadGroup() instanceof NonBlockingResource)); // Pretend to block without the overhead of calling Thread.yield() builder.markAsBlocking(BlockHoundUtil.class, "pretendBlock", "()V"); // This should never block as non blocking thread will run the task if pool was full builder.disallowBlockingCallsInside(NonBlockingRejectedExecutionHandler.class.getName(), "rejectedExecution"); // This loads up a file to load the key store and a resource for getContext builder.allowBlockingCallsInside(SslContextFactory.class.getName(), "loadKeyStore"); builder.allowBlockingCallsInside(SslContextFactory.class.getName(), "getContext"); // This reads in the mime.type file at class initialization builder.allowBlockingCallsInside(MediaTypeResolver.class.getName(), "populateFileMap"); // Loading a service may require opening a file from classpath builder.allowBlockingCallsInside(ServiceFinder.class.getName(), "load"); // BoundedLocalCache is unfortunately package private builder.allowBlockingCallsInside("com.github.benmanes.caffeine.cache.BoundedLocalCache", "performCleanUp"); handleJREClasses(builder); log4j(builder); } // Register all methods of a given class to allow for blocking - NOTE that if these methods invoke passed in code, // such as a Runnable/Callable, this should not be used! public static void allowPublicMethodsToBlock(BlockHound.Builder builder, Class<?> clazz) { allowMethodsToBlock(builder, clazz, true); } public static void allowMethodsToBlock(BlockHound.Builder builder, Class<?> clazz, boolean publicOnly) { Method[] methods = publicOnly ? clazz.getMethods() : clazz.getDeclaredMethods(); for (Method method : methods) { builder.allowBlockingCallsInside(clazz.getName(), method.getName()); } } private static void handleJREClasses(BlockHound.Builder builder) { // The runWorker method can block waiting for a new task to be submitted - this is okay builder.allowBlockingCallsInside(ForkJoinPool.class.getName(), "runWorker"); // The scan method is where the task is actually ran builder.disallowBlockingCallsInside(ForkJoinPool.class.getName(), "scan"); // SecureRandom reads from a socket builder.allowBlockingCallsInside(SecureRandom.class.getName(), "nextBytes"); // Just assume all the thread pools don't block - NOTE rejection policy can still be an issue! allowMethodsToBlock(builder, ThreadPoolExecutor.class, true); allowMethodsToBlock(builder, ScheduledThreadPoolExecutor.class, true); builder.allowBlockingCallsInside(ThreadPoolExecutor.class.getName(), "getTask"); builder.allowBlockingCallsInside(ThreadPoolExecutor.class.getName(), "processWorkerExit"); // Allow logging to block builder.allowBlockingCallsInside(java.util.logging.Logger.class.getName(), "log"); } private static void log4j(BlockHound.Builder builder) { try { Class.forName("org.apache.logging.log4j.spi.AbstractLogger"); builder.allowBlockingCallsInside(AbstractLogger.class.getName(), "logMessage"); } catch (ClassNotFoundException e) { // Ignore if no AbstractLogger } builder.allowBlockingCallsInside("org.apache.logging.log4j.core.Logger", "logMessage"); } }
4,367
45.967742
130
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/multimap/api/package-info.java
/** * MultimapCache API. * * @api.public */ package org.infinispan.multimap.api;
85
11.285714
36
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/multimap/api/BasicMultimapCache.java
package org.infinispan.multimap.api; import java.util.Collection; import java.util.concurrent.CompletableFuture; import org.infinispan.commons.util.Experimental; /** * {@link BasicMultimapCache} provides the common API for the two different types of multimap caches that Infinispan * provides: embedded and remote. <p> Please see the <a href="http://infinispan.org/documentation/">Infinispan * documentation</a> and/or the <a href="http://infinispan.org/docs/dev/getting_started/getting_started.html">5 Minute * Usage Tutorial</a> for more details on Infinispan. * <p/> * <p> MutimapCache is a type of Infinispan Cache that maps keys to values, similar to {@link * org.infinispan.commons.api.AsyncCache} in which each key can contain multiple values. * <pre> * foo &rarr; 1 * bar &rarr; 3, 4, 5 * </pre> * <p> <h2>Example</h2> * <pre> * * multimapCache.put("k", "v1").join(); * multimapCache.put("k", "v2").join(); * multimapCache.put("k", "v3").join(); * * Collection<String> results = multimapCache.get("k").join(); * * </pre> * <p> <h2>Eviction</h2> <p> Eviction works per key. This means all the values associated on a key will be evicted. * </p> * <p> * <h2>Views</h2> * <p> * The returned collections when calling "get" are views of the values on the key. Any change on these collections won't * affect the cache values on the key. * <p> * <h2>Null values</h2> Null values are not supported. The multimap cache won't have a null key or any null value. * <p> * Example * <pre> * multimapCache.put(null, "v1").join() &rarr; fails * multimapCache.put("k", null).join() &rarr; fails * multimapCache.put("k", "v1").join() &rarr; works and add's v1 * multimapCache.containsKey("k").join() &rarr; true * multimapCache.remove("k", "v1").join() &rarr; works, removes v1 and as the remaining collection is empty, the key is * removed * multimapCache.containsKey("k").join() &rarr; false * </pre> * <p> * * @author Katia Aresti, karesti@redhat.com * @see <a href="http://infinispan.org/documentation/">Infinispan documentation</a> * @since 9.2 */ @Experimental public interface BasicMultimapCache<K, V> { /** * Puts a key-value pair in this multimap cache. <ul> <li>If this multimap cache supports * duplicates, the value will be always added.</li> <li>If this multimap cache does <i>not support</i> duplicates and * the value exists on the key, nothing will be done.</li> </ul> * * @param key the key to be put * @param value the value to added * @return {@link CompletableFuture} containing a {@link Void} * @since 9.2 */ CompletableFuture<Void> put(K key, V value); /*** * Returns a <i>view collection</i> of the values associated with key in this multimap cache, * if any. Any changes to the retrieved collection won't change the values in this multimap cache. * <b>When this method returns an empty collection, it means the key was not found.</b> * * @param key to be retrieved * @return a {@link CompletableFuture} containing {@link Collection <V>} which is a view of the underlying values. * @since 9.2 */ CompletableFuture<Collection<V>> get(K key); /** * Removes all the key-value pairs associated with the key from this multimap cache, if such exists. * * @param key to be removed * @return a {@link CompletableFuture} containing {@link Boolean#TRUE} if the entry was removed, and {@link * Boolean#FALSE} when the entry was not removed * @since 9.2 */ CompletableFuture<Boolean> remove(K key); /** * Removes a key-value pair from this multimap cache, if such exists. Returns true when the * key-value pair has been removed from the key. * <p> * <ul> <li>In the case where duplicates are <b>not supported</b>, <b>only one</b> the key-value pair will be * removed, if such exists.</li> <li>In the case where duplicates are supported, <b>all the key-value pairs</b> will * be removed.</li> <li>If the values remaining after the remove call are empty, the whole entry will be * removed.</li> </ul> * * @param key key to be removed * @param value value to be removed * @return {@link CompletableFuture} containing {@link Boolean#TRUE} if the key-value pair was removed, and {@link * Boolean#FALSE} when the key-value pair was not removed * @since 9.2 */ CompletableFuture<Boolean> remove(K key, V value); /** * Returns {@link Boolean#TRUE} if this multimap cache contains the key. * * @param key the key that might exists in this multimap cache * @return {@link CompletableFuture} containing a {@link Boolean} * @since 9.2 */ CompletableFuture<Boolean> containsKey(K key); /** * Asynchronous method that returns {@link Boolean#TRUE} if this multimap cache contains the value at any key. * * @param value the value that might exists in any entry * @return {@link CompletableFuture} containing a {@link Boolean} * @since 9.2 */ CompletableFuture<Boolean> containsValue(V value); /** * Returns {@link Boolean#TRUE} if this multimap cache contains the key-value pair. * * @param key the key of the key-value pair * @param value the value of the key-value pair * @return {@link CompletableFuture} containing a {@link Boolean} * @since 9.2 */ CompletableFuture<Boolean> containsEntry(K key, V value); /** * Returns the number of key-value pairs in this multimap cache. It doesn't return the distinct number of keys. * <p> * This method <b>is blocking</b> in a explicit transaction context. * <p> * The {@link CompletableFuture} is a * * @return {@link CompletableFuture} containing the size as {@link Long} * @since 9.2 */ CompletableFuture<Long> size(); /** * Multimap can support duplicates on the same key k &rarr; ['a', 'a', 'b'] or not k &rarr; ['a', 'b'] depending on * configuration. * <p> * Returns duplicates are supported or not in this multimap cache. * * @return {@code true} if this multimap supports duplicate values for a given key. * @since 9.2 */ boolean supportsDuplicates(); }
6,249
37.819876
123
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/lock/api/package-info.java
/** * Clustered Locks API. * * @api.public */ package org.infinispan.lock.api;
83
11
32
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/lock/api/ClusteredLock.java
package org.infinispan.lock.api; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import org.infinispan.lock.exception.ClusteredLockException; /** * ClusteredLock is a data structure used for concurrent programming between Infinispan instances in cluster mode. * * A typical usage idiom for {@link ClusteredLock#lock} will be : * * {@code * * ClusteredLock lock = clm.get("lock"); * lock.lock() * .thenRun(() -> * try { * // manipulate protected state * } finally { * return lock.unlock(); * } * ) * } * * A typical usage idiom for {@link ClusteredLock#tryLock} will be : * * {@code * * lock.tryLock() * .thenCompose(result -> { * if (result) { * try { * // manipulate protected state * } finally { * return lock.unlock(); * } * } else { * // Do something else * } * }); * } * * @author Katia Aresti, karesti@redhat.com * @see <a href="http://infinispan.org/documentation/">Infinispan documentation</a> * @since 9.2 */ public interface ClusteredLock { /** * Acquires the lock. If the lock is not available then the {@link CompletableFuture} waits until the lock has been acquired. * Currently, there is no maximum time specified for a lock request to fail, so this could cause thread starvation. * * @return a completed {@link CompletableFuture} when the lock is acquired * @throws ClusteredLockException when the lock does not exist */ CompletableFuture<Void> lock(); /** * Acquires the lock only if it is free at the time of invocation. * Acquires the lock if it is available and returns immediately with with the {@link CompletableFuture} holding the value {@code true}. * If the lock is not available then this method will return immediately with the {@link CompletableFuture} holding the value {@code false}. * * @return {@code CompletableFuture(true)} if the lock was acquired and {@code CompletableFuture(false)} otherwise * @throws ClusteredLockException when the lock does not exist */ CompletableFuture<Boolean> tryLock(); /** * If the lock is available this method returns immediately with the {@link CompletableFuture} holding the value {@code true}. * If the lock is not available then the {@link CompletableFuture} waits until : * <ul> * <li>The lock is acquired</li> * <li>The specified waiting time elapses</li> * </ul> * * If the lock is acquired then the {@link CompletableFuture} will complete with the value {@code true}. * If the specified waiting time elapses then the {@link CompletableFuture} will complete with the value {@code false}. * If the time is less than or equal to zero, the method will not wait at all. * * @param time, the maximum time to wait for the lock * @param unit, the time unit of the {@code time} argument * @return {@code CompletableFuture(true)} if the lock was acquired and {@code CompletableFuture(false)} if the waiting time elapsed before the lock was acquired * @throws ClusteredLockException when the lock does not exist */ CompletableFuture<Boolean> tryLock(long time, TimeUnit unit); /** * Releases the lock. Only the holder of the lock may release the lock. * * @return a completed {@link CompletableFuture} when the lock is released * @throws ClusteredLockException when the lock does not exist */ CompletableFuture<Void> unlock(); /** * Returns a {@link CompletableFuture<Boolean>} holding {@code true} when the lock is locked and {@code false} when the lock is released. * * @return a {@link CompletableFuture} holding a {@link Boolean} * @throws ClusteredLockException when the lock does not exist */ CompletableFuture<Boolean> isLocked(); /** * Returns a {@link CompletableFuture<Boolean>} holding {@code true} when the lock is owned by the caller and * {@code false} when the lock is owned by someone else or it's released. * * @return a {@link CompletableFuture} holding a {@link Boolean} * @throws ClusteredLockException when the lock does not exist */ CompletableFuture<Boolean> isLockedByMe(); }
4,312
37.168142
164
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/lock/api/ClusteredLockConfiguration.java
package org.infinispan.lock.api; /** * A Clustered Lock can be reentrant and there are different ownership levels. * <p> * The only mode supported now is "non reentrant" locks for "nodes". * * @author Katia Aresti, karesti@redhat.com * @see <a href="http://infinispan.org/documentation/">Infinispan documentation</a> * @since 9.2 */ public class ClusteredLockConfiguration { private final OwnershipLevel ownershipLevel; // default NODE private final boolean reentrant; // default false /** * Default lock is non reentrant and the ownership level is {@link OwnershipLevel#NODE} */ public ClusteredLockConfiguration() { this.ownershipLevel = OwnershipLevel.NODE; this.reentrant = false; } /** * @return true if the lock is reentrant */ public boolean isReentrant() { return reentrant; } /** * @return the {@link OwnershipLevel} or this lock */ public OwnershipLevel getOwnershipLevel() { return ownershipLevel; } @Override public String toString() { final StringBuilder sb = new StringBuilder("ClusteredLockConfiguration{"); sb.append("ownershipLevel=").append(ownershipLevel.name()); sb.append(", reentrant=").append(reentrant); sb.append('}'); return sb.toString(); } }
1,303
26.744681
90
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/lock/api/OwnershipLevel.java
package org.infinispan.lock.api; /** * Ownership level is a configuration parameter for {@link ClusteredLock}. The level of the ownership scopes the * execution of the code once the lock is acquired. If the lock owner is the {@link #NODE}, this means that any thread * on the node can release the lock. * * @author Katia Aresti, karesti@redhat.com * @see <a href="http://infinispan.org/documentation/">Infinispan documentation</a> * @since 9.2 */ public enum OwnershipLevel { // The owner of the lock is a node. Only the node that owns the Lock can release it NODE, // The owner of the lock is an instance. Only the instance that owns the lock can release it INSTANCE }
691
37.444444
118
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/lock/api/ClusteredLockManager.java
package org.infinispan.lock.api; import java.util.concurrent.CompletableFuture; import org.infinispan.lock.exception.ClusteredLockException; /** * Provides the API to define, create and remove ClusteredLocks. * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ public interface ClusteredLockManager { /** * Defines a lock with the specific name and the default {@link ClusteredLockConfiguration}. It does not overwrite * existing configurations. Returns true if successfully defined or false if the lock is already defined or any other * failure. * * @param name, the name of the lock * @return true if the lock was successfully defined */ boolean defineLock(String name); /** * Defines a lock with the specific name and {@link ClusteredLockConfiguration}. It does not overwrite existing * configurations. Returns true if successfully defined or false if the lock is already defined or any other * failure. * * @param name, the name of the lock * @param configuration, a {@link ClusteredLockConfiguration} object with the configuration of the lock * @return true if the lock was successfully defined */ boolean defineLock(String name, ClusteredLockConfiguration configuration); /** * Get’s a {@link ClusteredLock} by it’s name. This method throws {@link ClusteredLockException} if the lock is not * not defined. A call of {@link #defineLock} must be done at least once in the cluster. This method will return the * same lock object depending on the {@link OwnershipLevel}. * * If the {@link OwnershipLevel} is {@link OwnershipLevel#NODE}, it wll return the same instance per {@link ClusteredLockManager} * If the {@link OwnershipLevel} is {@link OwnershipLevel#INSTANCE}, it wll return a new instance per call. * * @param name, the name of the lock * @return {@link ClusteredLock} instance * @throws ClusteredLockException, when the lock is not defined */ ClusteredLock get(String name); /** * Returns the configuration of a {@link ClusteredLock}, if such exists.This method throws {@link * ClusteredLockException} if the lock is not not defined. A call of {@link #defineLock} must be done at least once * in the cluster. * * @param name, the name of the lock * @return {@link ClusteredLockConfiguration} for this lock * @throws ClusteredLockException, when the lock is not defined */ ClusteredLockConfiguration getConfiguration(String name); /** * Checks if a lock is already defined. * * @param name, the lock name * @return {@code true} if this lock is defined */ boolean isDefined(String name); /** * Removes a {@link ClusteredLock} if such exists. * * @param name, the name of the lock * @return {@code true} if the lock is removed */ CompletableFuture<Boolean> remove(String name); /** * Releases - or unlocks - a {@link ClusteredLock} if such exists. * This method is used when we just want to force the release the lock no matter who is holding it at a given time. * Calling this method may cause concurrency issues and has to be used in exceptional situations. * * @param name, the name of the lock * @return {@code true} if the lock has been released */ CompletableFuture<Boolean> forceRelease(String name); }
3,399
38.08046
132
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/lock/exception/package-info.java
/** * Clustered Locks Exceptions. * * @api.public */ package org.infinispan.lock.exception;
96
12.857143
38
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/lock/exception/ClusteredLockException.java
package org.infinispan.lock.exception; /** * Exception used to handle errors on clustered locks * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ public class ClusteredLockException extends RuntimeException { public ClusteredLockException(String message) { super(message); } public ClusteredLockException(Throwable t) { super(t); } }
377
18.894737
62
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/api/StrongCounter.java
package org.infinispan.counter.api; import java.util.concurrent.CompletableFuture; /** * The strong consistent counter interface. * <p> * It provides atomic updates for the counter. All the operations are perform asynchronously and they complete the * {@link CompletableFuture} when completed. * * @author Pedro Ruivo * @since 9.0 */ public interface StrongCounter { /** * @return The counter name. */ String getName(); /** * It fetches the current value. * <p> * It may go remotely to fetch the current value. * * @return The current value. */ CompletableFuture<Long> getValue(); /** * Atomically increments the counter and returns the new value. * * @return The new value. */ default CompletableFuture<Long> incrementAndGet() { return addAndGet(1L); } /** * Atomically decrements the counter and returns the new value * * @return The new value. */ default CompletableFuture<Long> decrementAndGet() { return addAndGet(-1L); } /** * Atomically adds the given value and return the new value. * * @param delta The non-zero value to add. It can be negative. * @return The new value. */ CompletableFuture<Long> addAndGet(long delta); /** * Resets the counter to its initial value. */ CompletableFuture<Void> reset(); /** * Registers a {@link CounterListener} to this counter. * * @param listener The listener to register. * @param <T> The concrete type of the listener. It must implement {@link CounterListener}. * @return A {@link Handle} that allows to remove the listener via {@link Handle#remove()}. */ <T extends CounterListener> Handle<T> addListener(T listener); /** * Atomically sets the value to the given updated value if the current value {@code ==} the expected value. * <p> * It is the same as {@code return compareAndSwap(expect, update).thenApply(value -> value == expect);} * * @param expect the expected value * @param update the new value * @return {@code true} if successful, {@code false} otherwise. */ default CompletableFuture<Boolean> compareAndSet(long expect, long update) { return compareAndSwap(expect, update).thenApply(value -> value == expect); } /** * Atomically sets the value to the given updated value if the current value {@code ==} the expected value. * <p> * The operation is successful if the return value is equals to the expected value. * * @param expect the expected value. * @param update the new value. * @return the previous counter's value. */ CompletableFuture<Long> compareAndSwap(long expect, long update); /** * @return the {@link CounterConfiguration} used by this counter. */ CounterConfiguration getConfiguration(); /** * It removes this counter from the cluster. * <p> * Note that it doesn't remove the counter from the {@link CounterManager}. If you want to remove the counter from * the {@link CounterManager} use {@link CounterManager#remove(String)}. * * @return The {@link CompletableFuture} that is completed when the counter is removed from the cluster. */ CompletableFuture<Void> remove(); /** * It returns a synchronous strong counter for this instance. * * @return a {@link SyncStrongCounter}. */ SyncStrongCounter sync(); /** * Atomically sets the value to the given updated value * * @param value the expected value. * @return the previous counter's value. */ CompletableFuture<Long> getAndSet(long value); }
3,658
27.811024
117
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/api/SyncStrongCounter.java
package org.infinispan.counter.api; /** * A synchronous {@link StrongCounter}. * * @author Pedro Ruivo * @since 9.2 */ public interface SyncStrongCounter { /** * @see StrongCounter#incrementAndGet() */ default long incrementAndGet() { return addAndGet(1); } /** * @see StrongCounter#decrementAndGet() */ default long decrementAndGet() { return addAndGet(-1); } /** * @see StrongCounter#addAndGet(long) */ long addAndGet(long delta); /** * @see StrongCounter#reset() */ void reset(); /** * @see StrongCounter#decrementAndGet() */ long getValue(); /** * @see StrongCounter#compareAndSet(long, long) */ default boolean compareAndSet(long expect, long update) { return compareAndSwap(expect, update) == expect; } /** * @see StrongCounter#compareAndSwap(long, long) */ long compareAndSwap(long expect, long update); /** * @see StrongCounter#getAndSet(long) */ long getAndSet(long value); /** * @see StrongCounter#getName() */ String getName(); /** * @see StrongCounter#getConfiguration() */ CounterConfiguration getConfiguration(); /** * @see StrongCounter#remove() */ void remove(); }
1,279
16.777778
60
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/api/package-info.java
/** * Clustered Counters API. * * @api.public */ package org.infinispan.counter.api;
89
11.857143
35
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/api/CounterState.java
package org.infinispan.counter.api; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.protostream.annotations.ProtoEnumValue; import org.infinispan.protostream.annotations.ProtoTypeId; /** * The possible states for a counter value. * * @author Pedro Ruivo * @since 9.0 */ @ProtoTypeId(ProtoStreamTypeIds.COUNTER_STATE) public enum CounterState { /** * The counter value is valid. */ @ProtoEnumValue(number = 0) VALID, /** * The counter value has reached its min threshold, i.e. no thresholds has been reached. */ @ProtoEnumValue(number = 1) LOWER_BOUND_REACHED, /** * The counter value has reached its max threshold. */ @ProtoEnumValue(number = 2) UPPER_BOUND_REACHED; private static final CounterState[] CACHED_VALUES = CounterState.values(); public static CounterState valueOf(int index) { return CACHED_VALUES[index]; } }
934
22.375
91
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/api/Storage.java
package org.infinispan.counter.api; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.protostream.annotations.ProtoEnumValue; import org.infinispan.protostream.annotations.ProtoTypeId; /** * The storage mode of a counter. * * @author Pedro Ruivo * @since 9.0 */ @ProtoTypeId(ProtoStreamTypeIds.COUNTER_STORAGE) public enum Storage { /** * The counter value is lost when the cluster is restarted/stopped. */ @ProtoEnumValue(number = 0) VOLATILE, /** * The counter value is stored persistently and survives a cluster restart/stop. */ @ProtoEnumValue(number = 1) PERSISTENT; private static final Storage[] CACHED_VALUES = values(); public static Storage valueOf(int index) { return CACHED_VALUES[index]; } }
794
23.84375
83
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/api/CounterListener.java
package org.infinispan.counter.api; /** * A listener interface to listen to {@link StrongCounter} changes. * <p> * The events received will have the previous/current value and its previous/current state. * * @author Pedro Ruivo * @since 9.0 */ public interface CounterListener { void onUpdate(CounterEvent entry); }
328
20.933333
91
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/api/SyncWeakCounter.java
package org.infinispan.counter.api; /** * A synchronous {@link WeakCounter}. * * @author Pedro Ruivo * @since 9.2 */ public interface SyncWeakCounter { /** * @see WeakCounter#getName() */ String getName(); /** * @see WeakCounter#getValue() */ long getValue(); /** * @see WeakCounter#increment() */ default void increment() { add(1); } /** * @see WeakCounter#decrement() */ default void decrement() { add(-1); } /** * @see WeakCounter#add(long) */ void add(long delta); /** * @see WeakCounter#reset() */ void reset(); /** * @see WeakCounter#getConfiguration() */ CounterConfiguration getConfiguration(); /** * @see WeakCounter#remove() */ void remove(); }
801
13.070175
43
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/api/CounterType.java
package org.infinispan.counter.api; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.counter.exception.CounterOutOfBoundsException; import org.infinispan.protostream.annotations.ProtoEnumValue; import org.infinispan.protostream.annotations.ProtoTypeId; /** * The counter types. * * @author Pedro Ruivo * @since 9.0 */ @ProtoTypeId(ProtoStreamTypeIds.COUNTER_TYPE) public enum CounterType { /** * A strong consistent and unbounded counter. The counter will never throw a {@link * CounterOutOfBoundsException}. */ @ProtoEnumValue(number = 0) UNBOUNDED_STRONG, /** * A strong consistent and bounded counter. The counter will throw {@link CounterOutOfBoundsException} * if the boundaries are reached. The upper and lower bound are inclusive. */ @ProtoEnumValue(number = 1) BOUNDED_STRONG, /** * A weak consistent counter. It focus on write performance and its counter value is only calculated at read time. */ @ProtoEnumValue(number = 2) WEAK; private static final CounterType[] CACHED_VALUES = values(); public static CounterType valueOf(int index) { return CACHED_VALUES[index]; } }
1,196
28.925
117
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/api/CounterEvent.java
package org.infinispan.counter.api; /** * The event used by {@link CounterListener}. * * @author Pedro Ruivo * @since 9.0 */ public interface CounterEvent { /** * @return the previous value. */ long getOldValue(); /** * @return the previous state. */ CounterState getOldState(); /** * @return the counter value. */ long getNewValue(); /** * @return the counter state. */ CounterState getNewState(); }
468
13.65625
45
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/api/PropertyFormatter.java
package org.infinispan.counter.api; import static org.infinispan.counter.api.CounterConfiguration.builder; import java.util.Properties; import java.util.function.Consumer; import java.util.function.Function; /** * A property style format for {@link CounterConfiguration}. * * @author Pedro Ruivo * @since 9.2 */ public final class PropertyFormatter { private static final PropertyFormatter INSTANCE = new PropertyFormatter(); public static PropertyFormatter getInstance() { return INSTANCE; } public Properties format(CounterConfiguration configuration) { Properties properties = new Properties(); PropertyKey.TYPE.setProperty(configuration, properties); PropertyKey.STORAGE.setProperty(configuration, properties); PropertyKey.INITIAL_VALUE.setProperty(configuration, properties); switch (configuration.type()) { case UNBOUNDED_STRONG: break; case BOUNDED_STRONG: PropertyKey.UPPER_BOUND.setProperty(configuration, properties); PropertyKey.LOWER_BOUND.setProperty(configuration, properties); break; case WEAK: PropertyKey.CONCURRENCY.setProperty(configuration, properties); break; default: throw new IllegalStateException(); } return properties; } public CounterConfiguration.Builder from(Properties properties) { CounterType type = CounterType.valueOf(properties.getProperty(PropertyKey.TYPE.key)); CounterConfiguration.Builder builder = builder(type); fromProperty(properties, PropertyKey.STORAGE, Storage::valueOf, builder::storage); fromProperty(properties, PropertyKey.INITIAL_VALUE, Long::valueOf, builder::initialValue); switch (type) { case WEAK: fromProperty(properties, PropertyKey.CONCURRENCY, Integer::valueOf, builder::concurrencyLevel); break; case BOUNDED_STRONG: fromProperty(properties, PropertyKey.UPPER_BOUND, Long::valueOf, builder::upperBound); fromProperty(properties, PropertyKey.LOWER_BOUND, Long::valueOf, builder::lowerBound); break; case UNBOUNDED_STRONG: break; default: throw new IllegalStateException(); } return builder; } private <T> void fromProperty(Properties properties, PropertyKey key, Function<String, T> read, Consumer<T> setter) { String value = properties.getProperty(key.key); if (value != null) { setter.accept(read.apply(value)); } } private enum PropertyKey { TYPE("type") { @Override void setProperty(CounterConfiguration config, Properties properties) { properties.setProperty(key, String.valueOf(config.type())); } }, INITIAL_VALUE("initial-value") { @Override void setProperty(CounterConfiguration config, Properties properties) { properties.setProperty(key, String.valueOf(config.initialValue())); } }, STORAGE("storage") { @Override void setProperty(CounterConfiguration config, Properties properties) { properties.setProperty(key, String.valueOf(config.storage())); } }, UPPER_BOUND("upper-bound") { @Override void setProperty(CounterConfiguration config, Properties properties) { properties.setProperty(key, String.valueOf(config.upperBound())); } }, LOWER_BOUND("lower-bound") { @Override void setProperty(CounterConfiguration config, Properties properties) { properties.setProperty(key, String.valueOf(config.lowerBound())); } }, CONCURRENCY("concurrency-level") { @Override void setProperty(CounterConfiguration config, Properties properties) { properties.setProperty(key, String.valueOf(config.concurrencyLevel())); } }; final String key; PropertyKey(String key) { this.key = key; } abstract void setProperty(CounterConfiguration config, Properties properties); } }
4,171
33.766667
120
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/api/CounterConfiguration.java
package org.infinispan.counter.api; import java.util.Objects; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; /** * A counter configuration used to define counters cluster wide via {@link CounterManager#defineCounter(String, * CounterConfiguration)}. * <p> * The configuration must be built using {@link CounterConfiguration#builder(CounterType)}. Only {@link CounterType} is * required. * * @author Pedro Ruivo * @see CounterType * @since 9.0 */ @ProtoTypeId(ProtoStreamTypeIds.COUNTER_CONFIGURATION) public class CounterConfiguration { private final long initialValue; private final long upperBound; private final long lowerBound; private final long lifespan; private final int concurrencyLevel; private final CounterType type; private final Storage storage; @ProtoFactory CounterConfiguration(long initialValue, long lowerBound, long upperBound, int concurrencyLevel, CounterType type, Storage storage, long lifespan) { this.initialValue = initialValue; this.upperBound = upperBound; this.lowerBound = lowerBound; this.lifespan = lifespan; this.concurrencyLevel = concurrencyLevel; this.type = type; this.storage = storage; } public static Builder builder(CounterType type) { return new Builder(Objects.requireNonNull(type)); } @ProtoField(number = 1, defaultValue = "0") public long initialValue() { return initialValue; } @ProtoField(number = 3, defaultValue = "0") public long upperBound() { return upperBound; } @ProtoField(number = 2, defaultValue = "0") public long lowerBound() { return lowerBound; } @ProtoField(5) public CounterType type() { return type; } @ProtoField(number = 4, defaultValue = "0") public int concurrencyLevel() { return concurrencyLevel; } @ProtoField(6) public Storage storage() { return storage; } @ProtoField(number = 7, defaultValue = "0") public long lifespan() { return lifespan; } @Override public String toString() { return "CounterConfiguration{" + "initialValue=" + initialValue + ", upperBound=" + upperBound + ", lowerBound=" + lowerBound + ", concurrencyLevel=" + concurrencyLevel + ", type=" + type + ", storage=" + storage + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CounterConfiguration that = (CounterConfiguration) o; return initialValue == that.initialValue && upperBound == that.upperBound && lowerBound == that.lowerBound && concurrencyLevel == that.concurrencyLevel && type == that.type && storage == that.storage; } @Override public int hashCode() { int result = (int) (initialValue ^ (initialValue >>> 32)); result = 31 * result + (int) (upperBound ^ (upperBound >>> 32)); result = 31 * result + (int) (lowerBound ^ (lowerBound >>> 32)); result = 31 * result + concurrencyLevel; result = 31 * result + type.hashCode(); result = 31 * result + storage.hashCode(); return result; } /** * The builder of {@link CounterConfiguration}. */ public static class Builder { private final CounterType type; private long initialValue = 0; private long lowerBound = Long.MIN_VALUE; private long upperBound = Long.MAX_VALUE; private long lifespan = 0; private Storage storage = Storage.VOLATILE; private int concurrencyLevel = 16; private Builder(CounterType type) { this.type = type; } /** * Sets the initial value. * <p> * The default value is zero. * * @param initialValue the new initial value. */ public Builder initialValue(long initialValue) { this.initialValue = initialValue; return this; } /** * Sets the lower bound (inclusive) of the counter. * <p> * Only for {@link CounterType#BOUNDED_STRONG} counters. * <p> * The default value is {@link Long#MIN_VALUE}. * * @param lowerBound the new lower bound. */ public Builder lowerBound(long lowerBound) { this.lowerBound = lowerBound; return this; } /** * Sets the upper bound (inclusive) of the counter. * <p> * Only for {@link CounterType#BOUNDED_STRONG} counters. * <p> * The default value is {@link Long#MAX_VALUE}. * * @param upperBound the new upper bound. */ public Builder upperBound(long upperBound) { this.upperBound = upperBound; return this; } public Builder lifespan(long lifespan) { this.lifespan = lifespan; return this; } /** * Sets the storage mode of the counter. * <p> * The default value is {@link Storage#VOLATILE}. * * @param storage the new storage mode. * @see Storage */ public Builder storage(Storage storage) { this.storage = Objects.requireNonNull(storage); return this; } /** * Sets the concurrency level of the counter. * <p> * Only for {@link CounterType#WEAK}. * <p> * <p> * The concurrency level set the amount of concurrent updates that can happen simultaneous. It is trade-off * between the write performance and read performance. A higher value will allow more concurrent updates, however * it will take more time to compute the counter value. * <p> * The default value is 64. * * @param concurrencyLevel the new concurrency level. */ public Builder concurrencyLevel(int concurrencyLevel) { this.concurrencyLevel = concurrencyLevel; return this; } /** * @return the {@link CounterConfiguration} with this configuration. */ public CounterConfiguration build() { return new CounterConfiguration(initialValue, lowerBound, upperBound, concurrencyLevel, type, storage, lifespan); } } }
6,570
27.820175
119
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/api/WeakCounter.java
package org.infinispan.counter.api; import java.util.concurrent.CompletableFuture; /** * A weak consistent counter interface. * <p> * This interface represents a weak counter in the way that the write operations does not return a consistent results. * In this way, all the writes return a {@link CompletableFuture<Void>}. * <p> * Note: the reset operation is not atomic. * * @author Pedro Ruivo * @since 9.0 */ public interface WeakCounter { /** * @return The counter name. */ String getName(); /** * It returns the counter's value. * <p> * This value may be not the mot up-to-data value. * * @return The counter's value. */ long getValue(); /** * Increments the counter. */ default CompletableFuture<Void> increment() { return add(1L); } /** * Decrements the counter. */ default CompletableFuture<Void> decrement() { return add(-1L); } /** * Adds the given value to the new value. * * @param delta the value to add. */ CompletableFuture<Void> add(long delta); /** * Resets the counter to its initial value. */ CompletableFuture<Void> reset(); /** * Adds a {@link CounterListener} to this counter. * * @param listener The listener to add. * @param <T> The type of the listener. It must implement {@link CounterListener}. * @return A {@link Handle} that allows to remove the listener via {@link Handle#remove()} ()}. */ <T extends CounterListener> Handle<T> addListener(T listener); /** * @return the {@link CounterConfiguration} used by this counter. */ CounterConfiguration getConfiguration(); /** * It removes this counter from the cluster. * <p> * Note that it doesn't remove the counter from the {@link CounterManager}. If you want to remove the counter from * the {@link CounterManager} use {@link CounterManager#remove(String)}. * * @return The {@link CompletableFuture} that is completed when the counter is removed from the cluster. */ CompletableFuture<Void> remove(); /** * It returns a synchronous weak counter for this instance. * * @return a {@link SyncWeakCounter}. */ SyncWeakCounter sync(); }
2,264
23.89011
118
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/api/CounterManager.java
package org.infinispan.counter.api; import java.util.Collection; /** * The {@link CounterManager} creates, defines and returns counters. * <p> * It is thread-safe in the way that multiples threads can retrieve/create counters concurrently. If it is the first * time a counter is created, other concurrent threads may block until it is properly initialized. * <p> * A counter can be defined using {@link CounterManager#defineCounter(String, CounterConfiguration)} and {@link * CounterManager#isDefined(String)} returns if the counter is defined or not. * <p> * The counter can be retrieved/created using the {@link CounterManager#getStrongCounter(String)} or {@link * CounterManager#getWeakCounter(String)} to return an (un)bounded strong counter or weak counter. The operation will * fail if the counter is defined with a different type. For example, define a strong counter {@code "test"} and try to * retrieve using the {@code getWeakCounter("test"}. * * @author Pedro Ruivo * @see CounterConfiguration * @since 9.0 */ public interface CounterManager { /** * Returns the {@link StrongCounter} with that specific name. * <p> * If the {@link StrongCounter} does not exists, it is created based on the {@link CounterConfiguration}. * <p> * Note that the counter must be defined prior to this method invocation using {@link * CounterManager#defineCounter(String, CounterConfiguration)} or via global configuration. This method only supports * {@link CounterType#BOUNDED_STRONG} and {@link CounterType#UNBOUNDED_STRONG} counters. * * @param name the counter name. * @return the {@link StrongCounter} instance. * @throws org.infinispan.counter.exception.CounterException if unable to retrieve the counter. * @throws org.infinispan.counter.exception.CounterConfigurationException if the counter configuration is not valid * or it does not exists. */ StrongCounter getStrongCounter(String name); /** * Returns the {@link WeakCounter} with that specific name. * <p> * If the {@link WeakCounter} does not exists, it is created based on the {@link CounterConfiguration}. * <p> * Note that the counter must be defined prior to this method invocation using {@link * CounterManager#defineCounter(String, CounterConfiguration)} or via global configuration. This method only supports * {@link CounterType#WEAK} counters. * * @param name the counter name. * @return the {@link WeakCounter} instance. * @throws org.infinispan.counter.exception.CounterException if unable to retrieve the counter. * @throws org.infinispan.counter.exception.CounterConfigurationException if the counter configuration is not valid * or it does not exists. */ WeakCounter getWeakCounter(String name); /** * Defines a counter with the specific {@code name} and {@link CounterConfiguration}. * <p> * It does not overwrite existing configurations. * * @param name the counter name. * @param configuration the counter configuration * @return {@code true} if successfully defined or {@code false} if the counter exists or fails to defined. */ boolean defineCounter(String name, CounterConfiguration configuration); /** * It removes the counter and its configuration from the cluster. * * @param name The counter's name to remove */ void undefineCounter(String name); /** * @param name the counter name. * @return {@code true} if the counter is defined or {@code false} if the counter is not defined or fails to check. */ boolean isDefined(String name); /** * @param counterName the counter name. * @return the counter's {@link CounterConfiguration} or {@code null} if the counter is not defined. */ CounterConfiguration getConfiguration(String counterName); /** * It removes the counter from the cluster. * <p> * All instances returned by {@link #getWeakCounter(String)} or {@link #getStrongCounter(String)} are destroyed and * they shouldn't be used anymore. Also, the registered {@link CounterListener}s are removed and they aren't invoked * anymore. * * @param counterName The counter's name to remove. */ void remove(String counterName); /** * Returns a {@link Collection} of defined counter names. * * @return a {@link Collection} of defined counter names. */ Collection<String> getCounterNames(); }
4,648
42.046296
120
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/api/Handle.java
package org.infinispan.counter.api; /** * As a return of {@link StrongCounter#addListener(CounterListener)}, it is used to un-register the {@link CounterListener}. * * @author Pedro Ruivo * @since 9.0 */ public interface Handle<T extends CounterListener> { /** * @return the {@link CounterListener} managed by this. */ T getCounterListener(); /** * Removes the {@link CounterListener}. */ void remove(); }
442
20.095238
124
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/exception/package-info.java
/** * Clustered Counters Exceptions. * * @api.public */ package org.infinispan.counter.exception;
102
13.714286
41
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/exception/CounterOutOfBoundsException.java
package org.infinispan.counter.exception; import static java.lang.String.format; import org.infinispan.counter.api.StrongCounter; /** * A {@link CounterException} signalling that the {@link StrongCounter} has reached its bounds. * * @author Pedro Ruivo * @since 9.0 */ public class CounterOutOfBoundsException extends CounterException { public static final String FORMAT_MESSAGE = "%s reached."; public static final String UPPER_BOUND = "Upper bound"; public static final String LOWER_BOUND = "Lower bound"; public CounterOutOfBoundsException(String message) { super(message); } public boolean isUpperBoundReached() { return getMessage().endsWith(format(FORMAT_MESSAGE, UPPER_BOUND)); } public boolean isLowerBoundReached() { return getMessage().endsWith(format(FORMAT_MESSAGE, LOWER_BOUND)); } }
854
26.580645
95
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/exception/CounterConfigurationException.java
package org.infinispan.counter.exception; /** * Signals a missing configuration or an invalid configuration. * * @author Pedro Ruivo * @since 9.0 */ public class CounterConfigurationException extends CounterException { public CounterConfigurationException() { } public CounterConfigurationException(String message) { super(message); } public CounterConfigurationException(String message, Throwable cause) { super(message, cause); } public CounterConfigurationException(Throwable cause) { super(cause); } }
559
19.740741
74
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/exception/CounterNotFoundException.java
package org.infinispan.counter.exception; /** * Signal that an attempt to access a counter has failed. * * @since 14.0 */ public class CounterNotFoundException extends CounterException { public CounterNotFoundException() { } public CounterNotFoundException(String message) { super(message); } public CounterNotFoundException(String message, Throwable cause) { super(message, cause); } public CounterNotFoundException(Throwable cause) { super(cause); } public CounterNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
704
23.310345
124
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/exception/CounterException.java
package org.infinispan.counter.exception; /** * A {@link RuntimeException} related to counters. * * @author Pedro Ruivo * @since 9.0 */ public class CounterException extends RuntimeException { public CounterException() { } public CounterException(String message) { super(message); } public CounterException(String message, Throwable cause) { super(message, cause); } public CounterException(Throwable cause) { super(cause); } public CounterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
671
21.4
116
java
null
infinispan-main/commons/all/src/main/java/org/infinispan/counter/util/EncodeUtil.java
package org.infinispan.counter.util; import static org.infinispan.commons.logging.Log.CONTAINER; import java.util.function.Consumer; import java.util.function.IntConsumer; import java.util.function.IntSupplier; import java.util.function.LongConsumer; import java.util.function.LongSupplier; import java.util.function.Supplier; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.Storage; /** * Utility class to handle encoding or decoding counter's classes. * * @author Pedro Ruivo * @since 9.2 */ public final class EncodeUtil { /* 00000000 ||^- 1 WEAK, 0 STRONG |^-- 1 BOUNDED, 0 UNBOUNDED ^--- 1 PERSISTENT, 0 VOLATILE */ private static final byte WEAK_COUNTER = 0x01; private static final byte BOUNDED_COUNTER = 0x02; private static final byte UNBOUNDED_COUNTER = 0x00; private EncodeUtil() { } /** * Decodes the {@link CounterType}. * * @return the decoded {@link CounterType}. * @see #encodeTypeAndStorage(CounterConfiguration) */ public static Storage decodeStorage(byte flags) { return (flags & 0x04) == 0 ? Storage.VOLATILE : Storage.PERSISTENT; } /** * Decodes the {@link Storage}. * * @return the decoded {@link Storage}. * @see #encodeTypeAndStorage(CounterConfiguration) */ public static CounterType decodeType(byte flags) { switch (flags & 0x03) { case WEAK_COUNTER: return CounterType.WEAK; case BOUNDED_COUNTER: return CounterType.BOUNDED_STRONG; case UNBOUNDED_COUNTER: return CounterType.UNBOUNDED_STRONG; default: throw CONTAINER.invalidCounterTypeEncoded(); } } private static byte encodeStorage(Storage storage) { switch (storage) { case VOLATILE: return 0x00; case PERSISTENT: return 0x04; default: throw new IllegalStateException("Unknown storage mode: " + storage); } } private static byte encodeType(CounterType type) { switch (type) { case UNBOUNDED_STRONG: return UNBOUNDED_COUNTER; case BOUNDED_STRONG: return BOUNDED_COUNTER; case WEAK: return WEAK_COUNTER; default: throw new IllegalStateException(); } } /** * Encodes the {@link Storage} and the {@link CounterType}. * <p> * See the documentation for further details about the encoding. * <p> * * @return the encoded {@link Storage} and the {@link CounterType}. * @see <a href="https://infinispan.org/docs/dev/user_guide/user_guide.html#counter-config-encode">Counter * Configuration Encoding</a> */ public static byte encodeTypeAndStorage(CounterConfiguration configuration) { return (byte) (encodeType(configuration.type()) | encodeStorage(configuration.storage())); } /** * Encodes the configuration. * <p> * See the documentation for further details about the encoding. * <p> * * @see <a href="https://infinispan.org/docs/dev/user_guide/user_guide.html#counter-config-encode">Counter * Configuration Encoding</a> */ public static void encodeConfiguration(CounterConfiguration configuration, Consumer<Byte> byteConsumer, LongConsumer longConsumer, IntConsumer intConsumer) { byteConsumer.accept(encodeTypeAndStorage(configuration)); switch (configuration.type()) { case WEAK: intConsumer.accept(configuration.concurrencyLevel()); break; case BOUNDED_STRONG: longConsumer.accept(configuration.lowerBound()); longConsumer.accept(configuration.upperBound()); break; case UNBOUNDED_STRONG: break; default: throw new IllegalStateException(); } longConsumer.accept(configuration.initialValue()); } /** * Decodes a {@link CounterConfiguration} encoded by {@link #encodeConfiguration(CounterConfiguration, Consumer, * LongConsumer, IntConsumer)}. * * @return the decoded {@link CounterConfiguration}. * @see #encodeConfiguration(CounterConfiguration, Consumer, LongConsumer, IntConsumer) */ public static CounterConfiguration decodeConfiguration(Supplier<Byte> byteSupplier, LongSupplier longSupplier, IntSupplier intSupplier) { byte flags = byteSupplier.get(); CounterType type = decodeType(flags); CounterConfiguration.Builder builder = CounterConfiguration.builder(type); builder.storage(decodeStorage(flags)); switch (type) { case WEAK: builder.concurrencyLevel(intSupplier.getAsInt()); break; case BOUNDED_STRONG: builder.lowerBound(longSupplier.getAsLong()); builder.upperBound(longSupplier.getAsLong()); break; case UNBOUNDED_STRONG: default: break; } builder.initialValue(longSupplier.getAsLong()); return builder.build(); } }
5,150
30.796296
115
java
null
infinispan-main/commons/jdk21/src/main/java/org/infinispan/commons/jdk21/ThreadCreatorImpl.java
package org.infinispan.commons.jdk21; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ public class ThreadCreatorImpl implements org.infinispan.commons.spi.ThreadCreator { public Thread createThread(ThreadGroup group, Runnable runnable, boolean lightweight) { if (lightweight) { return Thread.ofVirtual().unstarted(runnable); } else { return new Thread(group, runnable); } } }
455
24.333333
90
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/ConfigEmbeddedCacheManagerReplication.java
private static EmbeddedCacheManager createCacheManagerFromXml() throws IOException { return new DefaultCacheManager("infinispan-replication.xml"); }
152
37.25
84
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/ClusteredCountersIsDefined.java
CounterManager manager = ... if (!manager.isDefined("someCounter")) { manager.define("someCounter", ...); }
112
21.6
40
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/GridFileSystemExample.java
Cache<String,byte[]> data = cacheManager.getCache("distributed"); Cache<String,GridFile.Metadata> metadata = cacheManager.getCache("replicated"); GridFilesystem fs = new GridFilesystem(data, metadata); // Create directories File file=fs.getFile("/tmp/testfile/stuff"); fs.mkdirs(); // creates directories /tmp/testfile/stuff // List all files and directories under "/usr/local" file=fs.getFile("/usr/local"); File[] files=file.listFiles(); // Create a new file file=fs.getFile("/tmp/testfile/stuff/README.txt"); file.createNewFile();
537
32.625
79
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/TemperatureMonitor.java
@ClientListener public class TemperatureChangesListener { private String location; TemperatureChangesListener(String location) { this.location = location; } @ClientCacheEntryCreated public void created(ClientCacheEntryCreatedEvent event) { if(event.getKey().equals(location)) { cache.getAsync(location) .whenComplete((temperature, ex) -> System.out.printf(">> Location %s Temperature %s", location, temperature)); } } }
503
27
96
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/StateTransferXsite.java
lon.sites().addBackup() .site("NYC") .backupFailurePolicy(BackupFailurePolicy.FAIL) .strategy(BackupConfiguration.BackupStrategy.SYNC) .stateTransfer() .chunkSize(512) .timeout(1200000) .maxRetries(30) .waitingTimeBetweenRetries(2000);
296
28.7
56
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/RESTTracingPropagation.java
HashMap<String, String> contextMap = new HashMap<>(); // Inject the request with the *current* Context, which contains our current Span. W3CTraceContextPropagator.getInstance().inject(Context.current(), contextMap, (carrier, key, value) -> carrier.put(key, value)); // Pass the context map in the header RestCacheClient client = restClient.cache(CACHE_NAME); client.put("aaa", MediaType.TEXT_PLAIN.toString(),RestEntity.create(MediaType.TEXT_PLAIN, "bbb"), contextMap);
472
46.3
110
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/EvictionPassivation.java
ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory().maxCount(100); builder.persistence().passivation(true); //Persistent storage configuration
167
41
75
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/AutowiredRemoteCacheManager.java
private final RemoteCacheManager cacheManager; @Autowired public YourClassName(RemoteCacheManager cacheManager) { this.cacheManager = cacheManager; }
155
21.285714
55
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/ConfigCustomInterceptors.java
Configuration config = new ConfigurationBuilder()   .customInterceptors().addInterceptor()    .interceptor(new FirstInterceptor()).position(InterceptorConfiguration.Position.FIRST) .interceptor(new LastInterceptor()).position(InterceptorConfiguration.Position.LAST) .interceptor(new FixPositionInterceptor()).index(8) .interceptor(new AfterInterceptor()).after(NonTransactionalLockingInterceptor.class) .interceptor(new BeforeInterceptor()).before(CallInterceptor.class)   .build();
500
54.666667
90
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/LibraryInitializerClient.java
ConfigurationBuilder remoteBuilder = new ConfigurationBuilder(); remoteBuilder.addServer().host(host).port(Integer.parseInt(port)); // Add your generated SerializationContextInitializer implementation. LibraryInitalizer initializer = new LibraryInitalizerImpl(); remoteBuilder.addContextInitializer(initializer);
314
44
69
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/GetAdvancedCache.java
AdvancedCache advancedCache = cache.getAdvancedCache();
56
27.5
55
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/CreateCache.java
Cache<String, String> myCache = manager.administration().createCache("myCache", "myTemplate");
95
47
94
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/CounterGetStrongCompareSwap.java
StrongCounter counter = counterManager.getStrongCounter("my-counter"); long oldValue = counter.getValue().get(); long currentValue, newValue; do { currentValue = oldValue; newValue = someLogic(oldValue); } while ((oldValue = counter.compareAndSwap(oldValue, newValue).get()) != currentValue);
299
36.5
88
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/HotRodTLS.java
ConfigurationBuilder clientBuilder = new ConfigurationBuilder(); clientBuilder .addServer() .host("127.0.0.1") .port(11222) .security() .ssl() // Server SNI hostname. .sniHostName("myservername") // Keystore that contains the public keys for {brandname} Server. // Clients use the trust store to verify {brandname} Server identities. .trustStoreFileName("/path/to/server/truststore") .trustStorePassword("truststorepassword".toCharArray()) .trustStoreType("PCKS12") // Keystore that contains client certificates. // Clients present these certificates to {brandname} Server. .keyStoreFileName("/path/to/client/keystore") .keyStorePassword("keystorepassword".toCharArray()) .keyStoreType("PCKS12") .authentication() // Clients must use the EXTERNAL mechanism for certificate authentication. .saslMechanism("EXTERNAL");
973
41.347826
83
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/PersistenceClusterLoader.java
ConfigurationBuilder b = new ConfigurationBuilder(); b.persistence() .addClusterLoader() .remoteCallTimeout(500);
122
23.6
52
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/SpringEnableCaching.java
@EnableCaching @Configuration public class Config { }
54
12.75
29
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/ConfigLoadCustomCache.java
public static void main(String args[]) throws Exception { Cache<Object, Object> c = new DefaultCacheManager("infinispan.xml").getCache("xml-configured-cache"); }
163
40
102
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/SpringCachableExample.java
@Transactional @Cacheable(value = "books", key = "#bookId") public Book findBook(Integer bookId) {...}
103
25
44
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/Visitor.java
public interface Vistor { Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable; Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable; Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable; Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable; Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable; ... etc ... }
523
36.428571
102
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/TaskExecute.java
// Add configuration for a locally running server. ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("127.0.0.1").port(11222); // Connect to the server. RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // Retrieve the remote cache. RemoteCache<String, String> cache = cacheManager.getCache(); // Create task parameters. Map<String, String> parameters = new HashMap<>(); parameters.put("name", "developer"); // Run the server task. String greet = cache.execute("hello-task", parameters); System.out.println(greet);
578
31.166667
74
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/LibraryInitializerClientSchema.java
/** * Register generated Protobuf schema with {brandname} Server. * This requires the RemoteCacheManager to be initialized. * * @param initializer The serialization context initializer for the schema. */ private void registerSchemas(SerializationContextInitializer initializer) { // Store schemas in the '___protobuf_metadata' cache to register them. // Using ProtobufMetadataManagerConstants might require the query dependency. final RemoteCache<String, String> protoMetadataCache = remoteCacheManager.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); // Add the generated schema to the cache. protoMetadataCache.put(initializer.getProtoFileName(), initializer.getProtoFile()); // Ensure the registered Protobuf schemas do not contain errors. // Throw an exception if errors exist. String errors = protoMetadataCache.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX); if (errors != null) { throw new IllegalStateException("Some Protobuf schema files contain errors: " + errors + "\nSchema :\n" + initializer.getProtoFileName()); } }
1,093
51.095238
148
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/ListenerPrintWhenAdded.java
@Listener public class PrintWhenAdded { Queue<CacheEntryCreatedEvent> events = new ConcurrentLinkedQueue<>();   @CacheEntryCreated   public CompletionStage<Void> print(CacheEntryCreatedEvent event) { events.add(event); return null;   } }
250
19.916667
71
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/PersistenceFileStore.java
ConfigurationBuilder builder = new ConfigurationBuilder(); builder.persistence().passivation(true) .addSoftIndexFileStore() .shared(false) .dataLocation("data") .indexLocation("index") .modificationQueueSize(2048);
262
31.875
58
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/ConfigPreconfiguredJgroups.java
GlobalConfiguration gc = new GlobalConfigurationBuilder() .transport().defaultTransport() .addProperty("configurationFile", "/default-configs/default-jgroups-tcp.xml") .build();
187
36.6
80
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/PersistenceUserEntityClass.java
@Entity public class User implements Serializable { @Id private String username; private String firstName; private String lastName; ... }
144
13.5
43
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/WriteOnlyMapTruncate.java
WriteOnlyMap<String, String> writeOnlyMap = ... CompletableFuture<Void> truncateFuture = writeOnlyMap.truncate(); truncateFuture.thenAccept(x -> "Cache contents cleared");
173
33.8
65
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/HotRodClientIntelligence.java
ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clientIntelligence(ClientIntelligence.BASIC);
113
37
58
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/RestHttpClient.java
package org.infinispan; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.Base64; /** * RestExample class shows you how to access your cache via HttpClient API with Java 11 or later. * * @author Gustavo Lira (glira@redhat.com) */ public class RestExample { private static final String SERVER_ADDRESS = "http://localhost:11222"; private static final String CACHE_URI = "/rest/v2/caches/default"; /** * postMethod create a named cache. * @param httpClient HTTP client that sends requests and receives responses * @param builder Encapsulates HTTP requests * @throws IOException * @throws InterruptedException */ public void postMethod(HttpClient httpClient, HttpRequest.Builder builder) throws IOException, InterruptedException { System.out.println("----------------------------------------"); System.out.println("Executing POST"); System.out.println("----------------------------------------"); HttpRequest request = builder.POST(HttpRequest.BodyPublishers.noBody()).build(); HttpResponse<Void> response = httpClient.send(request, HttpResponse.BodyHandlers.discarding()); System.out.println("----------------------------------------"); System.out.println(response.statusCode()); System.out.println("----------------------------------------"); } /** * putMethod stores a String value in your cache. * @param httpClient HTTP client that sends requests and receives responses * @param builder Encapsulates HTTP requests * @throws IOException * @throws InterruptedException */ public void putMethod(HttpClient httpClient, HttpRequest.Builder builder) throws IOException, InterruptedException { System.out.println("----------------------------------------"); System.out.println("Executing PUT"); System.out.println("----------------------------------------"); String cacheValue = "Infinispan REST Test"; HttpRequest request = builder.PUT(HttpRequest.BodyPublishers.ofString(cacheValue)).build(); HttpResponse<Void> response = httpClient.send(request, HttpResponse.BodyHandlers.discarding()); System.out.println("----------------------------------------"); System.out.println(response.statusCode()); System.out.println("----------------------------------------"); } /** * getMethod get a String value from your cache. * @param httpClient HTTP client that sends requests and receives responses * @param builder Encapsulates HTTP requests * @return String value * @throws IOException */ public String getMethod(HttpClient httpClient, HttpRequest.Builder builder) throws IOException, InterruptedException { System.out.println("----------------------------------------"); System.out.println("Executing GET"); System.out.println("----------------------------------------"); HttpRequest request = builder.GET().build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Executing get method of value: " + response.body()); System.out.println("----------------------------------------"); System.out.println(response.statusCode()); System.out.println("----------------------------------------"); return response.body(); } public static void main(String[] args) throws IOException, InterruptedException { RestExample restExample = new RestExample(); HttpClient httpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build(); restExample.postMethod(httpClient, getHttpReqestBuilder(String.format("%s%s", SERVER_ADDRESS, CACHE_URI))); restExample.putMethod(httpClient, getHttpReqestBuilder(String.format("%s%s/1", SERVER_ADDRESS, CACHE_URI))); restExample.getMethod(httpClient, getHttpReqestBuilder(String.format("%s%s/1", SERVER_ADDRESS, CACHE_URI))); } private static String basicAuth(String username, String password) { return "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes()); } private static final HttpRequest.Builder getHttpReqestBuilder(String url) { return HttpRequest.newBuilder() .uri(URI.create(url)) .header("Content-Type", "text/plain") .header("Authorization", basicAuth("user", "pass")); } }
4,531
42.576923
121
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/GrouperRegistration.java
Configuration c = new ConfigurationBuilder() .clustering().hash().groups().enabled().addGrouper(new KXGrouper()) .build();
129
31.5
70
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/ReadOnlyMapCompleted.java
import org.infinispan.functional.EntryView.*; import org.infinispan.functional.FunctionalMap.*; import org.infinispan.functional.Param.*; ReadOnlyMap<String, String> readOnlyMap = ... ReadOnlyMap<String, String> readOnlyMapCompleted = readOnlyMap.withParams(FutureMode.COMPLETED); Optional<String> readFuture = readOnlyMapCompleted.eval("key1", ReadEntryView::find).get();
374
45.875
96
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/HotRodExternal.java
ConfigurationBuilder clientBuilder = new ConfigurationBuilder(); clientBuilder .addServer() .host("127.0.0.1") .port(11222) .security() .ssl() // TrustStore stores trusted CA certificates for the server. .trustStoreFileName("/path/to/truststore") .trustStorePassword("truststorepassword".toCharArray()) .trustStoreType("PCKS12") // KeyStore stores valid client certificates. .keyStoreFileName("/path/to/keystore") .keyStorePassword("keystorepassword".toCharArray()) .keyStoreType("PCKS12") .authentication() .saslMechanism("EXTERNAL"); remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); RemoteCache<String, String> cache = remoteCacheManager.getCache("secured");
791
38.6
75
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/ConfigClustering.java
Configuration config = new ConfigurationBuilder()   .clustering()     .cacheMode(CacheMode.DIST_SYNC)     .l1().lifespan(25000L)     .hash().numOwners(3)   .build();
166
22.857143
49
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/PersistenceSqlTable.java
ConfigurationBuilder builder = new ConfigurationBuilder(); builder.persistence().addStore(TableJdbcStoreConfigurationBuilder.class) .dialect(DatabaseType.H2) .shared("true") .tableName("books") .schemaJdbcConfigurationBuilder() .messageName("books_value") .packageName("library");
321
34.777778
72
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/ABCMarshallingExternalizer.java
public static class ABCMarshallingExternalizer implements AdvancedExternalizer<ABCMarshalling> { @Override public void writeObject(ObjectOutput output, ABCMarshalling object) throws IOException { output.writeObject(object.getMap()); } @Override public ABCMarshalling readObject(ObjectInput input) throws IOException, ClassNotFoundException { ABCMarshalling hi = new ABCMarshalling(); hi.setMap((ConcurrentHashMap<Long, Long>) input.readObject()); return hi; } ... }
513
31.125
99
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/QueryExample.java
// Get the query factory from the cache QueryFactory queryFactory = org.infinispan.query.Search.getQueryFactory(cache); // Create an Ickle query that performs a full-text search using the ':' operator on the 'title' and 'authors.name' fields // You can perform full-text search only on indexed caches Query<Book> fullTextQuery = queryFactory.create("FROM org.infinispan.sample.Book b WHERE b.title:'infinispan' AND b.authors.name:'sanne'"); // Use the '=' operator to query fields in caches that are indexed or not // Non full-text operators apply only to fields that are not analyzed Query<Book> exactMatchQuery=queryFactory.create("FROM org.infinispan.sample.Book b WHERE b.isbn = '12345678' AND b.authors.name : 'sanne'"); // You can use full-text and non-full text operators in the same query Query<Book> query=queryFactory.create("FROM org.infinispan.sample.Book b where b.authors.name : 'Stephen' and b.description : (+'dark' -'tower')"); // Get the results List<Book> found=query.execute().list();
1,009
58.411765
147
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/BookIndexed.java
import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Text; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; @Indexed public class Book { @Text @ProtoField(number = 1) final String title; @Text @ProtoField(number = 2) final String description; @Basic @ProtoField(number = 3, defaultValue = "0") final int publicationYear; @ProtoFactory Book(String title, String description, int publicationYear) { this.title = title; this.description = description; this.publicationYear = publicationYear; } // public Getter methods omitted for brevity }
772
25.655172
64
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/ExternalizerRegisterId.java
GlobalConfigurationBuilder builder = ... builder.serialization()    .addAdvancedExternalizer(123, new Person.PersonExternalizer());
132
32.25
66
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/OffHeapMemory.java
ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory().storage(StorageType.OFF_HEAP).maxCount(500);
121
39.666667
61
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/ProtoStreamMarshaller.java
GlobalConfigurationBuilder builder = new GlobalConfigurationBuilder(); builder.serialization() .addContextInitializers(new LibraryInitializerImpl(), new SCIImpl());
172
42.25
76
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/SpringCacheManager.java
@EnableCaching @Configuration public class Config { @Bean public CacheManager cacheManager() { return new SpringEmbeddedCacheManager(infinispanCacheManager()); } private EmbeddedCacheManager infinispanCacheManager() { return new DefaultCacheManager(); } }
286
18.133333
70
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/PersonExternalizer.java
import org.infinispan.commons.marshall.Externalizer; import org.infinispan.commons.marshall.SerializeWith; @SerializeWith(Person.PersonExternalizer.class) public class Person {    final String name;    final int age;    public Person(String name, int age) {       this.name = name;       this.age = age;    }    public static class PersonExternalizer implements Externalizer<Person> {       @Override       public void writeObject(ObjectOutput output, Person person)             throws IOException {          output.writeObject(person.name);          output.writeInt(person.age);       }       @Override       public Person readObject(ObjectInput input)             throws IOException, ClassNotFoundException {          return new Person((String) input.readObject(), input.readInt());       }    } }
805
25.866667
75
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/Quickstart.java
public class Quickstart { public static void main(String args[]) throws Exception { Cache<Object, Object> c = new DefaultCacheManager().getCache(); } }
166
19.875
69
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/CounterGetStrong.java
CounterManager counterManager = ... StrongCounter aCounter = counterManager.getStrongCounter("my-counter");
108
35.333333
71
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/PartitionHandling.java
ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC) .partitionHandling() .whenSplit(PartitionHandling.DENY_READ_WRITES) .mergePolicy(MergePolicy.PREFERRED_NON_NULL);
246
40.166667
58
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/BackupSites.java
ConfigurationBuilder lon = new ConfigurationBuilder(); lon.sites().addBackup() .site("NYC") .backupFailurePolicy(BackupFailurePolicy.WARN) .strategy(BackupConfiguration.BackupStrategy.SYNC) .replicationTimeout(12000) .sites().addInUseBackupSite("NYC") .sites().addBackup() .site("SFO") .backupFailurePolicy(BackupFailurePolicy.IGNORE) .strategy(BackupConfiguration.BackupStrategy.ASYNC) .sites().addInUseBackupSite("SFO")
480
36
57
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/HotRodClientProperties.java
ConfigurationBuilder builder = new ConfigurationBuilder(); Properties p = new Properties(); try(Reader r = new FileReader("/path/to/hotrod-client.properties")) { p.load(r); builder.withProperties(p); } RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
283
34.5
74
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/ABCMarshallingExternalizerWrong.java
public static class ABCMarshallingExternalizer implements AdvancedExternalizer<ABCMarshalling> { @Override public void writeObject(ObjectOutput output, ABCMarshalling object) throws IOException { MapExternalizer ma = new MapExternalizer(); ma.writeObject(output, object.getMap()); } @Override public ABCMarshalling readObject(ObjectInput input) throws IOException, ClassNotFoundException { ABCMarshalling hi = new ABCMarshalling(); MapExternalizer ma = new MapExternalizer(); hi.setMap((ConcurrentHashMap<Long, Long>) ma.readObject(input)); return hi; } ... }
619
33.444444
99
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/PersistenceCustomStore.java
Configuration config = new ConfigurationBuilder() .persistence() .addStore(CustomStoreConfigurationBuilder.class) .build();
160
31.2
60
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/StaleReadExample.java
A=0 (non-cached), B=0 (cached in 2LC) TX1: write A = 1, write B = 1 TX1: start commit TX1: commit A, B in DB TX2: read A = 1 (from DB), read B = 0 (from 2LC) // breaks transactional atomicity TX1: update A, B in 2LC TX1: end commit Tx3: read A = 1, B = 1 // reads after TX1 commit completes are consistent again
312
33.777778
82
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/ExtrinsicGroup.java
public interface Grouper<T> { String computeGroup(T key, String group); Class<T> getKeyType(); }
106
16.833333
45
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/HotRodDisableTracingPropagation.java
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer() .host("127.0.0.1") .port(ConfigurationProperties.DEFAULT_HOTROD_PORT) .disableTracingPropagation();
261
31.75
71
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/HotRodCustomCBH.java
public class MyCallbackHandler implements CallbackHandler { final private String username; final private char[] password; final private String realm; public MyCallbackHandler(String username, String realm, char[] password) { this.username = username; this.password = password; this.realm = realm; } @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback callback : callbacks) { if (callback instanceof NameCallback) { NameCallback nameCallback = (NameCallback) callback; nameCallback.setName(username); } else if (callback instanceof PasswordCallback) { PasswordCallback passwordCallback = (PasswordCallback) callback; passwordCallback.setPassword(password); } else if (callback instanceof AuthorizeCallback) { AuthorizeCallback authorizeCallback = (AuthorizeCallback) callback; authorizeCallback.setAuthorized(authorizeCallback.getAuthenticationID().equals( authorizeCallback.getAuthorizationID())); } else if (callback instanceof RealmCallback) { RealmCallback realmCallback = (RealmCallback) callback; realmCallback.setText(realm); } else { throw new UnsupportedCallbackException(callback); } } } } ConfigurationBuilder clientBuilder = new ConfigurationBuilder(); clientBuilder.addServer() .host("127.0.0.1") .port(11222) .security().authentication() .serverName("myhotrodserver") .saslMechanism("DIGEST-MD5") .callbackHandler(new MyCallbackHandler("myuser","default","qwer1234!".toCharArray()));
1,786
40.55814
101
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/WriteOnlyMapExternalizer.java
import org.infinispan.functional.EntryView.*; import org.infinispan.functional.FunctionalMap.*; import org.infinispan.commons.marshall.Externalizer; import org.infinispan.commons.marshall.SerializeFunctionWith; WriteOnlyMap<String, String> writeOnlyMap = ... // Force a function to be Serializable Consumer<WriteEntryView<String>> function = new SetStringConstant<>(); CompletableFuture<Void> writeFuture = writeOnlyMap.eval("key1", function); @SerializeFunctionWith(value = SetStringConstant.Externalizer0.class) class SetStringConstant implements Consumer<WriteEntryView<String>> { @Override public void accept(WriteEntryView<String> view) { view.set("value1"); } public static final class Externalizer0 implements Externalizer<Object> { public void writeObject(ObjectOutput oo, Object o) { // No-op } public Object readObject(ObjectInput input) { return new SetStringConstant<>(); } } }
957
33.214286
76
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/InfinispanRemoteCacheCustomizer.java
@Bean public InfinispanRemoteCacheCustomizer customizer() { return b -> b.tcpKeepAlive(false); }
101
19.4
53
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/CounterListenerHandle.java
public interface Handle<T extends CounterListener> { T getCounterListener(); void remove(); }
100
19.2
52
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/Language.java
import org.infinispan.protostream.annotations.ProtoEnumValue; public enum Language { @ProtoEnumValue(number = 0, name = "EN") ENGLISH, @ProtoEnumValue(number = 1, name = "DE") GERMAN, @ProtoEnumValue(number = 2, name = "IT") ITALIAN, @ProtoEnumValue(number = 3, name = "ES") SPANISH, @ProtoEnumValue(number = 4, name = "FR") FRENCH; }
357
21.375
61
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/GetTypeClasses.java
@Override public Set<Class<? extends List>> getTypeClasses() {   return Util.<Class<? extends List>>asSet(          Util.loadClass("java.util.Collections$SingletonList")); }
174
28.166667
64
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/HotRodClientIntelligenceCluster.java
ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addCluster("NYC").clusterClientIntelligence(ClientIntelligence.BASIC);
138
45.333333
78
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/RequestBalancing.java
// Connect to the {brandname} cluster RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); // Obtain the remote cache RemoteCache<String, String> cache = cacheManager.getCache("test"); //Hot Rod client sends a request to the "s1" node cache.put("key1", "aValue"); //Hot Rod client sends a request to the "s2" node cache.put("key2", "aValue"); //Hot Rod client sends a request to the "s3" node String value = cache.get("key1"); //Hot Rod client sends the next request to the "s1" node again cache.remove("key2");
535
37.285714
74
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/JBossUserMarshaller.java
GlobalConfigurationBuilder builder = new GlobalConfigurationBuilder(); builder.serialization() .marshaller(new GenericJBossMarshaller()) .allowList() .addRegexps("org.infinispan.example.", "org.infinispan.concrete.SomeClass");
248
40.5
83
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/SpringCacheEvictAllEntriesExample.java
@Transactional @CacheEvict (value="books", key = "#bookId", allEntries = true) public void deleteAllBookEntries() {...}
120
29.25
63
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/HotRodOAuthBearerTokenCBH.java
String token = "..."; // Obtain the token from your OAuth2 provider TokenCallbackHandler tokenHandler = new TokenCallbackHandler(token); ConfigurationBuilder clientBuilder = new ConfigurationBuilder(); clientBuilder.addServer() .host("127.0.0.1") .port(11222) .security() .authentication() .saslMechanism("OAUTHBEARER") .callbackHandler(tokenHandler); remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); RemoteCache<String, String> cache = remoteCacheManager.getCache("secured"); // Refresh the token tokenHandler.setToken("newToken");
640
41.733333
75
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/RegisterCustomProtostuffSchema.java
RuntimeSchema.register(ExampleObject.class, new ExampleObjectSchema());
72
35.5
71
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/ConfigStats.java
GlobalConfiguration globalConfig = new GlobalConfigurationBuilder() .cacheContainer().statistics(true) .metrics().gauges(true).histograms(true) .jmx().enable() .build();
178
28.833333
67
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/GrouperImplementation.java
public class KXGrouper implements Grouper<String> { // The pattern requires a String key, of length 2, where the first character is // "k" and the second character is a digit. We take that digit, and perform // modular arithmetic on it to assign it to group "0" or group "1". private static Pattern kPattern = Pattern.compile("(^k)(<a>\\d</a>)$"); public String computeGroup(String key, String group) { Matcher matcher = kPattern.matcher(key); if (matcher.matches()) { String g = Integer.parseInt(matcher.group(2)) % 2 + ""; return g; } else { return null; } } public Class<String> getKeyType() { return String.class; } }
706
31.136364
82
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/GetClassLoader.java
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
80
39.5
79
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/HotRodForceReturnPerCache.java
ConfigurationBuilder builder = new ConfigurationBuilder(); // Return previous values for keys for invocations for a specific cache. builder.remoteCache("mycache") .forceReturnValues(true);
196
38.4
72
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/SpringCacheEvictEntryExample.java
@Transactional @CacheEvict (value="books", key = "#bookId") public void deleteBook(Integer bookId) {...}
105
25.5
44
java
null
infinispan-main/documentation/src/main/asciidoc/topics/code_examples/PiAppx.java
public class PiAppx { public static void main (String [] arg){ EmbeddedCacheManager cacheManager = .. boolean isCluster = .. int numPoints = 1_000_000_000; int numServers = isCluster ? cacheManager.getMembers().size() : 1; int numberPerWorker = numPoints / numServers; ClusterExecutor clusterExecutor = cacheManager.executor(); long start = System.currentTimeMillis(); // We receive results concurrently - need to handle that AtomicLong countCircle = new AtomicLong(); CompletableFuture<Void> fut = clusterExecutor.submitConsumer(m -> { int insideCircleCount = 0; for (int i = 0; i < numberPerWorker; i++) { double x = Math.random(); double y = Math.random(); if (insideCircle(x, y)) insideCircleCount++; } return insideCircleCount; }, (address, count, throwable) -> { if (throwable != null) { throwable.printStackTrace(); System.out.println("Address: " + address + " encountered an error: " + throwable); } else { countCircle.getAndAdd(count); } }); fut.whenComplete((v, t) -> { // This is invoked after all nodes have responded with a value or exception if (t != null) { t.printStackTrace(); System.out.println("Exception encountered while waiting:" + t); } else { double appxPi = 4.0 * countCircle.get() / numPoints; System.out.println("Distributed PI appx is " + appxPi + " using " + numServers + " node(s), completed in " + (System.currentTimeMillis() - start) + " ms"); } }); // May have to sleep here to keep alive if no user threads left } private static boolean insideCircle(double x, double y) { return (Math.pow(x - 0.5, 2) + Math.pow(y - 0.5, 2)) <= Math.pow(0.5, 2); } }
1,962
36.037736
117
java