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/test/java/org/infinispan/test/concurrent/DefaultCommandMatcher.java
package org.infinispan.test.concurrent; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.commands.DataCommand; import org.infinispan.commands.ReplicableCommand; import org.infinispan.commands.remote.CacheRpcCommand; import org.infinispan.remoting.transport.Address; /** * Generic {@link CommandMatcher} implementation that can use both {@link CacheRpcCommand} criteria (cache name, origin) * and {@link DataCommand} criteria (key). * * @author Dan Berindei * @since 7.0 */ public class DefaultCommandMatcher implements CommandMatcher { public static final Address LOCAL_ORIGIN_PLACEHOLDER = new AddressPlaceholder(); public static final Address ANY_REMOTE_PLACEHOLDER = new AddressPlaceholder(); private final Class<? extends ReplicableCommand> commandClass; private final String cacheName; private final Address origin; private final Object key; private final AtomicInteger actualMatchCount = new AtomicInteger(0); public DefaultCommandMatcher(Class<? extends ReplicableCommand> commandClass) { this(commandClass, null, null, null); } public DefaultCommandMatcher(Class<? extends CacheRpcCommand> commandClass, String cacheName, Address origin) { this(commandClass, cacheName, origin, null); } public DefaultCommandMatcher(Class<? extends DataCommand> commandClass, Object key) { this(commandClass, null, null, key); } DefaultCommandMatcher(Class<? extends ReplicableCommand> commandClass, String cacheName, Address origin, Object key) { this.commandClass = commandClass; this.cacheName = cacheName; this.origin = origin; this.key = key; } @Override public boolean accept(ReplicableCommand command) { if (commandClass != null && !commandClass.equals(command.getClass())) return false; if (cacheName != null && !cacheName.equals(((CacheRpcCommand) command).getCacheName().toString())) { return false; } if (origin != null && !addressMatches((CacheRpcCommand) command)) return false; if (key != null && !key.equals(((DataCommand) command).getKey())) return false; return true; } private boolean addressMatches(CacheRpcCommand command) { Address commandOrigin = command.getOrigin(); if (origin == LOCAL_ORIGIN_PLACEHOLDER) return commandOrigin == null; else if (origin == ANY_REMOTE_PLACEHOLDER) return commandOrigin != null; else return !origin.equals(commandOrigin); } private static class AddressPlaceholder implements Address { @Override public int compareTo(Address o) { throw new UnsupportedOperationException("This address should never be part of a view"); } } }
2,771
32.804878
121
java
null
infinispan-main/core/src/test/java/org/infinispan/test/concurrent/CacheComponentSequencerAction.java
package org.infinispan.test.concurrent; import org.infinispan.Cache; import org.infinispan.test.TestingUtil; /** * Replaces a cache component with a dynamic proxy that can interact with a {@link StateSequencer} when a method that * matches a {@link InvocationMatcher} is called. * * @author Dan Berindei * @since 7.0 */ public class CacheComponentSequencerAction<T> extends GlobalComponentSequencerAction<T> { private final Cache<?, ?> cache; public CacheComponentSequencerAction(StateSequencer stateSequencer, Cache<?, ?> cache, Class<T> componentClass, InvocationMatcher matcher) { super(stateSequencer, cache.getCacheManager(), componentClass, matcher); this.cache = cache; } @Override protected void replaceComponent() { if (ourHandler == null) { T component = cache.getAdvancedCache().getComponentRegistry().getComponent(componentClass); if (component == null) { throw new IllegalStateException("Attempting to wrap a non-existing component: " + componentClass); } ourHandler = new ProxyInvocationHandler(component, stateSequencer, matcher); T componentProxy = createComponentProxy(componentClass, ourHandler); TestingUtil.replaceComponent(cache, componentClass, componentProxy, true); } } }
1,315
36.6
143
java
null
infinispan-main/core/src/test/java/org/infinispan/test/concurrent/DefaultInvocationMatcher.java
package org.infinispan.test.concurrent; import java.util.concurrent.atomic.AtomicInteger; import org.hamcrest.Matcher; /** * Default {@link InvocationMatcher} implementation. * * @author Dan Berindei * @since 7.0 */ public class DefaultInvocationMatcher implements InvocationMatcher { private final String methodName; private final Matcher instanceMatcher; private final Matcher[] argumentMatchers; private final int matchCount; private final AtomicInteger matches = new AtomicInteger(); public DefaultInvocationMatcher(String methodName) { this(methodName, null, -1, null); } public DefaultInvocationMatcher(String methodName, Matcher instanceMatcher, int matchCount, Matcher... argumentMatchers) { this.methodName = methodName; this.instanceMatcher = instanceMatcher; this.argumentMatchers = argumentMatchers; this.matchCount = matchCount; } @Override public boolean accept(Object instance, String methodName, Object[] arguments) { if (!methodName.equals(this.methodName)) return false; if (instanceMatcher != null && !instanceMatcher.matches(instance)) return false; if (argumentMatchers != null) { for (int i = 0; i < argumentMatchers.length; i++) { if (argumentMatchers[i] != null && !argumentMatchers[i].matches(arguments[i])) return false; } } if (matchCount >= 0 && matches.getAndIncrement() != matchCount) { return false; } return true; } }
1,541
30.469388
125
java
null
infinispan-main/core/src/test/java/org/infinispan/test/concurrent/StateSequencerTest.java
package org.infinispan.test.concurrent; import static java.util.concurrent.TimeUnit.SECONDS; import static org.testng.AssertJUnit.assertFalse; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.Test; /** * {@link StateSequencer} test. * * @author Dan Berindei * @since 7.0 */ @Test(groups = "unit", testName = "test.concurrent.StateSequencerTest") public class StateSequencerTest extends AbstractInfinispanTest { public void testSingleThread() throws Exception { StateSequencer stateSequencer = new StateSequencer(); stateSequencer.logicalThread("t", "s0", "s1", "s2"); stateSequencer.advance("s0", 0, SECONDS); stateSequencer.advance("s1", 0, SECONDS); stateSequencer.advance("s2", 0, SECONDS); } @Test(expectedExceptions = IllegalArgumentException.class) public void testAdvanceToInvalidState() throws Exception { StateSequencer stateSequencer = new StateSequencer(); stateSequencer.advance("s1", 0, SECONDS); } @Test(expectedExceptions = IllegalArgumentException.class) public void testInvalidDependency() throws Exception { StateSequencer stateSequencer = new StateSequencer(); stateSequencer.logicalThread("t", "s1"); stateSequencer.order("s0", "s1"); } @Test(expectedExceptions = IllegalArgumentException.class) public void testInvalidDependency2() throws Exception { StateSequencer stateSequencer = new StateSequencer(); stateSequencer.logicalThread("t", "s1"); stateSequencer.order("s1", "s2"); } @Test(expectedExceptions = IllegalStateException.class) public void testDependencyCycle() throws Exception { StateSequencer stateSequencer = new StateSequencer(); stateSequencer.logicalThread("t", "s1", "s2", "s3", "s4"); stateSequencer.order("s4", "s2"); } public void testMultipleThreads() throws Exception { final StateSequencer stateSequencer = new StateSequencer(); stateSequencer.logicalThread("start", "start"); stateSequencer.logicalThread("t1", "t1:s1").order("start", "t1:s1"); stateSequencer.logicalThread("t2", "t2:s2").order("start", "t2:s2").order("t1:s1", "t2:s2"); stateSequencer.logicalThread("stop", "stop").order("t1:s1", "stop").order("t2:s2", "stop"); Future<Object> future1 = fork(new Callable<Object>() { @Override public Object call() throws Exception { stateSequencer.advance("t1:s1", 10, SECONDS); return null; } }); final AtomicBoolean t2s2Entered = new AtomicBoolean(false); Future<Object> future2 = fork(new Callable<Object>() { @Override public Object call() throws Exception { stateSequencer.enter("t2:s2", 10, SECONDS); t2s2Entered.set(true); stateSequencer.exit("t2:s2"); return null; } }); stateSequencer.enter("start", 0, SECONDS); Thread.sleep(500); assertFalse(future1.isDone()); assertFalse(future2.isDone()); assertFalse(t2s2Entered.get()); stateSequencer.exit("start"); stateSequencer.advance("stop", 10, SECONDS); future1.get(); future2.get(); } }
3,352
33.927083
98
java
null
infinispan-main/core/src/test/java/org/infinispan/test/concurrent/StateSequencerUtil.java
package org.infinispan.test.concurrent; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeoutException; import org.infinispan.Cache; import org.infinispan.commands.ReplicableCommand; import org.infinispan.interceptors.AsyncInterceptor; import org.infinispan.manager.EmbeddedCacheManager; /** * Various helper methods for working with {@link StateSequencer}s. * * @author Dan Berindei * @since 7.0 */ public class StateSequencerUtil { /** * Start decorating interceptor {@code interceptorClass} on {@code cache} to interact with a {@code StateSequencer}. */ public static InterceptorSequencerAction advanceOnInterceptor(StateSequencer stateSequencer, Cache<?, ?> cache, Class<? extends AsyncInterceptor> interceptorClass, CommandMatcher matcher) { return new InterceptorSequencerAction(stateSequencer, cache, interceptorClass, matcher); } /** * Start decorating the {@code InboundInvocationHandler} on {@code cacheManager} to interact with a {@code StateSequencer} * when a {@code CacheRpcCommand} is received. */ public static InboundRpcSequencerAction advanceOnInboundRpc(StateSequencer stateSequencer, Cache cache, CommandMatcher matcher) { return new InboundRpcSequencerAction(stateSequencer, cache, matcher); } /** * Start decorating the {@code RpcManager} on {@code cacheManager} to interact with a {@code StateSequencer} when a * command is sent. */ public static OutboundRpcSequencerAction advanceOnOutboundRpc(StateSequencer stateSequencer, Cache<?, ?> cache, CommandMatcher matcher) { return new OutboundRpcSequencerAction(stateSequencer, cache, matcher); } /** * Start decorating the component {@code componentClass} on {@code cache} to interact with a {@code StateSequencer} when a * method is called. */ public static CacheComponentSequencerAction advanceOnComponentMethod(StateSequencer stateSequencer, Cache<?, ?> cache, Class<?> componentClass, InvocationMatcher matcher) { return new CacheComponentSequencerAction(stateSequencer, cache, componentClass, matcher); } /** * Start decorating the component {@code componentClass} on {@code cacheManager} to interact with a {@code StateSequencer} * when a method is called. */ public static <T> GlobalComponentSequencerAction<T> advanceOnGlobalComponentMethod(StateSequencer stateSequencer, EmbeddedCacheManager cacheManager, Class<T> componentClass, InvocationMatcher matcher) { return new GlobalComponentSequencerAction(stateSequencer, cacheManager, componentClass, matcher); } /** * Start building a {@link CommandMatcher}. */ public static CommandMatcherBuilder matchCommand(Class<? extends ReplicableCommand> commandClass) { return new CommandMatcherBuilder(commandClass); } /** * Start building a {@link InvocationMatcher}. */ public static InvocationMatcherBuilder matchMethodCall(String methodName) { return new InvocationMatcherBuilder(methodName); } public static List<String> listCopy(List<String> statesUp) { return statesUp != null ? Collections.unmodifiableList(new LinkedList<String>(statesUp)) : null; } public static List<String> concat(String state1, String... additionalStates) { List<String> states = new ArrayList<String>(); states.add(state1); if (additionalStates != null) { states.addAll(Arrays.asList(additionalStates)); } return states; } /** * Advance to the every state in the {@code states} list, in the given order, but only if {@code condition} is true. * <p/> * Does nothing if {@code states} is {@code null} or empty. */ public static void advanceMultiple(StateSequencer stateSequencer, boolean condition, List<String> states) throws TimeoutException, InterruptedException { if (condition && states != null) { for (String state : states) { stateSequencer.advance(state); } } } }
4,162
37.546296
146
java
null
infinispan-main/core/src/test/java/org/infinispan/test/arquillian/DatagridManager.java
package org.infinispan.test.arquillian; import java.util.List; import java.util.concurrent.Future; import jakarta.transaction.RollbackException; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.MagicKey; import org.infinispan.manager.CacheContainer; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.Address; import org.infinispan.test.AbstractCacheTest; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.commons.test.ExceptionRunnable; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.ReplListener; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TransportFlags; import org.infinispan.util.concurrent.locks.LockManager; /** * An adapter class that enables users to call all important methods from * {@link MultipleCacheManagersTest}, {@link AbstractCacheTest} and * {@link AbstractInfinispanTest}, changing their visibility to public. * Usage of this class is in infinispan-arquillian-container project which * enables injecting of this class into a test case and forming a cluster * of cache managers/caches. * * A few methods from super-classes changed their names, mostly because * they cannot be overridden. All such methods have comments on them which * say "name change". * * * @author <a href="mailto:mgencur@redhat.com">Martin Gencur</a> * */ public class DatagridManager extends MultipleCacheManagersTest { @Override public void destroy() { TestingUtil.killCacheManagers(cacheManagers); cacheManagers.clear(); listeners.clear(); killSpawnedThreads(); } @Override protected void createCacheManagers() throws Throwable { //empty implementation } /* ========================= AbstractInfinispanTest methods ================== */ //name change public void waitForCondition(Condition ec, long timeout) { eventually(ec, timeout); } //name change public Future<?> forkThread(ExceptionRunnable r) throws Exception { return fork(r); } //name change public void waitForCondition(Condition ec) { eventually(ec); } /* =========================== AbstractCacheTest methods ====================== */ //name change public boolean xorOp(boolean b1, boolean b2) { return xor(b1, b2); } //name change public void assertKeyNotLocked(Cache cache, Object key) { assertEventuallyNotLocked(cache, key); } //name change public void assertKeyLocked(Cache cache, Object key) { assertLocked(cache, key); } //name change public boolean checkKeyLocked(Cache cache, Object key) { return checkLocked(cache, key); } /* ===================== MultipleCacheManagersTest methods ==================== */ //name change public void registerCacheManagers(CacheContainer... cacheContainers) { registerCacheManager(cacheContainers); } @Override public EmbeddedCacheManager addClusterEnabledCacheManager() { return super.addClusterEnabledCacheManager(); } @Override public EmbeddedCacheManager addClusterEnabledCacheManager(TransportFlags flags) { return super.addClusterEnabledCacheManager(flags); } @Override public EmbeddedCacheManager addClusterEnabledCacheManager(ConfigurationBuilder defaultConfig) { return super.addClusterEnabledCacheManager(defaultConfig); } @Override public EmbeddedCacheManager addClusterEnabledCacheManager(ConfigurationBuilder builder, TransportFlags flags) { return super.addClusterEnabledCacheManager(builder, flags); } @Override public void defineConfigurationOnAllManagers(String cacheName, ConfigurationBuilder b) { super.defineConfigurationOnAllManagers(cacheName, b); } @Override public void waitForClusterToForm(String cacheName) { super.waitForClusterToForm(cacheName); } @Override public void waitForClusterToForm() { super.waitForClusterToForm(); } @Override public void waitForClusterToForm(String... names) { super.waitForClusterToForm(names); } @Override public TransactionManager tm(Cache<?, ?> c) { return super.tm(c); } @Override public TransactionManager tm(int i, String cacheName) { return super.tm(i, cacheName); } @Override public TransactionManager tm(int i) { return super.tm(i); } @Override public Transaction tx(int i) { return super.tx(i); } @Override public void createClusteredCaches( int numMembersInCluster, String cacheName, ConfigurationBuilder builder) { super.createClusteredCaches(numMembersInCluster, cacheName, builder); } @Override public void createClusteredCaches( int numMembersInCluster, String cacheName, ConfigurationBuilder builder, TransportFlags flags) { super.createClusteredCaches(numMembersInCluster, cacheName, builder, flags); } @Override public ReplListener replListener(Cache cache) { return super.replListener(cache); } @Override public EmbeddedCacheManager manager(int i) { return super.manager(i); } @Override public Cache cache(int managerIndex, String cacheName) { return super.cache(managerIndex, cacheName); } @Override public void assertClusterSize(String message, int size) { super.assertClusterSize(message, size); } @Override public void removeCacheFromCluster(String cacheName) { super.removeCacheFromCluster(cacheName); } @Override public <A, B> Cache<A, B> cache(int index) { return super.cache(index); } @Override public Address address(int cacheIndex) { return super.address(cacheIndex); } @Override public AdvancedCache advancedCache(int i) { return super.advancedCache(i); } @Override public AdvancedCache advancedCache(int i, String cacheName) { return super.advancedCache(i, cacheName); } @Override public <K, V> List<Cache<K, V>> caches(String name) { return super.caches(name); } @Override public <K, V> List<Cache<K, V>> caches() { return super.caches(); } @Override public Address address(Cache c) { return super.address(c); } @Override public LockManager lockManager(int i) { return super.lockManager(i); } @Override public LockManager lockManager(int i, String cacheName) { return super.lockManager(i, cacheName); } @Override public List<EmbeddedCacheManager> getCacheManagers() { return super.getCacheManagers(); } @Override public void killMember(int cacheIndex) { super.killMember(cacheIndex); } @Override public Object getKeyForCache(int nodeIndex) { return super.getKeyForCache(nodeIndex); } @Override public Object getKeyForCache(int nodeIndex, String cacheName) { return super.getKeyForCache(nodeIndex, cacheName); } @Override public MagicKey getKeyForCache(Cache cache) { return super.getKeyForCache(cache); } @Override public void assertNotLocked(final String cacheName, final Object key) { super.assertNotLocked(cacheName, key); } @Override public void assertNotLocked(final Object key) { super.assertNotLocked(key); } @Override public boolean checkTxCount(int cacheIndex, int localTx, int remoteTx) { return super.checkTxCount(cacheIndex, localTx, remoteTx); } @Override public void assertNotLocked(int cacheIndex, Object key) { super.assertNotLocked(cacheIndex, key); } @Override public void assertLocked(int cacheIndex, Object key) { super.assertLocked(cacheIndex, key); } @Override public boolean checkLocked(int index, Object key) { return super.checkLocked(index, key); } @Override public Cache getLockOwner(Object key) { return super.getLockOwner(key); } @Override public Cache getLockOwner(Object key, String cacheName) { return super.getLockOwner(key, cacheName); } @Override public void assertKeyLockedCorrectly(Object key) { super.assertKeyLockedCorrectly(key); } @Override public void assertKeyLockedCorrectly(Object key, String cacheName) { super.assertKeyLockedCorrectly(key, cacheName); } @Override public void forceTwoPhase(int cacheIndex) throws SystemException, RollbackException { super.forceTwoPhase(cacheIndex); } /* ========== methods simulating those from SingleCacheManagerTest ========== */ public EmbeddedCacheManager manager() { return super.manager(0); } public <A, B> Cache<A, B> cache() { return super.cache(0); } public TransactionManager tm() { return super.cache(0).getAdvancedCache().getTransactionManager(); } public Transaction tx() { try { return super.cache(0).getAdvancedCache().getTransactionManager().getTransaction(); } catch (SystemException e) { throw new RuntimeException(e); } } public LockManager lockManager(String cacheName) { return super.lockManager(0, cacheName); } public LockManager lockManager() { return super.lockManager(0); } }
9,485
25.571429
114
java
null
infinispan-main/core/src/test/java/org/infinispan/test/dataconversion/AbstractTranscoderTest.java
package org.infinispan.test.dataconversion; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.Transcoder; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import java.util.Set; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; @Test(groups = "functional", testName = "rest.TranscoderTest") public abstract class AbstractTranscoderTest { protected Transcoder transcoder; protected Set<MediaType> supportedMediaTypes; @Test public void testTranscoderSupportedMediaTypes() { List<MediaType> supportedMediaTypesList = new ArrayList<>(supportedMediaTypes); assertTrue(supportedMediaTypesList.size() >= 2, "Must be at least 2 supported MediaTypes"); assertFalse(supportedMediaTypesList.get(0).match(supportedMediaTypesList.get(1)), "Supported MediaTypes Must be different"); } @Test public abstract void testTranscoderTranscode() throws Exception; }
1,017
34.103448
130
java
null
infinispan-main/core/src/test/java/org/infinispan/test/tx/TestLookup.java
package org.infinispan.test.tx; import jakarta.transaction.TransactionManager; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; public class TestLookup implements TransactionManagerLookup { @Override public TransactionManager getTransactionManager() throws Exception { throw new UnsupportedOperationException(); } }
353
22.6
71
java
null
infinispan-main/core/src/test/java/org/infinispan/test/jndi/DummyContext.java
package org.infinispan.test.jndi; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Hashtable; import java.util.concurrent.ConcurrentHashMap; import javax.naming.Binding; import javax.naming.Context; import javax.naming.Name; import javax.naming.NameClassPair; import javax.naming.NameParser; import javax.naming.NamingEnumeration; import javax.naming.NamingException; public class DummyContext implements Context { ConcurrentHashMap<String, Object> bindings = new ConcurrentHashMap<String, Object>(); boolean serializing; public DummyContext() { this.serializing = false; } public DummyContext(boolean serializing) { this.serializing = serializing; } /** * Retrieves the named object. If <tt>name</tt> is empty, returns a new instance of this context (which represents * the same naming context as this context, but its environment may be modified independently and it may be accessed * concurrently). * * @param name the name of the object to look up * @return the object bound to <tt>name</tt> * @throws NamingException if a naming exception is encountered * @see #lookup(String) * @see #lookupLink(Name) */ public Object lookup(Name name) throws NamingException { return null; } /** * Retrieves the named object. See {@link #lookup(Name)} for details. * * @param name the name of the object to look up * @return the object bound to <tt>name</tt> * @throws NamingException if a naming exception is encountered */ public Object lookup(String name) throws NamingException { try { deserialize(); return bindings.get(name); } finally { serialize(); } } /** * Binds a name to an object. All intermediate contexts and the target context (that named by all but terminal atomic * component of the name) must already exist. * * @param name the name to bind; may not be empty * @param obj the object to bind; possibly null * @throws javax.naming.NameAlreadyBoundException * if name is already bound * @throws javax.naming.directory.InvalidAttributesException * if object did not supply all mandatory attributes * @throws NamingException if a naming exception is encountered * @see #bind(String,Object) * @see #rebind(Name,Object) * @see javax.naming.directory.DirContext#bind(Name,Object, javax.naming.directory.Attributes) */ public void bind(Name name, Object obj) throws NamingException { bind("NAME: " + name.toString(), obj); } /** * Binds a name to an object. See {@link #bind(Name,Object)} for details. * * @param name the name to bind; may not be empty * @param obj the object to bind; possibly null * @throws javax.naming.NameAlreadyBoundException * if name is already bound * @throws javax.naming.directory.InvalidAttributesException * if object did not supply all mandatory attributes * @throws NamingException if a naming exception is encountered */ public void bind(String name, Object obj) throws NamingException { try { deserialize(); bindings.put(name, obj); } finally { serialize(); } } /** * Binds a name to an object, overwriting any existing binding. All intermediate contexts and the target context * (that named by all but terminal atomic component of the name) must already exist. * <p/> * <p> If the object is a <tt>DirContext</tt>, any existing attributes associated with the name are replaced with * those of the object. Otherwise, any existing attributes associated with the name remain unchanged. * * @param name the name to bind; may not be empty * @param obj the object to bind; possibly null * @throws javax.naming.directory.InvalidAttributesException * if object did not supply all mandatory attributes * @throws NamingException if a naming exception is encountered * @see #rebind(String,Object) * @see #bind(Name,Object) * @see javax.naming.directory.DirContext#rebind(Name,Object, javax.naming.directory.Attributes) * @see javax.naming.directory.DirContext */ public void rebind(Name name, Object obj) throws NamingException { bind(name, obj); } /** * Binds a name to an object, overwriting any existing binding. See {@link #rebind(Name,Object)} for details. * * @param name the name to bind; may not be empty * @param obj the object to bind; possibly null * @throws javax.naming.directory.InvalidAttributesException * if object did not supply all mandatory attributes * @throws NamingException if a naming exception is encountered */ public void rebind(String name, Object obj) throws NamingException { bind(name, obj); } /** * Unbinds the named object. Removes the terminal atomic name in <code>name</code> from the target context--that * named by all but the terminal atomic part of <code>name</code>. * <p/> * <p> This method is idempotent. It succeeds even if the terminal atomic name is not bound in the target context, * but throws <tt>NameNotFoundException</tt> if any of the intermediate contexts do not exist. * <p/> * <p> Any attributes associated with the name are removed. Intermediate contexts are not changed. * * @param name the name to unbind; may not be empty * @throws javax.naming.NameNotFoundException * if an intermediate context does not exist * @throws NamingException if a naming exception is encountered * @see #unbind(String) */ public void unbind(Name name) throws NamingException { unbind("NAME: " + name.toString()); } /** * Unbinds the named object. See {@link #unbind(Name)} for details. * * @param name the name to unbind; may not be empty * @throws javax.naming.NameNotFoundException * if an intermediate context does not exist * @throws NamingException if a naming exception is encountered */ public void unbind(String name) throws NamingException { try { deserialize(); bindings.remove(name); } finally { serialize(); } } /** * Binds a new name to the object bound to an old name, and unbinds the old name. Both names are relative to this * context. Any attributes associated with the old name become associated with the new name. Intermediate contexts of * the old name are not changed. * * @param oldName the name of the existing binding; may not be empty * @param newName the name of the new binding; may not be empty * @throws javax.naming.NameAlreadyBoundException * if <tt>newName</tt> is already bound * @throws NamingException if a naming exception is encountered * @see #rename(String,String) * @see #bind(Name,Object) * @see #rebind(Name,Object) */ public void rename(Name oldName, Name newName) throws NamingException { } /** * Binds a new name to the object bound to an old name, and unbinds the old name. See {@link #rename(Name,Name)} for * details. * * @param oldName the name of the existing binding; may not be empty * @param newName the name of the new binding; may not be empty * @throws javax.naming.NameAlreadyBoundException * if <tt>newName</tt> is already bound * @throws NamingException if a naming exception is encountered */ public void rename(String oldName, String newName) throws NamingException { } /** * Enumerates the names bound in the named context, along with the class names of objects bound to them. The contents * of any subcontexts are not included. * <p/> * <p> If a binding is added to or removed from this context, its effect on an enumeration previously returned is * undefined. * * @param name the name of the context to list * @return an enumeration of the names and class names of the bindings in this context. Each element of the * enumeration is of type <tt>NameClassPair</tt>. * @throws NamingException if a naming exception is encountered * @see #list(String) * @see #listBindings(Name) * @see javax.naming.NameClassPair */ public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { return null; } /** * Enumerates the names bound in the named context, along with the class names of objects bound to them. See {@link * #list(Name)} for details. * * @param name the name of the context to list * @return an enumeration of the names and class names of the bindings in this context. Each element of the * enumeration is of type <tt>NameClassPair</tt>. * @throws NamingException if a naming exception is encountered */ public NamingEnumeration<NameClassPair> list(String name) throws NamingException { return null; } /** * Enumerates the names bound in the named context, along with the objects bound to them. The contents of any * subcontexts are not included. * <p/> * <p> If a binding is added to or removed from this context, its effect on an enumeration previously returned is * undefined. * * @param name the name of the context to list * @return an enumeration of the bindings in this context. Each element of the enumeration is of type * <tt>Binding</tt>. * @throws NamingException if a naming exception is encountered * @see #listBindings(String) * @see #list(Name) * @see javax.naming.Binding */ public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { return null; } /** * Enumerates the names bound in the named context, along with the objects bound to them. See {@link * #listBindings(Name)} for details. * * @param name the name of the context to list * @return an enumeration of the bindings in this context. Each element of the enumeration is of type * <tt>Binding</tt>. * @throws NamingException if a naming exception is encountered */ public NamingEnumeration<Binding> listBindings(String name) throws NamingException { return null; } /** * Destroys the named context and removes it from the namespace. Any attributes associated with the name are also * removed. Intermediate contexts are not destroyed. * <p/> * <p> This method is idempotent. It succeeds even if the terminal atomic name is not bound in the target context, * but throws <tt>NameNotFoundException</tt> if any of the intermediate contexts do not exist. * <p/> * <p> In a federated naming system, a context from one naming system may be bound to a name in another. One can * subsequently look up and perform operations on the foreign context using a composite name. However, an attempt * destroy the context using this composite name will fail with <tt>NotContextException</tt>, because the foreign * context is not a "subcontext" of the context in which it is bound. Instead, use <tt>unbind()</tt> to remove the * binding of the foreign context. Destroying the foreign context requires that the <tt>destroySubcontext()</tt> be * performed on a context from the foreign context's "native" naming system. * * @param name the name of the context to be destroyed; may not be empty * @throws javax.naming.NameNotFoundException * if an intermediate context does not exist * @throws javax.naming.NotContextException * if the name is bound but does not name a context, or does not name a context of the * appropriate type * @throws javax.naming.ContextNotEmptyException * if the named context is not empty * @throws NamingException if a naming exception is encountered * @see #destroySubcontext(String) */ public void destroySubcontext(Name name) throws NamingException { } /** * Destroys the named context and removes it from the namespace. See {@link #destroySubcontext(Name)} for details. * * @param name the name of the context to be destroyed; may not be empty * @throws javax.naming.NameNotFoundException * if an intermediate context does not exist * @throws javax.naming.NotContextException * if the name is bound but does not name a context, or does not name a context of the * appropriate type * @throws javax.naming.ContextNotEmptyException * if the named context is not empty * @throws NamingException if a naming exception is encountered */ public void destroySubcontext(String name) throws NamingException { } /** * Creates and binds a new context. Creates a new context with the given name and binds it in the target context * (that named by all but terminal atomic component of the name). All intermediate contexts and the target context * must already exist. * * @param name the name of the context to create; may not be empty * @return the newly created context * @throws javax.naming.NameAlreadyBoundException * if name is already bound * @throws javax.naming.directory.InvalidAttributesException * if creation of the subcontext requires specification of mandatory attributes * @throws NamingException if a naming exception is encountered * @see #createSubcontext(String) * @see javax.naming.directory.DirContext#createSubcontext */ public Context createSubcontext(Name name) throws NamingException { return null; } /** * Creates and binds a new context. See {@link #createSubcontext(Name)} for details. * * @param name the name of the context to create; may not be empty * @return the newly created context * @throws javax.naming.NameAlreadyBoundException * if name is already bound * @throws javax.naming.directory.InvalidAttributesException * if creation of the subcontext requires specification of mandatory attributes * @throws NamingException if a naming exception is encountered */ public Context createSubcontext(String name) throws NamingException { return null; } /** * Retrieves the named object, following links except for the terminal atomic component of the name. If the object * bound to <tt>name</tt> is not a link, returns the object itself. * * @param name the name of the object to look up * @return the object bound to <tt>name</tt>, not following the terminal link (if any). * @throws NamingException if a naming exception is encountered * @see #lookupLink(String) */ public Object lookupLink(Name name) throws NamingException { return null; } /** * Retrieves the named object, following links except for the terminal atomic component of the name. See {@link * #lookupLink(Name)} for details. * * @param name the name of the object to look up * @return the object bound to <tt>name</tt>, not following the terminal link (if any) * @throws NamingException if a naming exception is encountered */ public Object lookupLink(String name) throws NamingException { return null; } /** * Retrieves the parser associated with the named context. In a federation of namespaces, different naming systems * will parse names differently. This method allows an application to get a parser for parsing names into their * atomic components using the naming convention of a particular naming system. Within any single naming system, * <tt>NameParser</tt> objects returned by this method must be equal (using the <tt>equals()</tt> test). * * @param name the name of the context from which to get the parser * @return a name parser that can parse compound names into their atomic components * @throws NamingException if a naming exception is encountered * @see #getNameParser(String) * @see javax.naming.CompoundName */ public NameParser getNameParser(Name name) throws NamingException { return null; } /** * Retrieves the parser associated with the named context. See {@link #getNameParser(Name)} for details. * * @param name the name of the context from which to get the parser * @return a name parser that can parse compound names into their atomic components * @throws NamingException if a naming exception is encountered */ public NameParser getNameParser(String name) throws NamingException { return null; } /** * Composes the name of this context with a name relative to this context. Given a name (<code>name</code>) relative * to this context, and the name (<code>prefix</code>) of this context relative to one of its ancestors, this method * returns the composition of the two names using the syntax appropriate for the naming system(s) involved. That is, * if <code>name</code> names an object relative to this context, the result is the name of the same object, but * relative to the ancestor context. None of the names may be null. * <p/> * For example, if this context is named "wiz.com" relative to the initial context, then * <pre> * composeName("east", "wiz.com") </pre> * might return <code>"east.wiz.com"</code>. If instead this context is named "org/research", then * <pre> * composeName("user/jane", "org/research") </pre> * might return <code>"org/research/user/jane"</code> while * <pre> * composeName("user/jane", "research") </pre> * returns <code>"research/user/jane"</code>. * * @param name a name relative to this context * @param prefix the name of this context relative to one of its ancestors * @return the composition of <code>prefix</code> and <code>name</code> * @throws NamingException if a naming exception is encountered * @see #composeName(String,String) */ public Name composeName(Name name, Name prefix) throws NamingException { return null; } /** * Composes the name of this context with a name relative to this context. See {@link #composeName(Name,Name)} for * details. * * @param name a name relative to this context * @param prefix the name of this context relative to one of its ancestors * @return the composition of <code>prefix</code> and <code>name</code> * @throws NamingException if a naming exception is encountered */ public String composeName(String name, String prefix) throws NamingException { return null; } /** * Adds a new environment property to the environment of this context. If the property already exists, its value is * overwritten. See class description for more details on environment properties. * * @param propName the name of the environment property to add; may not be null * @param propVal the value of the property to add; may not be null * @return the previous value of the property, or null if the property was not in the environment before * @throws NamingException if a naming exception is encountered * @see #getEnvironment() * @see #removeFromEnvironment(String) */ public Object addToEnvironment(String propName, Object propVal) throws NamingException { return null; } /** * Removes an environment property from the environment of this context. See class description for more details on * environment properties. * * @param propName the name of the environment property to remove; may not be null * @return the previous value of the property, or null if the property was not in the environment * @throws NamingException if a naming exception is encountered * @see #getEnvironment() * @see #addToEnvironment(String,Object) */ public Object removeFromEnvironment(String propName) throws NamingException { return null; } /** * Retrieves the environment in effect for this context. See class description for more details on environment * properties. * <p/> * <p> The caller should not make any changes to the object returned: their effect on the context is undefined. The * environment of this context may be changed using <tt>addToEnvironment()</tt> and * <tt>removeFromEnvironment()</tt>. * * @return the environment of this context; never null * @throws NamingException if a naming exception is encountered * @see #addToEnvironment(String,Object) * @see #removeFromEnvironment(String) */ public Hashtable<?, ?> getEnvironment() throws NamingException { return null; } /** * Closes this context. This method releases this context's resources immediately, instead of waiting for them to be * released automatically by the garbage collector. * <p/> * <p> This method is idempotent: invoking it on a context that has already been closed has no effect. Invoking any * other method on a closed context is not allowed, and results in undefined behaviour. * * @throws NamingException if a naming exception is encountered */ public void close() throws NamingException { } /** * Retrieves the full name of this context within its own namespace. * <p/> * <p> Many naming services have a notion of a "full name" for objects in their respective namespaces. For example, * an LDAP entry has a distinguished name, and a DNS record has a fully qualified name. This method allows the client * application to retrieve this name. The string returned by this method is not a JNDI composite name and should not * be passed directly to context methods. In naming systems for which the notion of full name does not make sense, * <tt>OperationNotSupportedException</tt> is thrown. * * @return this context's name in its own namespace; never null * @throws javax.naming.OperationNotSupportedException * if the naming system does not have the notion of a full name * @throws NamingException if a naming exception is encountered * @since 1.3 */ public String getNameInNamespace() throws NamingException { return null; } byte[] bytes = null; private void serialize() { if (serializing) { try { ByteArrayOutputStream bstream = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bstream); oos.writeObject(bindings); oos.close(); bstream.close(); bytes = bstream.toByteArray(); bindings = null; } catch (Exception e) { throw new RuntimeException(e); } } } @SuppressWarnings("unchecked") private void deserialize() { if (serializing) { if (bytes == null) bindings = new ConcurrentHashMap<String, Object>(); else { try { ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); bindings = (ConcurrentHashMap<String, Object>) ois.readObject(); ois.close(); bytes = null; } catch (Exception e) { throw new RuntimeException(e); } } } } }
23,896
41.826165
120
java
null
infinispan-main/core/src/test/java/org/infinispan/test/jndi/DummyContextFactory.java
package org.infinispan.test.jndi; import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.spi.InitialContextFactory; public class DummyContextFactory implements InitialContextFactory { static Context instance = new DummyContext(); /** * Creates an Initial Context for beginning name resolution. Special requirements of this context are supplied using * <code>environment</code>. * <p/> * The environment parameter is owned by the caller. The implementation will not modify the object or keep a * reference to it, although it may keep a reference to a clone or copy. * * @param environment The possibly null environment specifying information to be used in the creation of the initial * context. * @return A non-null initial context object that implements the Context interface. * @throws javax.naming.NamingException If cannot create an initial context. */ public Context getInitialContext(Hashtable environment) throws NamingException { return instance; } }
1,102
38.392857
119
java
null
infinispan-main/core/src/test/java/org/infinispan/test/op/TestOperation.java
package org.infinispan.test.op; import java.util.concurrent.CompletionStage; import org.infinispan.AdvancedCache; import org.infinispan.commands.ReplicableCommand; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.write.ValueMatcher; public interface TestOperation { Class<? extends VisitableCommand> getCommandClass(); Class<? extends ReplicableCommand> getBackupCommandClass(); Object getValue(); Object getPreviousValue(); Object getReturnValue(); void insertPreviousValue(AdvancedCache<Object, Object> cache, Object key); Object perform(AdvancedCache<Object, Object> cache, Object key); CompletionStage<?> performAsync(AdvancedCache<Object, Object> cache, Object key); ValueMatcher getValueMatcher(); Object getReturnValueWithRetry(); }
813
25.258065
84
java
null
infinispan-main/core/src/test/java/org/infinispan/test/op/TestFunctionalWriteOperation.java
package org.infinispan.test.op; import static org.infinispan.container.versioning.InequalVersionComparisonResult.EQUAL; import static org.infinispan.functional.FunctionalTestUtils.rw; import java.util.concurrent.CompletionStage; import org.infinispan.AdvancedCache; import org.infinispan.commands.ReplicableCommand; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.functional.ReadWriteKeyCommand; import org.infinispan.commands.functional.ReadWriteKeyValueCommand; import org.infinispan.commands.triangle.BackupWriteCommand; import org.infinispan.commands.write.ValueMatcher; import org.infinispan.container.versioning.NumericVersion; import org.infinispan.context.Flag; import org.infinispan.functional.FunctionalMap; import org.infinispan.functional.FunctionalTestUtils; import org.infinispan.functional.MetaParam; import org.infinispan.functional.decorators.FunctionalAdvancedCache; /** * Represents a functional write operation to test. * * @author Dan Berindei * @since 12.0 */ public enum TestFunctionalWriteOperation implements TestOperation { // Functional put create must return null even on retry (as opposed to non-functional) PUT_CREATE_FUNCTIONAL(ReadWriteKeyValueCommand.class, BackupWriteCommand.class, "v1", ValueMatcher.MATCH_ALWAYS, null, null, null), // Functional put overwrite must return the previous value (as opposed to non-functional) PUT_OVERWRITE_FUNCTIONAL(ReadWriteKeyValueCommand.class, BackupWriteCommand.class, "v1", ValueMatcher.MATCH_ALWAYS, "v0", "v0", "v0"), PUT_IF_ABSENT_FUNCTIONAL(ReadWriteKeyValueCommand.class, BackupWriteCommand.class, "v1", ValueMatcher.MATCH_EXPECTED, null, null, null), // Functional replace must return the previous value (as opposed to non-functional) REPLACE_FUNCTIONAL(ReadWriteKeyValueCommand.class, BackupWriteCommand.class, "v1", ValueMatcher.MATCH_NON_NULL, "v0", "v0", "v0"), REMOVE_FUNCTIONAL(ReadWriteKeyCommand.class, BackupWriteCommand.class, null, ValueMatcher.MATCH_NON_NULL, "v0", "v0", null), REPLACE_EXACT_FUNCTIONAL(ReadWriteKeyValueCommand.class, BackupWriteCommand.class, "v1", ValueMatcher.MATCH_EXPECTED, "v0", true, true), REMOVE_EXACT_FUNCTIONAL(ReadWriteKeyValueCommand.class, BackupWriteCommand.class, null, ValueMatcher.MATCH_EXPECTED, "v0", true, true), // Functional replace REPLACE_META_FUNCTIONAL(ReadWriteKeyValueCommand.class, BackupWriteCommand.class, "v1", ValueMatcher.MATCH_EXPECTED, "v0", true, true) ; private final Class<? extends VisitableCommand> commandClass; private final Class<? extends ReplicableCommand> backupCommandClass; private final Object value; private final ValueMatcher valueMatcher; private final Object previousValue; private final Object returnValue; // When retrying a write operation, we don't always have the previous value, so we sometimes // return the new value instead. For "exact" conditional operations, however, we always return the same value. // See https://issues.jboss.org/browse/ISPN-3422 private final Object returnValueWithRetry; TestFunctionalWriteOperation(Class<? extends VisitableCommand> commandClass, Class<? extends ReplicableCommand> backupCommandClass, Object value, ValueMatcher valueMatcher, Object previousValue, Object returnValue, Object returnValueWithRetry) { this.commandClass = commandClass; this.backupCommandClass = backupCommandClass; this.value = value; this.valueMatcher = valueMatcher; this.previousValue = previousValue; this.returnValue = returnValue; this.returnValueWithRetry = returnValueWithRetry; } public Class<? extends VisitableCommand> getCommandClass() { return commandClass; } public Class<? extends ReplicableCommand> getBackupCommandClass() { return backupCommandClass; } public Object getValue() { return value; } public Object getPreviousValue() { return previousValue; } public Object getReturnValue() { return returnValue; } @Override public void insertPreviousValue(AdvancedCache<Object, Object> cache, Object key) { switch (this) { case REPLACE_META_FUNCTIONAL: FunctionalMap.WriteOnlyMap<Object, Object> woMap = FunctionalTestUtils.wo(cache); FunctionalTestUtils.await(woMap.eval(key, wo -> { wo.set("v0", new MetaParam.MetaEntryVersion(new NumericVersion(1))); })); break; default: if (previousValue != null) { cache.withFlags(Flag.IGNORE_RETURN_VALUES).put(key, previousValue); } } } @Override public Object perform(AdvancedCache<Object, Object> cache, Object key) { AdvancedCache<Object, Object> functionalCache = FunctionalAdvancedCache.create(cache); switch (this) { case PUT_CREATE_FUNCTIONAL: return functionalCache.put(key, value); case PUT_OVERWRITE_FUNCTIONAL: return functionalCache.put(key, value); case PUT_IF_ABSENT_FUNCTIONAL: return functionalCache.putIfAbsent(key, value); case REPLACE_FUNCTIONAL: return functionalCache.replace(key, value); case REPLACE_EXACT_FUNCTIONAL: return functionalCache.replace(key, previousValue, value); case REMOVE_FUNCTIONAL: return functionalCache.remove(key); case REMOVE_EXACT_FUNCTIONAL: return functionalCache.remove(key, previousValue); case REPLACE_META_FUNCTIONAL: return FunctionalTestUtils.await(rw(cache).eval(key, "v1", (v, rw) -> { return rw.findMetaParam(MetaParam.MetaEntryVersion.class) .filter(ver -> ver.get().compareTo(new NumericVersion(1)) == EQUAL) .map(ver -> { rw.set(v, new MetaParam.MetaEntryVersion(new NumericVersion(2))); return true; }).orElse(false); })); default: throw new IllegalArgumentException("Unsupported operation: " + this); } } @Override public CompletionStage<?> performAsync(AdvancedCache<Object, Object> cache, Object key) { AdvancedCache<Object, Object> functionalCache = FunctionalAdvancedCache.create(cache); switch (this) { case PUT_CREATE_FUNCTIONAL: case PUT_OVERWRITE_FUNCTIONAL: return functionalCache.putAsync(key, value); case PUT_IF_ABSENT_FUNCTIONAL: return functionalCache.putIfAbsentAsync(key, value); case REPLACE_FUNCTIONAL: return functionalCache.replaceAsync(key, value); case REPLACE_EXACT_FUNCTIONAL: return functionalCache.replaceAsync(key, previousValue, value); case REMOVE_FUNCTIONAL: return functionalCache.removeAsync(key); case REMOVE_EXACT_FUNCTIONAL: return functionalCache.removeAsync(key, previousValue); case REPLACE_META_FUNCTIONAL: return rw(cache).eval(key, "v1", (v, rw) -> { return rw.findMetaParam(MetaParam.MetaEntryVersion.class) .filter(ver -> ver.get().compareTo(new NumericVersion(1)) == EQUAL) .map(ver -> { rw.set(v, new MetaParam.MetaEntryVersion(new NumericVersion(2))); return true; }).orElse(false); }); default: throw new IllegalArgumentException("Unsupported operation: " + this); } } @Override public ValueMatcher getValueMatcher() { return valueMatcher; } @Override public Object getReturnValueWithRetry() { return returnValueWithRetry; } }
7,889
43.829545
139
java
null
infinispan-main/core/src/test/java/org/infinispan/test/op/TestWriteOperation.java
package org.infinispan.test.op; import java.util.Collections; import java.util.concurrent.CompletionStage; import org.infinispan.AdvancedCache; import org.infinispan.commands.ReplicableCommand; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.triangle.BackupWriteCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.PutMapCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commands.write.ReplaceCommand; import org.infinispan.commands.write.ValueMatcher; import org.infinispan.context.Flag; /** * Represents a write operation to test. * * @author Dan Berindei * @since 6.0 */ public enum TestWriteOperation implements TestOperation { PUT_CREATE(PutKeyValueCommand.class, BackupWriteCommand.class, "v1", ValueMatcher.MATCH_ALWAYS, null, null, "v1"), PUT_OVERWRITE(PutKeyValueCommand.class, BackupWriteCommand.class, "v1", ValueMatcher.MATCH_ALWAYS, "v0", "v0", "v1"), PUT_IF_ABSENT(PutKeyValueCommand.class, BackupWriteCommand.class, "v1", ValueMatcher.MATCH_EXPECTED, null, null, null), REPLACE(ReplaceCommand.class, BackupWriteCommand.class, "v1", ValueMatcher.MATCH_NON_NULL, "v0", "v0", "v1"), REPLACE_EXACT(ReplaceCommand.class, BackupWriteCommand.class, "v1", ValueMatcher.MATCH_EXPECTED, "v0", true, true), REMOVE(RemoveCommand.class, BackupWriteCommand.class, null, ValueMatcher.MATCH_NON_NULL, "v0", "v0", null), REMOVE_EXACT(RemoveCommand.class, BackupWriteCommand.class, null, ValueMatcher.MATCH_EXPECTED, "v0", true, true), PUT_MAP_CREATE(PutMapCommand.class, BackupWriteCommand.class, "v1", ValueMatcher.MATCH_EXPECTED, null, null, null), // TODO Add TestWriteOperation enum values for compute/computeIfAbsent/computeIfPresent/merge ; private final Class<? extends VisitableCommand> commandClass; private final Class<? extends ReplicableCommand> backupCommandClass; private final Object value; private final ValueMatcher valueMatcher; private final Object previousValue; private final Object returnValue; // When retrying a write operation, we don't always have the previous value, so we sometimes // return the new value instead. For "exact" conditional operations, however, we always return the same value. // See https://issues.jboss.org/browse/ISPN-3422 private final Object returnValueWithRetry; TestWriteOperation(Class<? extends VisitableCommand> commandClass, Class<? extends ReplicableCommand> backupCommandClass, Object value, ValueMatcher valueMatcher, Object previousValue, Object returnValue, Object returnValueWithRetry) { this.commandClass = commandClass; this.backupCommandClass = backupCommandClass; this.value = value; this.valueMatcher = valueMatcher; this.previousValue = previousValue; this.returnValue = returnValue; this.returnValueWithRetry = returnValueWithRetry; } @Override public Class<? extends VisitableCommand> getCommandClass() { return commandClass; } @Override public Class<? extends ReplicableCommand> getBackupCommandClass() { return backupCommandClass; } @Override public Object getValue() { return value; } @Override public Object getPreviousValue() { return previousValue; } @Override public Object getReturnValue() { return returnValue; } @Override public void insertPreviousValue(AdvancedCache<Object, Object> cache, Object key) { if (previousValue != null) { cache.withFlags(Flag.IGNORE_RETURN_VALUES).put(key, previousValue); } } @Override public Object perform(AdvancedCache<Object, Object> cache, Object key) { switch (this) { case PUT_CREATE: case PUT_OVERWRITE: return cache.put(key, value); case PUT_IF_ABSENT: return cache.putIfAbsent(key, value); case REPLACE: return cache.replace(key, value); case REPLACE_EXACT: return cache.replace(key, previousValue, value); case REMOVE: return cache.remove(key); case REMOVE_EXACT: return cache.remove(key, previousValue); case PUT_MAP_CREATE: cache.putAll(Collections.singletonMap(key, value)); return null; default: throw new IllegalArgumentException("Unsupported operation: " + this); } } @Override public CompletionStage<?> performAsync(AdvancedCache<Object, Object> cache, Object key) { switch (this) { case PUT_CREATE: case PUT_OVERWRITE: return cache.putAsync(key, value); case PUT_IF_ABSENT: return cache.putIfAbsentAsync(key, value); case REPLACE: return cache.replaceAsync(key, value); case REPLACE_EXACT: return cache.replaceAsync(key, previousValue, value); case REMOVE: return cache.removeAsync(key); case REMOVE_EXACT: return cache.removeAsync(key, previousValue); case PUT_MAP_CREATE: return cache.putAllAsync(Collections.singletonMap(key, value)); default: throw new IllegalArgumentException("Unsupported operation: " + this); } } @Override public ValueMatcher getValueMatcher() { return valueMatcher; } @Override public Object getReturnValueWithRetry() { return returnValueWithRetry; } }
5,552
36.52027
122
java
null
infinispan-main/core/src/test/java/org/infinispan/test/data/Value.java
package org.infinispan.test.data; import java.util.Objects; import org.infinispan.protostream.annotations.ProtoField; public class Value { @ProtoField(number = 1) String name; @ProtoField(number = 2) String value; Value() {} public Value(String name, String value) { this.name = name; this.value = value; } public String getName() { return name; } public String getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Value value1 = (Value) o; return Objects.equals(name, value1.name) && Objects.equals(value, value1.value); } @Override public int hashCode() { return Objects.hash(name, value); } @Override public String toString() { return "Value{" + "name='" + name + '\'' + ", value='" + value + '\'' + '}'; } }
1,000
17.886792
64
java
null
infinispan-main/core/src/test/java/org/infinispan/test/data/Sex.java
package org.infinispan.test.data; import org.infinispan.protostream.annotations.ProtoEnumValue; public enum Sex { @ProtoEnumValue(number = 1) FEMALE, @ProtoEnumValue(number = 2) MALE, }
200
17.272727
61
java
null
infinispan-main/core/src/test/java/org/infinispan/test/data/Person.java
package org.infinispan.test.data; import java.io.Serializable; import java.util.Arrays; import java.util.Date; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.dataconversion.internal.JsonSerialization; import org.infinispan.commons.util.Util; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; public class Person implements Serializable, JsonSerialization, Comparable { String name; Address address; byte[] picture; Sex sex; Date birthDate; boolean acceptedToS; double moneyOwned; float moneyOwed; double decimalField; float realField; public Person() { // Needed for serialization } public Person(String name) { this(name, null); } public Person(String name, Address address) { this(name, address, null, null, null, false, 1.1, 0.4f, 10.3, 4.7f); } @ProtoFactory public Person(String name, Address address, byte[] picture, Sex sex, Date birthDate, boolean acceptedToS, double moneyOwned, float moneyOwed, double decimalField, float realField) { this.name = name; this.address = address; this.picture = picture; this.sex = sex; this.birthDate = birthDate; this.acceptedToS = acceptedToS; this.moneyOwned = moneyOwned; this.moneyOwed = moneyOwed; this.decimalField = decimalField; this.realField = realField; } @ProtoField(1) public String getName() { return name; } public void setName(String name) { this.name = name; } @ProtoField(2) public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } @ProtoField(3) public byte[] getPicture() { return picture; } public void setPicture(byte[] picture) { this.picture = picture; } @ProtoField(4) public Sex getSex() { return sex; } public void setSex(Sex sex) { this.sex = sex; } @ProtoField(value = 5) public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } @ProtoField(value = 6, defaultValue = "false", name = "accepted_tos") public boolean isAcceptedToS() { return acceptedToS; } public void setAcceptedToS(boolean acceptedToS) { this.acceptedToS = acceptedToS; } @ProtoField(value = 7, defaultValue = "1.1") public double getMoneyOwned() { return moneyOwned; } public void setMoneyOwned(double moneyOwned) { this.moneyOwned = moneyOwned; } @ProtoField(value = 8, defaultValue = "0.4") public float getMoneyOwed() { return moneyOwed; } public void setMoneyOwed(float moneyOwed) { this.moneyOwed = moneyOwed; } @ProtoField(value = 9, defaultValue = "10.3") public double getDecimalField() { return decimalField; } public void setDecimalField(double decimalField) { this.decimalField = decimalField; } @ProtoField(value = 10, defaultValue = "4.7") public float getRealField() { return realField; } public void setRealField(float realField) { this.realField = realField; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", address=" + address + ", picture=" + Util.toHexString(picture) + ", sex=" + sex + ", birthDate=" + birthDate + ", acceptedToS=" + acceptedToS + ", moneyOwned=" + moneyOwned + ", moneyOwed=" + moneyOwed + ", decimalField=" + decimalField + ", realField=" + realField + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Person person = (Person) o; if (address != null ? !address.equals(person.address) : person.address != null) return false; return commonEquals(person); } private boolean commonEquals(Person person) { if (name != null ? !name.equals(person.name) : person.name != null) return false; if (picture != null ? !Arrays.equals(picture, person.picture) : person.picture != null) return false; if (sex != null ? !sex.equals(person.sex) : person.sex != null) return false; if (birthDate != null ? !birthDate.equals(person.birthDate) : person.birthDate != null) return false; if (acceptedToS != person.acceptedToS) return false; if (moneyOwned != person.moneyOwned) return false; if (moneyOwed != person.moneyOwed) return false; if (decimalField != person.decimalField) return false; if (realField != person.realField) return false; return true; } public boolean equalsIgnoreWhitespaceAddress(Person person) { if (address != null ? !address.equalsIgnoreStreetWhitespace(person.address) : person.address != null) return false; return commonEquals(person); } @Override public int hashCode() { int result; result = (name != null ? name.hashCode() : 0); result = 29 * result + (address != null ? address.hashCode() : 0); result = 29 * result + (picture != null ? Arrays.hashCode(picture) : 0); result = 29 * result + (sex != null ? sex.hashCode() : 0); result = 29 * result + (birthDate != null ? birthDate.hashCode() : 0); result = 29 * result + Boolean.hashCode(acceptedToS); result = 29 * result + Double.hashCode(moneyOwned); result = 29 * result + Float.hashCode(moneyOwed); result = 29 * result + Double.hashCode(decimalField); result = 29 * result + Float.hashCode(realField); return result; } @Override public Json toJson() { return Json.object() .set("name", name) .set("address", Json.make(address)) .set("picture", picture) .set("sex", sex) .set("birthDate", birthDate == null ? 0 : birthDate.getTime()) .set("acceptedToS", acceptedToS) .set("moneyOwned", moneyOwned) .set("moneyOwed", moneyOwed) .set("decimalField", decimalField) .set("realField", realField); } @Override public int compareTo(Object o) { if (o instanceof Person) { Person o1 = (Person) o; return name.compareTo(o1.name); } throw new IllegalArgumentException("Person can't compate to " + o.getClass()); } }
6,610
27.373391
127
java
null
infinispan-main/core/src/test/java/org/infinispan/test/data/CountMarshallingPojo.java
package org.infinispan.test.data; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * A Pojo that records how many times it has been marshalled/unmarshalled based upon the number of calls to its * annotated setter/getter methods via the generated Protostream marhaller. Test instances should never attempt to call * the setter/getter methods directly as this will result in unexpected counts. */ public class CountMarshallingPojo { private static final Log log = LogFactory.getLog(CountMarshallingPojo.class); private static final Map<String, Integer> marshallCount = new ConcurrentHashMap<>(); private static final Map<String, Integer> unmarshallCount = new ConcurrentHashMap<>(); private String name; private int value; public static void reset(String name) { marshallCount.put(name, 0); unmarshallCount.put(name, 0); } public static int getMarshallCount(String name) { return marshallCount.getOrDefault(name, 0); } public static int getUnmarshallCount(String name) { return unmarshallCount.getOrDefault(name, 0); } CountMarshallingPojo() { } public CountMarshallingPojo(String name, int value) { this.name = name; this.value = value; } @ProtoField(number = 1, defaultValue = "0") int getValue() { return value; } void setValue(int i) { this.value = i; } @ProtoField(number = 2) String getName() { int serCount = marshallCount.merge(name, 1, Integer::sum); log.trace("marshallCount=" + serCount); return name; } void setName(String name) { this.name = name; int deserCount = unmarshallCount.merge(this.name, 1, Integer::sum); log.trace("unmarshallCount=" + deserCount); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CountMarshallingPojo that = (CountMarshallingPojo) o; return value == that.value; } @Override public int hashCode() { return Objects.hash(value); } @Override public String toString() { return "CountMarshallingPojo{" + "name=" + name + ", value=" + value + '}'; } }
2,446
26.494382
119
java
null
infinispan-main/core/src/test/java/org/infinispan/test/data/BrokenMarshallingPojo.java
package org.infinispan.test.data; import org.infinispan.commons.marshall.MarshallingException; import org.infinispan.protostream.annotations.ProtoField; public class BrokenMarshallingPojo { private boolean failOnMarshalling = true; public BrokenMarshallingPojo() {} public BrokenMarshallingPojo(boolean failOnMarshalling) { this.failOnMarshalling = failOnMarshalling; } @ProtoField(number = 1, defaultValue = "true") public boolean getIgnored() { if (failOnMarshalling) throw new MarshallingException(); return false; } public void setIgnored(boolean ignore) { if (!ignore) throw new MarshallingException(); } }
688
23.607143
60
java
null
infinispan-main/core/src/test/java/org/infinispan/test/data/Address.java
package org.infinispan.test.data; import java.io.Serializable; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.dataconversion.internal.JsonSerialization; import org.infinispan.protostream.annotations.ProtoField; public class Address implements Serializable, JsonSerialization { private static final long serialVersionUID = 5943073369866339615L; @ProtoField(1) String street = null; @ProtoField(value = 2, defaultValue = "San Jose") String city = "San Jose"; @ProtoField(number = 3, defaultValue = "0") int zip = 0; public Address() { } public Address(String street, String city, int zip) { this.street = street; this.city = city; this.zip = zip; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public int getZip() { return zip; } public void setZip(int zip) { this.zip = zip; } @Override public String toString() { return "street=" + getStreet() + ", city=" + getCity() + ", zip=" + getZip(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Address address = (Address) o; if (zip != address.zip) return false; if (city != null ? !city.equals(address.city) : address.city != null) return false; if (street != null ? !street.equals(address.street) : address.street != null) return false; return true; } public boolean equalsIgnoreStreetWhitespace(Address address) { if (zip != address.zip) return false; if (city != null ? !city.equals(address.city) : address.city != null) return false; if (street != null ? !street.trim().equals(address.street.trim()) : address.street != null) return false; return true; } @Override public int hashCode() { int result; result = (street != null ? street.hashCode() : 0); result = 29 * result + (city != null ? city.hashCode() : 0); result = 29 * result + zip; return result; } @Override public Json toJson() { return Json.object() .set("street", street) .set("city", city) .set("zip", zip); } }
2,451
24.020408
111
java
null
infinispan-main/core/src/test/java/org/infinispan/test/data/DelayedMarshallingPojo.java
package org.infinispan.test.data; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.test.TestingUtil; public class DelayedMarshallingPojo { int marshallDelay; int unmarshallDely; DelayedMarshallingPojo() {} public DelayedMarshallingPojo(int marshallDelay, int unmarshallDely) { this.marshallDelay = marshallDelay; this.unmarshallDely = unmarshallDely; } @ProtoField(number = 1, defaultValue = "false") boolean getIgnored() { if (marshallDelay > 0) TestingUtil.sleepThread(marshallDelay); return false; } // Should only be called by protostream when unmarshalling void setIgnored(boolean ignored) { if (unmarshallDely > 0) TestingUtil.sleepThread(unmarshallDely); } }
785
24.354839
73
java
null
infinispan-main/core/src/test/java/org/infinispan/test/data/Key.java
package org.infinispan.test.data; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Objects; import org.infinispan.protostream.annotations.ProtoField; public class Key implements Externalizable { private static final long serialVersionUID = 4745232904453872125L; @ProtoField(number = 1, name = "value1") String value; public Key() { } public Key(String value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return Objects.equals(value, ((Key) o).value); } @Override public int hashCode() { return value != null ? value.hashCode() : 0; } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(value); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { value = (String) in.readObject(); } }
1,073
21.851064
88
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/InCacheMode.java
package org.infinispan.test.fwk; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.infinispan.configuration.cache.CacheMode; /** * Mark which cache modes should the test be executed upon. This will be used to fill in * {@link org.infinispan.test.MultipleCacheManagersTest#cacheMode} for each of the modes. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) public @interface InCacheMode { CacheMode[] value(); }
633
29.190476
89
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/ChainMethodInterceptor.java
package org.infinispan.test.fwk; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.ITestContext; import org.testng.TestNGException; import org.testng.internal.MethodInstance; /** * This is a workaround for TestNG limitation allowing only single IMethodInterceptor instance. * Allows to use multiple {@link TestSelector} annotations in the test class hieararchy. * * Filters are executed before interceptors, and only on those classes that define them. Filters * should not have any side-effect and as these only remove test methods, the order of execution * is not important. * * The interceptors on superclasses will be executed before interceptors on subclasses, but * an interceptor is executed even on a class that does not define it (because the interceptor * is invoked once for the whole suite). * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class ChainMethodInterceptor implements IMethodInterceptor { private static final Log log = LogFactory.getLog(ChainMethodInterceptor.class); @Override public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) { try { Set<Class<? extends IMethodInterceptor>> interceptorSet = new HashSet<>(); List<Class<? extends IMethodInterceptor>> interceptorList = new ArrayList<>(); Set<Class<? extends Predicate<IMethodInstance>>> filters = new HashSet<>(); for (IMethodInstance method : methods) { findInterceptors(method.getInstance().getClass(), interceptorSet, interceptorList, filters); } if (!filters.isEmpty()) { List<? extends Predicate<IMethodInstance>> filterInstances = filters.stream().map(clazz -> { try { return clazz.getConstructor().newInstance(); } catch (Exception e) { throw new IllegalStateException("Cannot construct filter", e); } }).collect(Collectors.toList()); ArrayList<IMethodInstance> filteredMethods = new ArrayList<>(methods.size()); METHODS: for (IMethodInstance m : methods) { for (Predicate<IMethodInstance> filter : filterInstances) { if (hasFilter(m.getInstance().getClass(), filter.getClass()) && !filter.test(m)) continue METHODS; } filteredMethods.add(m); } methods = filteredMethods; } for (Class<? extends IMethodInterceptor> interceptor : interceptorList) { methods = interceptor.getConstructor().newInstance().intercept(methods, context); } return methods; } catch (Throwable t) { MethodInstance methodInstance = FakeTestClass.newFailureMethodInstance(new TestNGException(t), context.getCurrentXmlTest(), context, methods.get(0).getInstance()); return Collections.singletonList(methodInstance); } } private boolean hasFilter(Class<?> clazz, Class<? extends Predicate> filter) { if (clazz == null || clazz == Object.class) return false; TestSelector annotation = clazz.getAnnotation(TestSelector.class); if (annotation != null) { for (Class<? extends Predicate<IMethodInstance>> f : annotation.filters()) { if (f == filter) return true; } } return hasFilter(clazz.getSuperclass(), filter); } private void findInterceptors(Class<?> clazz, Set<Class<? extends IMethodInterceptor>> interceptorSet, List<Class<? extends IMethodInterceptor>> interceptorList, Set<Class<? extends Predicate<IMethodInstance>>> filters) { if (clazz == null || clazz.equals(Object.class)) return; findInterceptors(clazz.getSuperclass(), interceptorSet, interceptorList, filters); TestSelector annotation = clazz.getAnnotation(TestSelector.class); if (annotation != null) { for (Class<? extends IMethodInterceptor> interceptor : annotation.interceptors()) { if (interceptorSet.add(interceptor)) { interceptorList.add(interceptor); } } Collections.addAll(filters, annotation.filters()); } } }
4,639
43.190476
151
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/TransportFlags.java
package org.infinispan.test.fwk; /** * Flags that allow JGroups transport stack to be tweaked depending on the test * case requirements. For example, you can remove failure detection, or remove * merge protocol...etc. * * @author Galder Zamarreño * @since 5.1 */ public class TransportFlags { private boolean withFD; private boolean withMerge; private int siteIndex = -1; private String siteName; private String relayConfig; private boolean preserveConfig; public TransportFlags withFD(boolean withFD) { this.withFD = withFD; return this; } public boolean withFD() { return withFD; } public TransportFlags withMerge(boolean withMerge) { this.withMerge = withMerge; return this; } public boolean withMerge() { return withMerge; } /** * @deprecated Since 13.0, will be removed in 16.0 */ @Deprecated public TransportFlags withPortRange(int portRange) { return withSiteIndex(portRange); } public TransportFlags withSiteIndex(int siteIndex) { this.siteIndex = siteIndex; return this; } public TransportFlags withSiteName(String siteName) { this.siteName = siteName; return this; } public TransportFlags withRelayConfig(String relayConf) { this.relayConfig = relayConf; return this; } public TransportFlags withPreserveConfig(boolean preserveConfig) { this.preserveConfig = preserveConfig; return this; } public String siteName() { return siteName; } public String relayConfig() { return relayConfig; } /** * @deprecated Since 13.0, will be removed in 16.0 */ @Deprecated public int portRange() { return siteIndex(); } public int siteIndex() { return siteIndex; } public boolean isPortRangeSpecified() { return portRange() >= 0; } public boolean isRelayRequired() { return isPortRangeSpecified() && siteName != null; } public boolean isPreserveConfig() { return preserveConfig; } public static TransportFlags minimalXsiteFlags() { //minimal xsite flags return new TransportFlags().withSiteIndex(0).withSiteName("LON-1").withFD(true); } }
2,251
20.864078
86
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/TestClassLocal.java
package org.infinispan.test.fwk; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Serializable; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import java.util.function.Supplier; import org.infinispan.commons.marshall.SerializeWith; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.test.AbstractInfinispanTest; /** * @author Dan Berindei * @since 9.1 */ @SerializeWith(TestClassLocal.Externalizer.class) public class TestClassLocal<T> implements Serializable { private static final Map<String, TestClassLocal> values = new ConcurrentHashMap<>(); private final String name; private final AbstractInfinispanTest test; private final Supplier<T> supplier; private final Consumer<T> destroyer; private Object value; public TestClassLocal(String name, AbstractInfinispanTest test, Supplier<T> supplier, Consumer<T> destroyer) { this.name = name; this.test = test; this.supplier = supplier; this.destroyer = destroyer; values.put(id(), this); } @SuppressWarnings("unchecked") public T get() { synchronized (this) { if (value == null) { value = supplier.get(); TestResourceTracker.addResource(test.getTestName(), new TestResourceTracker.Cleaner<TestClassLocal<T>>(this) { @Override public void close() { ref.destroyer.accept(ref.get()); } }); } return (T) value; } } @SuppressWarnings("unchecked") void close() { T value = (T) values.remove(this); destroyer.accept(value); } public String id() { return name + "/" + test.toString(); } @Override public String toString() { return id(); } public static class Externalizer implements org.infinispan.commons.marshall.Externalizer<TestClassLocal> { @Override public void writeObject(ObjectOutput output, TestClassLocal object) throws IOException { output.writeUTF(object.id()); } @Override public TestClassLocal readObject(ObjectInput input) throws IOException, ClassNotFoundException { String id = input.readUTF(); return values.get(id); } } }
2,353
27.361446
122
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/CleanupAfterMethod.java
package org.infinispan.test.fwk; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Indicates that test cleanup happens after every test method. * * @author Manik Surtani * @version 4.2 */ @Retention(RetentionPolicy.RUNTIME) public @interface CleanupAfterMethod { }
312
19.866667
63
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/TransactionSetup.java
package org.infinispan.test.fwk; import jakarta.transaction.TransactionManager; import jakarta.transaction.UserTransaction; import org.infinispan.commons.util.LegacyKeySupportSystemProperties; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup; import org.infinispan.commons.tx.lookup.TransactionManagerLookup; /** * A simple abstraction for transaction manager interaction * * @author Jason T. Greene */ public class TransactionSetup { private interface Operations { UserTransaction getUserTransaction(); String getLookup(); TransactionManagerLookup lookup(); void cleanup(); TransactionManager getManager(); } public static final String JBOSS_TM = "jbosstm"; public static final String DUMMY_TM = "dummytm"; public static final String JTA = LegacyKeySupportSystemProperties.getProperty("infinispan.test.jta.tm", "infinispan.tm"); private static Operations operations; static { init(); } private static void init() { String property = JTA; if (DUMMY_TM.equalsIgnoreCase(property)) { System.out.println("Transaction manager used: Dummy"); final String lookup = EmbeddedTransactionManagerLookup.class.getName(); final EmbeddedTransactionManagerLookup instance = new EmbeddedTransactionManagerLookup(); operations = new Operations() { @Override public UserTransaction getUserTransaction() { return EmbeddedTransactionManagerLookup.getUserTransaction(); } @Override public void cleanup() { EmbeddedTransactionManagerLookup.cleanup(); } @Override public String getLookup() { return lookup; } @Override public TransactionManagerLookup lookup() { return instance; } @Override public TransactionManager getManager() { try { return instance.getTransactionManager(); } catch (Exception e) { throw new RuntimeException(e); } } }; } else { System.out.println("Transaction manager used: JBossTM"); final String lookup = JBossStandaloneJTAManagerLookup.class.getName(); final JBossStandaloneJTAManagerLookup instance = new JBossStandaloneJTAManagerLookup(); operations = new Operations() { @Override public UserTransaction getUserTransaction() { try { return instance.getUserTransaction(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void cleanup() { } @Override public String getLookup() { return lookup; } @Override public TransactionManagerLookup lookup() { return instance; } @Override public TransactionManager getManager() { try { return instance.getTransactionManager(); } catch (Exception e) { throw new RuntimeException(e); } } }; } } public static TransactionManager getManager() { return operations.getManager(); } public static String getManagerLookup() { return operations.getLookup(); } public static TransactionManagerLookup lookup() { return operations.lookup(); } public static UserTransaction getUserTransaction() { return operations.getUserTransaction(); } public static void cleanup() { operations.cleanup(); } }
3,999
26.972028
124
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/FailAllTestNGHook.java
package org.infinispan.test.fwk; import org.testng.IHookCallBack; import org.testng.IHookable; import org.testng.ITestResult; import org.testng.SkipException; /** * TestNG hook to fail all tests. * * Useful to check that the cache managers are shut down properly for failed tests. * * @author Dan Berindei * @since 7.0 */ public class FailAllTestNGHook implements IHookable { @Override public void run(IHookCallBack iHookCallBack, ITestResult iTestResult) { iHookCallBack.runTestMethod(iTestResult); throw new SkipException("Induced failure"); } }
578
24.173913
83
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/SuiteResourcesAndLogTest.java
package org.infinispan.test.fwk; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; /** * This class makes sure that all files are being deleted after each test run. It also logs testsuite information. * * @author Mircea.Markus@jboss.com * @author Galder Zamarreño */ @Test(groups = "functional", testName = "test.fwk.SuiteResourcesAndLogTest") public class SuiteResourcesAndLogTest { private static final Log log = LogFactory.getLog(SuiteResourcesAndLogTest.class); @BeforeSuite @AfterSuite public void printEnvInformation() { log("~~~~~~~~~~~~~~~~~~~~~~~~~ ENVIRONMENT INFO ~~~~~~~~~~~~~~~~~~~~~~~~~~"); log("jgroups.bind_addr = " + System.getProperty("jgroups.bind_addr")); log("java.runtime.version = " + System.getProperty("java.runtime.version")); log("java.runtime.name =" + System.getProperty("java.runtime.name")); log("java.vm.version = " + System.getProperty("java.vm.version")); log("java.vm.vendor = " + System.getProperty("java.vm.vendor")); log("os.name = " + System.getProperty("os.name")); log("os.version = " + System.getProperty("os.version")); log("sun.arch.data.model = " + System.getProperty("sun.arch.data.model")); log("sun.cpu.endian = " + System.getProperty("sun.cpu.endian")); log("protocol.stack = " + System.getProperty("protocol.stack")); log("infinispan.cluster.stack = " + System.getProperty("infinispan.cluster.stack")); log("infinispan.unsafe.allow_jdk8_chm = [Forced: requires JDK8 now]"); String preferIpV4 = System.getProperty("java.net.preferIPv4Stack"); log("java.net.preferIPv4Stack = " + preferIpV4); log("java.net.preferIPv6Stack = " + System.getProperty("java.net.preferIPv6Stack")); log("log4.configurationFile = " + System.getProperty("log4j.configurationFile")); log("MAVEN_OPTS = " + System.getProperty("MAVEN_OPTS")); log("~~~~~~~~~~~~~~~~~~~~~~~~~ ENVIRONMENT INFO ~~~~~~~~~~~~~~~~~~~~~~~~~~"); } private void log(String s) { System.out.println(s); log.info(s); } }
2,229
44.510204
114
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/TcpMPingEnvironmentTest.java
package org.infinispan.test.fwk; import static org.testng.Assert.fail; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.SocketAddress; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Properties; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.jgroups.JChannel; import org.jgroups.View; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * The purpose of this class is to test that/if tcp + mping works fine in the given environment. * * @author Mircea.Markus@jboss.com */ @Test(testName = "test.fwk.TcpMPingEnvironmentTest", groups = "manual", description = "This test just tests whether the HUdson environment allows proper binding to UDP sockets.") public class TcpMPingEnvironmentTest { Log log = LogFactory.getLog(TcpMPingEnvironmentTest.class); List<JChannel> openedChannles = new ArrayList<JChannel>(); private boolean success = false; private static final String IP_ADDRESS = "239.10.10.5"; @AfterMethod public void destroyCaches() { for (JChannel ch : openedChannles) { ch.disconnect(); ch.close(); } // tryPrintRoutingInfo(); if (!success) { Properties properties = System.getProperties(); log.trace("System props are " + properties); System.out.println("System props are " + properties); tryPrintRoutingInfo(); } } private void tryPrintRoutingInfo() { tryExecNativeCommand("/sbin/route", "Routing table is "); tryExecNativeCommand("/sbin/ip route get 239.10.10.5", "/sbin/ip route get " + IP_ADDRESS); } private void tryExecNativeCommand(String command, String printPrefix) { try { Process p = Runtime.getRuntime().exec(command); InputStream inputStream = p.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = reader.readLine(); StringBuilder result = new StringBuilder(); while (line != null) { result.append(line).append('\n'); line = reader.readLine(); } log.trace(printPrefix + result); inputStream.close(); } catch (IOException e) { log.trace("Cannot print " + printPrefix + " !",e); } } /** * Tests that different clusters are created and that they don't overlap. */ public void testDifferentClusters() throws Exception { JChannel first1 = new JChannel("stacks/tcp_mping/tcp1.xml"); JChannel first2 = new JChannel("stacks/tcp_mping/tcp1.xml"); JChannel first3 = new JChannel("stacks/tcp_mping/tcp1.xml"); initiChannel(first1); initiChannel(first2); initiChannel(first3); expectView(first1, first2, first3); JChannel second1 = new JChannel("stacks/tcp_mping/tcp2.xml"); JChannel second2 = new JChannel("stacks/tcp_mping/tcp2.xml"); JChannel second3 = new JChannel("stacks/tcp_mping/tcp2.xml"); initiChannel(second1); initiChannel(second2); initiChannel(second3); expectView(first1, first2, first3); expectView(second1, second2, second3); success = true; } public void testMcastSocketCreation() throws Exception { InetAddress mcast_addr = InetAddress.getByName(IP_ADDRESS); SocketAddress saddr = new InetSocketAddress(mcast_addr, 43589); MulticastSocket retval = null; try { success = false; retval = new MulticastSocket(saddr); success = true; } finally { if (retval != null) { try { retval.close(); } catch (Exception e) { e.printStackTrace(); } } } } public void testMcastSocketCreation2() throws Exception { InetAddress mcast_addr = InetAddress.getByName(IP_ADDRESS); int port = 43589; MulticastSocket retval = null; try { Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); StringBuilder okTrace = new StringBuilder(); StringBuilder failureTrace = new StringBuilder(); success = true; while (nis.hasMoreElements()) { retval = new MulticastSocket(port); NetworkInterface networkInterface = nis.nextElement(); retval.setNetworkInterface(networkInterface); try { retval.joinGroup(mcast_addr); String msg = "Successfully bind to " + networkInterface; okTrace.append(msg).append('\n'); } catch (IOException e) { e.printStackTrace(); String msg = "Failed to bind to " + networkInterface + "."; failureTrace.append(msg).append('\n'); success = false; } } if (success) { log.trace(okTrace); System.out.println("Sucessfull binding! " + okTrace); } else { String message = "Success : " + okTrace + ". Failures : " + failureTrace; log.error(message); System.out.println(message); throw new RuntimeException(message); } } finally { if (retval != null) { try { retval.close(); } catch (Exception e) { e.printStackTrace(); } } } } private void expectView(JChannel... channels) throws Exception { for (int i = 0; i < 20; i++) { boolean success = true; for (int j = 0; j < channels.length; j++) { View view = channels[j].getView(); if (view == null) { success = false; break; } success = success && (view.size() == channels.length); if (view.size() > channels.length) assert false : "Clusters see each other!"; } if (success) return; Thread.sleep(1000); } fail("Could not form cluster in given timeout"); } private void initiChannel(JChannel channel) throws Exception { openedChannles.add(channel); channel.setDiscardOwnMessages(true); channel.connect("someChannel"); } }
6,507
32.374359
112
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/InTransactionMode.java
package org.infinispan.test.fwk; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.infinispan.transaction.TransactionMode; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) public @interface InTransactionMode { TransactionMode[] value(); }
461
24.666667
50
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/CheckPoint.java
package org.infinispan.test.fwk; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.infinispan.test.TestingUtil; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * Behaves more or less like a map of {@link java.util.concurrent.Semaphore}s. * * One thread will wait for an event via {@code await(...)} or {@code awaitStrict(...)}, and one or more * other threads will trigger the event via {@code trigger(...)} or {@code triggerForever(...)}. * * @author Dan Berindei * @since 5.3 */ public class CheckPoint { private static final Log log = LogFactory.getLog(CheckPoint.class); public static final int INFINITE = 999999999; private final String id; private final Lock lock = new ReentrantLock(); private final Condition unblockCondition = lock.newCondition(); private final Map<String, EventStatus> events = new HashMap<>(); public CheckPoint() { this.id = ""; } public CheckPoint(String name) { this.id = "[" + name + "] "; } public void awaitStrict(String event, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { awaitStrict(event, 1, timeout, unit); } public CompletionStage<Void> awaitStrictAsync(String event, long timeout, TimeUnit unit, Executor executor) { return CompletableFuture.runAsync(() -> { try { awaitStrict(event, 1, timeout, unit); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (TimeoutException e) { CompletableFutures.rethrowExceptionIfPresent(e); } }, executor); } private boolean await(String event, long timeout, TimeUnit unit) throws InterruptedException { return await(event, 1, timeout, unit); } public void awaitStrict(String event, int count, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { if (!await(event, count, timeout, unit)) { throw new TimeoutException(id + "Timed out waiting for event " + event); } } private boolean await(String event, int count, long timeout, TimeUnit unit) throws InterruptedException { log.tracef("%sWaiting for event %s * %d", id, event, count); lock.lock(); try { EventStatus status = events.computeIfAbsent(event, k -> new EventStatus()); long waitNanos = unit.toNanos(timeout); while (waitNanos > 0) { if (status.available >= count) { status.available -= count; break; } waitNanos = unblockCondition.awaitNanos(waitNanos); } if (waitNanos <= 0) { log.errorf("%sTimed out waiting for event %s * %d (available = %d, total = %d)", id, event, count, status.available, status.total); // let the triggering thread know that we timed out status.available = -1; return false; } log.tracef("%sReceived event %s * %d (available = %d, total = %d)", id, event, count, status.available, status.total); return true; } finally { lock.unlock(); } } public String peek(long timeout, TimeUnit unit, String... expectedEvents) throws InterruptedException { log.tracef("%sWaiting for any one of events %s", id, Arrays.toString(expectedEvents)); String found = null; lock.lock(); try { long waitNanos = unit.toNanos(timeout); while (waitNanos > 0) { for (String event : expectedEvents) { EventStatus status = events.get(event); if (status != null && status.available >= 1) { found = event; break; } } if (found != null) break; waitNanos = unblockCondition.awaitNanos(waitNanos); } if (waitNanos <= 0) { log.tracef("%sPeek did not receive any of %s", id, Arrays.toString(expectedEvents)); return null; } EventStatus status = events.get(found); log.tracef("%sReceived event %s (available = %d, total = %d)", id, found, status.available, status.total); return found; } finally { lock.unlock(); } } public CompletableFuture<Void> future(String event, long timeout, TimeUnit unit, Executor executor) { return future(event, 1, timeout, unit, executor); } public CompletableFuture<Void> future(String event, int count, long timeout, TimeUnit unit, Executor executor) { return TestingUtil.orTimeout(future0(event, count), timeout, unit, executor) .thenRunAsync(() -> log.tracef("Received event %s * %d", event, count), executor); } public CompletableFuture<Void> future0(String event, int count) { log.tracef("%sWaiting for event %s * %d", id, event, count); lock.lock(); try { EventStatus status = events.get(event); if (status == null) { status = new EventStatus(); events.put(event, status); } if (status.available >= count) { status.available -= count; return CompletableFutures.completedNull(); } if (status.requests == null) { status.requests = new ArrayList<>(); } CompletableFuture<Void> f = new CompletableFuture<>(); status.requests.add(new Request(f, count)); return f; } finally { lock.unlock(); } } public void trigger(String event) { trigger(event, 1); } public void triggerForever(String event) { trigger(event, INFINITE); } public void trigger(String event, int count) { lock.lock(); try { EventStatus status = events.get(event); if (status == null) { status = new EventStatus(); events.put(event, status); } else if (status.available < 0) { throw new IllegalStateException(id + "Thread already timed out waiting for event " + event); } // If triggerForever is called more than once, it will cause an overflow and the waiters will fail. status.available = count != INFINITE ? status.available + count : INFINITE; status.total = count != INFINITE ? status.total + count : INFINITE; log.tracef("%sTriggering event %s * %d (available = %d, total = %d)", id, event, count, status.available, status.total); unblockCondition.signalAll(); if (status.requests != null) { if (count == INFINITE) { status.requests.forEach(request -> request.future.complete(null)); } else { Iterator<Request> iterator = status.requests.iterator(); while (status.available > 0 && iterator.hasNext()){ Request request = iterator.next(); if (request.count <= status.available) { request.future.complete(null); status.available -= request.count; iterator.remove(); } } } } } finally { lock.unlock(); } } @Override public String toString() { return "CheckPoint(" + id + ")" + events; } private static class EventStatus { int available; int total; public ArrayList<Request> requests; @Override public String toString() { return "" + available + "/" + total + ", requests=" + requests; } } private static class Request { final CompletableFuture<Void> future; final int count; private Request(CompletableFuture<Void> future, int count) { this.future = future; this.count = count; } @Override public String toString() { return "(" + count + ")"; } } }
8,517
33.346774
115
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/FakeTestClass.java
package org.infinispan.test.fwk; import java.lang.reflect.Method; import org.testng.ITestClass; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.TestNGException; import org.testng.internal.MethodInstance; import org.testng.internal.TestNGMethod; import org.testng.xml.XmlClass; import org.testng.xml.XmlTest; public class FakeTestClass implements ITestClass { private static final long serialVersionUID = -4871120395482207788L; private final Object instance; private final ITestNGMethod method; private final XmlTest xmlTest; public static MethodInstance newFailureMethodInstance(Exception e, XmlTest xmlTest, ITestContext context, Object instance) { Method failMethod; try { failMethod = TestFrameworkFailure.class.getMethod("fail"); } catch (NoSuchMethodException e1) { e1.addSuppressed(e); e1.printStackTrace(System.err); throw new TestNGException(e1); } Class<?> testClass = instance.getClass(); TestFrameworkFailure<?> fakeInstance = new TestFrameworkFailure<>(testClass, e); TestNGMethod testNGMethod = new TestNGMethod(failMethod, context.getSuite().getAnnotationFinder(), xmlTest, fakeInstance); ITestClass fakeTestClass = new FakeTestClass(testNGMethod, fakeInstance, xmlTest); testNGMethod.setTestClass(fakeTestClass); return new MethodInstance(testNGMethod); } FakeTestClass(ITestNGMethod method, Object instance, XmlTest xmlTest) { this.method = method; this.instance = instance; this.xmlTest = xmlTest; } @Override public Object[] getInstances(boolean reuse) { return new Object[]{instance}; } @Override public long[] getInstanceHashCodes() { return new long[]{instance.hashCode()}; } @Override public int getInstanceCount() { return 1; } @Override public ITestNGMethod[] getTestMethods() { return new ITestNGMethod[]{method}; } @Override public ITestNGMethod[] getBeforeTestMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getAfterTestMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getBeforeClassMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getAfterClassMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getBeforeSuiteMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getAfterSuiteMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getBeforeTestConfigurationMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getAfterTestConfigurationMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getBeforeGroupsMethods() { return new ITestNGMethod[0]; } @Override public ITestNGMethod[] getAfterGroupsMethods() { return new ITestNGMethod[0]; } @Override public String getName() { return instance.getClass().getName(); } @Override public XmlTest getXmlTest() { return xmlTest; } @Override public XmlClass getXmlClass() { return null; } @Override public String getTestName() { return null; } @Override public Class getRealClass() { return instance.getClass(); } @Override public void addInstance(Object instance) { } }
3,635
23.90411
108
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/CleanupAfterTest.java
package org.infinispan.test.fwk; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Indicates that test cleanup happens after all test methods. * * @author Manik Surtani * @version 4.2 */ @Retention(RetentionPolicy.RUNTIME) public @interface CleanupAfterTest { }
309
19.666667
62
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/ClusteringDependentLogicDelegator.java
package org.infinispan.test.fwk; import java.util.Map; import java.util.concurrent.CompletionStage; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.tx.VersionedPrepareCommand; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.versioning.IncrementableEntryVersion; import org.infinispan.container.versioning.VersionGenerator; import org.infinispan.context.Flag; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.persistence.util.EntryLoader; import org.infinispan.remoting.transport.Address; /** * A {@link org.infinispan.interceptors.locking.ClusteringDependentLogic} delegator * * @author Pedro Ruivo * @since 7.0 */ public class ClusteringDependentLogicDelegator implements ClusteringDependentLogic { private final ClusteringDependentLogic clusteringDependentLogic; public ClusteringDependentLogicDelegator(ClusteringDependentLogic clusteringDependentLogic) { this.clusteringDependentLogic = clusteringDependentLogic; } @Override public LocalizedCacheTopology getCacheTopology() { return clusteringDependentLogic.getCacheTopology(); } @Override public CompletionStage<Void> commitEntry(CacheEntry entry, FlagAffectedCommand command, InvocationContext ctx, Flag trackFlag, boolean l1Invalidation) { return clusteringDependentLogic.commitEntry(entry, command, ctx, trackFlag, l1Invalidation); } @Override public Commit commitType(FlagAffectedCommand command, InvocationContext ctx, int segment, boolean removed) { return clusteringDependentLogic.commitType(command, ctx, segment, removed); } @Override public CompletionStage<Map<Object, IncrementableEntryVersion>> createNewVersionsAndCheckForWriteSkews(VersionGenerator versionGenerator, TxInvocationContext context, VersionedPrepareCommand prepareCommand) { return clusteringDependentLogic.createNewVersionsAndCheckForWriteSkews(versionGenerator, context, prepareCommand); } @Override public Address getAddress() { return clusteringDependentLogic.getAddress(); } @Override public <K, V> EntryLoader<K, V> getEntryLoader() { return clusteringDependentLogic.getEntryLoader(); } @Override public void start() { clusteringDependentLogic.start(); } }
2,509
35.911765
210
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/TestSelector.java
package org.infinispan.test.fwk; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.function.Predicate; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; /** * See {@link ChainMethodInterceptor}. Works in a similar way as annotating test class * with {@link org.testng.annotations.Listeners} with {@link IMethodInterceptor} but allows * multiple interceptors and multiple filters. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface TestSelector { /** * Filters are applied before the interceptors to remove unwanted methods. */ Class<? extends Predicate<IMethodInstance>>[] filters() default {}; /** * Interceptors are applied later to e.g. sort methods. */ Class<? extends IMethodInterceptor>[] interceptors() default {}; }
995
30.125
91
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/FailAllSetupTestNGHook.java
package org.infinispan.test.fwk; import org.testng.IConfigurable; import org.testng.IConfigureCallBack; import org.testng.ITestNGMethod; import org.testng.ITestResult; /** * TestNG hook to fail all tests. * * Useful to check that the cache managers are shut down properly for failed tests. * * @author Dan Berindei * @since 7.0 */ public class FailAllSetupTestNGHook implements IConfigurable { @Override public void run(IConfigureCallBack callBack, ITestResult testResult) { ITestNGMethod testMethod = testResult.getMethod(); System.out.println("Running " + testMethod.getDescription()); callBack.runConfigurationMethod(testResult); if (testMethod.isBeforeMethodConfiguration() || testMethod.isBeforeClassConfiguration() || testMethod.isBeforeTestConfiguration()) { throw new RuntimeException("Induced failure"); } } }
878
29.310345
138
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/TestCacheManagerFactory.java
package org.infinispan.test.fwk; import static org.infinispan.test.fwk.JGroupsConfigBuilder.getJGroupsConfig; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.net.URL; import org.infinispan.commons.configuration.io.ConfigurationResourceResolvers; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.executors.ThreadPoolExecutorFactory; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.PlatformMBeanServerLookup; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.commons.util.FileLookupFactory; import org.infinispan.commons.util.LegacyKeySupportSystemProperties; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.global.ThreadPoolConfiguration; import org.infinispan.configuration.global.TransportConfiguration; import org.infinispan.configuration.internal.PrivateGlobalConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.factories.threads.CoreExecutorFactory; import org.infinispan.factories.threads.DefaultThreadFactory; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.remoting.transport.jgroups.JGroupsTransport; import org.infinispan.security.Security; import org.infinispan.transaction.TransactionMode; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * CacheManagers in unit tests should be created with this factory, in order to avoid resource clashes. See * http://community.jboss.org/wiki/ParallelTestSuite for more details. * * @author Mircea.Markus@jboss.com * @author Galder Zamarreño */ public class TestCacheManagerFactory { public static final String DEFAULT_CACHE_NAME = "defaultcache"; public static final int NAMED_EXECUTORS_THREADS_NO_QUEUE = 6; // Check *TxPartitionAndMerge*Test with taskset -c 1 before reducing the following 2 private static final int NAMED_EXECUTORS_THREADS_WITH_QUEUE = 6; private static final int NAMED_EXECUTORS_QUEUE_SIZE = 20; private static final int NAMED_EXECUTORS_KEEP_ALIVE = 30000; private static final String MARSHALLER = LegacyKeySupportSystemProperties.getProperty( "infinispan.test.marshaller.class", "infinispan.marshaller.class"); private static final Log log = LogFactory.getLog(TestCacheManagerFactory.class); /** * Note this method does not amend the global configuration to reduce overall resource footprint. It is therefore * suggested to use * {@link * org.infinispan.test.fwk.TestCacheManagerFactory#createClusteredCacheManager(org.infinispan.configuration.cache.ConfigurationBuilder, * TransportFlags)} instead when this is needed * * @param start Whether to start this cache container * @param gcb The global configuration builder to use * @param c The default configuration to use * @return The resultant cache manager that is created */ public static EmbeddedCacheManager newDefaultCacheManager(boolean start, GlobalConfigurationBuilder gcb, ConfigurationBuilder c) { setNodeName(gcb); GlobalConfiguration globalConfiguration = gcb.build(); checkJmx(globalConfiguration); DefaultCacheManager defaultCacheManager; if (c != null) { amendDefaultCache(gcb); ConfigurationBuilderHolder holder = new ConfigurationBuilderHolder(Thread.currentThread().getContextClassLoader(), gcb); holder.getNamedConfigurationBuilders().put(gcb.defaultCacheName().get(), c); defaultCacheManager = new DefaultCacheManager(holder, start); } else { defaultCacheManager = new DefaultCacheManager(gcb.build(), start); } TestResourceTracker.addResource(new CacheManagerCleaner(defaultCacheManager)); return defaultCacheManager; } public static DefaultCacheManager newDefaultCacheManager(boolean start, ConfigurationBuilderHolder holder) { GlobalConfigurationBuilder gcb = holder.getGlobalConfigurationBuilder(); if (holder.getDefaultConfigurationBuilder() != null) { amendDefaultCache(gcb); } setNodeName(gcb); checkJmx(gcb.build()); DefaultCacheManager defaultCacheManager = new DefaultCacheManager(holder, start); TestResourceTracker.addResource(new CacheManagerCleaner(defaultCacheManager)); return defaultCacheManager; } public static EmbeddedCacheManager fromXml(String xmlFile) throws IOException { return fromXml(xmlFile, false); } public static EmbeddedCacheManager fromXml(String xmlFile, boolean defaultParserOnly) throws IOException { return fromXml(xmlFile, defaultParserOnly, true); } public static EmbeddedCacheManager fromXml(String xmlFile, boolean defaultParserOnly, boolean start) throws IOException { return fromXml(xmlFile, defaultParserOnly, start, new TransportFlags()); } public static EmbeddedCacheManager fromXml(String xmlFile, boolean defaultParserOnly, boolean start, TransportFlags transportFlags) throws IOException { // Use parseURL because it sets an XMLResourceResolver and allows includes ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL url = FileLookupFactory.newInstance().lookupFileLocation(xmlFile, classLoader); ConfigurationBuilderHolder holder = parseURL(url, defaultParserOnly); return createClusteredCacheManager(start, holder, transportFlags); } public static EmbeddedCacheManager fromStream(InputStream is) { return fromStream(is, true); } public static EmbeddedCacheManager fromStream(InputStream is, boolean defaultParsersOnly) { return fromStream(is, defaultParsersOnly, true); } public static EmbeddedCacheManager fromStream(InputStream is, boolean defaultParsersOnly, boolean start) { return createClusteredCacheManager(start, parseStream(is, defaultParsersOnly), new TransportFlags()); } public static ConfigurationBuilderHolder parseFile(String xmlFile, boolean defaultParserOnly) throws IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try (InputStream is = FileLookupFactory.newInstance().lookupFileStrict(xmlFile, classLoader)) { return parseStream(is, defaultParserOnly); } } public static ConfigurationBuilderHolder parseURL(URL url, boolean defaultParsersOnly) throws IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); ParserRegistry parserRegistry = new ParserRegistry(classLoader, defaultParsersOnly, System.getProperties()); ConfigurationBuilderHolder holder = parserRegistry.parse(url); return updateTestName(holder); } public static ConfigurationBuilderHolder parseStream(InputStream is, boolean defaultParsersOnly) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); ParserRegistry parserRegistry = new ParserRegistry(classLoader, defaultParsersOnly, System.getProperties()); ConfigurationBuilderHolder holder = parserRegistry.parse(is, ConfigurationResourceResolvers.DEFAULT, MediaType.APPLICATION_XML); return updateTestName(holder); } private static ConfigurationBuilderHolder updateTestName(ConfigurationBuilderHolder holder) { // The node name is set in each DefaultThreadFactory individually, override it here String testShortName = TestResourceTracker.getCurrentTestShortName(); GlobalConfiguration gc = holder.getGlobalConfigurationBuilder().build(); updateNodeName(testShortName, gc.listenerThreadPool()); updateNodeName(testShortName, gc.expirationThreadPool()); updateNodeName(testShortName, gc.persistenceThreadPool()); updateNodeName(testShortName, gc.stateTransferThreadPool()); updateNodeName(testShortName, gc.asyncThreadPool()); updateNodeName(testShortName, gc.transport().transportThreadPool()); return holder; } private static void updateNodeName(String nodeName, ThreadPoolConfiguration threadPoolConfiguration) { if (threadPoolConfiguration.threadFactory() instanceof DefaultThreadFactory) { ((DefaultThreadFactory) threadPoolConfiguration.threadFactory()).setNode(nodeName); } } public static EmbeddedCacheManager fromString(String config) { return fromStream(new ByteArrayInputStream(config.getBytes())); } private static void markAsTransactional(boolean transactional, ConfigurationBuilder builder) { if (!transactional) { builder.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL); } else { builder.transaction() .transactionMode(TransactionMode.TRANSACTIONAL); builder.transaction().transactionManagerLookup(Util.getInstance(TransactionSetup.getManagerLookup(), TestCacheManagerFactory.class.getClassLoader())); } } private static void updateTransactionSupport(boolean transactional, ConfigurationBuilder builder) { if (transactional) amendJTA(builder); } private static void amendJTA(ConfigurationBuilder builder) { if (builder.transaction().transactionMode() == TransactionMode.TRANSACTIONAL && builder.transaction().transactionManagerLookup() == null) { builder.transaction().transactionManagerLookup(Util.getInstance(TransactionSetup.getManagerLookup(), TestCacheManagerFactory.class.getClassLoader())); } } /** * Creates an cache manager that does support clustering. */ public static EmbeddedCacheManager createClusteredCacheManager() { return createClusteredCacheManager(new ConfigurationBuilder(), new TransportFlags()); } public static EmbeddedCacheManager createClusteredCacheManager(ConfigurationBuilder defaultCacheConfig, TransportFlags flags) { return createClusteredCacheManager(GlobalConfigurationBuilder.defaultClusteredBuilder(), defaultCacheConfig, flags); } public static EmbeddedCacheManager createClusteredCacheManager(SerializationContextInitializer sci) { return createClusteredCacheManager(sci, new ConfigurationBuilder()); } public static EmbeddedCacheManager createClusteredCacheManager(SerializationContextInitializer sci, ConfigurationBuilder defaultCacheConfig) { GlobalConfigurationBuilder globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); if (sci != null) globalBuilder.serialization().addContextInitializer(sci); return createClusteredCacheManager(globalBuilder, defaultCacheConfig, new TransportFlags()); } public static EmbeddedCacheManager createClusteredCacheManager(GlobalConfigurationBuilder gcb, ConfigurationBuilder defaultCacheConfig) { return createClusteredCacheManager(gcb, defaultCacheConfig, new TransportFlags()); } public static EmbeddedCacheManager createClusteredCacheManager(ConfigurationBuilder defaultCacheConfig) { return createClusteredCacheManager(GlobalConfigurationBuilder.defaultClusteredBuilder(), defaultCacheConfig); } public static EmbeddedCacheManager createClusteredCacheManager(ConfigurationBuilderHolder holder) { return createClusteredCacheManager(true, holder); } public static EmbeddedCacheManager createClusteredCacheManager(boolean start, ConfigurationBuilderHolder holder) { return createClusteredCacheManager(start, holder, new TransportFlags()); } public static EmbeddedCacheManager createClusteredCacheManager(boolean start, ConfigurationBuilderHolder holder, TransportFlags flags) { amendGlobalConfiguration(holder.getGlobalConfigurationBuilder(), flags); for (ConfigurationBuilder builder : holder.getNamedConfigurationBuilders().values()) amendJTA(builder); return newDefaultCacheManager(start, holder); } public static EmbeddedCacheManager createClusteredCacheManager(GlobalConfigurationBuilder gcb, ConfigurationBuilder defaultCacheConfig, TransportFlags flags) { return createClusteredCacheManager(true, gcb, defaultCacheConfig, flags); } public static EmbeddedCacheManager createClusteredCacheManager(boolean start, GlobalConfigurationBuilder gcb, ConfigurationBuilder defaultCacheConfig, TransportFlags flags) { amendGlobalConfiguration(gcb, flags); if (defaultCacheConfig != null) { amendJTA(defaultCacheConfig); } return newDefaultCacheManager(start, gcb, defaultCacheConfig); } public static void amendGlobalConfiguration(GlobalConfigurationBuilder gcb, TransportFlags flags) { amendMarshaller(gcb); minimizeThreads(gcb); amendTransport(gcb, flags); } public static EmbeddedCacheManager createCacheManager(ConfigurationBuilder builder) { return createCacheManager(new GlobalConfigurationBuilder().nonClusteredDefault(), builder); } public static EmbeddedCacheManager createCacheManager(SerializationContextInitializer sci, ConfigurationBuilder builder) { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault(); if (sci != null) globalBuilder.serialization().addContextInitializer(sci); return createCacheManager(globalBuilder, builder); } public static EmbeddedCacheManager createCacheManager() { return createCacheManager((ConfigurationBuilder) null); } public static EmbeddedCacheManager createServerModeCacheManager() { return createServerModeCacheManager((ConfigurationBuilder) null); } public static EmbeddedCacheManager createServerModeCacheManager(ConfigurationBuilder builder) { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault(); globalBuilder.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true); return createCacheManager(globalBuilder, builder); } public static EmbeddedCacheManager createServerModeCacheManager(SerializationContextInitializer sci, ConfigurationBuilder builder) { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault(); globalBuilder.serialization().addContextInitializer(sci); return createServerModeCacheManager(globalBuilder, builder); } public static EmbeddedCacheManager createServerModeCacheManager(GlobalConfigurationBuilder gcb) { gcb.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true); return createCacheManager(gcb, new ConfigurationBuilder()); } public static EmbeddedCacheManager createServerModeCacheManager(GlobalConfigurationBuilder gcb, ConfigurationBuilder builder) { gcb.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true); return createCacheManager(gcb, builder); } public static EmbeddedCacheManager createCacheManager(boolean start) { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault(); amendGlobalConfiguration(globalBuilder, new TransportFlags()); return newDefaultCacheManager(start, globalBuilder, new ConfigurationBuilder()); } public static EmbeddedCacheManager createCacheManager(SerializationContextInitializer sci) { return createCacheManager(true, sci); } public static EmbeddedCacheManager createCacheManager(boolean start, SerializationContextInitializer sci) { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault(); amendGlobalConfiguration(globalBuilder, new TransportFlags()); if (sci != null) globalBuilder.serialization().addContextInitializer(sci); return newDefaultCacheManager(start, globalBuilder, null); } public static EmbeddedCacheManager createCacheManager(GlobalConfigurationBuilder globalBuilder, ConfigurationBuilder builder) { return createCacheManager(globalBuilder, builder, true); } public static EmbeddedCacheManager createCacheManager(GlobalConfigurationBuilder globalBuilder, ConfigurationBuilder builder, boolean start) { if (globalBuilder.transport().build().transport().transport() != null) { throw new IllegalArgumentException( "Use TestCacheManagerFactory.createClusteredCacheManager(...) for clustered cache managers"); } amendTransport(globalBuilder); return newDefaultCacheManager(start, globalBuilder, builder); } public static EmbeddedCacheManager createCacheManager(CacheMode mode, boolean indexing) { return createCacheManager(null, mode, indexing); } public static EmbeddedCacheManager createCacheManager(SerializationContextInitializer sci, CacheMode mode, boolean indexing) { GlobalConfigurationBuilder globalBuilder = mode.isClustered() ? new GlobalConfigurationBuilder().clusteredDefault() : new GlobalConfigurationBuilder().nonClusteredDefault(); if (sci != null) globalBuilder.serialization().addContextInitializer(sci); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(mode); if (indexing) { builder.indexing().enabled(true); } if (mode.isClustered()) { return createClusteredCacheManager(globalBuilder, builder); } else { return createCacheManager(globalBuilder, builder); } } public static void configureJmx(GlobalConfigurationBuilder builder, String jmxDomain, MBeanServerLookup mBeanServerLookup) { builder.jmx().enabled(true) .domain(jmxDomain) .mBeanServerLookup(mBeanServerLookup); } public static ConfigurationBuilder getDefaultCacheConfiguration(boolean transactional) { return getDefaultCacheConfiguration(transactional, false); } public static ConfigurationBuilder getDefaultCacheConfiguration(boolean transactional, boolean useCustomTxLookup) { ConfigurationBuilder builder = new ConfigurationBuilder(); markAsTransactional(transactional, builder); //don't changed the tx lookup. if (useCustomTxLookup) updateTransactionSupport(transactional, builder); return builder; } public static void amendTransport(GlobalConfigurationBuilder cfg) { amendTransport(cfg, new TransportFlags()); } private static void amendTransport(GlobalConfigurationBuilder builder, TransportFlags flags) { String testName = TestResourceTracker.getCurrentTestName(); GlobalConfiguration gc = builder.build(); if (!flags.isPreserveConfig() && gc.transport().transport() != null) { if (flags.isRelayRequired()) { // Respect siteName transport flag builder.transport().clusterName(flags.siteName() + "-" + testName); } else if (gc.transport().attributes().attribute(TransportConfiguration.CLUSTER_NAME).isModified()) { // Respect custom cluster name (e.g. from TestCluster) builder.transport().clusterName(gc.transport().clusterName() + "-" + testName); } else { builder.transport().clusterName(testName); } // Remove any configuration file that might have been set. builder.transport().removeProperty(JGroupsTransport.CONFIGURATION_FILE); builder.transport().removeProperty(JGroupsTransport.CHANNEL_CONFIGURATOR); builder.transport().addProperty(JGroupsTransport.CONFIGURATION_STRING, getJGroupsConfig(testName, flags)); } } public static void setNodeName(GlobalConfigurationBuilder builder) { if (builder.build().transport().nodeName() != null) return; String nextNodeName = TestResourceTracker.getNextNodeName(); // Set the node name even for local managers in order to set the name of the worker threads builder.transport().nodeName(nextNodeName); } public static void minimizeThreads(GlobalConfigurationBuilder builder) { ThreadPoolExecutorFactory executorFactoryWithQueue = CoreExecutorFactory.executorFactory(NAMED_EXECUTORS_THREADS_WITH_QUEUE, NAMED_EXECUTORS_THREADS_WITH_QUEUE, NAMED_EXECUTORS_QUEUE_SIZE, NAMED_EXECUTORS_KEEP_ALIVE, false); ThreadPoolExecutorFactory nonBlockingExecutorFactoryWithQueue = CoreExecutorFactory.executorFactory(NAMED_EXECUTORS_THREADS_WITH_QUEUE, NAMED_EXECUTORS_THREADS_WITH_QUEUE, NAMED_EXECUTORS_QUEUE_SIZE, NAMED_EXECUTORS_KEEP_ALIVE, true); builder.blockingThreadPool().threadPoolFactory(executorFactoryWithQueue); builder.nonBlockingThreadPool().threadPoolFactory(nonBlockingExecutorFactoryWithQueue); // Listener thread pool already has a single thread // builder.listenerThreadPool().threadPoolFactory(executorFactoryWithQueue); // TODO Scheduled thread pools don't have a threads limit // Timeout thread pool is not configurable at all } public static void amendDefaultCache(GlobalConfigurationBuilder builder) { if (!builder.defaultCacheName().isPresent()) { builder.defaultCacheName(DEFAULT_CACHE_NAME); } } public static void amendMarshaller(GlobalConfigurationBuilder builder) { if (MARSHALLER != null) { try { Marshaller marshaller = Util.getInstanceStrict(MARSHALLER, Thread.currentThread().getContextClassLoader()); builder.serialization().marshaller(marshaller); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { // No-op, stick to GlobalConfiguration default. } } } private static void checkJmx(GlobalConfiguration gc) { assert !(gc.jmx().enabled() && gc.jmx().mbeanServerLookup() instanceof PlatformMBeanServerLookup) : "Tests must configure a MBeanServerLookup other than the default PlatformMBeanServerLookup or not enable JMX"; } public static class CacheManagerCleaner extends TestResourceTracker.Cleaner<EmbeddedCacheManager> { protected CacheManagerCleaner(EmbeddedCacheManager ref) { super(ref); } @Override public void close() { Runnable action = () -> { if (!ref.getStatus().isTerminated()) { TestCacheManagerFactory.log.debugf("Stopping cache manager %s", ref); ref.stop(); } }; Security.doPrivileged(action); } } }
23,592
48.357741
159
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/JGroupsConfigBuilder.java
package org.infinispan.test.fwk; import static org.infinispan.commons.util.Immutables.immutableMapCopy; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.FD; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.FD_ALL; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.FD_ALL2; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.FD_ALL3; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.FD_SOCK; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.FD_SOCK2; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.LOCAL_PING; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.MERGE3; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.MPING; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.PING; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.TCP; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.TCP_NIO2; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.TEST_RELAY2; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.UDP; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.VERIFY_SUSPECT; import static org.infinispan.test.fwk.JGroupsConfigBuilder.ProtocolType.VERIFY_SUSPECT2; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.commons.util.LegacyKeySupportSystemProperties; import org.jgroups.conf.ConfiguratorFactory; import org.jgroups.conf.ProtocolConfiguration; import org.jgroups.conf.ProtocolStackConfigurator; import org.jgroups.conf.XmlConfigurator; /** * This class owns the logic of associating network resources(i.e. ports) with threads, in order to make sure that there * won't be any clashes between multiple clusters running in parallel on same host. Used for parallel test suite. * * @author Mircea.Markus@jboss.com * @author Galder Zamarreño */ public class JGroupsConfigBuilder { public static final int BASE_TCP_PORT = 7900; public static final int MAX_NODES_PER_SITE = 50; private static final int MAX_SITES_PER_THREAD = 4; public static final int MAX_NODES_PER_THREAD = MAX_NODES_PER_SITE * MAX_SITES_PER_THREAD; public static final String JGROUPS_STACK; private static final Map<String, ProtocolStackConfigurator> protocolStackConfigurator = new HashMap<>(); private static final ThreadLocal<Integer> threadTcpIndex = new ThreadLocal<>() { private final AtomicInteger counter = new AtomicInteger(0); @Override protected Integer initialValue() { return counter.getAndIncrement(); } }; /** * Holds unique mcast_addr for each thread used for JGroups channel construction. */ private static final ThreadLocal<Integer> threadUdpIndex = new ThreadLocal<>() { private final AtomicInteger counter = new AtomicInteger(0); @Override protected Integer initialValue() { return counter.getAndIncrement(); } }; private static final ConcurrentMap<String, Integer> testUdpIndex = new ConcurrentHashMap<>(); static { JGROUPS_STACK = LegacyKeySupportSystemProperties.getProperty("infinispan.cluster.stack", "infinispan.test.jgroups.protocol", "test-udp"); System.out.println("Transport protocol stack used = " + JGROUPS_STACK); // Load the XML just once protocolStackConfigurator.put("test-tcp", loadProtocolStack("stacks/tcp.xml")); protocolStackConfigurator.put("test-udp", loadProtocolStack("stacks/udp.xml")); protocolStackConfigurator.put("tcp", loadProtocolStack("default-configs/default-jgroups-tcp.xml")); protocolStackConfigurator.put("udp", loadProtocolStack("default-configs/default-jgroups-udp.xml")); } public static String getJGroupsConfig(String fullTestName, TransportFlags flags) { // With the XML already parsed, make a safe copy of the // protocol stack configurator and use that accordingly. JGroupsProtocolCfg jgroupsCfg = getJGroupsProtocolCfg(getConfigurator().getProtocolStack()); if (!flags.withFD()) removeFailureDetection(jgroupsCfg); if (!flags.isRelayRequired()) { removeRelay2(jgroupsCfg); } else { ProtocolConfiguration protocol = jgroupsCfg.getProtocol(TEST_RELAY2); protocol.getProperties().put("site", flags.siteName()); if (flags.relayConfig() != null) //if not specified, use default protocol.getProperties().put("config", flags.relayConfig()); } if (!flags.withMerge()) removeMerge(jgroupsCfg); replacePing(jgroupsCfg); int siteIndex = flags.siteIndex(); if (siteIndex > MAX_SITES_PER_THREAD) { throw new IllegalStateException("Currently we only support " + MAX_SITES_PER_THREAD + " ranges/sites!"); } replaceTcpStartPort(jgroupsCfg, siteIndex); replaceMCastAddressAndPort(jgroupsCfg, fullTestName, siteIndex); return jgroupsCfg.toString(); } public static ProtocolStackConfigurator getConfigurator() { ProtocolStackConfigurator stack = protocolStackConfigurator.get(JGROUPS_STACK); if (stack == null) { throw new IllegalStateException("Unknown protocol stack : " + JGROUPS_STACK); } return stack; } private static void replacePing(JGroupsProtocolCfg jgroupsCfg) { if (!jgroupsCfg.containsProtocol(LOCAL_PING)) { ProtocolType[] pingProtocols = new ProtocolType[]{MPING, PING}; ProtocolType pingProtocolToBeReplaced = null; for (ProtocolType protocol : pingProtocols) { if (jgroupsCfg.containsProtocol(protocol)) { pingProtocolToBeReplaced = protocol; break; } } if (pingProtocolToBeReplaced == null) { throw new IllegalStateException("Can't replace the ping protocol with LOCAL_PING"); } jgroupsCfg.replaceProtocol(pingProtocolToBeReplaced, new ProtocolConfiguration(LOCAL_PING.name(), new HashMap<>())); } } private static void removeMerge(JGroupsProtocolCfg jgroupsCfg) { jgroupsCfg.removeProtocol(MERGE3); } /** * Remove all failure detection related * protocols from the given JGroups stack. */ private static void removeFailureDetection(JGroupsProtocolCfg jgroupsCfg) { jgroupsCfg.removeProtocol(FD).removeProtocol(FD_SOCK).removeProtocol(FD_SOCK2) .removeProtocol(FD_ALL).removeProtocol(FD_ALL2).removeProtocol(FD_ALL3) .removeProtocol(VERIFY_SUSPECT).removeProtocol(VERIFY_SUSPECT2); } private static void removeRelay2(JGroupsProtocolCfg jgroupsCfg) { jgroupsCfg.removeProtocol(TEST_RELAY2); } private static void replaceMCastAddressAndPort(JGroupsProtocolCfg jgroupsCfg, String fullTestName, int siteIndex) { ProtocolConfiguration udp = jgroupsCfg.getProtocol(UDP); if (udp == null) return; Integer udpIndex = testUdpIndex.computeIfAbsent(fullTestName, k -> threadUdpIndex.get()); if (siteIndex < 0) { siteIndex = 0; } int clusterOffset = udpIndex * MAX_SITES_PER_THREAD + siteIndex; Map<String, String> props = udp.getProperties(); props.put("mcast_addr", "239.10.10." + clusterOffset); props.put("mcast_port", String.valueOf(46000 + clusterOffset)); replaceProperties(jgroupsCfg, props, UDP); } private static void replaceTcpStartPort(JGroupsProtocolCfg jgroupsCfg, int siteIndex) { ProtocolType transportProtocol = jgroupsCfg.transportType; if (transportProtocol != TCP && transportProtocol != TCP_NIO2) return; Map<String, String> props = jgroupsCfg.getProtocol(transportProtocol).getProperties(); Integer threadIndex = threadTcpIndex.get(); int startPort; int portRange; if (siteIndex >= 0) { // Site index set startPort = BASE_TCP_PORT + threadIndex * MAX_NODES_PER_THREAD + siteIndex * MAX_NODES_PER_SITE; portRange = MAX_NODES_PER_SITE; } else { // Site index not set, use the thread's full range startPort = BASE_TCP_PORT + threadIndex * MAX_NODES_PER_THREAD; portRange = MAX_NODES_PER_THREAD; } props.put("bind_port", String.valueOf(startPort)); // In JGroups, the port_range is inclusive props.put("port_range", String.valueOf(portRange - 1)); replaceProperties(jgroupsCfg, props, transportProtocol); } private static void replaceProperties( JGroupsProtocolCfg cfg, Map<String, String> newProps, ProtocolType type) { ProtocolConfiguration protocol = cfg.getProtocol(type); ProtocolConfiguration newProtocol = new ProtocolConfiguration(protocol.getProtocolName(), newProps); cfg.replaceProtocol(type, newProtocol); } private static ProtocolStackConfigurator loadProtocolStack(String relativePath) { try { return ConfiguratorFactory.getStackConfigurator(relativePath); } catch (Exception e) { throw new RuntimeException(e); } } private static JGroupsProtocolCfg getJGroupsProtocolCfg(List<ProtocolConfiguration> baseStack) { JGroupsXmxlConfigurator configurator = new JGroupsXmxlConfigurator(baseStack); List<ProtocolConfiguration> protoStack = configurator.getProtocolStack(); ProtocolType transportType = getProtocolType(protoStack.get(0).getProtocolName()); Map<ProtocolType, ProtocolConfiguration> protoMap = new HashMap<>(protoStack.size()); for (ProtocolConfiguration cfg : protoStack) { protoMap.put(getProtocolType(cfg.getProtocolName()), cfg); } return new JGroupsProtocolCfg(protoMap, configurator, transportType); } private static ProtocolType getProtocolType(String name) { int dotIndex = name.lastIndexOf("."); return ProtocolType.valueOf(dotIndex == -1 ? name : name.substring(dotIndex + 1)); } static class JGroupsXmxlConfigurator extends XmlConfigurator { protected JGroupsXmxlConfigurator(List<ProtocolConfiguration> protocols) { super(copy(protocols)); } static List<ProtocolConfiguration> copy(List<ProtocolConfiguration> protocols) { // Make a safe copy of the protocol stack to avoid concurrent modification issues List<ProtocolConfiguration> copy = new ArrayList<>(protocols.size()); for (ProtocolConfiguration p : protocols) { copy.add(new ProtocolConfiguration(p.getProtocolName(), immutableMapCopy(p.getProperties()))); } return copy; } } static class JGroupsProtocolCfg { final Map<ProtocolType, ProtocolConfiguration> protoMap; final XmlConfigurator configurator; final ProtocolType transportType; JGroupsProtocolCfg(Map<ProtocolType, ProtocolConfiguration> protoMap, XmlConfigurator configurator, ProtocolType transportType) { this.protoMap = protoMap; this.configurator = configurator; this.transportType = transportType; } JGroupsProtocolCfg addProtocol(ProtocolType type, ProtocolConfiguration cfg, int position) { protoMap.put(type, cfg); configurator.getProtocolStack().add(position, cfg); return this; } JGroupsProtocolCfg removeProtocol(ProtocolType type) { // Update the stack and map configurator.getProtocolStack().remove(protoMap.remove(type)); return this; } ProtocolConfiguration getProtocol(ProtocolType type) { return protoMap.get(type); } boolean containsProtocol(ProtocolType type) { return getProtocol(type) != null; } JGroupsProtocolCfg replaceProtocol(ProtocolType type, ProtocolConfiguration newCfg) { ProtocolConfiguration oldCfg = protoMap.get(type); int position = configurator.getProtocolStack().indexOf(oldCfg); // Remove protocol and put new configuration in same position return removeProtocol(type).addProtocol(type, newCfg, position); } @Override public String toString() { return configurator.getProtocolStackString(true); } } enum ProtocolType { TCP, TCP_NIO2, UDP, SHARED_LOOPBACK, RED, MPING, PING, TCPPING, LOCAL_PING, SHARED_LOOPBACK_PING, MERGE2, MERGE3, FD_SOCK, FD, VERIFY_SUSPECT, VERIFY_SUSPECT2, FD_ALL, FD_ALL2, FD_ALL3, FD_SOCK2, BARRIER, UNICAST, UNICAST2, UNICAST3, NAKACK, NAKACK2, RSVP, STABLE, GMS, UFC, MFC, FC, UFC_NB, MFC_NB, FRAG2, FRAG3, FRAG4, STREAMING_STATE_TRANSFER, TEST_RELAY2 } }
13,012
40.57508
143
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/TestFrameworkFailure.java
package org.infinispan.test.fwk; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; import org.mockito.Mockito; import org.testng.IInstanceInfo; import org.testng.TestNGException; import org.testng.annotations.Test; public class TestFrameworkFailure<T> implements IInstanceInfo<T> { private static final Set<String> OBJECT_METHODS = Arrays.stream(Object.class.getMethods()) .map(Method::getName) .collect(Collectors.toSet()); private final Throwable t; private final Class<T> testClass; public TestFrameworkFailure(Class<T> testClass, String format, Object... args) { this(testClass, new TestNGException(String.format(format, args))); } public TestFrameworkFailure(Class<T> testClass, Throwable t) { this.testClass = testClass; this.t = t; } // All the groups in TestNGSuiteChecksTest.REQUIRED_GROUPS, so the method is not excluded when running from Maven @Test(groups = {"unit", "functional", "xsite", "arquillian", "stress", "profiling", "manual", "unstable"}) public void fail() throws Throwable { throw t; } @Override public T getInstance() { return Mockito.mock(testClass, invocation -> { Method method = invocation.getMethod(); if (OBJECT_METHODS.contains(method.getName())) return invocation.callRealMethod(); throw t; }); } @Override public Class<T> getInstanceClass() { return testClass; } }
1,547
28.207547
116
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/MarshallingExceptionGenerator.java
package org.infinispan.test.fwk; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import org.infinispan.test.TestException; /** * Class that throws an exception on serialization or deserialization. * * @author Dan Berindei * @since 12.1 */ public class MarshallingExceptionGenerator implements Externalizable { private int countDownToMarshallingException; private int countDownToUnmarshallingException; public static MarshallingExceptionGenerator failOnSerialization(int count) { return new MarshallingExceptionGenerator(count, -1); } public static MarshallingExceptionGenerator failOnDeserialization(int count) { return new MarshallingExceptionGenerator(-1, count); } public MarshallingExceptionGenerator(int countDownToMarshallingException, int countDownToUnmarshallingException) { this.countDownToMarshallingException = countDownToMarshallingException; this.countDownToUnmarshallingException = countDownToUnmarshallingException; } public MarshallingExceptionGenerator() { this(0, 0); } @Override public String toString() { return "MarshallingExceptionGenerator{" + "countDownToMarshallingException=" + countDownToMarshallingException + ", countDownToUnmarshallingException=" + countDownToUnmarshallingException + '}'; } @Override public void writeExternal(ObjectOutput out) throws IOException { if (countDownToMarshallingException == 0) { throw new TestException(); } out.writeInt(countDownToMarshallingException - 1); out.writeInt(countDownToUnmarshallingException - 1); } @Override public void readExternal(ObjectInput in) throws IOException { this.countDownToMarshallingException = in.readInt(); this.countDownToUnmarshallingException = in.readInt(); if (countDownToUnmarshallingException == -1) { throw new TestException(); } } }
2,017
31.031746
117
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/TEST_RELAY2.java
package org.infinispan.test.fwk; import java.util.List; import java.util.Map; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.test.TestingUtil; import org.jgroups.conf.ClassConfigurator; import org.jgroups.protocols.relay.RELAY2; import org.jgroups.protocols.relay.config.RelayConfig; /** * RELAY2 only allows setting the bridge cluster name and properties via XML. * * This is a hack to change the bridge cluster name after the RELAY2 configuration is parsed, so that multiple * x-site tests can run in parallel. * * @author Dan Berindei * @since 9.2 */ public class TEST_RELAY2 extends RELAY2 { static { ClassConfigurator.addProtocol((short) 1321, TEST_RELAY2.class); } @Override protected void parseSiteConfiguration(Map<String, RelayConfig.SiteConfig> map) throws Exception { super.parseSiteConfiguration(map); String testName = TestResourceTracker.getCurrentTestName(); map.forEach((s, siteConfig) -> { List<RelayConfig.BridgeConfig> bridges = siteConfig.getBridges(); for (int i = 0; i < bridges.size(); i++) { RelayConfig.BridgeConfig bridgeConfig = bridges.get(i); String config = (String) TestingUtil.extractField(RelayConfig.PropertiesBridgeConfig.class, bridgeConfig, "config"); // Keep the same ports for all the tests, just change the cluster name String clusterName = "bridge-" + (testName != null ? testName : "namenotset"); bridges.set(i, new RelayConfig.PropertiesBridgeConfig(clusterName, config)); } }); } }
1,620
35.840909
118
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/CacheEntryDelegator.java
package org.infinispan.test.fwk; import org.infinispan.container.DataContainer; import org.infinispan.container.entries.CacheEntry; import org.infinispan.metadata.Metadata; /** * A {@link org.infinispan.container.entries.CacheEntry} delegator * * @author Pedro Ruivo * @since 7.0 */ public class CacheEntryDelegator implements CacheEntry { private final CacheEntry delegate; public CacheEntryDelegator(CacheEntry delegate) { this.delegate = delegate; } @Override public boolean isNull() { return delegate.isNull(); } @Override public Metadata getMetadata() { return delegate.getMetadata(); } @Override public void setMetadata(Metadata metadata) { delegate.setMetadata(metadata); } @Override public boolean isChanged() { return delegate.isChanged(); } @Override public boolean isCreated() { return delegate.isCreated(); } @Override public boolean isRemoved() { return delegate.isRemoved(); } @Override public boolean isEvicted() { return delegate.isEvicted(); } @Override public Object getKey() { return delegate.getKey(); } @Override public Object getValue() { return delegate.getValue(); } @Override public long getLifespan() { return delegate.getLifespan(); } @Override public long getMaxIdle() { return delegate.getMaxIdle(); } @Override public boolean skipLookup() { return delegate.skipLookup(); } @Override public long getCreated() { return delegate.getCreated(); } @Override public long getLastUsed() { return delegate.getLastUsed(); } @Override public Object setValue(Object value) { return delegate.setValue(value); } @Override public void commit(DataContainer container) { delegate.commit(container); } @Override public void setChanged(boolean changed) { delegate.setChanged(changed); } @Override public void setCreated(boolean created) { delegate.setCreated(created); } @Override public void setRemoved(boolean removed) { delegate.setRemoved(removed); } @Override public void setEvicted(boolean evicted) { delegate.setEvicted(evicted); } @Override public void setSkipLookup(boolean skipLookup) { delegate.setSkipLookup(skipLookup); } @Override public CacheEntry clone() { try { return (CacheEntry) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } }
2,607
18.176471
66
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/NamedTestMethod.java
package org.infinispan.test.fwk; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import org.testng.IClass; import org.testng.IRetryAnalyzer; import org.testng.ITestClass; import org.testng.ITestNGMethod; import org.testng.internal.ConstructorOrMethod; import org.testng.xml.XmlTest; public class NamedTestMethod implements ITestNGMethod { private final ITestNGMethod method; private final String name; public NamedTestMethod(ITestNGMethod method, String name) { this.method = method; this.name = name; } @Override public Class getRealClass() { return method.getRealClass(); } @Override public ITestClass getTestClass() { return method.getTestClass(); } @Override public void setTestClass(ITestClass cls) { method.setTestClass(cls); } @Override @Deprecated public Method getMethod() { return method.getMethod(); } @Override public String getMethodName() { return name; } @Override @Deprecated public Object[] getInstances() { return method.getInstances(); } @Override public Object getInstance() { return method.getInstance(); } @Override public long[] getInstanceHashCodes() { return method.getInstanceHashCodes(); } @Override public String[] getGroups() { return method.getGroups(); } @Override public String[] getGroupsDependedUpon() { return method.getGroupsDependedUpon(); } @Override public String getMissingGroup() { return method.getMissingGroup(); } @Override public void setMissingGroup(String group) { method.setMissingGroup(group); } @Override public String[] getBeforeGroups() { return method.getBeforeGroups(); } @Override public String[] getAfterGroups() { return method.getAfterGroups(); } @Override public String[] getMethodsDependedUpon() { return method.getMethodsDependedUpon(); } @Override public void addMethodDependedUpon(String methodName) { method.addMethodDependedUpon(methodName); } @Override public boolean isTest() { return method.isTest(); } @Override public boolean isBeforeMethodConfiguration() { return method.isBeforeMethodConfiguration(); } @Override public boolean isAfterMethodConfiguration() { return method.isAfterMethodConfiguration(); } @Override public boolean isBeforeClassConfiguration() { return method.isBeforeClassConfiguration(); } @Override public boolean isAfterClassConfiguration() { return method.isAfterClassConfiguration(); } @Override public boolean isBeforeSuiteConfiguration() { return method.isBeforeSuiteConfiguration(); } @Override public boolean isAfterSuiteConfiguration() { return method.isAfterSuiteConfiguration(); } @Override public boolean isBeforeTestConfiguration() { return method.isBeforeTestConfiguration(); } @Override public boolean isAfterTestConfiguration() { return method.isAfterTestConfiguration(); } @Override public boolean isBeforeGroupsConfiguration() { return method.isBeforeGroupsConfiguration(); } @Override public boolean isAfterGroupsConfiguration() { return method.isAfterGroupsConfiguration(); } @Override public long getTimeOut() { return method.getTimeOut(); } @Override public void setTimeOut(long timeOut) { method.setTimeOut(timeOut); } @Override public int getInvocationCount() { return method.getInvocationCount(); } @Override public void setInvocationCount(int count) { method.setInvocationCount(count); } @Override public int getTotalInvocationCount() { return method.getTotalInvocationCount(); } @Override public int getSuccessPercentage() { return method.getSuccessPercentage(); } @Override public String getId() { return method.getId(); } @Override public void setId(String id) { method.setId(id); } @Override public long getDate() { return method.getDate(); } @Override public void setDate(long date) { method.setDate(date); } @Override public boolean canRunFromClass(IClass testClass) { return method.canRunFromClass(testClass); } @Override public boolean isAlwaysRun() { return method.isAlwaysRun(); } @Override public int getThreadPoolSize() { return method.getThreadPoolSize(); } @Override public void setThreadPoolSize(int threadPoolSize) { method.setThreadPoolSize(threadPoolSize); } @Override public boolean getEnabled() { return method.getEnabled(); } @Override public String getDescription() { return method.getDescription(); } @Override public void setDescription(String s) { method.setDescription(s); } @Override public void incrementCurrentInvocationCount() { method.incrementCurrentInvocationCount(); } @Override public int getCurrentInvocationCount() { return method.getCurrentInvocationCount(); } @Override public void setParameterInvocationCount(int n) { method.setParameterInvocationCount(n); } @Override public int getParameterInvocationCount() { return method.getParameterInvocationCount(); } @Override public void setMoreInvocationChecker(Callable<Boolean> moreInvocationChecker) { method.setMoreInvocationChecker(moreInvocationChecker); } @Override public boolean hasMoreInvocation() { return method.hasMoreInvocation(); } @Override public ITestNGMethod clone() { return method.clone(); } @Override public IRetryAnalyzer getRetryAnalyzer() { return method.getRetryAnalyzer(); } @Override public void setRetryAnalyzer(IRetryAnalyzer retryAnalyzer) { method.setRetryAnalyzer(retryAnalyzer); } @Override public boolean skipFailedInvocations() { return method.skipFailedInvocations(); } @Override public void setSkipFailedInvocations(boolean skip) { method.setSkipFailedInvocations(skip); } @Override public long getInvocationTimeOut() { return method.getInvocationTimeOut(); } @Override public boolean ignoreMissingDependencies() { return method.ignoreMissingDependencies(); } @Override public void setIgnoreMissingDependencies(boolean ignore) { method.setIgnoreMissingDependencies(ignore); } @Override public List<Integer> getInvocationNumbers() { return method.getInvocationNumbers(); } @Override public void setInvocationNumbers(List<Integer> numbers) { method.setInvocationNumbers(numbers); } @Override public void addFailedInvocationNumber(int number) { method.addFailedInvocationNumber(number); } @Override public List<Integer> getFailedInvocationNumbers() { return method.getFailedInvocationNumbers(); } @Override public int getPriority() { return method.getPriority(); } @Override public void setPriority(int priority) { method.setPriority(priority); } @Override public XmlTest getXmlTest() { return method.getXmlTest(); } @Override public ConstructorOrMethod getConstructorOrMethod() { return method.getConstructorOrMethod(); } @Override public Map<String, String> findMethodParameters(XmlTest test) { return method.findMethodParameters(test); } @Override public String getQualifiedName() { return method.getQualifiedName(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof ITestNGMethod)) return false; return method.equals(o); } @Override public int hashCode() { return method.hashCode(); } }
8,016
20.153034
82
java
null
infinispan-main/core/src/test/java/org/infinispan/test/fwk/TestInternalCacheEntryFactory.java
package org.infinispan.test.fwk; import static org.infinispan.test.AbstractInfinispanTest.TIME_SERVICE; import org.infinispan.container.impl.InternalEntryFactory; import org.infinispan.container.impl.InternalEntryFactoryImpl; import org.infinispan.container.entries.ImmortalCacheEntry; import org.infinispan.container.entries.ImmortalCacheValue; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.entries.InternalCacheValue; import org.infinispan.container.entries.MortalCacheValue; import org.infinispan.container.entries.TransientCacheValue; import org.infinispan.container.entries.TransientMortalCacheValue; import org.infinispan.metadata.EmbeddedMetadata; import org.infinispan.test.TestingUtil; /** * A factory for internal entries for the test suite */ public class TestInternalCacheEntryFactory { private static final InternalEntryFactory FACTORY = new InternalEntryFactoryImpl(); static { TestingUtil.inject(FACTORY, TIME_SERVICE); } public static InternalCacheEntry create(Object key, Object value) { return new ImmortalCacheEntry(key, value); } public static InternalCacheValue create(Object value) { return new ImmortalCacheValue(value); } public static InternalCacheEntry create(Object key, Object value, long lifespan) { return create(FACTORY, key, value, lifespan); } public static <K,V> InternalCacheEntry<K,V> create(InternalEntryFactory factory, K key, V value, long lifespan) { //noinspection unchecked return factory.create(key, value, null, lifespan, -1); } public static InternalCacheEntry create(Object key, Object value, long lifespan, long maxIdle) { return create(FACTORY, key, value, lifespan, maxIdle); } public static <K,V> InternalCacheEntry<K,V> create(InternalEntryFactory factory, K key, V value, long lifespan, long maxIdle) { //noinspection unchecked return factory.create(key, value, null, lifespan, maxIdle); } public static InternalCacheEntry create(Object key, Object value, long created, long lifespan, long lastUsed, long maxIdle) { return FACTORY.create(key, value, new EmbeddedMetadata.Builder().build(), created, lifespan, lastUsed, maxIdle); } public static InternalCacheValue createValue(Object v, long created, long lifespan, long lastUsed, long maxIdle) { if (lifespan < 0 && maxIdle < 0) return new ImmortalCacheValue(v); if (lifespan > -1 && maxIdle < 0) return new MortalCacheValue(v, created, lifespan); if (lifespan < 0 && maxIdle > -1) return new TransientCacheValue(v, maxIdle, lastUsed); return new TransientMortalCacheValue(v, created, lifespan, maxIdle, lastUsed); } }
2,736
39.850746
130
java
null
infinispan-main/core/src/test/java/org/infinispan/test/transport/DelayedViewJGroupsTransport.java
package org.infinispan.test.transport; import java.lang.invoke.MethodHandles; import java.util.concurrent.CompletableFuture; import org.infinispan.remoting.transport.jgroups.JGroupsTransport; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.jgroups.View; public final class DelayedViewJGroupsTransport extends JGroupsTransport { private static Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); private final CompletableFuture<Void> waitLatch; public DelayedViewJGroupsTransport(CompletableFuture<Void> waitLatch) { this.waitLatch = waitLatch; } @Override public void receiveClusterView(View newView) { // check if this is an event of node going down, and if so wait for a signal to apply new view if (getMembers().size() > newView.getMembers().size()) { log.debugf("Delaying view %s", newView); waitLatch.thenAccept(__ -> { log.debugf("Unblocking view %s", newView); super.receiveClusterView(newView); }); } else { super.receiveClusterView(newView); } } public void assertUnblocked() { assert waitLatch.isDone(); } }
1,213
30.947368
100
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/XSiteMBeanTest.java
package org.infinispan.jmx; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.getCacheObjectName; import static org.infinispan.test.TestingUtil.k; import static org.infinispan.test.TestingUtil.replaceComponent; import static org.infinispan.test.TestingUtil.v; import static org.infinispan.test.TestingUtil.wrapComponent; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.Cache; import org.infinispan.commands.write.IracPutKeyValueCommand; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.distribution.BlockingInterceptor; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.transport.XSiteResponse; import org.infinispan.test.TestDataSCI; import org.infinispan.util.AbstractDelegatingRpcManager; import org.infinispan.xsite.AbstractMultipleSitesTest; import org.infinispan.xsite.XSiteBackup; import org.infinispan.xsite.XSiteReplicateCommand; import org.infinispan.xsite.irac.ManualIracManager; import org.infinispan.xsite.spi.AlwaysRemoveXSiteEntryMergePolicy; import org.infinispan.xsite.spi.DefaultXSiteEntryMergePolicy; import org.infinispan.xsite.spi.XSiteEntryMergePolicy; import org.infinispan.xsite.statetransfer.XSiteStateTransferManager; import org.testng.AssertJUnit; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Test for cross-site JMX attributes. * * @author Pedro Ruivo * @author Durgesh Anaokar * @since 13.0 */ @Test(groups = "functional", testName = "jmx.XSiteMBeanTest") public class XSiteMBeanTest extends AbstractMultipleSitesTest { private static final int N_SITES = 2; private static final int CLUSTER_SIZE = 1; private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); private final List<ManualIracManager> iracManagerList; private final List<ManualRpcManager> rpcManagerList; private final List<BlockingInterceptor<IracPutKeyValueCommand>> blockingInterceptorList; public XSiteMBeanTest() { this.iracManagerList = new ArrayList<>(N_SITES * CLUSTER_SIZE); this.rpcManagerList = new ArrayList<>(N_SITES * CLUSTER_SIZE); this.blockingInterceptorList = new ArrayList<>(N_SITES * CLUSTER_SIZE); } private static void assertSameAttributeAndOperation(MBeanServer mBeanServer, ObjectName objectName, Attribute attribute, String site) throws Exception { long val1 = invokeLongAttribute(mBeanServer, objectName, attribute); long val2 = invokeLongOperation(mBeanServer, objectName, attribute, site); log.debugf("%s op(%s) = %d", objectName, attribute, val2); assertEquals("Wrong value for " + attribute, val1, val2); } private static void assertAttribute(MBeanServer mBeanServer, ObjectName objectName, Attribute attribute, long expected) throws Exception { long val = invokeLongAttribute(mBeanServer, objectName, attribute); assertEquals("Wrong attribute value for " + attribute, expected, val); } private static void eventuallyAssertAttribute(MBeanServer mBeanServer, ObjectName objectName, Attribute attribute) { Supplier<Long> s = () -> { try { return invokeLongAttribute(mBeanServer, objectName, attribute); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }; eventuallyEquals("Wrong attribute " + attribute, 1L, s); } private static void assertHasAttribute(MBeanServer mBeanServer, ObjectName objectName, Attribute attribute) throws Exception { long val = invokeLongAttribute(mBeanServer, objectName, attribute); if (val == -1L) { fail("Attribute " + attribute + " expected to be different. " + val + " == -1"); } } private static void assertOperation(MBeanServer mBeanServer, ObjectName objectName, Attribute attribute, String site, long expected) throws Exception { long val = invokeLongOperation(mBeanServer, objectName, attribute, site); log.debugf("%s op(%s) = %d", objectName, attribute, val); assertEquals("Wrong operation value for " + attribute, expected, val); } private static long invokeLongOperation(MBeanServer mBeanServer, ObjectName rpcManager, Attribute attribute, String siteName) throws Exception { Object val = mBeanServer .invoke(rpcManager, attribute.operationName, new Object[]{siteName}, new String[]{String.class.getName()}); assertTrue(val instanceof Number); return ((Number) val).longValue(); } private static long invokeLongAttribute(MBeanServer mBeanServer, ObjectName objectName, Attribute attribute) throws Exception { Object val = mBeanServer.getAttribute(objectName, attribute.attributeName); log.debugf("%s attr(%s) = %d", objectName, attribute, val); assertTrue(val instanceof Number); return ((Number) val).longValue(); } private static int invokeQueueSizeAttribute(MBeanServer mBeanServer, ObjectName objectName) throws Exception { Object val = mBeanServer.getAttribute(objectName, Attribute.QUEUE_SIZE.attributeName); assertTrue(val instanceof Number); return ((Number) val).intValue(); } private static ManualRpcManager wrapRpcManager(Cache<?, ?> cache) { RpcManager rpcManager = extractComponent(cache, RpcManager.class); if (rpcManager instanceof ManualRpcManager) { return (ManualRpcManager) rpcManager; } return wrapComponent(cache, RpcManager.class, ManualRpcManager::new); } public void testRequestsSent(Method method) throws Exception { final String key = k(method); final String value = v(method); Cache<String, String> cache = cache(0, 0); MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); ObjectName rpcManager = getRpcManagerObjectName(0); assertTrue(mBeanServer.isRegistered(rpcManager)); resetRpcManagerStats(mBeanServer, rpcManager); cache.put(k(method), v(method)); assertEventuallyInSite(siteName(1), cache1 -> Objects.equals(value, cache1.get(key)), 10, TimeUnit.SECONDS); // the metrics are updated after the reply, so wait until the reply is received and the metrics updated awaitUnitKeysSent(); assertAttribute(mBeanServer, rpcManager, Attribute.REQ_SENT, 1); assertOperation(mBeanServer, rpcManager, Attribute.REQ_SENT, siteName(1), 1); assertHasAttribute(mBeanServer, rpcManager, Attribute.MIN_TIME); assertHasAttribute(mBeanServer, rpcManager, Attribute.AVG_TIME); assertHasAttribute(mBeanServer, rpcManager, Attribute.MAX_TIME); assertSameAttributeAndOperation(mBeanServer, rpcManager, Attribute.MIN_TIME, siteName(1)); assertSameAttributeAndOperation(mBeanServer, rpcManager, Attribute.AVG_TIME, siteName(1)); assertSameAttributeAndOperation(mBeanServer, rpcManager, Attribute.MAX_TIME, siteName(1)); // we only have 1 request, so min==max==avg assertEquals(invokeLongAttribute(mBeanServer, rpcManager, Attribute.MIN_TIME), invokeLongAttribute(mBeanServer, rpcManager, Attribute.MAX_TIME)); assertEquals(invokeLongAttribute(mBeanServer, rpcManager, Attribute.MIN_TIME), invokeLongAttribute(mBeanServer, rpcManager, Attribute.AVG_TIME)); resetRpcManagerStats(mBeanServer, rpcManager); } public void testRequestsReceived(Method method) throws Exception { final String key = k(method); final String value = v(method); Cache<String, String> cache = cache(0, 0); MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); ObjectName rpcManager = getRpcManagerObjectName(1); assertTrue(mBeanServer.isRegistered(rpcManager)); resetRpcManagerStats(mBeanServer, rpcManager); cache.put(k(method), v(method)); assertEventuallyInSite(siteName(1), cache1 -> Objects.equals(value, cache1.get(key)), 10, TimeUnit.SECONDS); assertAttribute(mBeanServer, rpcManager, Attribute.REQ_RECV, 1); assertOperation(mBeanServer, rpcManager, Attribute.REQ_RECV, siteName(0), 1); resetRpcManagerStats(mBeanServer, rpcManager); } public void testQueueSizeStats() throws Exception { MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); ObjectName iracManager = getIracManagerObjectName(0); assertTrue(mBeanServer.isRegistered(iracManager)); assertEquals(0, invokeQueueSizeAttribute(mBeanServer, iracManager)); ManualRpcManager rpcManager = rpcManagerList.get(0); // block request in RpcManager so the queue is not flush right away. BlockedRequest req = rpcManager.block(); cache(0, 0).put("key", "value"); // request is blocked, check the queue size req.awaitRequest(); assertEquals(1, invokeQueueSizeAttribute(mBeanServer, iracManager)); // let the request proceed rpcManager.unblock(); eventuallyAssertInAllSitesAndCaches(cache -> Objects.equals("value", cache.get("key"))); // the queue is clean after the reply is received. wait until it is. awaitUnitKeysSent(); assertEquals(0, invokeQueueSizeAttribute(mBeanServer, iracManager)); setStatisticsEnabled(mBeanServer, iracManager, false); assertEquals(-1, invokeQueueSizeAttribute(mBeanServer, iracManager)); setStatisticsEnabled(mBeanServer, iracManager, true); } public void testNumberOfConflictsStats() throws Exception { MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); ObjectName iracManager1 = getIracManagerObjectName(0); ObjectName iracManager2 = getIracManagerObjectName(1); assertTrue(mBeanServer.isRegistered(iracManager1)); assertTrue(mBeanServer.isRegistered(iracManager2)); assertAttribute(mBeanServer, iracManager1, Attribute.CONFLICTS, 0); assertAttribute(mBeanServer, iracManager2, Attribute.CONFLICTS, 0); createConflict(false); // make sure the conflict is seen eventuallyAssertAttribute(mBeanServer, iracManager1, Attribute.CONFLICTS); eventuallyAssertAttribute(mBeanServer, iracManager2, Attribute.CONFLICTS); assertAttribute(mBeanServer, iracManager1, Attribute.CONFLICT_LOCAL, 1); assertAttribute(mBeanServer, iracManager2, Attribute.CONFLICT_LOCAL, 0); assertAttribute(mBeanServer, iracManager1, Attribute.CONFLICT_REMOTE, 0); assertAttribute(mBeanServer, iracManager2, Attribute.CONFLICT_REMOTE, 1); assertAttribute(mBeanServer, iracManager1, Attribute.CONFLICT_MERGED, 0); assertAttribute(mBeanServer, iracManager2, Attribute.CONFLICT_MERGED, 0); // now reset statistics for (ObjectName objectName : Arrays.asList(iracManager1, iracManager2)) { resetIracManagerStats(mBeanServer, objectName); setStatisticsEnabled(mBeanServer, objectName, false); assertAttribute(mBeanServer, objectName, Attribute.CONFLICTS, -1); assertAttribute(mBeanServer, objectName, Attribute.CONFLICT_LOCAL, -1); assertAttribute(mBeanServer, objectName, Attribute.CONFLICT_REMOTE, -1); setStatisticsEnabled(mBeanServer, objectName, true); } } public void testNumberOfConflictMerged() throws Exception { MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); ObjectName iracManager1 = getIracManagerObjectName(0); ObjectName iracManager2 = getIracManagerObjectName(1); assertTrue(mBeanServer.isRegistered(iracManager1)); assertTrue(mBeanServer.isRegistered(iracManager2)); // replace merge policy to generate a new value replaceComponent(cache(0, 0), XSiteEntryMergePolicy.class, AlwaysRemoveXSiteEntryMergePolicy.getInstance(), true); replaceComponent(cache(1, 0), XSiteEntryMergePolicy.class, AlwaysRemoveXSiteEntryMergePolicy.getInstance(), true); assertAttribute(mBeanServer, iracManager1, Attribute.CONFLICT_MERGED, 0); assertAttribute(mBeanServer, iracManager2, Attribute.CONFLICT_MERGED, 0); createConflict(true); // make sure the conflict is seen eventuallyAssertAttribute(mBeanServer, iracManager1, Attribute.CONFLICT_MERGED); eventuallyAssertAttribute(mBeanServer, iracManager2, Attribute.CONFLICT_MERGED); // put back the default merge policy replaceComponent(cache(0, 0), XSiteEntryMergePolicy.class, DefaultXSiteEntryMergePolicy.getInstance(), true); replaceComponent(cache(1, 0), XSiteEntryMergePolicy.class, DefaultXSiteEntryMergePolicy.getInstance(), true); //reset stats for (ObjectName objectName : Arrays.asList(iracManager1, iracManager2)) { resetIracManagerStats(mBeanServer, objectName); setStatisticsEnabled(mBeanServer, objectName, false); assertAttribute(mBeanServer, objectName, Attribute.CONFLICT_MERGED, -1); setStatisticsEnabled(mBeanServer, objectName, true); } } public void testNumberOfDiscardsStats() throws Throwable { MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); ObjectName iracManager = getIracManagerObjectName(1); assertTrue(mBeanServer.isRegistered(iracManager)); assertAttribute(mBeanServer, iracManager, Attribute.DISCARDS, 0); createDiscard(); assertAttribute(mBeanServer, iracManager, Attribute.DISCARDS, 1); // now reset statistics resetIracManagerStats(mBeanServer, iracManager); setStatisticsEnabled(mBeanServer, iracManager, false); assertAttribute(mBeanServer, iracManager, Attribute.DISCARDS, -1); setStatisticsEnabled(mBeanServer, iracManager, true); } @Override protected int defaultNumberOfSites() { return N_SITES; } @Override protected int defaultNumberOfNodes() { return CLUSTER_SIZE; } @Override protected ConfigurationBuilder defaultConfigurationForSite(int siteIndex) { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); for (int i = 0; i < N_SITES; ++i) { if (i == siteIndex) { //don't add our site as backup. continue; } builder.sites() .addBackup() .site(siteName(i)) .strategy(BackupConfiguration.BackupStrategy.ASYNC); } builder.statistics().enable(); return builder; } @Override protected GlobalConfigurationBuilder defaultGlobalConfigurationForSite(int siteIndex) { GlobalConfigurationBuilder builder = GlobalConfigurationBuilder.defaultClusteredBuilder(); builder.serialization().addContextInitializer(TestDataSCI.INSTANCE); builder.cacheContainer() .statistics(true) .jmx().enable().domain("xsite-mbean-" + siteIndex).mBeanServerLookup(mBeanServerLookup) .metrics().accurateSize(true); return builder; } @Override protected void afterSitesCreated() { for (int i = 0; i < N_SITES; ++i) { for (Cache<?, ?> cache : caches(siteName(i))) { rpcManagerList.add(wrapRpcManager(cache)); iracManagerList.add(ManualIracManager.wrapCache(cache)); BlockingInterceptor<IracPutKeyValueCommand> interceptor = new BlockingInterceptor<>(new CyclicBarrier(2), IracPutKeyValueCommand.class, false, false); interceptor.suspend(true); blockingInterceptorList.add(interceptor); //noinspection deprecation cache.getAdvancedCache().getAsyncInterceptorChain().addInterceptor(interceptor, 0); } } } @AfterMethod(alwaysRun = true) @Override protected void clearContent() throws Throwable { rpcManagerList.forEach(ManualRpcManager::unblock); iracManagerList.forEach(m -> m.disable(ManualIracManager.DisableMode.DROP)); blockingInterceptorList.forEach(i -> i.suspend(true)); super.clearContent(); } private void awaitUnitKeysSent() { // we assume 1 node per site! assertEquals(1, defaultNumberOfNodes()); ManualIracManager iracManager = iracManagerList.get(0); eventually(iracManager::isEmpty); } private void createConflict(boolean isConflictMerged) { final String key = "conflict-key"; cache(0, 0).put(key, "value1"); // make sure all sites received the key eventuallyAssertInAllSitesAndCaches(cache -> Objects.equals("value1", cache.get(key))); // disable xsite so each site won't send anything to the others iracManagerList.forEach(ManualIracManager::enable); blockingInterceptorList.forEach(i -> i.suspend(false)); cache(0, 0).put(key, "v-2"); cache(1, 0).put(key, "v-3"); // enable xsite. this will send the keys! iracManagerList.forEach(manualIracManager -> manualIracManager.disable(ManualIracManager.DisableMode.SEND)); // wait until command is received. blockingInterceptorList.forEach(i -> { try { i.proceed(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }); blockingInterceptorList.forEach(i -> i.suspend(true)); // let the command go blockingInterceptorList.forEach(i -> { try { i.proceed(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }); if (isConflictMerged) { eventuallyAssertInAllSitesAndCaches(cache -> Objects.isNull(cache.get(key))); } else { eventuallyAssertInAllSitesAndCaches(cache -> Objects.equals("v-2", cache.get(key))); } } private void createDiscard() throws Throwable { // the discard is "simulated" by doing a state transfer. // The state transfer sends everything to the remote site. // The remote site ignores since it contains the same version. final String key = "discard-key"; cache(0, 0).put(key, "value1"); // make sure all sites received the key eventuallyAssertInAllSitesAndCaches(cache -> Objects.equals("value1", cache.get(key))); extractComponent(cache(0, 0), XSiteStateTransferManager.class).startPushState(siteName(1)); assertEventuallyInSite(siteName(0), cache -> extractComponent(cache, XSiteStateTransferManager.class).getRunningStateTransfers().isEmpty(), 10, TimeUnit.SECONDS); } private void resetRpcManagerStats(MBeanServer mBeanServer, ObjectName rpcManager) throws Exception { mBeanServer.invoke(rpcManager, "resetStatistics", new Object[0], new String[0]); assertAttribute(mBeanServer, rpcManager, Attribute.REQ_SENT, 0); assertAttribute(mBeanServer, rpcManager, Attribute.REQ_RECV, 0); assertAttribute(mBeanServer, rpcManager, Attribute.MIN_TIME, -1); assertAttribute(mBeanServer, rpcManager, Attribute.AVG_TIME, -1); assertAttribute(mBeanServer, rpcManager, Attribute.MAX_TIME, -1); for (int i = 0; i < N_SITES; ++i) { String site = siteName(i); assertOperation(mBeanServer, rpcManager, Attribute.REQ_SENT, site, 0); assertOperation(mBeanServer, rpcManager, Attribute.REQ_RECV, site, 0); assertOperation(mBeanServer, rpcManager, Attribute.MIN_TIME, site, -1); assertOperation(mBeanServer, rpcManager, Attribute.AVG_TIME, site, -1); assertOperation(mBeanServer, rpcManager, Attribute.MAX_TIME, site, -1); } } private void resetIracManagerStats(MBeanServer mBeanServer, ObjectName iracManager) throws Exception { mBeanServer.invoke(iracManager, "resetStatistics", new Object[0], new String[0]); assertAttribute(mBeanServer, iracManager, Attribute.CONFLICTS, 0); assertAttribute(mBeanServer, iracManager, Attribute.CONFLICT_LOCAL, 0); assertAttribute(mBeanServer, iracManager, Attribute.CONFLICT_REMOTE, 0); assertAttribute(mBeanServer, iracManager, Attribute.CONFLICT_MERGED, 0); assertAttribute(mBeanServer, iracManager, Attribute.DISCARDS, 0); } private void setStatisticsEnabled(MBeanServer mBeanServer, ObjectName objectName, boolean enabled) throws Exception { mBeanServer.setAttribute(objectName, new javax.management.Attribute("StatisticsEnabled", enabled)); } private String getJmxDomain(int siteIndex) { return manager(siteIndex, 0).getCacheManagerConfiguration().jmx().domain(); } private ObjectName getRpcManagerObjectName(int siteIndex) { return getCacheObjectName(getJmxDomain(siteIndex), getDefaultCacheName() + "(dist_sync)", "RpcManager"); } private ObjectName getIracManagerObjectName(int siteIndex) { return getCacheObjectName(getJmxDomain(siteIndex), getDefaultCacheName() + "(dist_sync)", "AsyncXSiteStatistics"); } private enum Attribute { REQ_SENT("NumberXSiteRequests", "NumberXSiteRequestsSentTo"), REQ_RECV("NumberXSiteRequestsReceived", "NumberXSiteRequestsReceivedFrom"), AVG_TIME("AverageXSiteReplicationTime", "AverageXSiteReplicationTimeTo"), MAX_TIME("MaximumXSiteReplicationTime", "MaximumXSiteReplicationTimeTo"), MIN_TIME("MinimumXSiteReplicationTime", "MinimumXSiteReplicationTimeTo"), QUEUE_SIZE("QueueSize", null), CONFLICTS("NumberOfConflicts", null), CONFLICT_LOCAL("NumberOfConflictsLocalWins", null), CONFLICT_REMOTE("NumberOfConflictsRemoteWins", null), CONFLICT_MERGED("NumberOfConflictsMerged", null), DISCARDS("NumberOfDiscards", null); final String attributeName; final String operationName; Attribute(String attributeName, String operationName) { this.attributeName = attributeName; this.operationName = operationName; } } private static class ManualRpcManager extends AbstractDelegatingRpcManager { private volatile BlockedRequest blockedRequest; public ManualRpcManager(RpcManager realOne) { super(realOne); } @Override public <O> XSiteResponse<O> invokeXSite(XSiteBackup backup, XSiteReplicateCommand<O> command) { BlockedRequest req = blockedRequest; if (req != null) { DummyXsiteResponse<O> rsp = new DummyXsiteResponse<>(); req.thenRun(() -> rsp.onRequest(super.invokeXSite(backup, command))); return rsp; } else { return super.invokeXSite(backup, command); } } BlockedRequest block() { BlockedRequest req = new BlockedRequest(); blockedRequest = req; return req; } void unblock() { BlockedRequest req = blockedRequest; if (req != null) { req.continueRequest(); blockedRequest = null; } } } private static class BlockedRequest extends CompletableFuture<Void> { private final CountDownLatch latch; private BlockedRequest() { latch = new CountDownLatch(1); } @Override public CompletableFuture<Void> thenRun(Runnable action) { latch.countDown(); return super.thenRun(action); } void awaitRequest() throws InterruptedException { AssertJUnit.assertTrue(latch.await(10, TimeUnit.SECONDS)); } void continueRequest() { complete(null); } } private static class DummyXsiteResponse<O> extends CompletableFuture<O> implements XSiteResponse<O>, XSiteResponse.XSiteResponseCompleted { private volatile XSiteResponse<O> realOne; private volatile XSiteBackup backup; private volatile long sendTimeStamp; private volatile long durationNanos; @Override public void onCompleted(XSiteBackup backup, long sendTimeNanos, long durationNanos, Throwable throwable) { this.backup = backup; this.sendTimeStamp = sendTimeNanos; this.durationNanos = durationNanos; if (throwable != null) { completeExceptionally(throwable); } else { complete(realOne.toCompletableFuture().join()); } } @Override public void whenCompleted(XSiteResponseCompleted xSiteResponseCompleted) { this.whenComplete((ignore, throwable) -> xSiteResponseCompleted.onCompleted(backup, sendTimeStamp, durationNanos, throwable)); } void onRequest(XSiteResponse<O> response) { realOne = response; response.whenCompleted(this); } } }
25,385
41.029801
162
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/CacheMBeanTest.java
package org.infinispan.jmx; import static org.infinispan.test.TestingUtil.checkMBeanOperationParameterNaming; import static org.infinispan.test.TestingUtil.getCacheManagerObjectName; import static org.infinispan.test.TestingUtil.getCacheObjectName; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.lang.reflect.Method; import javax.management.InstanceNotFoundException; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.manager.EmbeddedCacheManagerStartupException; import org.infinispan.test.CacheManagerCallable; import org.infinispan.commons.test.Exceptions; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.annotations.Test; @Test(groups = {"functional", "smoke"}, testName = "jmx.CacheMBeanTest") public class CacheMBeanTest extends MultipleCacheManagersTest { private static final Log log = LogFactory.getLog(CacheMBeanTest.class); public static final String JMX_DOMAIN = CacheMBeanTest.class.getSimpleName(); private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); @Override protected void createCacheManagers() throws Exception { GlobalConfigurationBuilder globalConfiguration = new GlobalConfigurationBuilder(); globalConfiguration .jmx().enabled(true) .domain(JMX_DOMAIN) .mBeanServerLookup(mBeanServerLookup); ConfigurationBuilder configuration = new ConfigurationBuilder(); EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(globalConfiguration, configuration); registerCacheManager(cacheManager); // Create the default cache and register its JMX beans cacheManager.getCache(); } public void testJmxOperationMetadata() throws Exception { ObjectName name = getCacheObjectName(JMX_DOMAIN, getDefaultCacheName() + "(local)"); checkMBeanOperationParameterNaming(mBeanServerLookup.getMBeanServer(), name); } public void testStartStopManagedOperations() throws Exception { ObjectName cacheObjectName = getCacheObjectName(JMX_DOMAIN, getDefaultCacheName() + "(local)"); ObjectName cacheManagerObjectName = getCacheManagerObjectName(JMX_DOMAIN); MBeanServer server = mBeanServerLookup.getMBeanServer(); server.invoke(cacheManagerObjectName, "startCache", new Object[0], new String[0]); assertEquals(ComponentStatus.RUNNING.toString(), server.getAttribute(cacheObjectName, "CacheStatus")); assertEquals("1", server.getAttribute(cacheManagerObjectName, "CreatedCacheCount")); assertEquals("1", server.getAttribute(cacheManagerObjectName, "RunningCacheCount")); server.invoke(cacheObjectName, "stop", new Object[0], new String[0]); assertFalse(cacheObjectName + " should NOT be registered", server.isRegistered(cacheObjectName)); assertEquals("1", server.getAttribute(cacheManagerObjectName, "CreatedCacheCount")); assertEquals("0", server.getAttribute(cacheManagerObjectName, "RunningCacheCount")); server.invoke(cacheManagerObjectName, "startCache", new Object[]{getDefaultCacheName()}, new String[]{String.class.getName()}); assertEquals(ComponentStatus.RUNNING.toString(), server.getAttribute(cacheObjectName, "CacheStatus")); assertEquals("1", server.getAttribute(cacheManagerObjectName, "CreatedCacheCount")); assertEquals("1", server.getAttribute(cacheManagerObjectName, "RunningCacheCount")); server.invoke(cacheObjectName, "stop", new Object[0], new String[0]); assertFalse(cacheObjectName + " should NOT be registered", server.isRegistered(cacheObjectName)); assertEquals("1", server.getAttribute(cacheManagerObjectName, "CreatedCacheCount")); assertEquals("0", server.getAttribute(cacheManagerObjectName, "RunningCacheCount")); server.invoke(cacheManagerObjectName, "startCache", new Object[]{getDefaultCacheName()}, new String[]{String.class.getName()}); assertEquals(ComponentStatus.RUNNING.toString(), server.getAttribute(cacheObjectName, "CacheStatus")); assertEquals("1", server.getAttribute(cacheManagerObjectName, "CreatedCacheCount")); assertEquals("1", server.getAttribute(cacheManagerObjectName, "RunningCacheCount")); server.invoke(cacheObjectName, "stop", new Object[0], new String[0]); assertFalse(cacheObjectName + " should NOT be registered", server.isRegistered(cacheObjectName)); assertEquals("1", server.getAttribute(cacheManagerObjectName, "CreatedCacheCount")); assertEquals("0", server.getAttribute(cacheManagerObjectName, "RunningCacheCount")); } public void testManagerStopRemovesCacheMBean(Method m) throws Exception { String otherJmxDomain = JMX_DOMAIN + "_" + m.getName(); ObjectName defaultOn = getCacheObjectName(otherJmxDomain, getDefaultCacheName() + "(local)"); ObjectName galderOn = getCacheObjectName(otherJmxDomain, "galder(local)"); ObjectName managerON = getCacheManagerObjectName(otherJmxDomain); GlobalConfigurationBuilder gc = new GlobalConfigurationBuilder(); gc.jmx().enabled(true) .domain(otherJmxDomain) .mBeanServerLookup(mBeanServerLookup); ConfigurationBuilder c = new ConfigurationBuilder(); c.statistics().enabled(true); EmbeddedCacheManager otherContainer = TestCacheManagerFactory.createCacheManager(gc, c); otherContainer.defineConfiguration("galder", new ConfigurationBuilder().build()); registerCacheManager(otherContainer); MBeanServer server = mBeanServerLookup.getMBeanServer(); server.invoke(managerON, "startCache", new Object[0], new String[0]); server.invoke(managerON, "startCache", new Object[]{"galder"}, new String[]{String.class.getName()}); assertEquals(ComponentStatus.RUNNING.toString(), server.getAttribute(defaultOn, "CacheStatus")); assertEquals(ComponentStatus.RUNNING.toString(), server.getAttribute(galderOn, "CacheStatus")); otherContainer.stop(); try { log.info(server.getMBeanInfo(managerON)); fail("Failure expected, " + managerON + " shouldn't be registered in mbean server"); } catch (InstanceNotFoundException e) { } try { log.info(server.getMBeanInfo(defaultOn)); fail("Failure expected, " + defaultOn + " shouldn't be registered in mbean server"); } catch (InstanceNotFoundException e) { } try { log.info(server.getMBeanInfo(galderOn)); fail("Failure expected, " + galderOn + " shouldn't be registered in mbean server"); } catch (InstanceNotFoundException e) { } } public void testDuplicateJmxDomainOnlyCacheExposesJmxStatistics() { GlobalConfigurationBuilder gc = new GlobalConfigurationBuilder(); gc.jmx().enabled(true) .domain(JMX_DOMAIN) .mBeanServerLookup(mBeanServerLookup); ConfigurationBuilder c = new ConfigurationBuilder(); c.statistics().enabled(true); Exceptions.expectException(EmbeddedCacheManagerStartupException.class, JmxDomainConflictException.class, () -> TestCacheManagerFactory.createCacheManager(gc, c)); } public void testAvoidLeakOfCacheMBeanWhenCacheStatisticsDisabled(Method m) { String otherJmxDomain = "jmx_" + m.getName(); GlobalConfigurationBuilder gc = new GlobalConfigurationBuilder(); gc.jmx().enabled(true) .domain(otherJmxDomain) .mBeanServerLookup(mBeanServerLookup); ConfigurationBuilder c = new ConfigurationBuilder(); c.statistics().available(false); withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager(gc, c)) { @Override public void call() { cm.getCache(); MBeanServer server = mBeanServerLookup.getMBeanServer(); ObjectName cacheObjectName = getCacheObjectName(otherJmxDomain, getDefaultCacheName() + "(local)"); assertTrue(cacheObjectName + " should be registered", server.isRegistered(cacheObjectName)); TestingUtil.killCacheManagers(cm); assertFalse(cacheObjectName + " should NOT be registered", server.isRegistered(cacheObjectName)); } }); } }
8,950
53.579268
133
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/ClusterContainerStatsMBeanTest.java
package org.infinispan.jmx; import static org.infinispan.test.TestingUtil.getCacheManagerObjectName; import java.util.stream.Stream; import javax.management.MBeanServer; import javax.management.ObjectName; import org.testng.annotations.Test; @Test(groups = "functional", testName = "jmx.ClusterContainerStatsMBeanTest") public class ClusterContainerStatsMBeanTest extends AbstractClusterMBeanTest { private final String componentName; public ClusterContainerStatsMBeanTest(String componentName) { super(ClusterContainerStatsMBeanTest.class.getName()); this.componentName = componentName; } @Override public Object[] factory() { return Stream.of("ClusterContainerStats", "LocalContainerStats") .map(ClusterContainerStatsMBeanTest::new) .toArray(); } @Override protected String parameters() { return String.format("[%s]", componentName); } public void testContainerStats() throws Exception { MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); ObjectName clusterStats = getCacheManagerObjectName(jmxDomain1, "DefaultCacheManager", componentName); assertAttributeValueGreaterThanOrEqualTo(mBeanServer, clusterStats, "MemoryAvailable", 1); assertAttributeValueGreaterThanOrEqualTo(mBeanServer, clusterStats, "MemoryMax", 1); assertAttributeValueGreaterThanOrEqualTo(mBeanServer, clusterStats, "MemoryTotal", 1); assertAttributeValueGreaterThanOrEqualTo(mBeanServer, clusterStats, "MemoryUsed", 1); } }
1,536
33.931818
108
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/CacheConfigurationMBeanTest.java
package org.infinispan.jmx; import static org.infinispan.test.TestingUtil.getCacheObjectName; import static org.testng.AssertJUnit.assertEquals; import javax.management.Attribute; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.container.impl.DefaultDataContainer; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * @author Tristan Tarrant * @since 8.1 */ @Test(groups = "functional", testName = "jmx.CacheConfigurationMBeanTest") public class CacheConfigurationMBeanTest extends SingleCacheManagerTest { private static final String JMX_DOMAIN = CacheConfigurationMBeanTest.class.getSimpleName(); private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder(); gcb.jmx().enabled(true).domain(JMX_DOMAIN).mBeanServerLookup(mBeanServerLookup); ConfigurationBuilder dcc = TestCacheManagerFactory.getDefaultCacheConfiguration(true); dcc.transaction().autoCommit(false); dcc.memory().size(1000); return TestCacheManagerFactory.createCacheManager(gcb, dcc); } public void testEvictionSize() throws Exception { MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); ObjectName defaultOn = getCacheObjectName(JMX_DOMAIN, getDefaultCacheName() + "(local)", "Configuration"); assertEquals(1000L, (long) mBeanServer.getAttribute(defaultOn, "evictionSize")); assertEquals(1000, cache().getCacheConfiguration().memory().size()); DefaultDataContainer<Object, Object> dataContainer = (DefaultDataContainer<Object, Object>) cache() .getAdvancedCache().getDataContainer(); assertEquals(1000, dataContainer.capacity()); mBeanServer.setAttribute(defaultOn, new Attribute("evictionSize", 2000L)); assertEquals(2000, cache().getCacheConfiguration().memory().size()); assertEquals(2000, dataContainer.capacity()); } }
2,447
44.333333
112
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/RpcManagerMBeanTest.java
package org.infinispan.jmx; import static org.infinispan.test.TestingUtil.checkMBeanOperationParameterNaming; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.getCacheObjectName; import static org.testng.Assert.assertEquals; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import javax.management.Attribute; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.Cache; import org.infinispan.commands.remote.SingleRpcCommand; import org.infinispan.commons.CacheException; import org.infinispan.commons.test.Exceptions; import org.infinispan.distribution.MagicKey; import org.infinispan.remoting.responses.SuccessfulResponse; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.rpc.RpcManagerImpl; import org.infinispan.remoting.transport.MockTransport; import org.infinispan.remoting.transport.Transport; import org.testng.annotations.Test; /** * @author Mircea.Markus@jboss.com * @author Galder Zamarreño */ @Test(groups = "functional", testName = "jmx.RpcManagerMBeanTest") public class RpcManagerMBeanTest extends AbstractClusterMBeanTest { public RpcManagerMBeanTest() { super(RpcManagerMBeanTest.class.getSimpleName()); } public void testJmxOperationMetadata() throws Exception { ObjectName rpcManager = getCacheObjectName(jmxDomain1, getDefaultCacheName() + "(repl_sync)", "RpcManager"); checkMBeanOperationParameterNaming(mBeanServerLookup.getMBeanServer(), rpcManager); } public void testEnableJmxStats() throws Exception { Cache<String, String> cache1 = manager(0).getCache(); Cache<String, String> cache2 = manager(1).getCache(); MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); ObjectName rpcManager1 = getCacheObjectName(jmxDomain1, getDefaultCacheName() + "(repl_sync)", "RpcManager"); ObjectName rpcManager2 = getCacheObjectName(jmxDomain2, getDefaultCacheName() + "(repl_sync)", "RpcManager"); assert mBeanServer.isRegistered(rpcManager1); assert mBeanServer.isRegistered(rpcManager2); Object statsEnabled = mBeanServer.getAttribute(rpcManager1, "StatisticsEnabled"); assert statsEnabled != null; assertEquals(statsEnabled, Boolean.TRUE); assertEquals(mBeanServer.getAttribute(rpcManager1, "StatisticsEnabled"), Boolean.TRUE); assertEquals(mBeanServer.getAttribute(rpcManager2, "StatisticsEnabled"), Boolean.TRUE); // The initial state transfer uses cache commands, so it also increases the ReplicationCount value long initialReplicationCount1 = (Long) mBeanServer.getAttribute(rpcManager1, "ReplicationCount"); cache1.put("key", "value2"); assertEquals(cache2.get("key"), "value2"); assertEquals(mBeanServer.getAttribute(rpcManager1, "ReplicationCount"), initialReplicationCount1 + 1); assertEquals(mBeanServer.getAttribute(rpcManager1, "ReplicationFailures"), (long) 0); // now reset statistics mBeanServer.invoke(rpcManager1, "resetStatistics", new Object[0], new String[0]); assertEquals(mBeanServer.getAttribute(rpcManager1, "ReplicationCount"), (long) 0); assertEquals(mBeanServer.getAttribute(rpcManager1, "ReplicationFailures"), (long) 0); mBeanServer.setAttribute(rpcManager1, new Attribute("StatisticsEnabled", Boolean.FALSE)); cache1.put("key", "value"); assertEquals(cache2.get("key"), "value"); assertEquals(mBeanServer.getAttribute(rpcManager1, "ReplicationCount"), (long) -1); assertEquals(mBeanServer.getAttribute(rpcManager1, "ReplicationFailures"), (long) -1); // reset stats enabled parameter mBeanServer.setAttribute(rpcManager1, new Attribute("StatisticsEnabled", Boolean.TRUE)); } @Test(dependsOnMethods = "testEnableJmxStats") public void testSuccessRatio() throws Exception { Cache<MagicKey, Object> cache1 = manager(0).getCache(); Cache<MagicKey, Object> cache2 = manager(1).getCache(); MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); ObjectName rpcManager1 = getCacheObjectName(jmxDomain1, getDefaultCacheName() + "(repl_sync)", "RpcManager"); // the previous test has reset the statistics assertEquals(mBeanServer.getAttribute(rpcManager1, "ReplicationCount"), (long) 0); assertEquals(mBeanServer.getAttribute(rpcManager1, "ReplicationFailures"), (long) 0); assertEquals(mBeanServer.getAttribute(rpcManager1, "SuccessRatio"), "N/A"); RpcManagerImpl rpcManager = (RpcManagerImpl) extractComponent(cache1, RpcManager.class); Transport originalTransport = rpcManager.getTransport(); try { MockTransport transport = new MockTransport(address(0)); transport.init(originalTransport.getViewId(), originalTransport.getMembers()); rpcManager.setTransport(transport); CompletableFuture<Object> put1 = cache1.putAsync(new MagicKey("a1", cache1), "b1"); timeService.advance(50); transport.expectCommand(SingleRpcCommand.class) .singleResponse(address(2), SuccessfulResponse.SUCCESSFUL_EMPTY_RESPONSE); put1.get(10, TimeUnit.SECONDS); CompletableFuture<Object> put2 = cache1.putAsync(new MagicKey("a2", cache2), "b2"); timeService.advance(10); transport.expectCommand(SingleRpcCommand.class) .singleResponse(address(2), SuccessfulResponse.SUCCESSFUL_EMPTY_RESPONSE); put2.get(10, TimeUnit.SECONDS); assertEquals(mBeanServer.getAttribute(rpcManager1, "ReplicationCount"), (long) 2); assertEquals(mBeanServer.getAttribute(rpcManager1, "SuccessRatio"), "100%"); long avgReplTime = (long) mBeanServer.getAttribute(rpcManager1, "AverageReplicationTime"); assertEquals(avgReplTime, 30); // If cache1 is the primary owner it will be a broadcast, otherwise a unicast CompletableFuture<Object> put3 = cache1.putAsync(new MagicKey("a3", cache1), "b3"); transport.expectCommand(SingleRpcCommand.class) .throwException(new RuntimeException()); Exceptions.expectCompletionException(CacheException.class, put3); CompletableFuture<Object> put4 = cache1.putAsync(new MagicKey("a4", cache2), "b4"); transport.expectCommand(SingleRpcCommand.class) .throwException(new RuntimeException()); Exceptions.expectCompletionException(CacheException.class, put4); assertEquals(mBeanServer.getAttribute(rpcManager1, "SuccessRatio"), ("50%")); } finally { rpcManager.setTransport(originalTransport); } } }
6,710
48.345588
115
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/CacheMgmtInterceptorMBeanTest.java
package org.infinispan.jmx; import static org.infinispan.test.TestingUtil.checkMBeanOperationParameterNaming; import static org.infinispan.test.TestingUtil.getCacheObjectName; import static org.infinispan.test.TestingUtil.k; import static org.infinispan.test.TestingUtil.v; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.AdvancedCache; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import io.reactivex.rxjava3.exceptions.Exceptions; /** * Test functionality in {@link org.infinispan.interceptors.impl.CacheMgmtInterceptor}. * * @author Mircea.Markus@jboss.com * @author Galder Zamarreño */ @Test(groups = "functional", testName = "jmx.CacheMgmtInterceptorMBeanTest") public class CacheMgmtInterceptorMBeanTest extends SingleCacheManagerTest { private ObjectName mgmtInterceptor; private AdvancedCache<?, ?> advanced; private DummyInMemoryStore loader; private static final String JMX_DOMAIN = CacheMgmtInterceptorMBeanTest.class.getSimpleName(); private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder globalConfiguration = new GlobalConfigurationBuilder(); globalConfiguration .jmx().enabled(true) .domain(JMX_DOMAIN) .mBeanServerLookup(mBeanServerLookup) .metrics().accurateSize(true); ConfigurationBuilder configuration = getDefaultStandaloneCacheConfig(false); configuration.memory().size(1) .persistence() .passivation(true) .addStore(DummyInMemoryStoreConfigurationBuilder.class); configuration.statistics().enable(); cacheManager = TestCacheManagerFactory.createCacheManager(globalConfiguration, configuration); cacheManager.defineConfiguration("test", configuration.build()); cache = cacheManager.getCache("test"); advanced = cache.getAdvancedCache(); mgmtInterceptor = getCacheObjectName(JMX_DOMAIN, "test(local)", "Statistics"); loader = TestingUtil.getFirstStore(cache); return cacheManager; } @AfterMethod public void resetStats() throws Exception { mBeanServerLookup.getMBeanServer().invoke(mgmtInterceptor, "resetStatistics", new Object[0], new String[0]); } public void testJmxOperationMetadata() throws Exception { checkMBeanOperationParameterNaming(mBeanServerLookup.getMBeanServer(), mgmtInterceptor); } public void testEviction(Method m) throws Exception { assertEvictions(0); assertNull(cache.get(k(m, "1"))); cache.put(k(m, "1"), v(m, 1)); //test explicit evict command cache.evict(k(m, "1")); assertTrue("the entry should have been evicted", loader.contains(k(m, "1"))); assertEvictions(1); assertEquals(v(m, 1), cache.get(k(m, "1"))); //test implicit eviction cache.put(k(m, "2"), v(m, 2)); // Evictions of unrelated keys are non blocking now so it may not be updated immediately eventuallyAssertEvictions(2); assertTrue("the entry should have been evicted", loader.contains(k(m, "1"))); } public void testGetKeyValue() throws Exception { assertMisses(0); assertHits(0); assertEquals(0, advanced.getStats().getHits()); assertAttributeValue("HitRatio", 0); cache.put("key", "value"); assertMisses(0); assertHits(0); assertAttributeValue("HitRatio", 0); assertEquals("value", cache.get("key")); assertMisses(0); assertHits(1); assertAttributeValue("HitRatio", 1); assertNull(cache.get("key_ne")); assertNull(cache.get("key_ne")); assertNull(cache.get("key_ne")); assertMisses(3); assertHits(1); assertAttributeValue("HitRatio", 0.25f); } public void testStores() throws Exception { assertEvictions(0); assertStores(0); cache.put("key", "value"); assertStores(1); cache.put("key", "value"); assertStores(2); assertCurrentNumberOfEntries(1); assertApproximateEntries(1); cache.evict("key"); assertCurrentNumberOfEntriesInMemory(0); assertApproximateEntriesInMemory(0); assertCurrentNumberOfEntries(1); assertApproximateEntries(1); Map<String, String> toAdd = new HashMap<>(); toAdd.put("key", "value"); toAdd.put("key2", "value2"); cache.putAll(toAdd); assertStores(4); TestingUtil.cleanUpDataContainerForCache(cache); assertCurrentNumberOfEntriesInMemory(1); assertApproximateEntriesInMemory(1); assertCurrentNumberOfEntries(2); assertApproximateEntries(2); resetStats(); toAdd = new HashMap<>(); toAdd.put("key3", "value3"); toAdd.put("key4", "value4"); cache.putAll(toAdd); assertStores(2); TestingUtil.cleanUpDataContainerForCache(cache); assertCurrentNumberOfEntriesInMemory(1); eventuallyAssertEvictions(2); assertCurrentNumberOfEntries(4); } public void testStoresPutForExternalRead() throws Exception { assertStores(0); cache.putForExternalRead("key", "value"); assertStores(1); cache.putForExternalRead("key", "value"); assertStores(1); } public void testStoresPutIfAbsent() throws Exception { assertStores(0); cache.putIfAbsent("voooo", "doooo"); assertStores(1); cache.putIfAbsent("voooo", "no-doooo"); assertStores(1); } public void testRemoves() throws Exception { assertStores(0); assertRemoveHits(0); assertRemoveMisses(0); cache.put("key", "value"); cache.put("key2", "value2"); cache.put("key3", "value3"); assertStores(3); assertRemoveHits(0); assertRemoveMisses(0); cache.remove("key"); cache.remove("key3"); cache.remove("key4"); assertRemoveHits(2); assertRemoveMisses(1); cache.remove("key2"); assertRemoveHits(3); assertRemoveMisses(1); } public void testGetAll() throws Exception { MBeanServer server = mBeanServerLookup.getMBeanServer(); assertEquals(0, advanced.getStats().getMisses()); assertEquals(0, advanced.getStats().getHits()); String hitRatioString = server.getAttribute(mgmtInterceptor, "HitRatio").toString(); Float hitRatio = Float.parseFloat(hitRatioString); assertEquals(0f, hitRatio); cache.put("key", "value"); assertEquals(0, advanced.getStats().getMisses()); assertEquals(0, advanced.getStats().getHits()); hitRatioString = server.getAttribute(mgmtInterceptor, "HitRatio").toString(); hitRatio = Float.parseFloat(hitRatioString); assertEquals(0f, hitRatio); Set<String> keySet = new HashSet<>(); keySet.add("key"); keySet.add("key1"); advanced.getAll(keySet); assertEquals(1, advanced.getStats().getMisses()); assertEquals(1, advanced.getStats().getHits()); hitRatioString = server.getAttribute(mgmtInterceptor, "HitRatio").toString(); hitRatio = Float.parseFloat(hitRatioString); assertEquals(0.5f, hitRatio); } private void eventuallyAssertAttributeValue(String attrName, float expectedValue) { eventuallyEquals(expectedValue, () -> { try { String receivedVal = mBeanServerLookup.getMBeanServer().getAttribute(mgmtInterceptor, attrName).toString(); return Float.parseFloat(receivedVal); } catch (Exception e) { throw Exceptions.propagate(e); } }); } private void assertAttributeValue(String attrName, float expectedValue) throws Exception { String receivedVal = mBeanServerLookup.getMBeanServer().getAttribute(mgmtInterceptor, attrName).toString(); assertEquals("expecting " + expectedValue + " for " + attrName + ", but received " + receivedVal, expectedValue, Float.parseFloat(receivedVal)); } private void eventuallyAssertEvictions(long expectedValue) { eventuallyAssertAttributeValue("Evictions", expectedValue); assertEquals(expectedValue, advanced.getStats().getEvictions()); } private void assertEvictions(long expectedValue) throws Exception { assertAttributeValue("Evictions", expectedValue); assertEquals(expectedValue, advanced.getStats().getEvictions()); } private void assertMisses(long expectedValue) throws Exception { assertAttributeValue("Misses", expectedValue); assertEquals(expectedValue, advanced.getStats().getMisses()); } private void assertHits(long expectedValue) throws Exception { assertAttributeValue("Hits", expectedValue); assertEquals(expectedValue, advanced.getStats().getHits()); } private void assertStores(long expectedValue) throws Exception { assertAttributeValue("Stores", expectedValue); assertEquals(expectedValue, advanced.getStats().getStores()); } private void assertRemoveHits(long expectedValue) throws Exception { assertAttributeValue("RemoveHits", expectedValue); assertEquals(expectedValue, advanced.getStats().getRemoveHits()); } private void assertRemoveMisses(long expectedValue) throws Exception { assertAttributeValue("RemoveMisses", expectedValue); assertEquals(expectedValue, advanced.getStats().getRemoveMisses()); } private void assertCurrentNumberOfEntries(int expectedValue) throws Exception { assertAttributeValue("NumberOfEntries", expectedValue); assertEquals(expectedValue, advanced.getStats().getCurrentNumberOfEntries()); } private void assertCurrentNumberOfEntriesInMemory(int expectedValue) throws Exception { assertAttributeValue("NumberOfEntriesInMemory", expectedValue); assertEquals(expectedValue, advanced.getStats().getCurrentNumberOfEntriesInMemory()); } private void assertApproximateEntries(int expectedValue) throws Exception { assertAttributeValue("ApproximateEntries", expectedValue); assertEquals(expectedValue, advanced.getStats().getApproximateEntries()); } private void assertApproximateEntriesInMemory(int expectedValue) throws Exception { assertAttributeValue("ApproximateEntriesInMemory", expectedValue); assertEquals(expectedValue, advanced.getStats().getApproximateEntriesInMemory()); } }
11,291
36.022951
150
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/CacheOpsTest.java
package org.infinispan.jmx; import static org.infinispan.test.TestingUtil.getCacheObjectName; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import javax.management.ObjectName; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test(groups = "functional", testName = "jmx.CacheOpsTest") public class CacheOpsTest extends SingleCacheManagerTest { private static final String JMX_DOMAIN = CacheOpsTest.class.getSimpleName(); private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder(); gcb.jmx().enabled(true).domain(JMX_DOMAIN).mBeanServerLookup(mBeanServerLookup); ConfigurationBuilder cfg = TestCacheManagerFactory.getDefaultCacheConfiguration(true); cfg.transaction().autoCommit(false) .memory().size(1000); return TestCacheManagerFactory.createCacheManager(gcb, cfg); } public void testClear() throws Exception { ObjectName cacheObjectName = getCacheObjectName(JMX_DOMAIN, getDefaultCacheName() + "(local)"); tm().begin(); cache().put("k", "v"); tm().commit(); assertFalse(cache().isEmpty()); mBeanServerLookup.getMBeanServer().invoke(cacheObjectName, "clear", new Object[0], new String[0]); assertTrue(cache().isEmpty()); } }
1,900
37.795918
104
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/ClusterCacheStatsMBeanTest.java
package org.infinispan.jmx; import static org.infinispan.test.TestingUtil.getCacheObjectName; import java.io.Serializable; import javax.management.Attribute; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.Cache; import org.testng.annotations.Test; @Test(groups = "functional", testName = "jmx.ClusterCacheStatsMBeanTest") public class ClusterCacheStatsMBeanTest extends AbstractClusterMBeanTest { public ClusterCacheStatsMBeanTest() { super(ClusterCacheStatsMBeanTest.class.getName()); } public void testClusterStats() throws Exception { Cache<String, Serializable> cache1 = manager(0).getCache(); MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); ObjectName clusterStats = getCacheObjectName(jmxDomain1, getDefaultCacheName() + "(repl_sync)", "ClusterCacheStats"); mBeanServer.setAttribute(clusterStats, new Attribute("StatisticsEnabled", false)); assert !(boolean) mBeanServer.getAttribute(clusterStats, "StatisticsEnabled"); mBeanServer.setAttribute(clusterStats, new Attribute("StatisticsEnabled", true)); assert (boolean) mBeanServer.getAttribute(clusterStats, "StatisticsEnabled"); long newStaleThreshold = 1000; mBeanServer.setAttribute(clusterStats, new Attribute("StaleStatsThreshold", newStaleThreshold)); assertAttributeValue(mBeanServer, clusterStats, "StaleStatsThreshold", newStaleThreshold); cache1.put("a1", "b1"); cache1.put("a2", "b2"); cache1.put("a3", "b3"); cache1.put("a4", "b4"); assertAttributeValue(mBeanServer, clusterStats, "HitRatio", 0.0); assertAttributeValue(mBeanServer, clusterStats, "NumberOfEntries", 4); assertAttributeValue(mBeanServer, clusterStats, "Stores", 4); assertAttributeValue(mBeanServer, clusterStats, "Evictions", 0); cache1.remove("a1"); cache1.get("a1"); cache1.get("a2"); //sleep so we pick up refreshed values after remove timeService.advance(newStaleThreshold + 1); assertAttributeValueGreaterThanOrEqualTo(mBeanServer, clusterStats, "AverageWriteTime", 0); assertAttributeValueGreaterThanOrEqualTo(mBeanServer, clusterStats, "AverageReadTime", 0); assertAttributeValueGreaterThanOrEqualTo(mBeanServer, clusterStats, "AverageRemoveTime", 0); assertAttributeValue(mBeanServer, clusterStats, "HitRatio", 0.5); assertAttributeValue(mBeanServer, clusterStats, "RemoveHits", 1); assertAttributeValue(mBeanServer, clusterStats, "RemoveMisses", 0); assertAttributeValue(mBeanServer, clusterStats, "NumberOfLocksAvailable", 0); assertAttributeValue(mBeanServer, clusterStats, "NumberOfLocksHeld", 0); assertAttributeValue(mBeanServer, clusterStats, "Activations", 0); assertAttributeValue(mBeanServer, clusterStats, "Passivations", 0); assertAttributeValue(mBeanServer, clusterStats, "Invalidations", 0); assertAttributeValue(mBeanServer, clusterStats, "CacheLoaderLoads", 0); assertAttributeValue(mBeanServer, clusterStats, "CacheLoaderMisses", 0); assertAttributeValue(mBeanServer, clusterStats, "StoreWrites", 0); } }
3,185
43.25
123
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/JmxStatsFunctionalTest.java
package org.infinispan.jmx; import static org.infinispan.commons.test.Exceptions.expectException; import static org.infinispan.test.TestingUtil.existsDomain; import static org.infinispan.test.TestingUtil.getCacheManagerObjectName; import static org.infinispan.test.TestingUtil.getCacheObjectName; import static org.infinispan.test.fwk.TestCacheManagerFactory.configureJmx; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import java.util.Properties; import javax.management.MBeanServer; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.manager.EmbeddedCacheManagerStartupException; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Functional test for checking jmx statistics exposure. * * @author Mircea.Markus@jboss.com * @author Galder Zamarreño * @since 4.0 */ @Test(groups = {"functional", "smoke"}, testName = "jmx.JmxStatsFunctionalTest") public class JmxStatsFunctionalTest extends AbstractInfinispanTest { private static final String JMX_DOMAIN = JmxStatsFunctionalTest.class.getSimpleName(); private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); private final MBeanServer server = mBeanServerLookup.getMBeanServer(); private EmbeddedCacheManager cm, cm2, cm3; @AfterMethod(alwaysRun = true) public void destroyCacheManager() { TestingUtil.killCacheManagers(cm, cm2, cm3); cm = null; cm2 = null; cm3 = null; } /** * Create a local cache, two replicated caches and see that everything is correctly registered. */ public void testDefaultDomain() { GlobalConfigurationBuilder globalConfiguration = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalConfiguration, JMX_DOMAIN, mBeanServerLookup); cm = TestCacheManagerFactory.createClusteredCacheManager(globalConfiguration, new ConfigurationBuilder()); String jmxDomain = cm.getCacheManagerConfiguration().jmx().domain(); ConfigurationBuilder localCache = config();//local by default cm.defineConfiguration("local_cache", localCache.build()); ConfigurationBuilder remote1 = config();//local by default remote1.clustering().cacheMode(CacheMode.REPL_SYNC); cm.defineConfiguration("remote1", remote1.build()); ConfigurationBuilder remote2 = config();//local by default remote2.clustering().cacheMode(CacheMode.INVALIDATION_ASYNC); cm.defineConfiguration("remote2", remote2.build()); cm.getCache("local_cache"); cm.getCache("remote1"); cm.getCache("remote2"); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "local_cache(local)", "Statistics"))); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "remote1(repl_sync)", "RpcManager"))); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "remote1(repl_sync)", "Statistics"))); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "remote2(invalidation_async)", "RpcManager"))); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "remote2(invalidation_async)", "Statistics"))); TestingUtil.killCacheManagers(cm); assertFalse(server.isRegistered(getCacheObjectName(jmxDomain, "local_cache(local)", "Statistics"))); assertFalse(server.isRegistered(getCacheObjectName(jmxDomain, "remote1(repl_sync)", "RpcManager"))); assertFalse(server.isRegistered(getCacheObjectName(jmxDomain, "remote1(repl_sync)", "Statistics"))); assertFalse(server.isRegistered(getCacheObjectName(jmxDomain, "remote2(invalidation_async)", "RpcManager"))); assertFalse(server.isRegistered(getCacheObjectName(jmxDomain, "remote2(invalidation_async)", "Statistics"))); } public void testDifferentDomain() { GlobalConfigurationBuilder globalConfiguration = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalConfiguration, JMX_DOMAIN, mBeanServerLookup); cm = TestCacheManagerFactory.createClusteredCacheManager(globalConfiguration, new ConfigurationBuilder()); String jmxDomain = cm.getCacheManagerConfiguration().jmx().domain(); ConfigurationBuilder localCache = config();//local by default cm.defineConfiguration("local_cache", localCache.build()); cm.getCache("local_cache"); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "local_cache(local)", "Statistics"))); } public void testOnlyGlobalJmxStatsEnabled() { GlobalConfigurationBuilder globalConfiguration = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalConfiguration, JMX_DOMAIN, mBeanServerLookup); cm = TestCacheManagerFactory.createClusteredCacheManager(globalConfiguration, new ConfigurationBuilder()); String jmxDomain = cm.getCacheManagerConfiguration().jmx().domain(); ConfigurationBuilder localCache = config();//local by default localCache.statistics().disable(); cm.defineConfiguration("local_cache", localCache.build()); ConfigurationBuilder remote1 = config();//local by default remote1.statistics().disable(); remote1.clustering().cacheMode(CacheMode.REPL_SYNC); cm.defineConfiguration("remote1", remote1.build()); cm.getCache("local_cache"); cm.getCache("remote1"); assertTrue(server.isRegistered(getCacheManagerObjectName(jmxDomain))); // Statistics MBean is always enabled now assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "local_cache(local)", "Statistics"))); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "remote1(repl_sync)", "Statistics"))); // Since ISPN-2290 assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "remote1(repl_sync)", "LockManager"))); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "local_cache(local)", "LockManager"))); } public void testOnlyPerCacheJmxStatsEnabled() { GlobalConfigurationBuilder globalConfiguration = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalConfiguration, JMX_DOMAIN, mBeanServerLookup); cm = TestCacheManagerFactory.createClusteredCacheManager(globalConfiguration, new ConfigurationBuilder()); String jmxDomain = cm.getCacheManagerConfiguration().jmx().domain(); ConfigurationBuilder localCache = config();//local by default localCache.statistics().enable(); cm.defineConfiguration("local_cache", localCache.build()); ConfigurationBuilder remote1 = config();//local by default remote1.statistics().enable(); remote1.clustering().cacheMode(CacheMode.REPL_SYNC); cm.defineConfiguration("remote1", remote1.build()); cm.getCache("local_cache"); cm.getCache("remote1"); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "local_cache(local)", "Statistics"))); // Since ISPN-2290 assertTrue(server.isRegistered(getCacheManagerObjectName(jmxDomain))); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "remote1(repl_sync)", "RpcManager"))); } public void testMultipleManagersOnSameServerFails(Method method) { final String jmxDomain = JMX_DOMAIN + '_' + method.getName(); GlobalConfigurationBuilder globalConfiguration = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalConfiguration, jmxDomain, mBeanServerLookup); cm = TestCacheManagerFactory.createClusteredCacheManager(globalConfiguration, new ConfigurationBuilder()); ConfigurationBuilder localCache = config();//local by default localCache.statistics().enable(); cm.defineConfiguration("local_cache", localCache.build()); cm.getCache("local_cache"); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "local_cache(local)", "Statistics"))); GlobalConfigurationBuilder globalConfiguration2 = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalConfiguration2, jmxDomain, mBeanServerLookup); expectException(EmbeddedCacheManagerStartupException.class, JmxDomainConflictException.class, () -> TestCacheManagerFactory.createClusteredCacheManager(globalConfiguration2, new ConfigurationBuilder())); } public void testMultipleManagersOnSameServerWithCloneFails() { GlobalConfigurationBuilder globalConfiguration = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalConfiguration, JMX_DOMAIN, mBeanServerLookup); cm = TestCacheManagerFactory.createClusteredCacheManager(globalConfiguration, new ConfigurationBuilder()); String jmxDomain = cm.getCacheManagerConfiguration().jmx().domain(); ConfigurationBuilder localCache = config();//local by default localCache.statistics().enable(); cm.defineConfiguration("local_cache", localCache.build()); cm.getCache("local_cache"); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "local_cache(local)", "Statistics"))); GlobalConfigurationBuilder globalConfiguration2 = new GlobalConfigurationBuilder(); globalConfiguration2.read(globalConfiguration.build()); globalConfiguration2.transport().defaultTransport(); expectException(EmbeddedCacheManagerStartupException.class, JmxDomainConflictException.class, () -> TestCacheManagerFactory.createClusteredCacheManager(globalConfiguration2, new ConfigurationBuilder())); } public void testMultipleManagersOnSameServer() { String jmxDomain = JMX_DOMAIN; GlobalConfigurationBuilder globalConfiguration = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalConfiguration, jmxDomain, mBeanServerLookup); cm = TestCacheManagerFactory.createClusteredCacheManager(globalConfiguration, new ConfigurationBuilder()); ConfigurationBuilder localCache = config();//local by default localCache.statistics().enable(); cm.defineConfiguration("local_cache", localCache.build()); cm.getCache("local_cache"); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "local_cache(local)", "Statistics"))); String jmxDomain2 = JMX_DOMAIN + 2; GlobalConfigurationBuilder globalConfiguration2 = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalConfiguration2, jmxDomain2, mBeanServerLookup); cm2 = TestCacheManagerFactory.createClusteredCacheManager(globalConfiguration2, new ConfigurationBuilder()); ConfigurationBuilder localCache2 = config();//local by default localCache2.statistics().enable(); cm2.defineConfiguration("local_cache", localCache.build()); cm2.getCache("local_cache"); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain2, "local_cache(local)", "Statistics"))); String jmxDomain3 = JMX_DOMAIN + 3; GlobalConfigurationBuilder globalConfiguration3 = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalConfiguration3, jmxDomain3, mBeanServerLookup); cm3 = TestCacheManagerFactory.createClusteredCacheManager(globalConfiguration3, new ConfigurationBuilder()); ConfigurationBuilder localCache3 = config();//local by default localCache3.statistics().enable(); cm3.defineConfiguration("local_cache", localCache.build()); cm3.getCache("local_cache"); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain3, "local_cache(local)", "Statistics"))); } public void testUnregisterJmxInfoOnStop() { GlobalConfigurationBuilder globalConfiguration = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalConfiguration, JMX_DOMAIN, mBeanServerLookup); cm = TestCacheManagerFactory.createClusteredCacheManager(globalConfiguration, new ConfigurationBuilder()); String jmxDomain = cm.getCacheManagerConfiguration().jmx().domain(); ConfigurationBuilder localCache = config();//local by default localCache.statistics().enable(); cm.defineConfiguration("local_cache", localCache.build()); cm.getCache("local_cache"); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "local_cache(local)", "Statistics"))); TestingUtil.killCacheManagers(cm); assertFalse(server.isRegistered(getCacheObjectName(jmxDomain, "local_cache(local)", "Statistics"))); assertFalse(existsDomain(server, jmxDomain)); } public void testCorrectUnregistering() { assertFalse(existsDomain(server, "infinispan")); GlobalConfigurationBuilder globalConfiguration = new GlobalConfigurationBuilder(); configureJmx(globalConfiguration, JMX_DOMAIN, mBeanServerLookup); cm = TestCacheManagerFactory.createCacheManager(globalConfiguration, new ConfigurationBuilder()); ConfigurationBuilder localCache = config();//local by default cm.defineConfiguration("local_cache", localCache.build()); cm.getCache("local_cache"); String jmxDomain = cm.getCacheManagerConfiguration().jmx().domain(); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "local_cache(local)", "Statistics"))); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "local_cache(local)", "Cache"))); //now register a global one GlobalConfigurationBuilder globalConfiguration2 = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalConfiguration2, JMX_DOMAIN + 2, mBeanServerLookup); cm2 = TestCacheManagerFactory.createClusteredCacheManager(globalConfiguration2, new ConfigurationBuilder()); ConfigurationBuilder remoteCache = new ConfigurationBuilder(); remoteCache.statistics().enable(); remoteCache.clustering().cacheMode(CacheMode.REPL_SYNC); cm2.defineConfiguration("remote_cache", remoteCache.build()); cm2.getCache("remote_cache"); String jmxDomain2 = cm2.getCacheManagerConfiguration().jmx().domain(); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain2, "remote_cache(repl_sync)", "Cache"))); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain2, "remote_cache(repl_sync)", "Statistics"))); cm2.stop(); assertTrue(server.isRegistered(getCacheObjectName(jmxDomain, "local_cache(local)", "Statistics"))); assertFalse(server.isRegistered(getCacheObjectName(jmxDomain2, "remote_cache(repl_sync)", "CacheComponent"))); assertFalse(server.isRegistered(getCacheObjectName(jmxDomain2, "remote_cache(repl_sync)", "Statistics"))); cm.stop(); assertFalse(server.isRegistered(getCacheObjectName(jmxDomain, "local_cache(local)", "Statistics"))); assertFalse(server.isRegistered(getCacheObjectName(jmxDomain2, "remote_cache(repl_sync)", "Statistics"))); } public void testStopUnstartedCacheManager() { GlobalConfigurationBuilder globalConfiguration = new GlobalConfigurationBuilder(); configureJmx(globalConfiguration, JMX_DOMAIN, mBeanServerLookup); cm = TestCacheManagerFactory.createCacheManager(globalConfiguration, new ConfigurationBuilder()); cm.stop(); } public void testConfigurationProperties() throws Exception { GlobalConfigurationBuilder globalConfiguration = GlobalConfigurationBuilder.defaultClusteredBuilder(); globalConfiguration.transport().siteId("TESTVALUE1"); globalConfiguration.transport().rackId("TESTVALUE2"); globalConfiguration.transport().machineId("TESTVALUE3"); configureJmx(globalConfiguration, JMX_DOMAIN, mBeanServerLookup); cm = TestCacheManagerFactory.createClusteredCacheManager(globalConfiguration, new ConfigurationBuilder()); String jmxDomain = cm.getCacheManagerConfiguration().jmx().domain(); ConfigurationBuilder localCache = config(); localCache.memory().storageType(StorageType.BINARY); cm.defineConfiguration("local_cache1", localCache.build()); localCache.memory().storageType(StorageType.OBJECT); cm.defineConfiguration("local_cache2", localCache.build()); cm.getCache("local_cache1"); cm.getCache("local_cache2"); Properties props1 = (Properties) server.getAttribute(getCacheObjectName(jmxDomain, "local_cache1(local)", "Cache"), "configurationAsProperties"); Properties props2 = (Properties) server.getAttribute(getCacheObjectName(jmxDomain, "local_cache2(local)", "Cache"), "configurationAsProperties"); Properties propsGlobal = (Properties) server.getAttribute(getCacheManagerObjectName(jmxDomain), "globalConfigurationAsProperties"); // configurationAsProperties excludes deprecated methods from the reflection, so 'storageType' is not available anymore. assert "BINARY".equals(props1.getProperty("memory.storage")); assert "OBJECT".equals(props2.getProperty("memory.storage")); log.tracef("propsGlobal=%s", propsGlobal); assert "TESTVALUE1".equals(propsGlobal.getProperty("transport.siteId")); assert "TESTVALUE2".equals(propsGlobal.getProperty("transport.rackId")); assert "TESTVALUE3".equals(propsGlobal.getProperty("transport.machineId")); } private ConfigurationBuilder config() { ConfigurationBuilder configuration = new ConfigurationBuilder(); configuration.clustering().stateTransfer().fetchInMemoryState(false).statistics().enable(); return configuration; } }
17,872
55.028213
151
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/ClusteredCacheManagerMBeanTest.java
package org.infinispan.jmx; import static org.infinispan.factories.KnownComponentNames.NON_BLOCKING_EXECUTOR; import static org.infinispan.factories.KnownComponentNames.TIMEOUT_SCHEDULE_EXECUTOR; import static org.infinispan.test.TestingUtil.extractGlobalComponent; import static org.infinispan.test.TestingUtil.getCacheManagerObjectName; import static org.infinispan.test.TestingUtil.getJGroupsChannelObjectName; import static org.infinispan.test.fwk.TestCacheManagerFactory.configureJmx; import static org.infinispan.test.fwk.TestCacheManagerFactory.createClusteredCacheManager; import static org.testng.Assert.assertNotEquals; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.concurrent.ExecutorService; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.testng.annotations.Test; /** * Clustered cache manager MBean test * * @author Galder Zamarreño * @since 4.2 */ @Test(groups = "functional", testName = "jmx.ClusteredCacheManagerMBeanTest") public class ClusteredCacheManagerMBeanTest extends MultipleCacheManagersTest { private static final String JMX_DOMAIN = ClusteredCacheManagerMBeanTest.class.getSimpleName(); private static final String JMX_DOMAIN2 = JMX_DOMAIN + "2"; private static final String CACHE_NAME = "mycache"; private ObjectName name1; private ObjectName name2; private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); @Override protected void createCacheManagers() throws Throwable { GlobalConfigurationBuilder globalConfig1 = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalConfig1, JMX_DOMAIN, mBeanServerLookup); ConfigurationBuilder config = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC); config.statistics().enable(); EmbeddedCacheManager cacheManager1 = createClusteredCacheManager(globalConfig1, config, new TransportFlags()); cacheManager1.start(); GlobalConfigurationBuilder globalConfig2 = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalConfig2, JMX_DOMAIN2, mBeanServerLookup); EmbeddedCacheManager cacheManager2 = createClusteredCacheManager(globalConfig2, config, new TransportFlags()); cacheManager2.start(); registerCacheManager(cacheManager1, cacheManager2); name1 = getCacheManagerObjectName(JMX_DOMAIN); name2 = getCacheManagerObjectName(JMX_DOMAIN2); defineConfigurationOnAllManagers(CACHE_NAME, config); manager(0).getCache(CACHE_NAME); manager(1).getCache(CACHE_NAME); } public void testAddressInformation() throws Exception { MBeanServer server = mBeanServerLookup.getMBeanServer(); String cm1Address = manager(0).getAddress().toString(); String cm2Address = manager(1).getAddress().toString(); assertEquals(cm1Address, server.getAttribute(name1, "NodeAddress")); assertTrue(server.getAttribute(name1, "ClusterMembers").toString().contains(cm1Address)); assertNotEquals("local", server.getAttribute(name1, "PhysicalAddresses")); assertEquals(2, server.getAttribute(name1, "ClusterSize")); assertEquals(cm2Address, server.getAttribute(name2, "NodeAddress")); assertTrue(server.getAttribute(name2, "ClusterMembers").toString().contains(cm2Address)); assertNotEquals("local", server.getAttribute(name2, "PhysicalAddresses")); assertEquals(2, server.getAttribute(name2, "ClusterSize")); String cm1members = (String) server.getAttribute(name1, "ClusterMembersPhysicalAddresses"); assertEquals(2, cm1members.substring(1, cm1members.length() - 2).split(",\\s+").length); } public void testJGroupsInformation() throws Exception { MBeanServer server = mBeanServerLookup.getMBeanServer(); ObjectName jchannelName1 = getJGroupsChannelObjectName(manager(0)); ObjectName jchannelName2 = getJGroupsChannelObjectName(manager(1)); assertEquals(server.getAttribute(name1, "NodeAddress"), server.getAttribute(jchannelName1, "address")); assertEquals(server.getAttribute(name2, "NodeAddress"), server.getAttribute(jchannelName2, "address")); assertTrue((Boolean) server.getAttribute(jchannelName1, "connected")); assertTrue((Boolean) server.getAttribute(jchannelName2, "connected")); } public void testExecutorMBeans() throws Exception { MBeanServer server = mBeanServerLookup.getMBeanServer(); ObjectName objectName = getCacheManagerObjectName(JMX_DOMAIN, "DefaultCacheManager", TIMEOUT_SCHEDULE_EXECUTOR); assertTrue(server.isRegistered(objectName)); assertEquals(Integer.MAX_VALUE, server.getAttribute(objectName, "MaximumPoolSize")); String javaVersion = System.getProperty("java.version"); assertEquals(javaVersion.startsWith("1.8.") ? 0L : 10L, server.getAttribute(objectName, "KeepAliveTime")); ExecutorService executor = extractGlobalComponent(manager(0), ExecutorService.class, NON_BLOCKING_EXECUTOR); executor.submit(() -> {}); objectName = getCacheManagerObjectName(JMX_DOMAIN, "DefaultCacheManager", NON_BLOCKING_EXECUTOR); assertTrue(server.isRegistered(objectName)); assertEquals(30000L, server.getAttribute(objectName, "KeepAliveTime")); assertEquals(TestCacheManagerFactory.NAMED_EXECUTORS_THREADS_NO_QUEUE, server.getAttribute(objectName, "MaximumPoolSize")); } }
5,974
51.412281
118
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/CacheManagerMBeanTest.java
package org.infinispan.jmx; import static java.lang.String.format; import static org.infinispan.factories.KnownComponentNames.TIMEOUT_SCHEDULE_EXECUTOR; import static org.infinispan.test.TestingUtil.checkMBeanOperationParameterNaming; import static org.infinispan.test.TestingUtil.extractGlobalComponent; import static org.infinispan.test.TestingUtil.getCacheManagerObjectName; import static org.infinispan.test.TestingUtil.getCacheObjectName; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import java.util.Arrays; import java.util.concurrent.ScheduledExecutorService; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.ServiceNotFoundException; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.CacheContainer; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.manager.EmbeddedCacheManagerStartupException; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Tests whether the attributes defined by DefaultCacheManager work correct. * * @author Mircea.Markus@jboss.com * @author Galder Zamarreño * @since 4.0 */ @Test(groups = "functional", testName = "jmx.CacheManagerMBeanTest") public class CacheManagerMBeanTest extends SingleCacheManagerTest { private static final String JMX_DOMAIN = CacheManagerMBeanTest.class.getSimpleName(); private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); private final MBeanServer server = mBeanServerLookup.getMBeanServer(); private ObjectName name; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder globalConfiguration = new GlobalConfigurationBuilder(); globalConfiguration.jmx().enabled(true).domain(JMX_DOMAIN).mBeanServerLookup(mBeanServerLookup); ConfigurationBuilder configuration = new ConfigurationBuilder(); cacheManager = TestCacheManagerFactory.createCacheManager(globalConfiguration, configuration); name = getCacheManagerObjectName(JMX_DOMAIN); mBeanServerLookup.getMBeanServer().invoke(name, "startCache", new Object[0], new String[0]); return cacheManager; } public void testJmxOperations() throws Exception { assertEquals("1", server.getAttribute(name, "CreatedCacheCount")); assertEquals("1", server.getAttribute(name, "DefinedCacheCount")); assertEquals(format("[%s(created)]", getDefaultCacheName()), server.getAttribute(name, "DefinedCacheNames")); assertEquals("1", server.getAttribute(name, "RunningCacheCount")); //now define some new caches cacheManager.defineConfiguration("a", new ConfigurationBuilder().build()); cacheManager.defineConfiguration("b", new ConfigurationBuilder().build()); cacheManager.defineConfiguration("c", new ConfigurationBuilder().build()); assertEquals("1", server.getAttribute(name, "CreatedCacheCount")); assertEquals("4", server.getAttribute(name, "DefinedCacheCount")); assertEquals("1", server.getAttribute(name, "RunningCacheCount")); String attribute = (String) server.getAttribute(name, "DefinedCacheConfigurationNames"); String[] names = attribute.substring(1, attribute.length() - 1).split(","); assertTrue(Arrays.binarySearch(names, "a") >= 0); assertTrue(Arrays.binarySearch(names, "b") >= 0); assertTrue(Arrays.binarySearch(names, "c") >= 0); //now start some caches server.invoke(name, "startCache", new Object[]{"a"}, new String[]{String.class.getName()}); server.invoke(name, "startCache", new Object[]{"b"}, new String[]{String.class.getName()}); assertEquals("3", server.getAttribute(name, "CreatedCacheCount")); assertEquals("4", server.getAttribute(name, "DefinedCacheCount")); assertEquals("3", server.getAttribute(name, "RunningCacheCount")); attribute = (String) server.getAttribute(name, "DefinedCacheNames"); assertTrue(attribute.contains("a(")); assertTrue(attribute.contains("b(")); assertTrue(attribute.contains("c(")); } public void testJmxOperationMetadata() throws Exception { checkMBeanOperationParameterNaming(mBeanServerLookup.getMBeanServer(), name); } public void testInvokeJmxOperationNotExposed() { Exceptions.expectException(MBeanException.class, ServiceNotFoundException.class, () -> mBeanServerLookup.getMBeanServer().invoke(name, "stop", new Object[]{}, new String[]{})); } public void testSameDomain() { GlobalConfigurationBuilder gc = new GlobalConfigurationBuilder(); gc.jmx().enabled(true).domain(JMX_DOMAIN).mBeanServerLookup(mBeanServerLookup); ConfigurationBuilder c = new ConfigurationBuilder(); Exceptions.expectException(EmbeddedCacheManagerStartupException.class, () -> TestCacheManagerFactory.createCacheManager(gc, c)); } public void testJmxRegistrationAtStartupAndStop(Method m) throws Exception { String otherJmxDomain = JMX_DOMAIN + "_" + m.getName(); GlobalConfigurationBuilder gc = new GlobalConfigurationBuilder(); gc.jmx().enabled(true).domain(otherJmxDomain).mBeanServerLookup(mBeanServerLookup); CacheContainer otherContainer = TestCacheManagerFactory.createCacheManager(gc, null); ObjectName otherName = getCacheManagerObjectName(otherJmxDomain); try { assertEquals("0", mBeanServerLookup.getMBeanServer().getAttribute(otherName, "CreatedCacheCount")); } finally { otherContainer.stop(); } Exceptions.expectException(InstanceNotFoundException.class, () -> mBeanServerLookup.getMBeanServer().getAttribute(otherName, "CreatedCacheCount")); } public void testCustomCacheManagerName(Method m) throws Exception { String otherJmxDomain = JMX_DOMAIN + "_" + m.getName(); GlobalConfigurationBuilder gc = new GlobalConfigurationBuilder(); gc.jmx().enabled(true).domain(otherJmxDomain).mBeanServerLookup(mBeanServerLookup); gc.cacheManagerName("Hibernate2LC"); CacheContainer otherContainer = TestCacheManagerFactory.createCacheManager(gc, null); try { ObjectName otherName = getCacheManagerObjectName(otherJmxDomain, "Hibernate2LC"); assertEquals("0", mBeanServerLookup.getMBeanServer().getAttribute(otherName, "CreatedCacheCount")); } finally { otherContainer.stop(); } } public void testAddressInformation() throws Exception { assertEquals("local", server.getAttribute(name, "NodeAddress")); assertEquals("local", server.getAttribute(name, "ClusterMembers")); assertEquals("local", server.getAttribute(name, "PhysicalAddresses")); assertEquals(1, server.getAttribute(name, "ClusterSize")); } @Test(dependsOnMethods = "testJmxOperations") public void testCacheMBeanUnregisterOnRemove() { cacheManager.defineConfiguration("test", new ConfigurationBuilder().build()); assertNotNull(cacheManager.getCache("test")); ObjectName cacheMBean = getCacheObjectName(JMX_DOMAIN, "test(local)"); assertTrue(server.isRegistered(cacheMBean)); cacheManager.administration().removeCache("test"); assertFalse(server.isRegistered(cacheMBean)); } public void testExecutorMBeans() throws Exception { ScheduledExecutorService timeoutExecutor = extractGlobalComponent(cacheManager, ScheduledExecutorService.class, TIMEOUT_SCHEDULE_EXECUTOR); timeoutExecutor.submit(() -> {}); ObjectName objectName = getCacheManagerObjectName(JMX_DOMAIN, "DefaultCacheManager", TIMEOUT_SCHEDULE_EXECUTOR); assertTrue(server.isRegistered(objectName)); assertEquals(1, server.getAttribute(objectName, "PoolSize")); assertEquals(Integer.MAX_VALUE, server.getAttribute(objectName, "MaximumPoolSize")); } }
8,422
48.547059
153
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/ActivationAndPassivationInterceptorMBeanTest.java
package org.infinispan.jmx; import static org.infinispan.test.TestingUtil.getCacheObjectName; import static org.infinispan.test.TestingUtil.k; import static org.infinispan.test.TestingUtil.v; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import javax.management.Attribute; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Tester class for ActivationInterceptor and PassivationInterceptor. * * @author Mircea.Markus@jboss.com * @author Galder Zamarreño */ @Test(groups = "functional", testName = "jmx.ActivationAndPassivationInterceptorMBeanTest") public class ActivationAndPassivationInterceptorMBeanTest extends SingleCacheManagerTest { private static final String JMX_DOMAIN = ActivationAndPassivationInterceptorMBeanTest.class.getSimpleName(); private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); private DummyInMemoryStore loader; private ObjectName activationInterceptorObjName; private ObjectName passivationInterceptorObjName; protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder(); globalBuilder.jmx().enabled(true) .mBeanServerLookup(mBeanServerLookup) .domain(JMX_DOMAIN); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory().size(1) .statistics().enable() .persistence() .passivation(true) .addStore(DummyInMemoryStoreConfigurationBuilder.class); return TestCacheManagerFactory.createCacheManager(globalBuilder, builder); } @Override protected void setup() throws Exception { super.setup(); activationInterceptorObjName = getCacheObjectName(JMX_DOMAIN, getDefaultCacheName() + "(local)", "Activation"); passivationInterceptorObjName = getCacheObjectName(JMX_DOMAIN, getDefaultCacheName() + "(local)", "Passivation"); loader = TestingUtil.getFirstStore(cache); } @AfterMethod public void resetStats() throws Exception { MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); mBeanServer.invoke(activationInterceptorObjName, "resetStatistics", new Object[0], new String[0]); mBeanServer.invoke(passivationInterceptorObjName, "resetStatistics", new Object[0], new String[0]); } public void passivateAll() throws Exception { mBeanServerLookup.getMBeanServer().invoke(passivationInterceptorObjName, "passivateAll", new Object[0], new String[0]); } public void testDisableStatistics() throws Exception { MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); mBeanServer.setAttribute(activationInterceptorObjName, new Attribute("StatisticsEnabled", Boolean.FALSE)); assert mBeanServer.getAttribute(activationInterceptorObjName, "Activations").toString().equals("N/A"); mBeanServer.setAttribute(activationInterceptorObjName, new Attribute("StatisticsEnabled", Boolean.TRUE)); } public void testActivationOnGet(Method m) { assertActivationCount(0); assert cache.get(k(m)) == null; assertActivationCount(0); loader.write(MarshalledEntryUtil.create(k(m), v(m), cache)); assert loader.contains(k(m)); assert cache.get(k(m)).equals(v(m)); assertActivationCount(1); assert !loader.contains(k(m)); } public void testActivationOnPut(Method m) { assertActivationCount(0); assert cache.get(k(m)) == null; assertActivationCount(0); loader.write(MarshalledEntryUtil.create(k(m), v(m), cache)); assert loader.contains(k(m)); cache.put(k(m), v(m, 2)); assert cache.get(k(m)).equals(v(m, 2)); assertActivationCount(1); assert !loader.contains(k(m)) : "this should only be persisted on evict"; } public void testActivationOnReplace(Method m) { assertActivationCount(0); assertNull(cache.get(k(m))); assertActivationCount(0); loader.write(MarshalledEntryUtil.create(k(m), v(m), cache)); assertTrue(loader.contains(k(m))); Object prev = cache.replace(k(m), v(m, 2)); assertNotNull(prev); assertEquals(v(m), prev); assertActivationCount(1); assertFalse(loader.contains(k(m))); } public void testActivationOnPutMap(Method m) { assertActivationCount(0); assertNull(cache.get(k(m))); assertActivationCount(0); loader.write(MarshalledEntryUtil.create(k(m), v(m), cache)); assertTrue(loader.contains(k(m))); Map<String, String> toAdd = new HashMap<>(); toAdd.put(k(m), v(m, 2)); cache.putAll(toAdd); assertActivationCount(1); Object obj = cache.get(k(m)); assertNotNull(obj); assertEquals(v(m, 2), obj); assertFalse(loader.contains(k(m))); } public void testPassivationOnEvict(Method m) throws Exception { assertPassivationCount(0); cache.put(k(m), v(m)); cache.put(k(m, 2), v(m, 2)); cache.evict(k(m)); assertPassivationCount(1); cache.evict(k(m, 2)); assertPassivationCount(2); cache.evict("not_existing_key"); assertPassivationCount(2); } public void testPassivateAll(Method m) throws Exception { assertPassivationCount(0); for (int i = 0; i < 10; i++) { cache.put(k(m, i), v(m, i)); } passivateAll(); assertPassivationCount(9); } private void assertActivationCount(long activationCount) { eventuallyEquals(activationCount, () -> { try { return Long.parseLong(mBeanServerLookup.getMBeanServer() .getAttribute(activationInterceptorObjName, "Activations").toString()); } catch (Exception e) { throw Util.rewrapAsCacheException(e); } }); } private void assertPassivationCount(long activationCount) throws Exception { long passivations = Long.parseLong(mBeanServerLookup.getMBeanServer() .getAttribute(passivationInterceptorObjName, "Passivations").toString()); assertEquals(activationCount, passivations); } }
7,224
37.430851
125
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/CacheLoaderAndCacheWriterInterceptorMBeanTest.java
package org.infinispan.jmx; import static org.infinispan.test.TestingUtil.checkMBeanOperationParameterNaming; import static org.infinispan.test.TestingUtil.getCacheObjectName; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Tests the jmx functionality from CacheLoaderInterceptor and CacheWriterInterceptor. * * @author Mircea.Markus@jboss.com * @author Galder Zamarreño */ @Test(groups = "functional", testName = "jmx.CacheLoaderAndCacheWriterInterceptorMBeanTest") public class CacheLoaderAndCacheWriterInterceptorMBeanTest extends SingleCacheManagerTest { private static final String JMX_DOMAIN = CacheLoaderAndCacheWriterInterceptorMBeanTest.class.getName(); private ObjectName loaderInterceptorObjName; private ObjectName storeInterceptorObjName; private DummyInMemoryStore store; private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder configuration = getDefaultStandaloneCacheConfig(false); configuration .statistics().enable() .persistence() .passivation(false) .addStore(DummyInMemoryStoreConfigurationBuilder.class); GlobalConfigurationBuilder globalConfiguration = new GlobalConfigurationBuilder(); globalConfiguration .cacheContainer().statistics(true) .jmx().enabled(true).domain(JMX_DOMAIN).mBeanServerLookup(mBeanServerLookup); cacheManager = TestCacheManagerFactory.createCacheManager(globalConfiguration, configuration); cacheManager.defineConfiguration("test", configuration.build()); cache = cacheManager.getCache("test"); loaderInterceptorObjName = getCacheObjectName(JMX_DOMAIN, "test(local)", "CacheLoader"); storeInterceptorObjName = getCacheObjectName(JMX_DOMAIN, "test(local)", "CacheStore"); store = TestingUtil.getFirstStore(cache); return cacheManager; } @AfterMethod public void resetStats() throws Exception { MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); mBeanServer.invoke(loaderInterceptorObjName, "resetStatistics", new Object[0], new String[0]); mBeanServer.invoke(storeInterceptorObjName, "resetStatistics", new Object[0], new String[0]); } public void testJmxOperationMetadata() throws Exception { MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); checkMBeanOperationParameterNaming(mBeanServer, loaderInterceptorObjName); checkMBeanOperationParameterNaming(mBeanServer, storeInterceptorObjName); } public void testPutKeyValue() throws Exception { assertStoreAccess(0, 0, 0); cache.put("key", "value"); assertStoreAccess(0, 1, 1); cache.put("key", "value2"); assertStoreAccess(0, 1, 2); store.write(MarshalledEntryUtil.create("a", "b", cache)); cache.put("a", "c"); assertStoreAccess(1, 1, 3); assert store.loadEntry("a").getValue().equals("c"); } public void testGetValue() throws Exception { assertStoreAccess(0, 0, 0); cache.put("key", "value"); assertStoreAccess(0, 1, 1); assert cache.get("key").equals("value"); assertStoreAccess(0, 1, 1); store.write(MarshalledEntryUtil.create("a", "b", cache)); assert cache.get("a").equals("b"); assertStoreAccess(1, 1, 1); assert cache.get("no_such_key") == null; assertStoreAccess(1, 2, 1); } public void testRemoveValue() throws Exception { assertStoreAccess(0, 0, 0); cache.put("key", "value"); assertStoreAccess(0, 1, 1); assert cache.get("key").equals("value"); assertStoreAccess(0, 1, 1); assert cache.remove("key").equals("value"); assertStoreAccess(0, 1, 1); cache.remove("no_such_key"); assertStoreAccess(0, 2, 1); store.write(MarshalledEntryUtil.create("a", "b", cache)); assert cache.remove("a").equals("b"); assertStoreAccess(1, 2, 1); } public void testReplaceCommand() throws Exception { assertStoreAccess(0, 0, 0); cache.put("key", "value"); assertStoreAccess(0, 1, 1); assert cache.replace("key", "value2").equals("value"); assertStoreAccess(0, 1, 2); store.write(MarshalledEntryUtil.create("a", "b", cache)); assert cache.replace("a", "c").equals("b"); assertStoreAccess(1, 1, 3); assert cache.replace("no_such_key", "c") == null; assertStoreAccess(1, 2, 3); } public void testFlagMissNotCounted() throws Exception { assertStoreAccess(0, 0, 0); cache.put("key", "value"); assertStoreAccess(0, 1, 1); cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD).get("no_such_key"); assertStoreAccess(0, 1, 1); } private void assertStoreAccess(int loadsCount, int missesCount, int storeCount) throws Exception { assertLoadCount(loadsCount, missesCount); assertStoreCount(storeCount); } private void assertLoadCount(int loadsCount, int missesCount) throws Exception { MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); String actualLoadCount = mBeanServer.getAttribute(loaderInterceptorObjName, "CacheLoaderLoads").toString(); assert Integer.valueOf(actualLoadCount).equals(loadsCount) : "expected " + loadsCount + " loads count and received " + actualLoadCount; String actualMissesCount = mBeanServer.getAttribute(loaderInterceptorObjName, "CacheLoaderMisses").toString(); assert Integer.valueOf(actualMissesCount).equals(missesCount) : "expected " + missesCount + " misses count, and received " + actualMissesCount; } private void assertStoreCount(int count) throws Exception { String actualStoreCount = mBeanServerLookup.getMBeanServer().getAttribute(storeInterceptorObjName, "WritesToTheStores").toString(); assert Integer.valueOf(actualStoreCount).equals(count) : "expected " + count + " store counts, but received " + actualStoreCount; } }
6,831
40.156627
149
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/CacheAvailabilityJmxTest.java
package org.infinispan.jmx; import static org.testng.Assert.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.Arrays; import javax.management.Attribute; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.distribution.DistributionManager; import org.infinispan.partitionhandling.PartitionHandling; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; /** * @author Dan Berindei */ @Test(groups = "functional", testName = "jmx.CacheAvailabilityJmxTest") public class CacheAvailabilityJmxTest extends MultipleCacheManagersTest { private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); @Override protected void createCacheManagers() throws Throwable { addClusterEnabledCacheManager(getGlobalConfigurationBuilder("r1"), getConfigurationBuilder()); addClusterEnabledCacheManager(getGlobalConfigurationBuilder("r1"), getConfigurationBuilder()); waitForClusterToForm(); } private ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC) .stateTransfer().awaitInitialTransfer(false) .partitionHandling().whenSplit(PartitionHandling.DENY_READ_WRITES); return cb; } private GlobalConfigurationBuilder getGlobalConfigurationBuilder(String rackId) { int nodeIndex = cacheManagers.size(); GlobalConfigurationBuilder gcb = GlobalConfigurationBuilder.defaultClusteredBuilder(); gcb.jmx().enabled(true) .domain(getClass().getSimpleName() + nodeIndex) .mBeanServerLookup(mBeanServerLookup) .transport().rackId(rackId); return gcb; } public void testAvailabilityChange() throws Exception { MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); final String cacheName = manager(0).getCacheManagerConfiguration().defaultCacheName().get(); String domain0 = manager(1).getCacheManagerConfiguration().jmx().domain(); final ObjectName cacheName0 = TestingUtil.getCacheObjectName(domain0, cacheName + "(dist_sync)"); String domain1 = manager(1).getCacheManagerConfiguration().jmx().domain(); final ObjectName cacheName1 = TestingUtil.getCacheObjectName(domain1, cacheName + "(dist_sync)"); // Check initial state DistributionManager dm0 = advancedCache(0).getDistributionManager(); assertEquals(Arrays.asList(address(0), address(1)), dm0.getCacheTopology().getCurrentCH().getMembers()); assertNull(dm0.getCacheTopology().getPendingCH()); assertTrue(mBeanServer.isRegistered(cacheName0)); assertEquals("AVAILABLE", mBeanServer.getAttribute(cacheName0, "CacheAvailability")); assertEquals("AVAILABLE", mBeanServer.getAttribute(cacheName1, "CacheAvailability")); // Enter degraded mode log.debugf("Entering degraded mode"); mBeanServer.setAttribute(cacheName0, new Attribute("CacheAvailability", "DEGRADED_MODE")); eventually(() -> { Object availability0 = mBeanServer.getAttribute(cacheName0, "CacheAvailability"); Object availability1 = mBeanServer.getAttribute(cacheName1, "CacheAvailability"); return "DEGRADED_MODE".equals(availability0) && "DEGRADED_MODE".equals(availability1); }); // Add 2 nodes log.debugf("Starting 2 new nodes"); addClusterEnabledCacheManager(getGlobalConfigurationBuilder("r2"), getConfigurationBuilder()); addClusterEnabledCacheManager(getGlobalConfigurationBuilder("r2"), getConfigurationBuilder()); cache(2); cache(3); // Check that no rebalance happened after 1 second Thread.sleep(1000); assertEquals(Arrays.asList(address(0), address(1)), dm0.getCacheTopology().getCurrentCH().getMembers()); assertNull(dm0.getCacheTopology().getPendingCH()); assertEquals("DEGRADED_MODE", mBeanServer.getAttribute(cacheName0, "CacheAvailability")); assertEquals("DEGRADED_MODE", mBeanServer.getAttribute(cacheName1, "CacheAvailability")); // Enter available mode log.debugf("Back to available mode"); mBeanServer.setAttribute(cacheName0, new Attribute("CacheAvailability", "AVAILABLE")); eventually(() -> { Object availability0 = mBeanServer.getAttribute(cacheName0, "CacheAvailability"); Object availability1 = mBeanServer.getAttribute(cacheName1, "CacheAvailability"); return "AVAILABLE".equals(availability0) && "AVAILABLE".equals(availability1); }); // Check that the cache now has 4 nodes, and the CH is balanced TestingUtil.waitForNoRebalance(cache(0), cache(1), cache(2), cache(3)); } }
5,147
45.378378
110
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/ClusteredCacheMgmtInterceptorMBeanTest.java
package org.infinispan.jmx; import static org.infinispan.test.TestingUtil.getCacheObjectName; import static org.infinispan.test.fwk.TestCacheManagerFactory.configureJmx; import static org.testng.AssertJUnit.assertEquals; import java.util.HashMap; import java.util.Map; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.Cache; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * @author Galder Zamarreño * @since 5.2 */ @Test(groups = "functional", testName = "jmx.ClusteredCacheMgmtInterceptorMBeanTest") public class ClusteredCacheMgmtInterceptorMBeanTest extends MultipleCacheManagersTest { private static final String JMX_DOMAIN_1 = ClusteredCacheMgmtInterceptorMBeanTest.class.getSimpleName() + "-1"; private static final String JMX_DOMAIN_2 = ClusteredCacheMgmtInterceptorMBeanTest.class.getSimpleName() + "-2"; private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); @Override protected void createCacheManagers() throws Throwable { GlobalConfigurationBuilder globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalBuilder, JMX_DOMAIN_1, mBeanServerLookup); ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); builder.statistics().enable(); EmbeddedCacheManager cm1 = TestCacheManagerFactory.createClusteredCacheManager(globalBuilder, builder); GlobalConfigurationBuilder globalBuilder2 = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalBuilder2, JMX_DOMAIN_2, mBeanServerLookup); EmbeddedCacheManager cm2 = TestCacheManagerFactory.createClusteredCacheManager(globalBuilder2, builder); registerCacheManager(cm1, cm2); } public void testCorrectStatsInCluster() throws Exception { Cache<String, String> cache1 = cache(0); Cache<String, String> cache2 = cache(1); cache1.put("k", "v"); assertEquals("v", cache2.get("k")); ObjectName stats1 = getCacheObjectName(JMX_DOMAIN_1, getDefaultCacheName() + "(repl_sync)", "Statistics"); ObjectName stats2 = getCacheObjectName(JMX_DOMAIN_2, getDefaultCacheName() + "(repl_sync)", "Statistics"); MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); assertEquals(1L, mBeanServer.getAttribute(stats1, "Stores")); assertEquals(0L, mBeanServer.getAttribute(stats2, "Stores")); Map<String, String> values = new HashMap<>(); values.put("k1", "v1"); values.put("k2", "v2"); values.put("k3", "v3"); cache2.putAll(values); assertEquals(1L, mBeanServer.getAttribute(stats1, "Stores")); assertEquals(3L, mBeanServer.getAttribute(stats2, "Stores")); cache1.remove("k"); assertEquals(1L, mBeanServer.getAttribute(stats1, "RemoveHits")); assertEquals(0L, mBeanServer.getAttribute(stats2, "RemoveHits")); } }
3,378
42.320513
114
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/HealthJmxTest.java
package org.infinispan.jmx; import static org.infinispan.test.fwk.TestCacheManagerFactory.configureJmx; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.health.HealthStatus; import org.infinispan.health.jmx.HealthJMXExposer; import org.infinispan.partitionhandling.PartitionHandling; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.commons.test.TestResourceTracker; import org.testng.annotations.Test; @Test(groups = "functional", testName = "jmx.HealthJmxTest") public class HealthJmxTest extends MultipleCacheManagersTest { private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); @Override protected void createCacheManagers() throws Throwable { addClusterEnabledCacheManager(getGlobalConfigurationBuilder("r1"), getConfigurationBuilder()) .defineConfiguration("test", getConfigurationBuilder().build()); } private ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC) .stateTransfer().awaitInitialTransfer(false) .partitionHandling().whenSplit(PartitionHandling.DENY_READ_WRITES); return cb; } private GlobalConfigurationBuilder getGlobalConfigurationBuilder(String rackId) { GlobalConfigurationBuilder gcb = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(gcb, getClass().getSimpleName(), mBeanServerLookup); gcb.transport().rackId(rackId); return gcb; } public void testHealthCheckAPI() throws Exception { //given //we need this to start a cache with a custom name cacheManagers.get(0).getCache("test").put("1", "1"); MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); //when String domain0 = manager(0).getCacheManagerConfiguration().jmx().domain(); ObjectName healthAPI0 = TestingUtil.getCacheManagerObjectName(domain0, "DefaultCacheManager", HealthJMXExposer.OBJECT_NAME); Object numberOfCpus = mBeanServer.getAttribute(healthAPI0, "NumberOfCpus"); Object totalMemoryKb = mBeanServer.getAttribute(healthAPI0, "TotalMemoryKb"); Object freeMemoryKb = mBeanServer.getAttribute(healthAPI0, "FreeMemoryKb"); Object clusterHealth = mBeanServer.getAttribute(healthAPI0, "ClusterHealth"); Object clusterName = mBeanServer.getAttribute(healthAPI0, "ClusterName"); Object numberOfNodes = mBeanServer.getAttribute(healthAPI0, "NumberOfNodes"); Object cacheHealth = mBeanServer.getAttribute(healthAPI0, "CacheHealth"); //then assertTrue((int) numberOfCpus > 0); assertTrue((long) totalMemoryKb > 0); assertTrue((long) freeMemoryKb > 0); assertEquals((String) clusterHealth, HealthStatus.HEALTHY.toString()); assertEquals((String) clusterName, TestResourceTracker.getCurrentTestName()); assertEquals((int) numberOfNodes, 1); assertEquals(((String[]) cacheHealth)[0], "test"); assertEquals(((String[]) cacheHealth)[1], HealthStatus.HEALTHY.toString()); } }
3,654
45.265823
132
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/CacheContainerStatsMBeanTest.java
package org.infinispan.jmx; import static org.infinispan.test.TestingUtil.getCacheManagerObjectName; import java.io.Serializable; import javax.management.Attribute; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.Cache; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.CacheContainer; import org.infinispan.stats.CacheContainerStats; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.infinispan.util.ControlledTimeService; import org.testng.annotations.Test; @Test(groups = "functional", testName = "jmx.CacheContainerStatsMBeanTest") public class CacheContainerStatsMBeanTest extends MultipleCacheManagersTest { private final String cachename = CacheContainerStatsMBeanTest.class.getName(); private final String cachename2 = cachename + "2"; private static final String JMX_DOMAIN = CacheContainerStatsMBeanTest.class.getSimpleName(); private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); private ControlledTimeService timeService; @Override protected void createCacheManagers() throws Throwable { timeService = new ControlledTimeService(); ConfigurationBuilder defaultConfig = new ConfigurationBuilder(); GlobalConfigurationBuilder gcb1 = GlobalConfigurationBuilder.defaultClusteredBuilder(); gcb1.cacheContainer().statistics(true) .jmx().enabled(true).domain(JMX_DOMAIN).mBeanServerLookup(mBeanServerLookup) .metrics().accurateSize(true); CacheContainer cacheManager1 = TestCacheManagerFactory.createClusteredCacheManager(gcb1, defaultConfig, new TransportFlags()); TestingUtil.replaceComponent(cacheManager1, TimeService.class, timeService, true); cacheManager1.start(); GlobalConfigurationBuilder gcb2 = GlobalConfigurationBuilder.defaultClusteredBuilder(); gcb2.cacheContainer().statistics(true) .jmx().enabled(true).domain(JMX_DOMAIN + 2).mBeanServerLookup(mBeanServerLookup); CacheContainer cacheManager2 = TestCacheManagerFactory.createClusteredCacheManager(gcb2, defaultConfig, new TransportFlags()); TestingUtil.replaceComponent(cacheManager2, TimeService.class, timeService, true); cacheManager2.start(); registerCacheManager(cacheManager1, cacheManager2); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.REPL_SYNC).statistics().enable(); defineConfigurationOnAllManagers(cachename, cb); defineConfigurationOnAllManagers(cachename2, cb); waitForClusterToForm(cachename); } public void testClusterStats() throws Exception { Cache<String, Serializable> cache1 = manager(0).getCache(cachename); MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); ObjectName nodeStats = getCacheManagerObjectName(JMX_DOMAIN, "DefaultCacheManager", CacheContainerStats.OBJECT_NAME); mBeanServer.setAttribute(nodeStats, new Attribute("StatisticsEnabled", Boolean.TRUE)); cache1.put("a1", "b1"); cache1.put("a2", "b2"); cache1.put("a3", "b3"); cache1.put("a4", "b4"); assertAttributeValue(mBeanServer, nodeStats, "NumberOfEntries", 4); assertAttributeValue(mBeanServer, nodeStats, "Stores", 4); assertAttributeValue(mBeanServer, nodeStats, "Evictions", 0); assertAttributeValueGreaterThanOrEqual(mBeanServer, nodeStats, "AverageWriteTime", 0); cache1.remove("a1"); // Advance 1 second for the cached stats to expire timeService.advance(1000); assertAttributeValue(mBeanServer, nodeStats, "RemoveHits", 1); Cache<String, Serializable> cache3 = manager(0).getCache(cachename2); cache3.put("a10", "b1"); cache3.put("a11", "b2"); cache3.put("a12", "b3"); cache3.put("a13", "b4"); // Advance 1 second for the cached stats to expire timeService.advance(1000); assertAttributeValue(mBeanServer, nodeStats, "NumberOfEntries", 7); assertAttributeValue(mBeanServer, nodeStats, "Stores", 8); assertAttributeValue(mBeanServer, nodeStats, "Evictions", 0); assertAttributeValueGreaterThanOrEqual(mBeanServer, nodeStats, "AverageWriteTime", 0); } public void testClusterStatsDisabled() throws Exception { MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); ObjectName nodeStats = getCacheManagerObjectName(JMX_DOMAIN, "DefaultCacheManager", CacheContainerStats.OBJECT_NAME); mBeanServer.setAttribute(nodeStats, new Attribute("StatisticsEnabled", Boolean.FALSE)); assertAttributeValue(mBeanServer, nodeStats, "NumberOfEntries", -1); assertAttributeValue(mBeanServer, nodeStats, "AverageReadTime", -1); assertAttributeValue(mBeanServer, nodeStats, "AverageRemoveTime", -1); assertAttributeValue(mBeanServer, nodeStats, "AverageWriteTime", -1); assertAttributeValue(mBeanServer, nodeStats, "Stores", -1); assertAttributeValue(mBeanServer, nodeStats, "Evictions", -1); assertAttributeValue(mBeanServer, nodeStats, "Hits", -1); assertAttributeValue(mBeanServer, nodeStats, "Misses", -1); assertAttributeValue(mBeanServer, nodeStats, "RemoveHits", -1); } private void assertAttributeValue(MBeanServer mBeanServer, ObjectName oName, String attrName, long expectedValue) throws Exception { String receivedVal = mBeanServer.getAttribute(oName, attrName).toString(); assert Long.parseLong(receivedVal) == expectedValue : "expecting " + expectedValue + " for " + attrName + ", but received " + receivedVal; } private void assertAttributeValueGreaterThanOrEqual(MBeanServer mBeanServer, ObjectName oName, String attrName, long valueToCompare) throws Exception { String receivedVal = mBeanServer.getAttribute(oName, attrName).toString(); assert Long.parseLong(receivedVal) >= valueToCompare : "expecting " + receivedVal + " for " + attrName + ", to be greater than" + valueToCompare; } }
6,534
46.355072
116
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/AbstractClusterMBeanTest.java
package org.infinispan.jmx; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.commands.module.TestGlobalConfigurationBuilder; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.commons.time.ControlledTimeService; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; /** * @author Ryan Emerson * @since 9.0 */ abstract class AbstractClusterMBeanTest extends MultipleCacheManagersTest { final String jmxDomain1; final String jmxDomain2; final String jmxDomain3; final ControlledTimeService timeService = new ControlledTimeService(); protected final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); AbstractClusterMBeanTest(String clusterName) { this.jmxDomain1 = clusterName; this.jmxDomain2 = clusterName + "2"; this.jmxDomain3 = clusterName + "3"; } @Override protected void createCacheManagers() throws Throwable { createManager(jmxDomain1); createManager(jmxDomain2); createManager(jmxDomain3); waitForClusterToForm(getDefaultCacheName()); } private void createManager(String jmxDomain) { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.REPL_SYNC).statistics().enable(); GlobalConfigurationBuilder gcb = GlobalConfigurationBuilder.defaultClusteredBuilder(); gcb.cacheContainer().statistics(true) .metrics().accurateSize(true) .metrics().accurateSize(true) .jmx().enabled(true).domain(jmxDomain) .mBeanServerLookup(mBeanServerLookup) .serialization().addContextInitializer(TestDataSCI.INSTANCE); gcb.addModule(TestGlobalConfigurationBuilder.class) .testGlobalComponent(TimeService.class.getName(), timeService); addClusterEnabledCacheManager(gcb, cb); } void assertAttributeValue(MBeanServer mBeanServer, ObjectName oName, String attrName, double expectedValue) throws Exception { String receivedVal = mBeanServer.getAttribute(oName, attrName).toString(); assertEquals(expectedValue, Double.parseDouble(receivedVal)); } void assertAttributeValue(MBeanServer mBeanServer, ObjectName oName, String attrName, long expectedValue) throws Exception { String receivedVal = mBeanServer.getAttribute(oName, attrName).toString(); assertEquals(expectedValue, Long.parseLong(receivedVal)); } void assertAttributeValueGreaterThanOrEqualTo(MBeanServer mBeanServer, ObjectName oName, String attrName, long valueToCompare) throws Exception { String receivedVal = mBeanServer.getAttribute(oName, attrName).toString(); assertTrue(valueToCompare <= Long.parseLong(receivedVal)); } }
3,246
38.597561
110
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/TxInterceptorMBeanTest.java
package org.infinispan.jmx; import static org.infinispan.test.TestingUtil.getCacheObjectName; import static org.infinispan.test.fwk.TestCacheManagerFactory.configureJmx; import static org.testng.AssertJUnit.assertEquals; import javax.management.MBeanServer; import javax.management.ObjectName; import jakarta.transaction.TransactionManager; import org.infinispan.Cache; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.distribution.rehash.XAResourceAdapter; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; @Test(groups = "functional", testName = "jmx.TxInterceptorMBeanTest") public class TxInterceptorMBeanTest extends MultipleCacheManagersTest { private static final String JMX_DOMAIN = TxInterceptorMBeanTest.class.getSimpleName(); private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); private ObjectName txInterceptor; private ObjectName txInterceptor2; private TransactionManager tm; private Cache<String, String> cache1; private Cache<String, String> cache2; @Override protected void createCacheManagers() throws Throwable { GlobalConfigurationBuilder globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); configureJmx(globalBuilder, JMX_DOMAIN, mBeanServerLookup); EmbeddedCacheManager cacheManager1 = TestCacheManagerFactory.createClusteredCacheManager(globalBuilder, new ConfigurationBuilder()); registerCacheManager(cacheManager1); GlobalConfigurationBuilder globalBuilder2 = GlobalConfigurationBuilder.defaultClusteredBuilder(); globalBuilder2.cacheManagerName("SecondDefaultCacheManager"); configureJmx(globalBuilder2, JMX_DOMAIN + 2, mBeanServerLookup); EmbeddedCacheManager cacheManager2 = TestCacheManagerFactory.createClusteredCacheManager(globalBuilder2, new ConfigurationBuilder()); registerCacheManager(cacheManager2); ConfigurationBuilder configuration = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true); configuration.statistics().enable(); cacheManager1.defineConfiguration("test", configuration.build()); cacheManager2.defineConfiguration("test", configuration.build()); cache1 = cacheManager1.getCache("test"); cache2 = cacheManager2.getCache("test"); txInterceptor = getCacheObjectName(JMX_DOMAIN, "test(repl_sync)", "Transactions"); txInterceptor2 = getCacheObjectName(JMX_DOMAIN + 2, "test(repl_sync)", "Transactions", "SecondDefaultCacheManager"); tm = TestingUtil.getTransactionManager(cache1); } @AfterMethod public void resetStats() throws Exception { TestingUtil.getMBeanServer(cache1).invoke(txInterceptor, "resetStatistics", new Object[0], new String[0]); TestingUtil.getMBeanServer(cache2).invoke(txInterceptor2, "resetStatistics", new Object[0], new String[0]); } public void testJmxOperationMetadata() throws Exception { TestingUtil.checkMBeanOperationParameterNaming(TestingUtil.getMBeanServer(cache1), txInterceptor); } public void testCommit() throws Exception { assertCommitRollback(0, 0, cache1, txInterceptor); tm.begin(); //enlist another resource adapter to force TM to execute 2PC (otherwise 1PC) tm.getTransaction().enlistResource(new XAResourceAdapter()); assertCommitRollback(0, 0, cache1, txInterceptor); cache1.put("key", "value"); assertCommitRollback(0, 0, cache1, txInterceptor); tm.commit(); assertCommitRollback(1, 0, cache1, txInterceptor); } public void testRollback() throws Exception { assertCommitRollback(0, 0, cache1, txInterceptor); tm.begin(); assertCommitRollback(0, 0, cache1, txInterceptor); cache1.put("key", "value"); assertCommitRollback(0, 0, cache1, txInterceptor); tm.rollback(); assertCommitRollback(0, 1, cache1, txInterceptor); } public void testRemoteCommit() throws Exception { assertCommitRollback(0, 0, cache2, txInterceptor2); tm.begin(); assertCommitRollback(0, 0, cache2, txInterceptor2); //enlist another resource adapter to force TM to execute 2PC (otherwise 1PC) tm.getTransaction().enlistResource(new XAResourceAdapter()); cache2.put("key", "value"); assertCommitRollback(0, 0, cache2, txInterceptor2); tm.commit(); assertCommitRollback(1, 0, cache2, txInterceptor2); } public void testRemoteRollback() throws Exception { assertCommitRollback(0, 0, cache2, txInterceptor2); tm.begin(); assertCommitRollback(0, 0, cache2, txInterceptor2); cache2.put("key", "value"); assertCommitRollback(0, 0, cache2, txInterceptor2); tm.rollback(); assertCommitRollback(0, 1, cache2, txInterceptor2); } private void assertCommitRollback(int commit, int rollback, Cache<String, String> cache, ObjectName objectName) throws Exception { MBeanServer mBeanServer = TestingUtil.getMBeanServer(cache); Long commitCount = (Long) mBeanServer.getAttribute(objectName, "Commits"); assertEquals("expecting " + commit + " commits, received " + commitCount, commit, commitCount.intValue()); Long rollbackCount = (Long) mBeanServer.getAttribute(objectName, "Rollbacks"); assertEquals("expecting " + rollback + " rollbacks, received " + rollbackCount, rollback, rollbackCount.intValue()); } }
5,851
45.07874
139
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/CustomMBeanServerPropertiesTest.java
package org.infinispan.jmx; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.Properties; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "jmx.CustomMBeanServerPropertiesTest") public class CustomMBeanServerPropertiesTest extends AbstractInfinispanTest { public void testDeclarativeCustomMBeanServerLookupProperties() { String cfg = "<infinispan>" + "<cache-container default-cache=\"default\">" + "<jmx enabled=\"true\" mbean-server-lookup=\"" + TestLookup.class.getName() + "\">" + "<property name=\"key\">value</property>" + "</jmx>" + "<local-cache name=\"default\"/>" + "</cache-container>" + "</infinispan>"; InputStream stream = new ByteArrayInputStream(cfg.getBytes()); EmbeddedCacheManager cm = null; try { cm = TestCacheManagerFactory.fromStream(stream); cm.getCache(); MBeanServerLookup mbsl = cm.getCacheManagerConfiguration().jmx().mbeanServerLookup(); assertTrue(mbsl instanceof TestLookup); assertEquals("value", ((TestLookup) mbsl).props.get("key")); } finally { TestingUtil.killCacheManagers(cm); } } public void testProgrammaticCustomMBeanServerLookupProperties() { EmbeddedCacheManager cm = null; try { GlobalConfigurationBuilder gc = new GlobalConfigurationBuilder(); TestLookup mbsl = new TestLookup(); gc.jmx().enabled(true).mBeanServerLookup(mbsl).addProperty("key", "value"); ConfigurationBuilder cfg = new ConfigurationBuilder(); cm = TestCacheManagerFactory.createCacheManager(gc, cfg); cm.getCache(); assertEquals("value", mbsl.props.get("key")); } finally { TestingUtil.killCacheManagers(cm); } } public static final class TestLookup implements MBeanServerLookup { Properties props; private final MBeanServer mBeanServer = MBeanServerFactory.newMBeanServer(); @Override public MBeanServer getMBeanServer(Properties props) { this.props = props; return mBeanServer; } } }
2,774
35.513158
97
java
null
infinispan-main/core/src/test/java/org/infinispan/jmx/MvccLockManagerMBeanTest.java
package org.infinispan.jmx; import static org.infinispan.test.TestingUtil.checkMBeanOperationParameterNaming; import static org.infinispan.test.TestingUtil.getCacheObjectName; import javax.management.ObjectName; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.infinispan.transaction.tm.EmbeddedTransactionManager; import org.testng.annotations.Test; /** * Test the JMX functionality in {@link org.infinispan.util.concurrent.locks.LockManager}. * * @author Mircea.Markus@jboss.com * @author Galder Zamarreño */ @Test(groups = "functional", testName = "jmx.MvccLockManagerMBeanTest") public class MvccLockManagerMBeanTest extends SingleCacheManagerTest { private static final int CONCURRENCY_LEVEL = 129; private ObjectName lockManagerObjName; private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); private static final String JMX_DOMAIN = MvccLockManagerMBeanTest.class.getSimpleName(); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder configuration = getDefaultStandaloneCacheConfig(true); configuration .locking() .concurrencyLevel(CONCURRENCY_LEVEL) .useLockStriping(true) .transaction() .transactionManagerLookup(new EmbeddedTransactionManagerLookup()); GlobalConfigurationBuilder globalConfiguration = new GlobalConfigurationBuilder(); globalConfiguration .jmx().enabled(true) .domain(JMX_DOMAIN) .mBeanServerLookup(mBeanServerLookup); cacheManager = TestCacheManagerFactory.createCacheManager(globalConfiguration, configuration); cacheManager.defineConfiguration("test", configuration.build()); cache = cacheManager.getCache("test"); lockManagerObjName = getCacheObjectName(JMX_DOMAIN, "test(local)", "LockManager"); return cacheManager; } public void testJmxOperationMetadata() throws Exception { checkMBeanOperationParameterNaming(mBeanServerLookup.getMBeanServer(), lockManagerObjName); } public void testConcurrencyLevel() throws Exception { assertAttributeValue("ConcurrencyLevel", CONCURRENCY_LEVEL); } public void testNumberOfLocksHeld() throws Exception { EmbeddedTransactionManager tm = (EmbeddedTransactionManager) tm(); tm.begin(); cache.put("key", "value"); tm.getTransaction().runPrepare(); assertAttributeValue("NumberOfLocksHeld", 1); tm.getTransaction().runCommit(false); assertAttributeValue("NumberOfLocksHeld", 0); } public void testNumberOfLocksAvailable() throws Exception { EmbeddedTransactionManager tm = (EmbeddedTransactionManager) tm(); int initialAvailable = getAttrValue("NumberOfLocksAvailable"); tm.begin(); cache.put("key", "value"); tm.getTransaction().runPrepare(); assertAttributeValue("NumberOfLocksHeld", 1); assertAttributeValue("NumberOfLocksAvailable", initialAvailable - 1); tm.getTransaction().runCommit(true); assertAttributeValue("NumberOfLocksAvailable", initialAvailable); assertAttributeValue("NumberOfLocksHeld", 0); } private void assertAttributeValue(String attrName, int expectedVal) throws Exception { int cl = getAttrValue(attrName); assert cl == expectedVal : "expected " + expectedVal + ", but received " + cl; } private int getAttrValue(String attrName) throws Exception { return Integer.parseInt(mBeanServerLookup.getMBeanServer().getAttribute(lockManagerObjName, attrName).toString()); } }
4,046
39.878788
120
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/CacheListenerCacheLoaderTest.java
package org.infinispan.notifications; import java.util.Collections; import java.util.LinkedList; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryLoaded; import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryPassivatedEvent; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(groups = "functional", testName = "notifications.CacheListenerCacheLoaderTest") public class CacheListenerCacheLoaderTest extends AbstractInfinispanTest { EmbeddedCacheManager cm; @BeforeMethod public void setUp() { cm = TestCacheManagerFactory.createCacheManager(false); ConfigurationBuilder c = new ConfigurationBuilder(); c.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName("no_passivation"); cm.defineConfiguration("no_passivation", c.build()); c = new ConfigurationBuilder(); c.persistence().passivation(true).addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName("passivation"); cm.defineConfiguration("passivation", c.build()); } @AfterMethod public void tearDown() { TestingUtil.killCacheManagers(cm); cm = null; } public void testLoadingAndStoring() { Cache c = cm.getCache("no_passivation"); TestListener l = new TestListener(); c.addListener(l); assert l.loaded.isEmpty(); assert l.activated.isEmpty(); assert l.passivated.isEmpty(); c.put("k", "v"); assert l.loaded.isEmpty(); assert l.activated.isEmpty(); assert l.passivated.isEmpty(); c.evict("k"); assert l.loaded.isEmpty(); assert l.activated.isEmpty(); assert l.passivated.isEmpty(); c.remove("k"); assert l.loaded.contains("k"); assert l.loaded.size() == 1; assert l.activated.isEmpty(); assert l.passivated.isEmpty(); c.put("k", "v"); c.evict("k"); assert l.loaded.size() == 1; assert l.activated.isEmpty(); assert l.passivated.isEmpty(); c.putAll(Collections.singletonMap("k2", "v2")); assert l.loaded.size() == 1; assert l.activated.isEmpty(); assert l.passivated.isEmpty(); c.putAll(Collections.singletonMap("k", "v-new")); assert l.passivated.isEmpty(); assert l.loaded.size() == 1; assert l.activated.isEmpty(); c.clear(); assert l.passivated.isEmpty(); assert l.loaded.size() == 1; assert l.activated.isEmpty(); c.putAll(Collections.singletonMap("k2", "v-new")); c.evict("k2"); assert l.passivated.isEmpty(); assert l.loaded.size() == 1; assert l.activated.isEmpty(); c.replace("k2", "something"); assert l.passivated.isEmpty(); assert l.loaded.size() == 2; assert l.loaded.contains("k2"); assert l.activated.isEmpty(); } public void testActivatingAndPassivating() { Cache c = cm.getCache("passivation"); TestListener l = new TestListener(); c.addListener(l); assert l.loaded.isEmpty(); assert l.activated.isEmpty(); assert l.passivated.isEmpty(); c.put("k", "v"); assert l.loaded.isEmpty(); assert l.activated.isEmpty(); assert l.passivated.isEmpty(); c.evict("k"); assert l.loaded.isEmpty(); assert l.activated.isEmpty(); assert l.passivated.contains("k"); c.remove("k"); assert l.loaded.contains("k"); assert l.activated.contains("k"); assert l.passivated.contains("k"); // We should be fine if we evict a non existent key c.evict("k"); } @Listener static public class TestListener { List<Object> loaded = new LinkedList<Object>(); List<Object> activated = new LinkedList<Object>(); List<Object> passivated = new LinkedList<Object>(); @CacheEntryLoaded public void handleLoaded(CacheEntryEvent e) { if (e.isPre()) loaded.add(e.getKey()); } @CacheEntryActivated public void handleActivated(CacheEntryEvent e) { if (e.isPre()) activated.add(e.getKey()); } @CacheEntryPassivated public void handlePassivated(CacheEntryPassivatedEvent e) { if (e.isPre()) passivated.add(e.getKey()); } void reset() { loaded.clear(); activated.clear(); passivated.clear(); } } }
5,084
28.736842
94
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/MergeViewTest.java
package org.infinispan.notifications; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.notifications.cachemanagerlistener.annotation.Merged; import org.infinispan.notifications.cachemanagerlistener.event.MergeEvent; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TransportFlags; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.jgroups.protocols.DISCARD; import org.testng.annotations.Test; /** * @author Mircea.Markus@jboss.com */ @Test(groups = "functional", testName = "notifications.MergeViewTest") public class MergeViewTest extends MultipleCacheManagersTest { private static final Log log = LogFactory.getLog(MergeViewTest.class); private DISCARD discard; private MergeListener ml0; private MergeListener ml1; @Override protected void createCacheManagers() throws Throwable { addClusterEnabledCacheManager(getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true), new TransportFlags().withMerge(true)); ml0 = new MergeListener(); manager(0).addListener(ml0); discard = TestingUtil.getDiscardForCache(manager(0)); discard.discardAll(true); addClusterEnabledCacheManager(getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true), new TransportFlags().withMerge(true)); ml1 = new MergeListener(); manager(1).addListener(ml1); cache(0).put("k", "v0"); cache(1).put("k", "v1"); Thread.sleep(2000); assert advancedCache(0).getRpcManager().getTransport().getMembers().size() == 1; assert advancedCache(1).getRpcManager().getTransport().getMembers().size() == 1; } public void testMergeViewHappens() { discard.discardAll(false); TestingUtil.blockUntilViewsReceived(60000, cache(0), cache(1)); TestingUtil.waitForNoRebalance(cache(0), cache(1)); assert ml0.isMerged && ml1.isMerged; cache(0).put("k", "v2"); assertEquals(cache(0).get("k"), "v2"); assertEquals(cache(1).get("k"), "v2"); } @Listener public static class MergeListener { volatile boolean isMerged; @Merged public void viewMerged(MergeEvent vce) { log.info("vce = " + vce); isMerged = true; } } }
2,450
31.25
94
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/AsyncNotificationTest.java
package org.infinispan.notifications; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotSame; import java.util.concurrent.CompletionStage; import java.util.concurrent.CountDownLatch; import org.infinispan.Cache; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(groups = "functional", testName = "notifications.AsyncNotificationTest") public class AsyncNotificationTest extends AbstractInfinispanTest { Cache<String, String> c; EmbeddedCacheManager cm; @BeforeMethod public void setUp() { cm = TestCacheManagerFactory.createCacheManager(false); c = cm.getCache(); } @AfterMethod public void tearDown() { TestingUtil.killCacheManagers(cm); cm = null; c = null; } public void testAsyncNotification() throws InterruptedException { CountDownLatch latch = new CountDownLatch(3); AbstractListener nonBlockingListener = new NonBlockingListener(latch); AbstractListener syncListener = new SyncListener(latch); AbstractListener asyncListener = new AsyncListener(latch); c.addListener(nonBlockingListener); c.addListener(syncListener); c.addListener(asyncListener); c.put("k", "v"); latch.await(); Thread currentThread = Thread.currentThread(); assertEquals(currentThread, nonBlockingListener.caller); assertEquals(currentThread, syncListener.caller); assertNotSame(currentThread, asyncListener.caller); } public abstract static class AbstractListener { Thread caller; CountDownLatch latch; protected AbstractListener(CountDownLatch latch) { this.latch = latch; } } @Listener public static class NonBlockingListener extends AbstractListener { public NonBlockingListener(CountDownLatch latch) { super(latch); } @CacheEntryCreated public CompletionStage<Void> handle(CacheEntryCreatedEvent e) { if (e.isPre()) { caller = Thread.currentThread(); latch.countDown(); } return CompletableFutures.completedNull(); } } @Listener(sync = true) public static class SyncListener extends AbstractListener { public SyncListener(CountDownLatch latch) { super(latch); } @CacheEntryCreated public void handle(CacheEntryCreatedEvent e) { if (e.isPre()) { caller = Thread.currentThread(); latch.countDown(); } } } @Listener(sync = false) public static class AsyncListener extends AbstractListener { public AsyncListener(CountDownLatch latch) { super(latch); } @CacheEntryCreated public void handle(CacheEntryCreatedEvent e) { if (e.isPre()) { caller = Thread.currentThread(); latch.countDown(); } } } }
3,396
29.881818
79
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/DistListenerTest.java
package org.infinispan.notifications; import static org.testng.AssertJUnit.assertEquals; import java.util.List; import java.util.stream.IntStream; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged; import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent; import org.infinispan.remoting.transport.Address; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.Test; /** * Used to verify which nodes are going to receive events in case it's configured * as DIST: all key owners and the node which is performing the operation will receive * a notification. * * @author Sanne Grinovero &lt;sanne@hibernate.org&gt; (C) 2011 Red Hat Inc. * @since 5.0 */ @Test(groups = "functional", testName = "notifications.DistListenerTest") public class DistListenerTest extends MultipleCacheManagersTest { private TestListener listener; @Override protected void createCacheManagers() throws Throwable { createCluster(getDefaultClusteredCacheConfig( CacheMode.DIST_SYNC, true), 3); waitForClusterToForm(); } public void testRemoteGet() { final String key1 = this.getClass().getName() + "K1"; List<Address> owners = cacheTopology(0).getDistribution(key1).writeOwners(); assert owners.size() == 2: "Key should have 2 owners"; Cache<String, String> owner1 = getCacheForAddress(owners.get(0)); Cache<String, String> owner2 = getCacheForAddress(owners.get(1)); assert owner1 != owner2; Cache<String, String> nonOwner = null; for (int i=0; i<3; i++) { if (this.<String, String>cache(i) != owner1 && this.<String, String>cache(i) != owner2) { nonOwner = cache(i); break; } } assert nonOwner != null; listener = new TestListener(); // test owner puts and listens: assertCreated(false); assertModified(false); owner1.addListener(listener); owner1.put(key1, "hello"); assertModified(false); assertCreated(true); assertCreated(false); assertModified(false); owner1.put(key1, "hello"); assertModified(true); assertCreated(false); // now de-register: owner1.removeListener(listener); owner1.put(key1, "hello"); assertModified(false); assertCreated(false); // put on non-owner and listens on owner: owner1.addListener(listener); nonOwner.put(key1, "hello"); assertModified(true); assertCreated(false); owner1.removeListener(listener); assertModified(false); assertCreated(false); //listen on non-owner: nonOwner.addListener(listener); nonOwner.put(key1, "hello"); assertModified(false); assertCreated(false); //listen on non-owner non-putting: owner1.put(key1, "hello"); assertModified(false); assertCreated(false); } public void testRehashNoEvent() { listener = new TestListener(); caches().forEach(c -> { c.addListener(listener); c.getCacheManager().addListener(listener); }); // Insert some values IntStream.range(0, 10).boxed().forEach(i -> cache(0).put(i, i)); assertCreated(true); assertModified(false); assertViewChanged(false); // Now add a new node and shutdown createClusteredCaches(1, getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true)); killMember(cacheManagers.size() - 1); // We shouldn't have any events still... assertCreated(false); assertModified(false); assertViewChanged(true); } private void assertCreated(boolean b) { assertEquals(b, listener.created); listener.created = false; } private void assertModified(boolean b) { assertEquals(b, listener.modified); listener.modified = false; } private void assertViewChanged(boolean b) { assertEquals(b, listener.viewChanged); listener.viewChanged = false; } private <K, V> Cache<K, V> getCacheForAddress(Address a) { for (Cache<K, V> c: this.<K, V>caches()) if (c.getAdvancedCache().getRpcManager().getAddress().equals(a)) return c; return null; } @Listener static public class TestListener { boolean created = false; boolean modified = false; boolean viewChanged = false; @CacheEntryCreated @SuppressWarnings("unused") public void create(CacheEntryEvent e) { created = true; } @CacheEntryModified @SuppressWarnings("unused") public void modify(CacheEntryEvent e) { modified = true; } @ViewChanged @SuppressWarnings("unused") public void viewChanged(ViewChangedEvent e) { viewChanged = true; } } }
5,176
29.098837
90
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/CacheListenerRemovalTest.java
package org.infinispan.notifications; import static org.testng.AssertJUnit.assertEquals; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.Cache; import org.infinispan.manager.CacheContainer; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author Manik Surtani */ @Test(groups = "functional", testName = "notifications.CacheListenerRemovalTest") public class CacheListenerRemovalTest extends AbstractInfinispanTest { Cache<String, String> cache; CacheContainer cm; @BeforeMethod public void setUp() { cm = TestCacheManagerFactory.createCacheManager(false); cache = cm.getCache(); } @AfterMethod public void tearDown() { TestingUtil.killCacheManagers(cm); cm = null; cache = null; } public void testListenerRemoval() { cache.put("x", "y"); AtomicInteger i = new AtomicInteger(0); int listenerSize = cache.getListeners().size(); CacheListener l = new CacheListener(i); cache.addListener(l); assertEquals(listenerSize + 1, cache.getListeners().size()); assert cache.getListeners().contains(l); assert 0 == i.get(); cache.get("x"); assert 1 == i.get(); // remove the replListener cache.removeListener(l); assertEquals(listenerSize, cache.getListeners().size()); i.set(0); assert 0 == i.get(); cache.get("x"); assert 0 == i.get(); } @Listener public static class CacheListener { AtomicInteger i; private CacheListener(AtomicInteger i) { this.i = i; } @CacheEntryVisited public void listen(Event e) { if (e.isPre()) i.incrementAndGet(); } } }
2,069
26.972973
81
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/ConcurrentNotificationTest.java
package org.infinispan.notifications; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.Cache; import org.infinispan.manager.CacheContainer; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(groups = {"functional", "smoke"}, testName = "notifications.ConcurrentNotificationTest") public class ConcurrentNotificationTest extends AbstractInfinispanTest { Cache<String, String> cache; CacheContainer cm; CacheListener listener; Log log = LogFactory.getLog(ConcurrentNotificationTest.class); @BeforeMethod public void setUp() { cm = TestCacheManagerFactory.createCacheManager(false); cache = cm.getCache(); listener = new CacheListener(); cache.addListener(listener); } @AfterMethod public void tearDown() { TestingUtil.killCacheManagers(cm); cm = null; cache = null; listener = null; } public void testThreads() throws Exception { Thread workers[] = new Thread[20]; final List<Exception> exceptions = new LinkedList<Exception>(); final int loops = 100; final CountDownLatch latch = new CountDownLatch(1); for (int i = 0; i < workers.length; i++) { workers[i] = new Thread() { @Override public void run() { try { latch.await(); } catch (InterruptedException e) { } for (int j = 0; j < loops; j++) { try { cache.put("key", "value"); } catch (Exception e) { exceptions.add(new Exception("Caused on thread " + getName() + " in loop " + j + " when doing a put()", e)); } try { cache.remove("key"); } catch (Exception e) { exceptions.add(new Exception("Caused on thread " + getName() + " in loop " + j + " when doing a remove()", e)); } try { cache.get("key"); } catch (Exception e) { log.error("Exception received!", e); exceptions.add(new Exception("Caused on thread " + getName() + " in loop " + j + " when doing a get()", e)); } } } }; workers[i].start(); } latch.countDown(); for (Thread t : workers) t.join(); for (Exception e : exceptions) throw e; // we cannot ascertain the exact number of invocations on the replListener since some removes would mean that other // gets would miss. And this would cause no notification to fire for that get. And we cannot be sure of the // timing between removes and gets, so we just make sure *some* of these have got through, and no exceptions // were thrown due to concurrent access. assert loops * workers.length < listener.counter.get(); } @Listener static public class CacheListener { private AtomicInteger counter = new AtomicInteger(0); @CacheEntryModified @CacheEntryRemoved @CacheEntryVisited @CacheEntryCreated public void catchEvent(Event e) { if (e.isPre()) counter.getAndIncrement(); } } }
4,164
33.421488
132
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/CacheNotifierImplInitialTransferReplTest.java
package org.infinispan.notifications.cachelistener; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.Test; @Test(groups = "unit", testName = "notifications.cachelistener.CacheNotifierImplInitialTransferReplTest") public class CacheNotifierImplInitialTransferReplTest extends BaseCacheNotifierImplInitialTransferTest { protected CacheNotifierImplInitialTransferReplTest() { super(CacheMode.REPL_SYNC); } }
454
34
105
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/CacheNotifierInvalidationTest.java
package org.infinispan.notifications.cachelistener; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.Event.Type; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.Test; /** * Simple test class that tests to make sure invalidation events are raised on remote * nodes * * @author wburns * @since 4.0 */ @Test(groups = "functional", testName = "notifications.cachelistener.CacheNotifierInvalidationTest") public class CacheNotifierInvalidationTest extends MultipleCacheManagersTest { protected final String CACHE_NAME = "testCache"; protected ConfigurationBuilder builderUsed; @Override protected void createCacheManagers() throws Throwable { builderUsed = new ConfigurationBuilder(); builderUsed.clustering().cacheMode(CacheMode.INVALIDATION_SYNC); createClusteredCaches(3, CACHE_NAME, builderUsed); } @Listener private static class AllCacheEntryListener { private final List<CacheEntryEvent> events = Collections.synchronizedList( new ArrayList<CacheEntryEvent>()); @CacheEntryVisited @CacheEntryActivated @CacheEntryModified @CacheEntryRemoved @CacheEntryCreated @CacheEntryInvalidated @CacheEntryPassivated public void listenEvent(CacheEntryEvent event) { events.add(event); } } /** * Basic test to ensure that a remote node's is notified of invalidation */ @Test public void testRemoteNodeValueInvalidated() { String key = "key"; String value = "value"; Cache<String, String> cache0 = cache(0, CACHE_NAME); cache0.put(key, value); AllCacheEntryListener listener = new AllCacheEntryListener(); cache0.addListener(listener); String value2 = "value2"; // Now update the key which will invalidate cache0's key cache(1, CACHE_NAME).put(key, value2); assertEquals(2, listener.events.size()); CacheEntryEvent event = listener.events.get(0); assertEquals(Type.CACHE_ENTRY_INVALIDATED, event.getType()); assertEquals(key, event.getKey()); assertEquals(value, event.getValue()); assertTrue(event.isPre()); assertFalse(event.isOriginLocal()); event = listener.events.get(1); assertEquals(Type.CACHE_ENTRY_INVALIDATED, event.getType()); assertEquals(key, event.getKey()); assertEquals(value, event.getValue()); assertFalse(event.isPre()); assertFalse(event.isOriginLocal()); } }
3,570
35.814433
100
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/DuplicatedEventsTest.java
package org.infinispan.notifications.cachelistener; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.util.LinkedList; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.Test; /** * ISPN-3354 * * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "notifications.cachelistener.DuplicatedEventsTest") public class DuplicatedEventsTest extends MultipleCacheManagersTest { public void testNonDuplicate() { final Cache<String, String> cacheA = cache(0); final Cache<String, String> cacheB = cache(1); final MyCacheListener listenerA = new MyCacheListener(); cacheA.addListener(listenerA); final MyCacheListener listenerB = new MyCacheListener(); cacheB.addListener(listenerB); cacheA.put("a", "a"); /* * We expect 2 events on both nodes: pre-create, post-create */ assertEquals(2, listenerA.events.size()); assertEquals(2, listenerB.events.size()); checkEvents(listenerA, "a"); checkEvents(listenerB, "a"); /* * So far so good, let's try another key, say "b" */ listenerA.events.clear(); listenerB.events.clear(); cacheA.put("b", "b"); /* * We expect 2 events again */ assertEquals(2, listenerA.events.size()); assertEquals(2, listenerB.events.size()); checkEvents(listenerA, "b"); checkEvents(listenerB, "b"); /* * Let's try another one, say "a0" */ listenerA.events.clear(); listenerB.events.clear(); cacheA.put("a0", "a0"); /* * We expect another 2 events */ assertEquals(2, listenerA.events.size()); assertEquals(2, listenerB.events.size()); checkEvents(listenerA, "a0"); checkEvents(listenerB, "a0"); } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); builder.clustering().hash().numSegments(60); createClusteredCaches(2, builder); } private void checkEvents(MyCacheListener listener, String expectedKey) { assertTrue(listener.events.get(0) instanceof CacheEntryCreatedEvent); assertEquals(expectedKey, listener.events.get(0).getKey()); assertTrue(listener.events.get(0).isPre()); assertTrue(listener.events.get(1) instanceof CacheEntryCreatedEvent); assertEquals(expectedKey, listener.events.get(1).getKey()); assertFalse(listener.events.get(1).isPre()); } @Listener public class MyCacheListener { private List<CacheEntryEvent<String, String>> events = new LinkedList<CacheEntryEvent<String, String>>(); @CacheEntryCreated public void created(CacheEntryCreatedEvent<String, String> event) { events.add(event); } @CacheEntryModified public void modified(CacheEntryModifiedEvent<String, String> event) { events.add(event); } @CacheEntryRemoved public void removed(CacheEntryRemovedEvent<String, String> event) { events.add(event); } } }
4,038
30.310078
111
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/BaseCacheNotifierImplInitialTransferTest.java
package org.infinispan.notifications.cachelistener; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.infinispan.cache.impl.EncoderCache; import org.infinispan.commands.CommandsFactory; import org.infinispan.commons.marshall.StreamingMarshaller; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.entries.ImmortalCacheEntry; import org.infinispan.container.entries.TransientMortalCacheEntry; import org.infinispan.container.impl.InternalEntryFactoryImpl; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.NonTxInvocationContext; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.encoding.DataConversion; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.KnownComponentNames; import org.infinispan.factories.impl.BasicComponentRegistry; import org.infinispan.factories.impl.MockBasicComponentRegistry; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.cluster.ClusterEventManager; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.notifications.cachelistener.filter.CacheEventConverter; import org.infinispan.notifications.cachelistener.filter.CacheEventFilter; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.reactive.publisher.impl.ClusterPublisherManager; import org.infinispan.reactive.publisher.impl.Notifications; import org.infinispan.reactive.publisher.impl.SegmentPublisherSupplier; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.util.concurrent.BlockingManager; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.WithinThreadExecutor; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.reactivestreams.Publisher; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; @Test(groups = "unit", testName = "notifications.cachelistener.BaseCacheNotifierImplInitialTransferTest") public abstract class BaseCacheNotifierImplInitialTransferTest extends AbstractInfinispanTest { CacheNotifierImpl n; EncoderCache mockCache; InvocationContext ctx; ClusterPublisherManager mockPublisherManager; protected CacheMode cacheMode; protected BaseCacheNotifierImplInitialTransferTest(CacheMode mode) { if (mode.isDistributed()) { throw new IllegalArgumentException("This test only works with non distributed cache modes"); } this.cacheMode = mode; } private enum Operation { PUT(Event.Type.CACHE_ENTRY_MODIFIED) { @Override public void raiseEvent(CacheNotifier notifier, Object key, Object prevValue, Object newValue, InvocationContext ctx) { notifier.notifyCacheEntryModified(key, newValue, null, prevValue, null, true, ctx, null); notifier.notifyCacheEntryModified(key, newValue, null, prevValue, null, false, ctx, null); } }, REMOVE(Event.Type.CACHE_ENTRY_REMOVED) { @Override public void raiseEvent(CacheNotifier notifier, Object key, Object prevValue, Object newValue, InvocationContext ctx) { notifier.notifyCacheEntryRemoved(key, prevValue, null, true, ctx, null); notifier.notifyCacheEntryRemoved(key, prevValue, null, false, ctx, null); } }, CREATE(Event.Type.CACHE_ENTRY_CREATED) { @Override public void raiseEvent(CacheNotifier notifier, Object key, Object prevValue, Object newValue, InvocationContext ctx) { notifier.notifyCacheEntryCreated(key, newValue, null, true, ctx, null); notifier.notifyCacheEntryCreated(key, newValue, null, false, ctx, null); } }; private final Event.Type type; Operation(Event.Type type) { this.type = type; } public Event.Type getType() { return type; } public abstract void raiseEvent(CacheNotifier notifier, Object key, Object prevValue, Object newValue, InvocationContext ctx); } @BeforeMethod public void setUp() { n = new CacheNotifierImpl(); mockCache = mock(EncoderCache.class); EmbeddedCacheManager cacheManager = mock(EmbeddedCacheManager.class); when(mockCache.getCacheManager()).thenReturn(cacheManager); when(mockCache.getAdvancedCache()).thenReturn(mockCache); when(mockCache.getKeyDataConversion()).thenReturn(DataConversion.IDENTITY_KEY); when(mockCache.getValueDataConversion()).thenReturn(DataConversion.IDENTITY_VALUE); Configuration config = new ConfigurationBuilder().clustering().cacheMode(cacheMode).build(); GlobalConfiguration globalConfig = GlobalConfigurationBuilder.defaultClusteredBuilder().build(); when(mockCache.getStatus()).thenReturn(ComponentStatus.INITIALIZING); mockPublisherManager = mock(ClusterPublisherManager.class); ComponentRegistry componentRegistry = mock(ComponentRegistry.class); when(mockCache.getComponentRegistry()).thenReturn(componentRegistry); MockBasicComponentRegistry mockRegistry = new MockBasicComponentRegistry(); when(componentRegistry.getComponent(BasicComponentRegistry.class)).thenReturn(mockRegistry); mockRegistry.registerMocks(RpcManager.class, CommandsFactory.class); mockRegistry.registerMock(KnownComponentNames.INTERNAL_MARSHALLER, StreamingMarshaller.class); ClusteringDependentLogic.LocalLogic cdl = new ClusteringDependentLogic.LocalLogic(); cdl.init(null, config, mock(KeyPartitioner.class)); ClusterEventManager cem = mock(ClusterEventManager.class); when(cem.sendEvents(any())).thenReturn(CompletableFutures.completedNull()); BlockingManager handler = mock(BlockingManager.class); when(handler.continueOnNonBlockingThread(any(), any())).thenReturn(CompletableFutures.completedNull()); TestingUtil.inject(n, mockCache, cdl, config, globalConfig, mockRegistry, mockPublisherManager, new InternalEntryFactoryImpl(), cem, mock(KeyPartitioner.class), handler, TestingUtil.named(KnownComponentNames.ASYNC_NOTIFICATION_EXECUTOR, new WithinThreadExecutor())); n.start(); ctx = new NonTxInvocationContext(null); } // TODO: commented out until local listners support includeCurrentState // public void testSimpleCacheStartingNonClusterListener() { // testSimpleCacheStarting(new StateListenerNotClustered()); // } public void testSimpleCacheStartingClusterListener() { testSimpleCacheStarting(new StateListenerClustered()); } private void testSimpleCacheStarting(final StateListener<String, String> listener) { final List<CacheEntry<String, String>> initialValues = new ArrayList<>(10); for (int i = 0; i < 10; i++) { String key = "key-" + i; String value = "value-" + i; initialValues.add(new ImmortalCacheEntry(key, value)); } when(mockPublisherManager.entryPublisher(any(), any(), any(), anyLong(), any(), anyInt(), any())) .thenReturn(wrapCompletionPublisher(Flowable.fromIterable(initialValues))); n.addListener(listener); verifyEvents(isClustered(listener), listener, initialValues); } public void testFilterConverterUnusedDuringIteration() { testFilterConverterUnusedDuringIteration(new StateListenerClustered()); } private void testFilterConverterUnusedDuringIteration(final StateListener<String, String> listener) { final List<CacheEntry<String, String>> initialValues = new ArrayList<CacheEntry<String, String>>(10); for (int i = 0; i < 10; i++) { String key = "key-" + i; String value = "value-" + i; initialValues.add(new ImmortalCacheEntry(key, value)); } // Note we don't actually use the filter/converter to retrieve values since it is being mocked, thus we can assert // the filter/converter are not used by us when(mockPublisherManager.entryPublisher(any(), any(), any(), anyLong(), any(), anyInt(), any())) .thenReturn(wrapCompletionPublisher(Flowable.fromIterable(initialValues))); CacheEventFilter filter = mock(CacheEventFilter.class, withSettings().serializable()); CacheEventConverter converter = mock(CacheEventConverter.class, withSettings().serializable()); n.addListener(listener, filter, converter); verifyEvents(isClustered(listener), listener, initialValues); verify(filter, never()).accept(any(), any(), any(Metadata.class), any(), any(Metadata.class), any(EventType.class)); verify(converter, never()).convert(any(), any(), any(Metadata.class), any(), any(Metadata.class), any(EventType.class)); } public void testMetadataAvailable() { final List<CacheEntry<String, String>> initialValues = new ArrayList<>(10); for (int i = 0; i < 10; i++) { String key = "key-" + i; String value = "value-" + i; initialValues.add(new TransientMortalCacheEntry(key, value, i, -1, System.currentTimeMillis())); } // Note we don't actually use the filter/converter to retrieve values since it is being mocked, thus we can assert // the filter/converter are not used by us when(mockPublisherManager.entryPublisher(any(), any(), any(), anyLong(), any(), anyInt(), any())) .thenReturn(wrapCompletionPublisher(Flowable.fromIterable(initialValues))); CacheEventFilter filter = mock(CacheEventFilter.class, withSettings().serializable()); CacheEventConverter converter = mock(CacheEventConverter.class, withSettings().serializable()); StateListener<String, String> listener = new StateListenerClustered(); n.addListener(listener, filter, converter); verifyEvents(isClustered(listener), listener, initialValues); for (CacheEntryEvent<String, String> event : listener.events) { String key = event.getKey(); Metadata metadata = event.getMetadata(); assertNotNull(metadata); assertEquals(metadata.lifespan(), -1); assertEquals(metadata.maxIdle(), Long.parseLong(key.substring(4))); } } private void verifyEvents(boolean isClustered, StateListener<String, String> listener, List<CacheEntry<String, String>> expected) { assertEquals(listener.events.size(), isClustered ? expected.size() : expected.size() * 2); int eventPosition = 0; for (CacheEntryEvent<String, String> event : listener.events) { // Even checks means it will be post and have a value - note we force every check to be // even for clustered since those should always be post int position; boolean isPost; if (isClustered) { isPost = true; position = eventPosition; } else { isPost = (eventPosition & 1) == 1; position = eventPosition / 2; } assertEquals(event.getType(), Event.Type.CACHE_ENTRY_CREATED); assertEquals(event.getKey(), expected.get(position).getKey()); assertEquals(event.isPre(), !isPost); if (isPost) { assertEquals(event.getValue(), expected.get(position).getValue()); } else { assertNull(event.getValue()); } eventPosition++; } } // TODO: commented out until local listners support includeCurrentState // public void testCreateAfterIterationBeganButNotIteratedValueYetNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { // testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerNotClustered(), Operation.CREATE); // } public void testCreateAfterIterationBeganButNotIteratedValueYetClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerClustered(), Operation.CREATE); } // TODO: commented out until local listners support includeCurrentState // public void testRemoveAfterIterationBeganButNotIteratedValueYetNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { // testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerNotClustered(), Operation.REMOVE); // } public void testRemoveAfterIterationBeganButNotIteratedValueYetClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerClustered(), Operation.REMOVE); } // TODO: commented out until local listners support includeCurrentState // public void testModificationAfterIterationBeganButNotIteratedValueYetNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { // testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerNotClustered(), Operation.PUT); // } public void testModificationAfterIterationBeganButNotIteratedValueYetClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerClustered(), Operation.PUT); } /** * This test is to verify that the modification event replaces the current value for the key */ private void testModificationAfterIterationBeganButNotIteratedValueYet(final StateListener<String, String> listener, Operation operation) throws InterruptedException, TimeoutException, BrokenBarrierException, ExecutionException { final List<CacheEntry<String, String>> initialValues = new ArrayList<>(); for (int i = 0; i < 10; i++) { String key = "key-" + i; String value = "value-" + i; initialValues.add(new ImmortalCacheEntry(key, value)); } final CyclicBarrier barrier = new CyclicBarrier(2); when(mockPublisherManager.entryPublisher(any(), any(), any(), anyLong(), any(), anyInt(), any())) .thenReturn(wrapCompletionPublisher(Flowable.defer(() -> { barrier.await(10, TimeUnit.SECONDS); barrier.await(10, TimeUnit.SECONDS); return Flowable.fromIterable(initialValues); }))); Future<Void> future = fork(() -> { n.addListener(listener); return null; }); barrier.await(10, TimeUnit.SECONDS); log.debugf("Synced with publisher, performing operation"); String prevValue = initialValues.get(3).getValue(); switch (operation) { case REMOVE: String key = "key-3"; n.notifyCacheEntryRemoved(key, prevValue, null, true, ctx, null); n.notifyCacheEntryRemoved(key, prevValue, null, false, ctx, null); // We shouldn't see the event at all now! initialValues.remove(3); break; case CREATE: key = "new-key"; String value = "new-value"; n.notifyCacheEntryCreated(key, value, null, true, ctx, null); n.notifyCacheEntryCreated(key, value, null, false, ctx, null); // Need to add a new value to the end initialValues.add(new ImmortalCacheEntry(key, value)); break; case PUT: key = "key-3"; value = "value-3-changed"; n.notifyCacheEntryModified(key, value, null, prevValue, null, true, ctx, null); n.notifyCacheEntryModified(key, value, null, prevValue, null, false, ctx, null); // Now remove the old value and put in the new one initialValues.remove(3); initialValues.add(3, new ImmortalCacheEntry(key, value)); break; default: throw new IllegalArgumentException("Unsupported Operation provided " + operation); } log.debugf("Operation done, let the iteration complete"); barrier.await(10, TimeUnit.SECONDS); future.get(10, TimeUnit.MINUTES); verifyEvents(isClustered(listener), listener, initialValues); } // TODO: commented out until local listners support includeCurrentState // public void testCreateAfterIterationBeganAndIteratedValueNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { // testModificationAfterIterationBeganAndIteratedValue(new StateListenerNotClustered(), Operation.CREATE); // } public void testCreateAfterIterationBeganAndIteratedValueClustered() throws Exception { testModificationAfterIterationBeganAndIteratedValue(new StateListenerClustered(), Operation.CREATE); } // TODO: commented out until local listners support includeCurrentState // public void testRemoveAfterIterationBeganAndIteratedValueNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { // testModificationAfterIterationBeganAndIteratedValue(new StateListenerNotClustered(), Operation.REMOVE); // } public void testRemoveAfterIterationBeganAndIteratedValueClustered() throws Exception { testModificationAfterIterationBeganAndIteratedValue(new StateListenerClustered(), Operation.REMOVE); } // TODO: commented out until local listners support includeCurrentState // public void testModificationAfterIterationBeganAndIteratedValueNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { // testModificationAfterIterationBeganAndIteratedValue(new StateListenerNotClustered(), Operation.PUT); // } public void testModificationAfterIterationBeganAndIteratedValueClustered() throws Exception { testModificationAfterIterationBeganAndIteratedValue(new StateListenerClustered(), Operation.PUT); } /** * This test is to verify that the modification event is sent after the creation event is done */ private void testModificationAfterIterationBeganAndIteratedValue(final StateListener<String, String> listener, Operation operation) throws Exception { final List<CacheEntry<String, String>> initialValues = new ArrayList<CacheEntry<String, String>>(); for (int i = 0; i < 10; i++) { String key = "key-" + i; String value = "value-" + i; initialValues.add(new ImmortalCacheEntry(key, value)); } final CyclicBarrier barrier = new CyclicBarrier(2); when(mockPublisherManager.entryPublisher(any(), any(), any(), anyLong(), any(), anyInt(), any())) .thenReturn(wrapCompletionPublisher(Flowable.fromIterable(initialValues) .doOnComplete(() -> { barrier.await(10, TimeUnit.SECONDS); barrier.await(10, TimeUnit.SECONDS); }))); Future<Void> future = fork(() -> { n.addListener(listener); return null; }); barrier.await(10, TimeUnit.SECONDS); String key; String prevValue; String value; switch (operation) { case REMOVE: key = "key-3"; value = null; prevValue = initialValues.get(3).getValue(); break; case CREATE: key = "new-key"; value = "new-value"; prevValue = null; break; case PUT: key = "key-3"; value = "key-3-new"; prevValue = initialValues.get(3).getValue(); break; default: throw new IllegalArgumentException("Unsupported Operation provided " + operation); } operation.raiseEvent(n, key, prevValue, value, ctx); // Now let the iteration complete barrier.await(10, TimeUnit.SECONDS); future.get(10, TimeUnit.MINUTES); boolean isClustered = isClustered(listener); // We should have 1 or 2 (local) events due to the modification coming after we iterated on it. Note the value // isn't brought up until the iteration is done assertEquals(listener.events.size(), isClustered ? initialValues.size() + 1 : (initialValues.size() + 1) * 2); int position = 0; for (CacheEntry<String, String> expected : initialValues) { if (isClustered) { CacheEntryEvent<String, String> event = listener.events.get(position); assertEquals(event.getType(), Event.Type.CACHE_ENTRY_CREATED); assertEquals(event.isPre(), false); assertEquals(event.getKey(), expected.getKey()); assertEquals(event.getValue(), expected.getValue()); } else { CacheEntryEvent<String, String> event = listener.events.get(position * 2); assertEquals(event.getType(), Event.Type.CACHE_ENTRY_CREATED); assertEquals(event.isPre(), true); assertEquals(event.getKey(), expected.getKey()); assertNull(event.getValue()); event = listener.events.get((position * 2) + 1); assertEquals(event.getType(), Event.Type.CACHE_ENTRY_CREATED); assertEquals(event.isPre(), false); assertEquals(event.getKey(), expected.getKey()); assertEquals(event.getValue(), expected.getValue()); } position++; } // We should have 2 extra events at the end which are our modifications if (isClustered) { CacheEntryEvent<String, String> event = listener.events.get(position); assertEquals(event.getType(), operation.getType()); assertEquals(event.isPre(), false); assertEquals(event.getKey(), key); assertEquals(event.getValue(), value); } else { CacheEntryEvent<String, String> event = listener.events.get(position * 2); assertEquals(event.getType(), operation.getType()); assertEquals(event.isPre(), true); assertEquals(event.getKey(), key); assertEquals(event.getValue(), prevValue); event = listener.events.get((position * 2) + 1); assertEquals(event.getType(), operation.getType()); assertEquals(event.isPre(), false); assertEquals(event.getKey(), key); assertEquals(event.getValue(), value); } } private boolean isClustered(StateListener listener) { return listener.getClass().getAnnotation(Listener.class).clustered(); } protected static abstract class StateListener<K, V> { final List<CacheEntryEvent<K, V>> events = new ArrayList<>(); private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); @CacheEntryCreated @CacheEntryModified @CacheEntryRemoved public synchronized void onCacheNotification(CacheEntryEvent<K, V> event) { log.tracef("Received event: %s", event); events.add(event); } } @Listener(includeCurrentState = true, clustered = false) private static class StateListenerNotClustered extends StateListener { } @Listener(includeCurrentState = true, clustered = true) private static class StateListenerClustered extends StateListener { } private SegmentPublisherSupplier<CacheEntry<String, String>> wrapCompletionPublisher( Flowable<CacheEntry<String, String>> flowable) { return new SegmentPublisherSupplier<CacheEntry<String, String>>() { @Override public Publisher<CacheEntry<String, String>> publisherWithoutSegments() { return flowable; } @Override public Publisher<Notification<CacheEntry<String, String>>> publisherWithSegments() { // This may need to be changed if a test requires the actual segment return flowable.map(entry -> (Notification<CacheEntry<String, String>>) Notifications.value(entry, 0)) .concatWith(Single.just(Notifications.segmentComplete(0))); } }; } }
26,264
45.486726
123
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/CacheNotifierTest.java
package org.infinispan.notifications.cachelistener; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.hamcrest.MockitoHamcrest.argThat; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.hamcrest.CustomTypeSafeMatcher; import org.hamcrest.Matcher; import org.infinispan.Cache; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.write.PutMapCommand; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.metadata.Metadata; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test(groups = "functional", testName = "notifications.cachelistener.CacheNotifierTest") public class CacheNotifierTest extends AbstractInfinispanTest { protected Cache<Object, Object> cache; protected EmbeddedCacheManager cm; @BeforeMethod public void setUp() throws Exception { ConfigurationBuilder c = new ConfigurationBuilder(); c .transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL) .clustering().cacheMode(CacheMode.LOCAL) .locking().isolationLevel(IsolationLevel.REPEATABLE_READ); cm = TestCacheManagerFactory.createCacheManager(c); cache = getCache(); CacheNotifier mockNotifier = mock(CacheNotifier.class, i -> CompletableFutures.completedNull()); doReturn(true).when(mockNotifier).hasListener(any()); TestingUtil.replaceComponent(cache, CacheNotifier.class, mockNotifier, true); } protected Cache<Object, Object> getCache() { return cm.getCache(); } @AfterMethod public void tearDown() throws Exception { TestingUtil.killCaches(cache); cm.stop(); } @AfterClass public void destroyManager() { TestingUtil.killCacheManagers(cache.getCacheManager()); } private CacheNotifier getMockNotifier(Cache cache) { return cache.getAdvancedCache().getComponentRegistry().getComponent(CacheNotifier.class); } protected Matcher<FlagAffectedCommand> getFlagMatcher() { Matcher<FlagAffectedCommand> flagAffectedCommandMatcher = new CustomTypeSafeMatcher<FlagAffectedCommand>("SKIP_LISTENER_NOTIFICATION") { @Override protected boolean matchesSafely(FlagAffectedCommand item) { return !item.hasAnyFlag(FlagBitSets.SKIP_LISTENER_NOTIFICATION); } }; return flagAffectedCommandMatcher; } public void testVisit() throws Exception { Matcher<FlagAffectedCommand> matcher = getFlagMatcher(); initCacheData(cache, Collections.singletonMap("key", "value")); cache.get("key"); verify(getMockNotifier(cache)).notifyCacheEntryVisited(eq("key"), eq("value"), eq(true), isA(InvocationContext.class), argThat(matcher)); verify(getMockNotifier(cache)).notifyCacheEntryVisited(eq("key"), eq("value"), eq(false), isA(InvocationContext.class), argThat(matcher)); } public void testRemoveData() throws Exception { Matcher<FlagAffectedCommand> matcher = getFlagMatcher(); Map<String, String> data = new HashMap<>(); data.put("key", "value"); data.put("key2", "value2"); initCacheData(cache, data); cache.remove("key2"); verify(getMockNotifier(cache)).notifyCacheEntryRemoved(eq("key2"), eq("value2"), any(Metadata.class), eq(true), isA(InvocationContext.class), argThat(matcher)); verify(getMockNotifier(cache)).notifyCacheEntryRemoved(eq("key2"), eq("value2"), any(Metadata.class), eq(false), isA(InvocationContext.class), argThat(matcher)); } public void testPutMap() throws Exception { Matcher<FlagAffectedCommand> matcher = getFlagMatcher(); Map<Object, Object> data = new HashMap<Object, Object>(); data.put("key", "value"); data.put("key2", "value2"); cache.putAll(data); expectSingleEntryCreated(cache, "key", "value", matcher); expectSingleEntryCreated(cache, "key2", "value2", matcher); } public void testOnlyModification() throws Exception { Matcher<FlagAffectedCommand> matcher = getFlagMatcher(); initCacheData(cache, Collections.singletonMap("key", "value")); cache.put("key", "value2"); verify(getMockNotifier(cache)).notifyCacheEntryModified(eq("key"), eq("value2"), any(Metadata.class), eq("value"), any(Metadata.class), eq(true), isA(InvocationContext.class), argThat(matcher)); verify(getMockNotifier(cache)).notifyCacheEntryModified(eq("key"), eq("value2"), any(Metadata.class), eq("value"), any(Metadata.class), eq(false), isA(InvocationContext.class), argThat(matcher)); cache.put("key", "value2"); verify(getMockNotifier(cache)).notifyCacheEntryModified(eq("key"), eq("value2"), any(Metadata.class), eq("value2"), any(Metadata.class), eq(true), isA(InvocationContext.class), argThat(matcher)); verify(getMockNotifier(cache)).notifyCacheEntryModified(eq("key"), eq("value2"), any(Metadata.class), eq("value2"), any(Metadata.class), eq(false), isA(InvocationContext.class), argThat(matcher)); } public void testReplaceNotification() throws Exception { Matcher<FlagAffectedCommand> matcher = getFlagMatcher(); initCacheData(cache, Collections.singletonMap("key", "value")); cache.replace("key", "value", "value2"); verify(getMockNotifier(cache)).notifyCacheEntryModified(eq("key"), eq("value2"), any(Metadata.class), eq("value"), any(Metadata.class), eq(true), isA(InvocationContext.class), argThat(matcher)); verify(getMockNotifier(cache)).notifyCacheEntryModified(eq("key"), eq("value2"), any(Metadata.class), eq("value"), any(Metadata.class), eq(false), isA(InvocationContext.class), argThat(matcher)); } public void testReplaceNoNotificationOnNoChange() throws Exception { initCacheData(cache, Collections.singletonMap("key", "value")); cache.replace("key", "value2", "value3"); Matcher<FlagAffectedCommand> matcher = getFlagMatcher(); verify(getMockNotifier(cache), never()).notifyCacheEntryModified(eq("key"), eq("value3"), any(Metadata.class), eq("value3"), any(Metadata.class), eq(true), any(InvocationContext.class), argThat(matcher)); verify(getMockNotifier(cache), never()).notifyCacheEntryModified(eq("key"), eq("value3"), any(Metadata.class), eq("value3"), any(Metadata.class), eq(false), any(InvocationContext.class), argThat(matcher)); } public void testNonexistentVisit() throws Exception { cache.get("doesNotExist"); } public void testNonexistentRemove() throws Exception { cache.remove("doesNotExist"); } public void testCreation() throws Exception { creation(cache, getFlagMatcher()); } private void creation(Cache<Object, Object> cache, Matcher<FlagAffectedCommand> matcher) { cache.put("key", "value"); expectSingleEntryCreated(cache, "key", "value", matcher); } private void initCacheData(Cache cache, Map<String, String> data) { cache.putAll(data); verify(getMockNotifier(cache), atLeastOnce()).notifyCacheEntryCreated(any(), any(), any(Metadata.class), anyBoolean(), isA(InvocationContext.class), getExpectedPutMapCommand()); } protected PutMapCommand getExpectedPutMapCommand() { return isA(PutMapCommand.class); } private void expectSingleEntryCreated(Cache cache, Object key, Object value, Matcher<FlagAffectedCommand> matcher) { verify(getMockNotifier(cache)) .notifyCacheEntryCreated(eq(key), eq(value), any(Metadata.class), eq(true), any(InvocationContext.class), argThat(matcher)); verify(getMockNotifier(cache)) .notifyCacheEntryCreated(eq(key), eq(value), any(Metadata.class), eq(false), any(InvocationContext.class), argThat(matcher)); } }
9,123
41.046083
130
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/CacheNotifierImplInitialTransferInvalTest.java
package org.infinispan.notifications.cachelistener; import java.io.IOException; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.Test; // Since all tests currently are clustered only, there is no reason to even enable this test as nothing would work @Test(groups = "unit", testName = "notifications.cachelistener.CacheNotifierImplInitialTransferInvalTest") public class CacheNotifierImplInitialTransferInvalTest extends BaseCacheNotifierImplInitialTransferTest { protected CacheNotifierImplInitialTransferInvalTest() { super(CacheMode.INVALIDATION_SYNC); } @Override // This is disabled because invalidation caches don't work with cluster listeners @Test(enabled = false) public void testModificationAfterIterationBeganButNotIteratedValueYetClustered() { } @Override // This is disabled because invalidation caches don't work with cluster listeners @Test(enabled = false) public void testSimpleCacheStartingClusterListener() { } @Override // This is disabled because invalidation caches don't work with cluster listeners @Test(enabled = false) public void testModificationAfterIterationBeganAndIteratedValueClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { } @Override // This is disabled because invalidation caches don't work with cluster listeners @Test(enabled = false) public void testCreateAfterIterationBeganAndIteratedValueClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { } @Override // This is disabled because invalidation caches don't work with cluster listeners @Test(enabled = false) public void testCreateAfterIterationBeganButNotIteratedValueYetClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { } @Override // This is disabled because invalidation caches don't work with cluster listeners @Test(enabled = false) public void testRemoveAfterIterationBeganAndIteratedValueClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { } @Override // This is disabled because invalidation caches don't work with cluster listeners @Test(enabled = false) public void testRemoveAfterIterationBeganButNotIteratedValueYetClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { } @Override // This is disabled because invalidation caches don't work with cluster listeners @Test(enabled = false) public void testFilterConverterUnusedDuringIteration() { } @Override // This is disabled because invalidation caches don't work with cluster listeners @Test(enabled = false) public void testMetadataAvailable() { } }
3,047
40.753425
182
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/CacheEventFilterConverterTest.java
package org.infinispan.notifications.cachelistener; import static org.mockito.ArgumentMatchers.notNull; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverter; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Test class that verifies the optimization for using a CacheEventFilterConverter works properly. * * @author wburns * @since 7.0 */ @Test(groups = "functional", testName = "notifications.cachelistener.CacheEventFilterConverterTest") public class CacheEventFilterConverterTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.createCacheManager(true); } public void testFilterConvertedCalledOnlyOnce() { Object value = new Object(); CacheEventFilterConverter<Object, Object, Object> filterConverter = mock(CacheEventFilterConverter.class); when(filterConverter.filterAndConvert(notNull(), any(), any(), any(), any(), any(EventType.class))).thenReturn(value); CacheListener listener = new CacheListener(); cache.addListener(listener, filterConverter, filterConverter); cache.put("key", "value"); assertEquals(2, listener.getInvocationCount()); verify(filterConverter, times(2)).filterAndConvert(any(), any(), any(), any(), any(), any()); verify(filterConverter, never()).accept(any(), any(), any(), any(), any(), any()); verify(filterConverter, never()).convert(any(), any(), any(), any(), any(), any()); } }
2,434
42.482143
112
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/ListenerExceptionTest.java
package org.infinispan.notifications.cachelistener; import static org.infinispan.test.TestingUtil.k; import static org.infinispan.test.TestingUtil.v; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.lang.reflect.Method; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.RollbackException; import org.infinispan.Cache; import org.infinispan.commons.CacheException; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.remoting.transport.jgroups.SuspectException; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.Test; /** * Tests the behaviour of caches when hooked listeners throw exceptions under * different circumstances with XA transactions. * * @author Galder Zamarreño * @author Tomas Sykora * @since 5.0 */ @Test(groups = "functional", testName = "notifications.cachelistener.ListenerExceptionTest") public class ListenerExceptionTest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig( CacheMode.REPL_SYNC, true); builder.transaction().useSynchronization(false) .recovery().enabled(false); createClusteredCaches(2, builder); } public void testPreOpExceptionListenerOnCreate(Method m) { doCallsWithExcepList(m, true, FailureLocation.ON_CREATE); } public void testPostOpExceptionListenerOnCreate(Method m) { doCallsWithExcepList(m, false, FailureLocation.ON_CREATE); } public void testPreOpExceptionListenerOnPut(Method m) { manager(0).getCache().put(k(m), "init"); doCallsWithExcepList(m, true, FailureLocation.ON_MODIFIED); } public void testPostOpExceptionListenerOnPut(Method m) { manager(0).getCache().put(k(m), "init"); doCallsWithExcepList(m, false, FailureLocation.ON_MODIFIED); } public void testPreOpExceptionListenerOnCreateAsync(Method m) { doCallsWithExcepListAsync(m, true, FailureLocation.ON_CREATE); } public void testPostOpExceptionListenerOnCreateAsync(Method m) { doCallsWithExcepListAsync(m, false, FailureLocation.ON_CREATE); } public void testPreOpExceptionListenerOnPutAsync(Method m) { manager(0).getCache().put(k(m), "init"); doCallsWithExcepListAsync(m, true, FailureLocation.ON_MODIFIED); } public void testPostOpExceptionListenerOnPutAsync(Method m) { manager(0).getCache().put(k(m), "init"); doCallsWithExcepListAsync(m, false, FailureLocation.ON_MODIFIED); } private void doCallsWithExcepList(Method m, boolean isInjectInPre, FailureLocation failLoc) { Cache<String, String> cache = manager(0).getCache(); ErrorInducingListener listener = new ErrorInducingListener(isInjectInPre, failLoc); cache.addListener(listener); try { cache.put(k(m), v(m)); } catch (CacheException e) { Throwable cause = e.getCause(); if (isInjectInPre) assertExpectedException(cause, cause instanceof SuspectException); else assertExpectedException(cause, cause instanceof RollbackException || cause instanceof HeuristicRollbackException); // Expected, now try to simulate a failover listener.injectFailure = false; manager(1).getCache().put(k(m), v(m, 2)); return; } fail("Should have failed"); } private void assertExpectedException(Throwable cause, boolean condition) { assertTrue("Unexpected exception cause " + cause, condition); } /** * If it is used asynchronous listener all callbacks are made in separate thread. Exceptions are only logged, not * thrown. See {@link org.infinispan.notifications.impl.AbstractListenerImpl} invoke() method logic */ private void doCallsWithExcepListAsync(Method m, boolean isInjectInPre, FailureLocation failLoc) { Cache<String, String> cache = manager(0).getCache(); ErrorInducingListenerAsync listenerAsync = new ErrorInducingListenerAsync(isInjectInPre, failLoc); cache.addListener(listenerAsync); try { cache.put(k(m), v(m)); } finally { cache.removeListener(listenerAsync); } assert cache.get(k(m)).equals(v(m)); assert listenerAsync.caller != Thread.currentThread(); } @Listener public static class ErrorInducingListener { boolean injectFailure = true; boolean isInjectInPre; FailureLocation failureLocation; public ErrorInducingListener(boolean injectInPre, FailureLocation failLoc) { this.isInjectInPre = injectInPre; this.failureLocation = failLoc; } @CacheEntryCreated @SuppressWarnings("unused") public void entryCreated(CacheEntryEvent event) throws Exception { if (failureLocation == FailureLocation.ON_CREATE) injectFailure(event); } @CacheEntryModified @SuppressWarnings("unused") public void entryModified(CacheEntryEvent event) throws Exception { if (failureLocation == FailureLocation.ON_MODIFIED) injectFailure(event); } private void injectFailure(CacheEntryEvent event) { if (injectFailure) { if (isInjectInPre && event.isPre()) throwSuspectException(); else if (!isInjectInPre && !event.isPre()) throwSuspectException(); } } private void throwSuspectException() { throw new SuspectException(String.format( "Simulated suspicion when isPre=%b and in %s", isInjectInPre, failureLocation)); } } @Listener(sync = false) public static class ErrorInducingListenerAsync { boolean injectFailure = true; boolean isInjectInPre; FailureLocation failureLocation; Thread caller; public ErrorInducingListenerAsync(boolean injectInPre, FailureLocation failLoc) { this.isInjectInPre = injectInPre; this.failureLocation = failLoc; } @CacheEntryCreated @SuppressWarnings("unused") public void entryCreated(CacheEntryEvent event) throws Exception { caller = Thread.currentThread(); if (failureLocation == FailureLocation.ON_CREATE) injectFailure(event); } @CacheEntryModified @SuppressWarnings("unused") public void entryModified(CacheEntryEvent event) throws Exception { caller = Thread.currentThread(); if (failureLocation == FailureLocation.ON_MODIFIED) injectFailure(event); } private void injectFailure(CacheEntryEvent event) { if (injectFailure) { if (isInjectInPre && event.isPre()) throwSuspectException(); else if (!isInjectInPre && !event.isPre()) throwSuspectException(); } } private void throwSuspectException() { throw new SuspectException(String.format( "Simulated ASYNC suspicion when isPre=%b and in %s", isInjectInPre, failureLocation)); } } private static enum FailureLocation { ON_CREATE, ON_MODIFIED } }
7,729
34.458716
126
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/CacheNotifierPersistenceFilterTest.java
package org.infinispan.notifications.cachelistener; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.ImmortalCacheEntry; import org.infinispan.eviction.impl.PassivationManager; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.annotation.TopologyChanged; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent; import org.infinispan.notifications.cachelistener.filter.CacheEventFilter; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.Test; /** * Simple test class that tests to make sure other events are properly handled for filters * * @author wburns * @since 4.0 */ @Test(groups = "functional", testName = "notifications.cachelistener.CacheNotifierPersistenceFilterTest") public class CacheNotifierPersistenceFilterTest extends MultipleCacheManagersTest { protected final String CACHE_NAME = "testCache"; protected ConfigurationBuilder builderUsed; @Override protected void createCacheManagers() throws Throwable { builderUsed = new ConfigurationBuilder(); builderUsed.clustering().cacheMode(CacheMode.REPL_SYNC); builderUsed.persistence().passivation(true).addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(CACHE_NAME); createClusteredCaches(3, CACHE_NAME, builderUsed); } private static class EventKeyFilter implements CacheEventFilter<String, String> { private final Event.Type type; private final Object key; public EventKeyFilter(Event.Type type, Object key) { this.type = type; this.key = key; } @Override public boolean accept(String key, String oldValue, Metadata oldMetadata, String newValue, Metadata newMetadata, EventType eventType) { boolean accept = type == eventType.getType() && this.key.equals(key); return accept; } } @Listener private static class TestListener { private final List<CacheEntryVisitedEvent> visitedEvents = Collections.synchronizedList( new ArrayList<CacheEntryVisitedEvent>()); private final List<TopologyChangedEvent> topologyEvents = Collections.synchronizedList( new ArrayList<TopologyChangedEvent>()); @CacheEntryVisited public void entryVisited(CacheEntryVisitedEvent event) { visitedEvents.add(event); } @TopologyChanged public void topologyChanged(TopologyChangedEvent event) { topologyEvents.add(event); } } @Listener private static class AllCacheEntryListener { private final List<CacheEntryEvent> events = Collections.synchronizedList( new ArrayList<CacheEntryEvent>()); @CacheEntryVisited @CacheEntryActivated @CacheEntryModified @CacheEntryRemoved @CacheEntryCreated @CacheEntryInvalidated @CacheEntryPassivated public void listenEvent(CacheEntryEvent event) { events.add(event); } } @Test public void testPassivationBlocked() { String key = "key"; String value = "value"; Cache<String, String> cache0 = cache(0, CACHE_NAME); AllCacheEntryListener listener = new AllCacheEntryListener(); cache0.addListener(listener, new EventKeyFilter(Event.Type.CACHE_ENTRY_PASSIVATED, key), null); PassivationManager passivationManager = cache0.getAdvancedCache().getComponentRegistry().getComponent( PassivationManager.class); CompletionStages.join(passivationManager.passivateAsync(new ImmortalCacheEntry(key, value))); assertEquals(2, listener.events.size()); assertEquals(Event.Type.CACHE_ENTRY_PASSIVATED, listener.events.get(0).getType()); assertEquals(key, listener.events.get(0).getKey()); assertEquals(value, listener.events.get(0).getValue()); assertEquals(Event.Type.CACHE_ENTRY_PASSIVATED, listener.events.get(1).getType()); assertEquals(key, listener.events.get(1).getKey()); assertNull(listener.events.get(1).getValue()); CompletionStages.join(passivationManager.passivateAsync(new ImmortalCacheEntry("not" + key, value))); // We shouldn't have received any additional events assertEquals(2, listener.events.size()); } @Test public void testActivationBlocked() { String key = "key"; String value = "value"; Cache<String, String> cache0 = cache(0, CACHE_NAME); PassivationManager passivationManager = cache0.getAdvancedCache().getComponentRegistry().getComponent( PassivationManager.class); // Passivate 2 entries to resurrect CompletionStages.join(passivationManager.passivateAsync(new ImmortalCacheEntry(key, value))); CompletionStages.join(passivationManager.passivateAsync(new ImmortalCacheEntry("not" + key, value))); AllCacheEntryListener listener = new AllCacheEntryListener(); cache0.addListener(listener, new EventKeyFilter(Event.Type.CACHE_ENTRY_ACTIVATED, key), null); assertEquals(value, cache0.get("not" + key)); // We shouldn't have received any events assertEquals(0, listener.events.size()); assertEquals(value, cache0.get(key)); assertEquals(2, listener.events.size()); assertEquals(Event.Type.CACHE_ENTRY_ACTIVATED, listener.events.get(0).getType()); assertEquals(key, listener.events.get(0).getKey()); assertEquals(value, listener.events.get(0).getValue()); assertEquals(Event.Type.CACHE_ENTRY_ACTIVATED, listener.events.get(0).getType()); assertEquals(key, listener.events.get(1).getKey()); assertEquals(value, listener.events.get(1).getValue()); } }
7,010
40.982036
140
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/OnlyPrimaryOwnerTest.java
package org.infinispan.notifications.cachelistener; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.CompletionStage; import org.infinispan.cache.impl.EncoderCache; import org.infinispan.commands.CommandsFactory; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.tx.VersionedPrepareCommand; import org.infinispan.commons.dataconversion.Encoder; import org.infinispan.commons.marshall.StreamingMarshaller; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.impl.InternalEntryFactory; import org.infinispan.container.versioning.IncrementableEntryVersion; import org.infinispan.container.versioning.VersionGenerator; import org.infinispan.context.Flag; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.NonTxInvocationContext; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.distribution.TestAddress; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.distribution.ch.impl.DefaultConsistentHash; import org.infinispan.encoding.DataConversion; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.KnownComponentNames; import org.infinispan.factories.impl.BasicComponentRegistry; import org.infinispan.factories.impl.MockBasicComponentRegistry; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.cachelistener.cluster.ClusterEventManager; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.persistence.util.EntryLoader; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.transport.Address; import org.infinispan.test.TestingUtil; import org.infinispan.topology.CacheTopology; import org.infinispan.util.concurrent.BlockingManager; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(testName = "notifications.cachelistener.OnlyPrimaryOwnerTest", groups = "unit") public class OnlyPrimaryOwnerTest { CacheNotifierImpl n; EncoderCache mockCache; PrimaryOwnerCacheListener cl; InvocationContext ctx; MockCDL cdl = new MockCDL(); @BeforeMethod public void setUp() { n = new CacheNotifierImpl(); mockCache = mock(EncoderCache.class); EmbeddedCacheManager cacheManager = mock(EmbeddedCacheManager.class); when(mockCache.getCacheManager()).thenReturn(cacheManager); when(mockCache.getAdvancedCache()).thenReturn(mockCache); when(mockCache.getKeyDataConversion()).thenReturn(DataConversion.IDENTITY_KEY); when(mockCache.getValueDataConversion()).thenReturn(DataConversion.IDENTITY_VALUE); when(mockCache.getStatus()).thenReturn(ComponentStatus.INITIALIZING); ComponentRegistry componentRegistry = mock(ComponentRegistry.class); when(mockCache.getComponentRegistry()).thenReturn(componentRegistry); MockBasicComponentRegistry mockRegistry = new MockBasicComponentRegistry(); when(componentRegistry.getComponent(BasicComponentRegistry.class)).thenReturn(mockRegistry); mockRegistry.registerMocks(RpcManager.class, CommandsFactory.class, Encoder.class); mockRegistry.registerMock(KnownComponentNames.INTERNAL_MARSHALLER, StreamingMarshaller.class); Configuration config = new ConfigurationBuilder().memory().storageType(StorageType.OBJECT).build(); ClusterEventManager cem = mock(ClusterEventManager.class); when(cem.sendEvents(any())).thenReturn(CompletableFutures.completedNull()); TestingUtil.inject(n, mockCache, cdl, config, mockRegistry, mock(InternalEntryFactory.class), cem, mock(KeyPartitioner.class), mock(BlockingManager.class)); cl = new PrimaryOwnerCacheListener(); n.start(); n.addListener(cl); ctx = new NonTxInvocationContext(null); } private static class MockCDL implements ClusteringDependentLogic { private static final TestAddress PRIMARY = new TestAddress(0); private static final TestAddress BACKUP = new TestAddress(1); private static final TestAddress NON_OWNER = new TestAddress(2); boolean isOwner, isPrimaryOwner; @Override public LocalizedCacheTopology getCacheTopology() { List<Address> members = Arrays.asList(PRIMARY, BACKUP, NON_OWNER); List<Address>[] ownership = new List[]{Arrays.asList(PRIMARY, BACKUP)}; ConsistentHash ch = new DefaultConsistentHash(2, 1, members, null, ownership); CacheTopology cacheTopology = new CacheTopology(0, 0, ch, null, CacheTopology.Phase.NO_REBALANCE, null, null); Address localAddress = isPrimaryOwner ? PRIMARY : (isOwner ? BACKUP : NON_OWNER); return new LocalizedCacheTopology(CacheMode.DIST_SYNC, cacheTopology, key -> 0, localAddress, true); } @Override public CompletionStage<Void> commitEntry(CacheEntry entry, FlagAffectedCommand command, InvocationContext ctx, Flag trackFlag, boolean l1Invalidation) { throw new UnsupportedOperationException(); } @Override public Commit commitType(FlagAffectedCommand command, InvocationContext ctx, int segment, boolean removed) { return isOwner ? Commit.COMMIT_LOCAL : Commit.NO_COMMIT; } @Override public CompletionStage<Map<Object, IncrementableEntryVersion>> createNewVersionsAndCheckForWriteSkews(VersionGenerator versionGenerator, TxInvocationContext context, VersionedPrepareCommand prepareCommand) { throw new UnsupportedOperationException(); } @Override public Address getAddress() { throw new UnsupportedOperationException(); } @Override public <K, V> EntryLoader<K, V> getEntryLoader() { throw new UnsupportedOperationException(); } @Override public void start() { } } public void testOwnership() { // Is not owner nor primary owner cdl.isOwner = false; cdl.isPrimaryOwner = false; n.notifyCacheEntryCreated("reject", "v1", null, true, ctx, null); n.notifyCacheEntryCreated("reject", "v1", null, false, ctx, null); assert !cl.isReceivedPost(); assert !cl.isReceivedPre(); assert cl.getInvocationCount() == 0; // Is an owner but not primary owner cdl.isOwner = true; cdl.isPrimaryOwner = false; n.notifyCacheEntryCreated("reject", "v1", null, true, ctx, null); n.notifyCacheEntryCreated("reject", "v1", null, false, ctx, null); assert !cl.isReceivedPost(); assert !cl.isReceivedPre(); assert cl.getInvocationCount() == 0; // Is primary owner cdl.isOwner = true; cdl.isPrimaryOwner = true; n.notifyCacheEntryCreated("accept", "v1", null, true, ctx, null); n.notifyCacheEntryCreated("accept", "v1", null, false, ctx, null); assert cl.isReceivedPost(); assert cl.isReceivedPre(); assert cl.getInvocationCount() == 2; assert cl.getEvents().get(0).getCache() == mockCache; assert cl.getEvents().get(0).getType() == Event.Type.CACHE_ENTRY_CREATED; assert ((CacheEntryCreatedEvent) cl.getEvents().get(0)).getKey().equals("accept"); assert ((CacheEntryCreatedEvent) cl.getEvents().get(0)).getValue() == null; assert cl.getEvents().get(1).getCache() == mockCache; assert cl.getEvents().get(1).getType() == Event.Type.CACHE_ENTRY_CREATED; assert ((CacheEntryCreatedEvent) cl.getEvents().get(1)).getKey().equals("accept"); assert ((CacheEntryCreatedEvent) cl.getEvents().get(1)).getValue().equals("v1"); } }
8,389
45.353591
213
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/SkipListenerCacheNotifierTest.java
package org.infinispan.notifications.cachelistener; import org.hamcrest.CustomTypeSafeMatcher; import org.hamcrest.Matcher; import org.infinispan.Cache; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.context.Flag; import org.infinispan.context.impl.FlagBitSets; import org.testng.annotations.Test; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ @Test(groups = "functional", testName = "notifications.cachelistener.SkipListenerCacheNotifierTest") public class SkipListenerCacheNotifierTest extends CacheNotifierTest { @Override protected Cache<Object, Object> getCache() { return cm.getCache().getAdvancedCache().withFlags(Flag.SKIP_LISTENER_NOTIFICATION); } @Override protected Matcher<FlagAffectedCommand> getFlagMatcher() { return new CustomTypeSafeMatcher<FlagAffectedCommand>("") { @Override protected boolean matchesSafely(FlagAffectedCommand item) { return item.hasAnyFlag(FlagBitSets.SKIP_LISTENER_NOTIFICATION); } }; } }
1,044
32.709677
100
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/ListenerExceptionWithSynchronizationTest.java
package org.infinispan.notifications.cachelistener; import static org.infinispan.test.TestingUtil.k; import static org.infinispan.test.TestingUtil.v; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.lang.reflect.Method; import jakarta.transaction.RollbackException; import org.infinispan.Cache; import org.infinispan.commons.CacheException; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.remoting.transport.jgroups.SuspectException; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.Test; /** * Tests listener exception behaivour when caches are configured with * synchronization instead of XA. * * @author Galder Zamarreño * @since 5.2 */ @Test(groups = "functional", testName = "notifications.cachelistener.ListenerExceptionWithSynchronizationTest") public class ListenerExceptionWithSynchronizationTest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig( CacheMode.REPL_SYNC, true); builder.transaction().useSynchronization(true); createClusteredCaches(2, builder); } public void testPreOpExceptionListenerOnCreate(Method m) { doCallsWithExcepList(m, true, FailureLocation.ON_CREATE); } public void testPostOpExceptionListenerOnCreate(Method m) { // Post listener events now happen after commit, so failures there // don't have an impact on the operation outcome with synchronization doCallsNormal(m, false, FailureLocation.ON_CREATE); } public void testPreOpExceptionListenerOnPut(Method m) { manager(0).getCache().put(k(m), "init"); doCallsWithExcepList(m, true, FailureLocation.ON_MODIFIED); } public void testPostOpExceptionListenerOnPut(Method m) { manager(0).getCache().put(k(m), "init"); // Post listener events now happen after commit, so failures there // don't have an impact on the operation outcome with synchronization doCallsNormal(m, false, FailureLocation.ON_MODIFIED); } private void doCallsNormal(Method m, boolean isInjectInPre, FailureLocation failLoc) { Cache<String, String> cache = manager(0).getCache(); ErrorInducingListener listener = new ErrorInducingListener(isInjectInPre, failLoc); cache.addListener(listener); cache.put(k(m), v(m)); } private void doCallsWithExcepList(Method m, boolean isInjectInPre, FailureLocation failLoc) { Cache<String, String> cache = manager(0).getCache(); ErrorInducingListener listener = new ErrorInducingListener(isInjectInPre, failLoc); cache.addListener(listener); try { cache.put(k(m), v(m)); } catch (CacheException e) { Throwable cause = e.getCause(); if (isInjectInPre) assertExpectedException(cause, cause instanceof SuspectException); else assertExpectedException(cause, cause instanceof RollbackException); // Expected, now try to simulate a failover listener.injectFailure = false; manager(1).getCache().put(k(m), v(m, 2)); return; } fail("Should have failed"); } private void assertExpectedException(Throwable cause, boolean condition) { assertTrue("Unexpected exception cause " + cause, condition); } @Listener public static class ErrorInducingListener { boolean injectFailure = true; boolean isInjectInPre; FailureLocation failureLocation; public ErrorInducingListener(boolean injectInPre, FailureLocation failLoc) { this.isInjectInPre = injectInPre; this.failureLocation = failLoc; } @CacheEntryCreated @SuppressWarnings("unused") public void entryCreated(CacheEntryEvent event) throws Exception { if (failureLocation == FailureLocation.ON_CREATE) injectFailure(event); } @CacheEntryModified @SuppressWarnings("unused") public void entryModified(CacheEntryEvent event) throws Exception { if (failureLocation == FailureLocation.ON_MODIFIED) injectFailure(event); } private void injectFailure(CacheEntryEvent event) { if (injectFailure) { if (isInjectInPre && event.isPre()) throwSuspectException(); else if (!isInjectInPre && !event.isPre()) throwSuspectException(); } } private void throwSuspectException() { throw new SuspectException(String.format( "Simulated suspicion when isPre=%b and in %s", isInjectInPre, failureLocation)); } } private static enum FailureLocation { ON_CREATE, ON_MODIFIED } }
5,231
34.351351
111
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/CacheListener.java
package org.infinispan.notifications.cachelistener; import java.util.ArrayList; import java.util.List; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted; import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired; import org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryLoaded; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.annotation.TransactionCompleted; import org.infinispan.notifications.cachelistener.annotation.TransactionRegistered; import org.infinispan.notifications.cachelistener.event.Event; /** * Listens to everything * * @author Manik Surtani * @since 4.0 */ @Listener public class CacheListener { List<Event> events = new ArrayList<>(); boolean receivedPre; boolean receivedPost; int invocationCount; public void reset() { events.clear(); receivedPost = false; receivedPre = false; invocationCount = 0; } public List<Event> getEvents() { return events; } public boolean isReceivedPre() { return receivedPre; } public boolean isReceivedPost() { return receivedPost; } public int getInvocationCount() { return invocationCount; } // handler @CacheEntryActivated @CacheEntryCreated @CacheEntriesEvicted @CacheEntryInvalidated @CacheEntryLoaded @CacheEntryModified @CacheEntryPassivated @CacheEntryRemoved @CacheEntryVisited @TransactionCompleted @TransactionRegistered @CacheEntryExpired public void handle(Event e) { events.add(e); if (e.isPre()) receivedPre = true; else receivedPost = true; invocationCount++; } }
2,309
27.170732
83
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/CacheNotifierFilterTest.java
package org.infinispan.notifications.cachelistener; import static org.testng.AssertJUnit.assertEquals; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import org.infinispan.Cache; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.annotation.TopologyChanged; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent; import org.infinispan.notifications.cachelistener.filter.CacheEventFilter; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.annotations.Test; /** * Simple test class that tests to make sure other events are properly handled for filters * * @author wburns * @since 4.0 */ @Test(groups = "functional", testName = "notifications.cachelistener.CacheNotifierFilterTest") public class CacheNotifierFilterTest extends MultipleCacheManagersTest { protected final String CACHE_NAME = "testCache"; protected ConfigurationBuilder builderUsed; @Override protected void createCacheManagers() throws Throwable { builderUsed = new ConfigurationBuilder(); builderUsed.clustering().cacheMode(CacheMode.REPL_SYNC); createClusteredCaches(3, CACHE_NAME, builderUsed); } private static class VisitedFilter implements CacheEventFilter<String, String> { @Override public boolean accept(String key, String oldValue, Metadata oldMetadata, String newValue, Metadata newMetadata, EventType eventType) { return eventType.getType() != Event.Type.CACHE_ENTRY_VISITED; } } @SuppressWarnings("unused") @Listener private static class TestListener { private static final Log log = LogFactory.getLog(TestListener.class); private final List<CacheEntryVisitedEvent> visitedEvents = Collections.synchronizedList( new ArrayList<>()); private final List<TopologyChangedEvent> topologyEvents = Collections.synchronizedList(new ArrayList<>()); @CacheEntryVisited public void entryVisited(CacheEntryVisitedEvent event) { log.tracef("Visited %s", event.getKey()); visitedEvents.add(event); } @TopologyChanged public void topologyChanged(TopologyChangedEvent event) { topologyEvents.add(event); } } @SuppressWarnings("unused") @Listener private static class AllCacheEntryListener { private final List<CacheEntryEvent> events = Collections.synchronizedList(new ArrayList<>()); @CacheEntryVisited @CacheEntryActivated @CacheEntryModified @CacheEntryRemoved @CacheEntryCreated @CacheEntryInvalidated @CacheEntryPassivated public void listenEvent(CacheEntryEvent event) { events.add(event); } } /** * Basic test to ensure that non modification events are properly filtered */ @Test public void testCacheEntryVisitedEventFiltered() { String key = "key"; String value = "value"; Cache<String, String> cache0 = cache(0, CACHE_NAME); cache0.put(key, value); TestListener listener = new TestListener(); CacheEventFilter<String, String> filter = (k, oldValue, oldMetadata, newValue, newMetadata, eventType) -> !Objects.equals(k, key); cache0.addFilteredListener(listener, filter, null, Util.asSet(CacheEntryVisited.class)); assertEquals(value, cache0.get(key)); assertEquals(0, listener.visitedEvents.size()); // Verify others work still as well String notKey = "not" + key; cache0.put(notKey, value); cache0.get("not" + key); cache0.getAdvancedCache().getAll(Collections.singleton("not" + key)); assertEquals(4, listener.visitedEvents.size()); } @Test public void testNonCacheEventsNotFiltered() { Cache<String, String> cache0 = cache(0, CACHE_NAME); TestListener listener = new TestListener(); // This would block all cache events cache0.addListener(listener, (key, oldValue, oldMetadata, newValue, newMetadata, eventType) -> false, null); EmbeddedCacheManager cm = addClusterEnabledCacheManager(); cm.createCache(CACHE_NAME, builderUsed.build()); waitForClusterToForm(CACHE_NAME); // Adding a node requires 4 topologies x2 for pre/post = 8 assertEquals(8, listener.topologyEvents.size()); } @Test public void testVisitationsBlocked() { String key = "key"; String value = "value"; Cache<String, String> cache0 = cache(0, CACHE_NAME); cache0.put(key, value); AllCacheEntryListener listener = new AllCacheEntryListener(); cache0.addListener(listener, new VisitedFilter(), null); assertEquals(value, cache0.get(key)); assertEquals(0, listener.events.size()); // Verify others don't work as well String notKey = "not" + key; cache0.put(notKey, value); cache0.get("not" + key); // We should have 2 create events assertEquals(2, listener.events.size()); assertEquals(Event.Type.CACHE_ENTRY_CREATED, listener.events.get(0).getType()); assertEquals(Event.Type.CACHE_ENTRY_CREATED, listener.events.get(1).getType()); } }
6,379
36.97619
140
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/CacheNotifierTxTest.java
package org.infinispan.notifications.cachelistener; import static org.mockito.ArgumentMatchers.notNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.util.Collections; import java.util.HashMap; import java.util.Map; import jakarta.transaction.TransactionManager; import org.infinispan.Cache; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.PutMapCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.InvocationContext; import org.infinispan.manager.CacheContainer; import org.infinispan.metadata.Metadata; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(groups = "functional", testName = "notifications.cachelistener.CacheNotifierTxTest") public class CacheNotifierTxTest extends AbstractInfinispanTest { private Cache<Object, Object> cache; private TransactionManager tm; private CacheContainer cm; @BeforeMethod public void setUp() throws Exception { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(true); builder.transaction().autoCommit(false) .clustering().cacheMode(CacheMode.LOCAL) .locking().isolationLevel(IsolationLevel.REPEATABLE_READ); cm = TestCacheManagerFactory.createCacheManager(builder); cache = cm.getCache(); tm = TestingUtil.getTransactionManager(cache); CacheNotifier mockNotifier = mock(CacheNotifier.class, i -> CompletableFutures.completedNull()); doReturn(true).when(mockNotifier).hasListener(any()); TestingUtil.replaceComponent(cache, CacheNotifier.class, mockNotifier, true); } @AfterMethod public void tearDown() throws Exception { TestingUtil.killCaches(cache); cm.stop(); } @AfterClass public void destroyManager() { TestingUtil.killCacheManagers(cache.getCacheManager()); } private CacheNotifier getMockNotifier(Cache cache) { return cache.getAdvancedCache().getComponentRegistry().getComponent(CacheNotifier.class); } private void initCacheData(Object key, Object value) { initCacheData(Collections.singletonMap(key, value)); } private void initCacheData(Map<Object, Object> data) { try { tm.begin(); cache.putAll(data); tm.commit(); } catch (Exception e) { throw new RuntimeException(e); } expectTransactionBoundaries(true); verify(getMockNotifier(cache), atLeastOnce()).notifyCacheEntryCreated(notNull(), notNull(), any(Metadata.class), anyBoolean(), any(InvocationContext.class), any(PutMapCommand.class)); clearInvocations(getMockNotifier(cache)); } private void expectSingleEntryCreated(Object key, Object value) { expectSingleEntryCreated(key, value, getMockNotifier(cache)); } private void expectSingleEntryOnlyPreCreated(Object key, Object value) { expectSingleEntryOnlyPreCreated(key, value, getMockNotifier(cache)); } static void expectSingleEntryCreated(Object key, Object value, CacheNotifier mockNotifier) { verify(mockNotifier).notifyCacheEntryCreated(eq(key), eq(value), any(Metadata.class), eq(true), isA(InvocationContext.class), isA(PutKeyValueCommand.class)); verify(mockNotifier).notifyCacheEntryCreated(eq(key), eq(value), any(Metadata.class), eq(false), isA(InvocationContext.class), isNull()); } static void expectSingleEntryOnlyPreCreated(Object key, Object value, CacheNotifier mockNotifier) { verify(mockNotifier).notifyCacheEntryCreated(eq(key), eq(value), any(Metadata.class), eq(true), isA(InvocationContext.class), isA(PutKeyValueCommand.class)); } private void expectTransactionBoundaries(boolean successful) { verify(getMockNotifier(cache)).notifyTransactionRegistered(isA(GlobalTransaction.class), anyBoolean()); verify(getMockNotifier(cache)).notifyTransactionCompleted(isA(GlobalTransaction.class), eq(successful), isA(InvocationContext.class)); } // -- now the transactional ones public void testTxNonexistentRemove() throws Exception { tm.begin(); cache.remove("doesNotExist"); tm.commit(); expectTransactionBoundaries(true); } public void testTxCreationCommit() throws Exception { tm.begin(); cache.put("key", "value"); tm.commit(); expectTransactionBoundaries(true); expectSingleEntryCreated("key", "value"); } public void testTxCreationRollback() throws Exception { tm.begin(); cache.put("key", "value"); tm.rollback(); expectTransactionBoundaries(false); expectSingleEntryOnlyPreCreated("key", "value"); } public void testTxOnlyModification() throws Exception { initCacheData("key", "value"); tm.begin(); cache.put("key", "value2"); tm.commit(); expectTransactionBoundaries(true); verify(getMockNotifier(cache)).notifyCacheEntryModified(eq("key"), eq("value2"), any(Metadata.class), eq("value"), any(Metadata.class), eq(true), isA(InvocationContext.class), isA(PutKeyValueCommand.class)); verify(getMockNotifier(cache)).notifyCacheEntryModified(eq("key"), eq("value2"), any(Metadata.class), eq("value"), any(Metadata.class), eq(false), isA(InvocationContext.class), isNull()); } public void testTxRemoveData() throws Exception { Map<Object, Object> data = new HashMap<>(); data.put("key", "value"); data.put("key2", "value2"); initCacheData(data); tm.begin(); cache.remove("key2"); tm.commit(); expectTransactionBoundaries(true); verify(getMockNotifier(cache)).notifyCacheEntryRemoved(eq("key2"), eq("value2"), any(Metadata.class), eq(true), isA(InvocationContext.class), isA(RemoveCommand.class)); verify(getMockNotifier(cache)).notifyCacheEntryRemoved(eq("key2"), eq("value2"), any(Metadata.class), eq(false), isA(InvocationContext.class), isNull()); } }
7,014
37.756906
140
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/ListenerRegistrationTest.java
package org.infinispan.notifications.cachelistener; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.util.List; import org.infinispan.AdvancedCache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.StorageType; import org.infinispan.container.impl.InternalEntryFactoryImpl; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.impl.BasicComponentRegistry; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.notifications.IncorrectListenerException; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.cluster.ClusterEventManager; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; @Test(groups = "unit", testName = "notifications.cachelistener.ListenerRegistrationTest") public class ListenerRegistrationTest extends AbstractInfinispanTest { private CacheNotifierImpl newNotifier() { CacheNotifierImpl notifier = new CacheNotifierImpl(); AdvancedCache mockCache = mock(AdvancedCache.class, RETURNS_DEEP_STUBS); ComponentRegistry registry = mock(ComponentRegistry.class); Configuration config = mock(Configuration.class, RETURNS_DEEP_STUBS); when(config.clustering().cacheMode()).thenReturn(CacheMode.LOCAL); when(config.memory().storageType()).thenReturn(StorageType.OBJECT); TestingUtil.inject(notifier, mockCache, new ClusteringDependentLogic.LocalLogic(), config, new InternalEntryFactoryImpl(), mock(ClusterEventManager.class), mock(BasicComponentRegistry.class)); return notifier; } public void testControl() { Object l = new TestControlListener(); CacheNotifierImpl n = newNotifier(); n.addListener(l); assertEquals(1, n.getListeners().size()); } public void testCacheListenerNoMethods() { Object l = new TestCacheListenerNoMethodsListener(); CacheNotifierImpl n = newNotifier(); n.addListener(l); assertEquals("Hello", l.toString()); assertTrue("No listeners should be registered.", n.getListeners().isEmpty()); // since the valid listener has no methods to listen } public void testNonAnnotatedListener() { Object l = new TestNonAnnotatedListener(); CacheNotifierImpl n = newNotifier(); try { n.addListener(l); fail("Should not accept an un-annotated cache listener"); } catch (IncorrectListenerException icle) { // expected } assertTrue("No listeners should be registered.", n.getListeners().isEmpty()); } public void testNonPublicListener() { Object l = new TestNonPublicListener(); CacheNotifierImpl n = newNotifier(); try { n.addListener(l); fail("Should not accept a private callback class"); } catch (IncorrectListenerException icle) { // expected } assertTrue("No listeners should be registered.", n.getListeners().isEmpty()); } public void testNonPublicListenerMethod() { Object l = new TestNonPublicListenerMethodListener(); CacheNotifierImpl n = newNotifier(); n.addListener(l); // should not fail, should just not register anything assertTrue("No listeners should be registered.", n.getListeners().isEmpty()); } public void testNonVoidReturnTypeMethod() { Object l = new TestNonVoidReturnTypeMethodListener(); CacheNotifierImpl n = newNotifier(); try { n.addListener(l); fail("Should not accept a listener method with a return type"); } catch (IncorrectListenerException icle) { // expected } assertTrue("No listeners should be registered.", n.getListeners().isEmpty()); } public void testIncorrectMethodSignature1() { Object l = new TestIncorrectMethodSignature1Listener(); CacheNotifierImpl n = newNotifier(); try { n.addListener(l); fail("Should not accept a cache listener with a bad method signature"); } catch (IncorrectListenerException icle) { // expected } assertTrue("No listeners should be registered.", n.getListeners().isEmpty()); } public void testIncorrectMethodSignature2() { Object l = new TestIncorrectMethodSignature2Listener(); CacheNotifierImpl n = newNotifier(); try { n.addListener(l); fail("Should not accept a cache listener with a bad method signature"); } catch (IncorrectListenerException icle) { // expected } assertTrue("No listeners should be registered.", n.getListeners().isEmpty()); } public void testIncorrectMethodSignature3() { Object l = new TestIncorrectMethodSignature3Listener(); CacheNotifierImpl n = newNotifier(); try { n.addListener(l); fail("Should not accept a cache listener with a bad method signature"); } catch (IncorrectListenerException icle) { // expected } assertTrue("No listeners should be registered.", n.getListeners().isEmpty()); } public void testUnassignableMethodSignature() { Object l = new TestUnassignableMethodSignatureListener(); CacheNotifierImpl n = newNotifier(); try { n.addListener(l); fail("Should not accept a cache listener with a bad method signature"); } catch (IncorrectListenerException icle) { // expected } assertTrue("No listeners should be registered.", n.getListeners().isEmpty()); } public void testPartlyUnassignableMethodSignature() { Object l = new TestPartlyUnassignableMethodSignatureListener(); CacheNotifierImpl n = newNotifier(); try { n.addListener(l); fail("Should not accept a cache listener with a bad method signature"); } catch (IncorrectListenerException icle) { // expected } } public void testMultipleMethods() { Object l = new TestMultipleMethodsListener(); CacheNotifierImpl n = newNotifier(); n.addListener(l); List invocations = n.cacheEntryVisitedListeners; assertEquals(1, invocations.size()); invocations = n.cacheEntryRemovedListeners; assertEquals(1, invocations.size()); assertEquals(1, n.getListeners().size()); } public void testMultipleAnnotationsOneMethod() { Object l = new TestMultipleAnnotationsOneMethodListener(); CacheNotifierImpl n = newNotifier(); n.addListener(l); List invocations = n.cacheEntryVisitedListeners; assertEquals(1, invocations.size()); invocations = n.cacheEntryRemovedListeners; assertEquals(1, invocations.size()); assertEquals(1, n.getListeners().size()); } public void testMultipleMethodsOneAnnotation() { Object l = new TestMultipleMethodsOneAnnotationListener(); CacheNotifierImpl n = newNotifier(); n.addListener(l); List invocations = n.cacheEntryVisitedListeners; assertEquals(2, invocations.size()); assertEquals(1, n.getListeners().size()); } @Listener static public class TestControlListener { @CacheEntryVisited @CacheEntryRemoved public void callback(Event e) { } } @Listener static public class TestCacheListenerNoMethodsListener { public String toString() { return "Hello"; } } static public class TestNonAnnotatedListener { public String toString() { return "Hello"; } } @Listener static protected class TestNonPublicListener { @CacheEntryVisited public void callback() { } } @Listener static public class TestNonPublicListenerMethodListener { @CacheEntryVisited protected void callback(Event e) { } } @Listener static public class TestNonVoidReturnTypeMethodListener { @CacheEntryVisited public String callback(Event e) { return "Hello"; } } @Listener static public class TestIncorrectMethodSignature1Listener { @CacheEntryVisited public void callback() { } } @Listener static public class TestIncorrectMethodSignature2Listener { @CacheEntryVisited public void callback(Event e, String s) { } } @Listener static public class TestIncorrectMethodSignature3Listener { @CacheEntryVisited public void callback(Event e, String... s) { } } @Listener static public class TestUnassignableMethodSignatureListener { @CacheEntryVisited public void callback(CacheEntryRemovedEvent e) { } } @Listener static public class TestPartlyUnassignableMethodSignatureListener { @CacheEntryVisited @CacheEntryRemoved public void callback(CacheEntryRemovedEvent e) { } } @Listener static public class TestMultipleMethodsListener { @CacheEntryVisited public void callback1(Event e) { } @CacheEntryRemoved public void callback2(Event e) { } } @Listener static public class TestMultipleAnnotationsOneMethodListener { @CacheEntryRemoved @CacheEntryVisited public void callback(Event nme) { } } @Listener static public class TestMultipleMethodsOneAnnotationListener { @CacheEntryVisited public void callback1(Event e) { } @CacheEntryVisited public void callback2(Event e) { } } }
10,147
32.055375
136
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/FakeEncoderRegistry.java
package org.infinispan.notifications.cachelistener; import java.util.Collections; import java.util.Set; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.Transcoder; import org.infinispan.marshall.core.EncoderRegistryImpl; class FakeEncoderRegistry extends EncoderRegistryImpl { @Override public Object convert(Object o, MediaType from, MediaType to) { return o; } @Override public Transcoder getTranscoder(MediaType mediaType, MediaType another) { return new Transcoder() { @Override public Object transcode(Object content, MediaType contentType, MediaType destinationType) { return content; } @Override public Set<MediaType> getSupportedMediaTypes() { return Collections.emptySet(); } }; } }
864
26.903226
100
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/MultipleListenerConverterTest.java
package org.infinispan.notifications.cachelistener; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.util.Arrays; import java.util.Collection; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.notifications.cachelistener.filter.AbstractCacheEventFilterConverter; import org.infinispan.notifications.cachelistener.filter.CacheEventConverter; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * This test is to make sure that when more than 1 listener is installed they don't affect each other * * @author wburns * @since 7.0 */ @Test(groups = "functional", testName = "notifications.cachelistener.MultipleListenerConverterTest") public class MultipleListenerConverterTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.createCacheManager(new ConfigurationBuilder()); } private static class StringConverter implements CacheEventConverter<Object, Object, String> { private final String append; public StringConverter(String append) { this.append = append; } @Override public String convert(Object key, Object oldValue, Metadata oldMetadata, Object newValue, Metadata newMetadata, EventType eventType) { return String.valueOf(newValue) + "-" + append; } } private static class StringFilterConverter extends AbstractCacheEventFilterConverter { private final String append; public StringFilterConverter(String append) { this.append = append; } @Override public Object filterAndConvert(Object key, Object oldValue, Metadata oldMetadata, Object newValue, Metadata newMetadata, EventType eventType) { return String.valueOf(newValue) + "-" + append; } } public void testMultipleListenersWithDifferentConverters() { CacheListener listener1 = new CacheListener(); CacheListener listener2 = new CacheListener(); CacheListener listener3 = new CacheListener(); cache.addListener(listener1, null, new StringConverter("listener-1")); cache.addListener(listener2, null, new StringConverter("listener-2")); cache.addListener(listener3, null, new StringConverter("listener-3")); insertKeyValueAndVerifyListenerNotifications(Arrays.asList(listener1, listener2, listener3)); } public void testMultipleListenersWithDifferentFilterConverters() { CacheListener listener1 = new CacheListener(); CacheListener listener2 = new CacheListener(); CacheListener listener3 = new CacheListener(); StringFilterConverter filterConverter1 = new StringFilterConverter("listener-1"); StringFilterConverter filterConverter2 = new StringFilterConverter("listener-2"); StringFilterConverter filterConverter3 = new StringFilterConverter("listener-3"); cache.addListener(listener1, filterConverter1, filterConverter1); cache.addListener(listener2, filterConverter2, filterConverter2); cache.addListener(listener3, filterConverter3, filterConverter3); insertKeyValueAndVerifyListenerNotifications(Arrays.asList(listener1, listener2, listener3)); } private void insertKeyValueAndVerifyListenerNotifications(Collection<CacheListener> listeners) { cache.put("key", "value"); int i = 1; for (CacheListener listener : listeners) { assertEquals("Listener" + i + "failed", 2, listener.getEvents().size()); Event event = listener.getEvents().get(0); assertEquals("Listener" + i + "failed", Event.Type.CACHE_ENTRY_CREATED, event.getType()); CacheEntryCreatedEvent createdEvent = (CacheEntryCreatedEvent) event; assertTrue("Listener" + i + "failed", createdEvent.isPre()); assertEquals("Listener" + i + "failed", "key", createdEvent.getKey()); assertEquals("Listener" + i + "failed", "null-listener-" + i, createdEvent.getValue()); event = listener.getEvents().get(1); assertEquals("Listener" + i + "failed", Event.Type.CACHE_ENTRY_CREATED, event.getType()); createdEvent = (CacheEntryCreatedEvent) event; assertFalse("Listener" + i + "failed", createdEvent.isPre()); assertEquals("Listener" + i + "failed", "key", createdEvent.getKey()); assertEquals("Listener" + i + "failed", "value-listener-" + i,createdEvent.getValue()); ++i; } } }
4,962
42.920354
149
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/SimpleCacheNotifierTest.java
package org.infinispan.notifications.cachelistener; import org.hamcrest.Matcher; import org.infinispan.Cache; import org.infinispan.commands.FlagAffectedCommand; import org.infinispan.commands.write.PutMapCommand; import org.infinispan.commons.configuration.Combine; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.event.CacheEntryVisitedEvent; import org.testng.annotations.Test; import static org.hamcrest.CoreMatchers.nullValue; import static org.mockito.ArgumentMatchers.isNull; /** * @author Mircea Markus * @since 5.1 */ @Test(groups = "functional", testName = "notifications.cachelistener.SimpleCacheNotifierTest") public class SimpleCacheNotifierTest extends CacheNotifierTest { @Override protected Cache<Object, Object> getCache() { cm.defineConfiguration("simple", new ConfigurationBuilder().read(cm.getDefaultCacheConfiguration(), Combine.DEFAULT) .clustering().simpleCache(true) .statistics().available(false) .build()); Cache cache = cm.getCache("simple"); // without any listeners the notifications are ignored cache.addListener(new DummyListener()); return cache; } @Override protected Matcher<FlagAffectedCommand> getFlagMatcher() { return nullValue(FlagAffectedCommand.class); } @Override protected PutMapCommand getExpectedPutMapCommand() { return isNull(); } @Listener private class DummyListener { @CacheEntryVisited public void onVisited(CacheEntryVisitedEvent e) {} } }
1,719
32.72549
122
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/PrimaryOwnerCacheListener.java
package org.infinispan.notifications.cachelistener; import java.util.ArrayList; import java.util.List; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted; import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryLoaded; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.annotation.TransactionCompleted; import org.infinispan.notifications.cachelistener.annotation.TransactionRegistered; import org.infinispan.notifications.cachelistener.event.Event; @Listener(primaryOnly = true) public class PrimaryOwnerCacheListener { List<Event> events = new ArrayList<Event>(); boolean receivedPre; boolean receivedPost; int invocationCount; public void reset() { events.clear(); receivedPost = false; receivedPre = false; invocationCount = 0; } public List<Event> getEvents() { return events; } public boolean isReceivedPre() { return receivedPre; } public boolean isReceivedPost() { return receivedPost; } public int getInvocationCount() { return invocationCount; } // handler @CacheEntryActivated @CacheEntryCreated @CacheEntriesEvicted @CacheEntryInvalidated @CacheEntryLoaded @CacheEntryModified @CacheEntryPassivated @CacheEntryRemoved @CacheEntryVisited @TransactionCompleted @TransactionRegistered public void handle(Event e) { events.add(e); if (e.isPre()) receivedPre = true; else receivedPost = true; invocationCount++; } }
2,169
28.324324
83
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/CacheNotifierImplInitialTransferDistTest.java
package org.infinispan.notifications.cachelistener; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doAnswer; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.reactive.publisher.impl.ClusterPublisherManager; import org.infinispan.reactive.publisher.impl.SegmentPublisherSupplier; import org.infinispan.test.Mocks; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.CheckPoint; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.annotations.Test; @Test(groups = "unit", testName = "notifications.cachelistener.CacheNotifierImplInitialTransferDistTest") public class CacheNotifierImplInitialTransferDistTest extends MultipleCacheManagersTest { private final String CACHE_NAME = "DistInitialTransferListener"; @Override protected void createCacheManagers() throws Throwable { createClusteredCaches(3, CACHE_NAME, getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC)); } private enum Operation { PUT(Event.Type.CACHE_ENTRY_MODIFIED), CREATE(Event.Type.CACHE_ENTRY_CREATED), REMOVE(Event.Type.CACHE_ENTRY_REMOVED) { @Override public <K, V> Object perform(Cache<K, V> cache, K key, V value) { return cache.remove(key); } }; private final Event.Type type; Operation(Event.Type type) { this.type = type; } public Event.Type getType() { return type; } public <K, V> Object perform(Cache<K, V> cache, K key, V value) { return cache.put(key, value); } } // TODO: commented out until local listners support includeCurrentState // public void testSimpleCacheStartingNonClusterListener() { // testSimpleCacheStarting(new StateListenerNotClustered()); // } public void testSimpleCacheStartingClusterListener() { testSimpleCacheStarting(new StateListenerClustered()); } private void testSimpleCacheStarting(final StateListener<String, String> listener) { final Map<String, String> expectedValues = new HashMap<>(10); Cache<String, String> cache = cache(0, CACHE_NAME); populateCache(cache, expectedValues); cache.addListener(listener); try { verifyEvents(isClustered(listener), listener, expectedValues); } finally { cache.removeListener(listener); } } private void populateCache(Cache<String, String> cache, Map<String, String> expectedValues) { for (int i = 0; i < 10; i++) { String key = "key-" + i; String value = "value-" + i; expectedValues.put(key, value); cache.put(key, value); } } private void verifyEvents(boolean isClustered, StateListener<String, String> listener, Map<String, String> expected) { assertEquals(listener.events.size(), isClustered ? expected.size() : expected.size() * 2); boolean isPost = true; for (CacheEntryEvent<String, String> event : listener.events) { // Even checks means it will be post and have a value - note we force every check to be // even for clustered since those should always be post if (!isClustered) { isPost = !isPost; } assertEquals(event.getType(), Event.Type.CACHE_ENTRY_CREATED); assertTrue(expected.containsKey(event.getKey())); assertEquals(event.isPre(), !isPost); if (isPost) { assertEquals(event.getValue(), expected.get(event.getKey())); } else { assertNull(event.getValue()); } } } // TODO: commented out until local listners support includeCurrentState // public void testCreateAfterIterationBeganButNotIteratedValueYetNonOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { // testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerNotClustered(), Operation.CREATE, false); // } public void testCreateAfterIterationBeganButNotIteratedValueYetNonOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerClustered(), Operation.CREATE, false); } // TODO: commented out until local listners support includeCurrentState // public void testCreateAfterIterationBeganButNotIteratedValueYetOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { // testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerNotClustered(), Operation.CREATE, true); // } public void testCreateAfterIterationBeganButNotIteratedValueYetOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerClustered(), Operation.CREATE, true); } // TODO: commented out until local listners support includeCurrentState // public void testModificationAfterIterationBeganButNotIteratedValueYetNonOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { // testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerNotClustered(), Operation.PUT, false); // } public void testModificationAfterIterationBeganButNotIteratedValueYetNonOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerClustered(), Operation.PUT, false); } // TODO: commented out until local listners support includeCurrentState // public void testModificationAfterIterationBeganButNotIteratedValueYetOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { // testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerNotClustered(), Operation.PUT, true); // } public void testModificationAfterIterationBeganButNotIteratedValueYetOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerClustered(), Operation.PUT, true); } // TODO: commented out until local listners support includeCurrentState // public void testRemoveAfterIterationBeganButNotIteratedValueYetNonOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { // testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerNotClustered(), Operation.REMOVE, false); // } public void testRemoveAfterIterationBeganButNotIteratedValueYetNonOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerClustered(), Operation.REMOVE, false); } // TODO: commented out until local listners support includeCurrentState // public void testRemoveAfterIterationBeganButNotIteratedValueYetOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { // testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerNotClustered(), Operation.REMOVE, true); // } public void testRemoveAfterIterationBeganButNotIteratedValueYetOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException { testModificationAfterIterationBeganButNotIteratedValueYet(new StateListenerClustered(), Operation.REMOVE, true); } /** * This test is to verify that the modification event replaces the current value for the key */ private void testModificationAfterIterationBeganButNotIteratedValueYet(final StateListener<String, String> listener, Operation operation, boolean shouldBePrimaryOwner) throws InterruptedException, TimeoutException, BrokenBarrierException, ExecutionException { final Map<String, String> expectedValues = new HashMap<>(10); final Cache<String, String> cache = cache(0, CACHE_NAME); populateCache(cache, expectedValues); final CheckPoint checkPoint = new CheckPoint(); registerBlockingPublisher(checkPoint, cache); checkPoint.triggerForever(Mocks.AFTER_INVOCATION); checkPoint.triggerForever(Mocks.AFTER_RELEASE); try { String keyToChange = findKeyBasedOnOwnership("key-to-change", cache.getAdvancedCache().getDistributionManager() .getCacheTopology(), shouldBePrimaryOwner); String value = prepareOperation(operation, cache, keyToChange); if (value != null) { expectedValues.put(keyToChange, value); } Future<Void> future = fork(() -> { cache.addListener(listener); return null; }); checkPoint.awaitStrict(Mocks.BEFORE_INVOCATION, 10, TimeUnit.SECONDS); operation.perform(cache, keyToChange, value); // Now let the iteration complete checkPoint.triggerForever(Mocks.BEFORE_RELEASE); future.get(10, TimeUnit.SECONDS); verifyEvents(isClustered(listener), listener, expectedValues); } finally { cache.removeListener(listener); } } private String prepareOperation(Operation operation, Cache<String, String> cache, String keyToChange) { String value; switch (operation) { case CREATE: value = "new-value"; break; case PUT: cache.put(keyToChange, "initial-value"); value = "changed-value"; break; case REMOVE: cache.put(keyToChange, "initial-value"); value = null; break; default: throw new IllegalArgumentException("Unsupported Operation provided " + operation); } return value; } /** * This test is to verify that the modification event is sent after the creation event is done */ private void testModificationAfterIterationBeganAndCompletedSegmentValueOwner(final StateListener<String, String> listener, Operation operation, boolean shouldBePrimaryOwner) throws IOException, InterruptedException, TimeoutException, BrokenBarrierException, ExecutionException { final Map<String, String> expectedValues = new HashMap<>(10); final Cache<String, String> cache = cache(0, CACHE_NAME); populateCache(cache, expectedValues); CheckPoint checkPoint = new CheckPoint(); registerBlockingPublisher(checkPoint, cache); checkPoint.triggerForever(Mocks.BEFORE_RELEASE); try { String keyToChange = findKeyBasedOnOwnership("key-to-change", cache.getAdvancedCache().getDistributionManager() .getCacheTopology(), shouldBePrimaryOwner); String value = prepareOperation(operation, cache, keyToChange); if (cache.get(keyToChange) != null) { expectedValues.put(keyToChange, cache.get(keyToChange)); } Future<Void> future = fork(() -> { cache.addListener(listener); return null; }); checkPoint.awaitStrict(Mocks.AFTER_INVOCATION, 30, TimeUnit.SECONDS); Object oldValue = operation.perform(cache, keyToChange, value); // Now let the iteration complete checkPoint.triggerForever(Mocks.AFTER_RELEASE); future.get(30, TimeUnit.SECONDS); boolean isClustered = isClustered(listener); // We should have 1 or 2 (local) events due to the modification coming after we iterated on it. Note the value // isn't brought up until the iteration is done assertEquals(listener.events.size(), isClustered ? expectedValues.size() + 1 : (expectedValues.size() + 1) * 2); // Assert the first 10/20 since they should all be from iteration - this may not work since segments complete earlier.. boolean isPost = true; int position = 0; for (; position < (isClustered ? expectedValues.size() : expectedValues.size() * 2); ++position) { // Even checks means it will be post and have a value - note we force every check to be // even for clustered since those should always be post if (!isClustered) { isPost = !isPost; } CacheEntryEvent event = listener.events.get(position); assertEquals(event.getType(), Event.Type.CACHE_ENTRY_CREATED); assertTrue(expectedValues.containsKey(event.getKey())); assertEquals(event.isPre(), !isPost); if (isPost) { assertEquals(event.getValue(), expectedValues.get(event.getKey())); } else { assertNull(event.getValue()); } } // We should have 2 extra events at the end which are our modifications if (isClustered) { CacheEntryEvent<String, String> event = listener.events.get(position); assertEquals(event.getType(), operation.getType()); assertEquals(event.isPre(), false); assertEquals(event.getKey(), keyToChange); assertEquals(event.getValue(), value); } else { CacheEntryEvent<String, String> event = listener.events.get(position); assertEquals(event.getType(), operation.getType()); assertEquals(event.isPre(), true); assertEquals(event.getKey(), keyToChange); assertEquals(event.getValue(), oldValue); event = listener.events.get(position + 1); assertEquals(event.getType(), operation.getType()); assertEquals(event.isPre(), false); assertEquals(event.getKey(), keyToChange); assertEquals(event.getValue(), value); } } finally { cache.removeListener(listener); } } private String findKeyBasedOnOwnership(String keyPrefix, LocalizedCacheTopology cacheTopology, boolean shouldBePrimaryOwner) { for (int i = 0; i < 1000; i++) { String key = keyPrefix + i; boolean isPrimaryOwner = cacheTopology.getDistribution(key).isPrimary(); if (isPrimaryOwner == shouldBePrimaryOwner) { if (shouldBePrimaryOwner) { log.debugf("Found key %s with primary owner %s, segment %d", key, cacheTopology.getLocalAddress(), cacheTopology.getSegment(key)); } else { log.debugf("Found key %s with primary owner != %s, segment %d", key, cacheTopology.getLocalAddress(), cacheTopology.getSegment(key)); } return key; } } throw new RuntimeException("No key could be found for owner, this may be a bug in test or really bad luck!"); } // TODO: commented out until local listners support includeCurrentState // public void testCreateAfterIterationBeganAndCompletedSegmentValueNonOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { // testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerNotClustered(), Operation.CREATE, false); // } public void testCreateAfterIterationBeganAndCompletedSegmentValueNonOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerClustered(), Operation.CREATE, false); } // TODO: commented out until local listners support includeCurrentState // public void testCreateAfterIterationBeganAndCompletedSegmentValueOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { // testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerNotClustered(), Operation.CREATE, true); // } public void testCreateAfterIterationBeganAndCompletedSegmentValueOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerClustered(), Operation.CREATE, true); } // TODO: commented out until local listners support includeCurrentState // public void testModificationAfterIterationBeganAndCompletedSegmentValueNonOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { // testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerNotClustered(), Operation.PUT, false); // } public void testModificationAfterIterationBeganAndCompletedSegmentValueNonOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerClustered(), Operation.PUT, false); } // TODO: commented out until local listners support includeCurrentState // public void testModificationAfterIterationBeganAndCompletedSegmentValueOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { // testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerNotClustered(), Operation.PUT, true); // } public void testModificationAfterIterationBeganAndCompletedSegmentValueOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerClustered(), Operation.PUT, true); } // TODO: commented out until local listners support includeCurrentState // public void testRemoveAfterIterationBeganAndCompletedSegmentValueNonOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { // testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerNotClustered(), Operation.REMOVE, false); // } public void testRemoveAfterIterationBeganAndCompletedSegmentValueNonOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerClustered(), Operation.REMOVE, false); } // TODO: commented out until local listners support includeCurrentState // public void testRemoveAfterIterationBeganAndCompletedSegmentValueOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { // testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerNotClustered(), Operation.REMOVE, true); // } public void testRemoveAfterIterationBeganAndCompletedSegmentValueOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { testModificationAfterIterationBeganAndCompletedSegmentValueOwner(new StateListenerClustered(), Operation.REMOVE, true); } protected void testIterationBeganAndSegmentNotComplete(final StateListener<String, String> listener, Operation operation, boolean shouldBePrimaryOwner) throws TimeoutException, InterruptedException, ExecutionException { final Map<String, String> expectedValues = new HashMap<>(10); final Cache<String, String> cache = cache(0, CACHE_NAME); populateCache(cache, expectedValues); String keyToChange = findKeyBasedOnOwnership("key-to-change-", cache.getAdvancedCache().getDistributionManager().getCacheTopology(), shouldBePrimaryOwner); String value = prepareOperation(operation, cache, keyToChange); if (cache.get(keyToChange) != null) { expectedValues.put(keyToChange, cache.get(keyToChange)); } CheckPoint checkPoint = new CheckPoint(); checkPoint.triggerForever(Mocks.AFTER_RELEASE); int segmentToUse = cache.getAdvancedCache().getDistributionManager().getCacheTopology().getSegment(keyToChange); // do the operation, which should put it in the queue. waitUntilClosingSegment(cache, segmentToUse, checkPoint); Future<Void> future = fork(() -> { cache.addListener(listener); return null; }); try { checkPoint.awaitStrict(Mocks.BEFORE_INVOCATION, 10, TimeUnit.SECONDS); Object oldValue = operation.perform(cache, keyToChange, value); // Now let the iteration complete checkPoint.triggerForever(Mocks.BEFORE_RELEASE); future.get(10, TimeUnit.SECONDS); boolean isClustered = isClustered(listener); // We should have 1 or 2 (local) events due to the modification coming after we iterated on it. Note the value // isn't brought up until the iteration is done assertEquals(listener.events.size(), isClustered ? expectedValues.size() + 1 : (expectedValues.size() + 1) * 2); // If it is clustered, then the modify can occur in the middle. In non clustered we have to block all events // just in case of tx event listeners (ie. tx start/tx end would have to wrap all events) and such so we can't // release them early. The cluster listeners aren't affected by transaction since it those are not currently // supported if (isClustered) { CacheEntryEvent event = null; boolean foundEarlierCreate = false; // We iterate backwards so we only have to do it once for (int i = listener.events.size() - 1; i >= 0; --i) { CacheEntryEvent currentEvent = listener.events.get(i); if (currentEvent.getKey().equals(keyToChange) && operation.getType() == currentEvent.getType()) { if (event == null) { event = currentEvent; // We can remove safely since we are doing backwards counter as well listener.events.remove(i); // If it is a create there is no previous create if (operation.getType() == Event.Type.CACHE_ENTRY_CREATED) { foundEarlierCreate = true; break; } } else { fail("There should only be a single event in the event queue!"); } } else if (event != null && (foundEarlierCreate = event.getKey().equals(currentEvent.getKey()))) { break; } } // This should have been set assertTrue(foundEarlierCreate, "There was no matching create event for key " + event.getKey()); assertEquals(event.getType(), operation.getType()); assertEquals(event.isPre(), false); assertEquals(event.getValue(), value); } // Assert the first 10/20 since they should all be from iteration - this may not work since segments complete earlier.. boolean isPost = true; int position = 0; for (; position < (isClustered ? expectedValues.size() : expectedValues.size() * 2); ++position) { // Even checks means it will be post and have a value - note we force every check to be // even for clustered since those should always be post if (!isClustered) { isPost = !isPost; } CacheEntryEvent<String, String> event = listener.events.get(position); assertEquals(event.getType(), Event.Type.CACHE_ENTRY_CREATED); assertTrue(expectedValues.containsKey(event.getKey())); assertEquals(event.isPre(), !isPost); if (isPost) { assertEquals(event.getValue(), expectedValues.get(event.getKey())); } else { assertNull(event.getValue()); } } // We should have 2 extra events at the end which are our modifications if (!isClustered) { CacheEntryEvent<String, String> event = listener.events.get(position); assertEquals(event.getType(), operation.getType()); assertEquals(event.isPre(), true); assertEquals(event.getKey(), keyToChange); assertEquals(event.getValue(), oldValue); event = listener.events.get(position + 1); assertEquals(event.getType(), operation.getType()); assertEquals(event.isPre(), false); assertEquals(event.getKey(), keyToChange); assertEquals(event.getValue(), value); } } finally { cache.removeListener(listener); } } // TODO: commented out until local listners support includeCurrentState // public void testCreateAfterIterationBeganAndSegmentNotCompleteValueNonOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { // testIterationBeganAndSegmentNotComplete(new StateListenerNotClustered(), Operation.CREATE, false); // } public void testCreateAfterIterationBeganAndSegmentNotCompleteValueNonOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { testIterationBeganAndSegmentNotComplete(new StateListenerClustered(), Operation.CREATE, false); } // TODO: commented out until local listners support includeCurrentState // public void testCreateAfterIterationBeganAndSegmentNotCompleteValueOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { // testIterationBeganAndSegmentNotComplete(new StateListenerNotClustered(), Operation.CREATE, true); // } public void testCreateAfterIterationBeganAndSegmentNotCompleteValueOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { testIterationBeganAndSegmentNotComplete(new StateListenerClustered(), Operation.CREATE, true); } // TODO: commented out until local listners support includeCurrentState // public void testModificationAfterIterationBeganAndSegmentNotCompleteValueNonOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { // testIterationBeganAndSegmentNotComplete(new StateListenerNotClustered(), Operation.PUT, false); // } public void testModificationAfterIterationBeganAndSegmentNotCompleteValueNonOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { testIterationBeganAndSegmentNotComplete(new StateListenerClustered(), Operation.PUT, false); } // TODO: commented out until local listners support includeCurrentState // public void testModificationAfterIterationBeganAndSegmentNotCompleteValueOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { // testIterationBeganAndSegmentNotComplete(new StateListenerNotClustered(), Operation.PUT, true); // } public void testModificationAfterIterationBeganAndSegmentNotCompleteValueOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { testIterationBeganAndSegmentNotComplete(new StateListenerClustered(), Operation.PUT, true); } // TODO: commented out until local listners support includeCurrentState // public void testRemoveAfterIterationBeganAndSegmentNotCompleteValueNonOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { // testIterationBeganAndSegmentNotComplete(new StateListenerNotClustered(), Operation.REMOVE, false); // } public void testRemoveAfterIterationBeganAndSegmentNotCompleteValueNonOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { testIterationBeganAndSegmentNotComplete(new StateListenerClustered(), Operation.REMOVE, false); } // TODO: commented out until local listners support includeCurrentState // public void testRemoveAfterIterationBeganAndSegmentNotCompleteValueOwnerNotClustered() // throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { // testIterationBeganAndSegmentNotComplete(new StateListenerNotClustered(), Operation.REMOVE, true); // } public void testRemoveAfterIterationBeganAndSegmentNotCompleteValueOwnerClustered() throws InterruptedException, BrokenBarrierException, TimeoutException, ExecutionException, IOException { testIterationBeganAndSegmentNotComplete(new StateListenerClustered(), Operation.REMOVE, true); } private boolean isClustered(StateListener listener) { return listener.getClass().getAnnotation(Listener.class).clustered(); } protected static abstract class StateListener<K, V> { final List<CacheEntryEvent<K, V>> events = Collections.synchronizedList(new ArrayList<>()); private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); @CacheEntryCreated @CacheEntryModified @CacheEntryRemoved public void onCacheNotification(CacheEntryEvent<K, V> event) { log.tracef("Received event: %s", event); events.add(event); } } @Listener(includeCurrentState = true, clustered = false) private static class StateListenerNotClustered extends StateListener<String, String> { } @Listener(includeCurrentState = true, clustered = true) private static class StateListenerClustered extends StateListener<String, String> { } private void segmentCompletionWaiter(AtomicBoolean shouldFire, CheckPoint checkPoint) throws TimeoutException, InterruptedException { // Only 2 callers should come in here, so first will always succeed and second will always fail if (shouldFire.compareAndSet(false, true)) { log.tracef("We were first to check segment completion"); } else { log.tracef("We were last to check segment completion, so notifying main thread"); // Wait for main thread to sync up checkPoint.trigger("pre_complete_segment_invoked"); // Now wait until main thread lets us through checkPoint.awaitStrict("pre_complete_segment_released", 10, TimeUnit.SECONDS); } } protected void waitUntilClosingSegment(final Cache<?, ?> cache, int segment, CheckPoint checkPoint) { ClusterPublisherManager<Object, String> spy = Mocks.replaceComponentWithSpy(cache, ClusterPublisherManager.class); doAnswer(invocation -> { SegmentPublisherSupplier<?> publisher = (SegmentPublisherSupplier<?>) invocation.callRealMethod(); return Mocks.blockingSegmentPublisherOnElement(publisher, checkPoint, n -> n.isSegmentComplete() && n.completedSegment() == segment); }).when(spy).entryPublisher(any(), any(), any(), anyLong(), any(), anyInt(), any()); } private static void registerBlockingPublisher(final CheckPoint checkPoint, Cache<?, ?> cache) { ClusterPublisherManager<Object, String> spy = Mocks.replaceComponentWithSpy(cache, ClusterPublisherManager.class); doAnswer(invocation -> { SegmentPublisherSupplier<?> result = (SegmentPublisherSupplier<?>) invocation.callRealMethod(); return Mocks.blockingPublisher(result, checkPoint); }).when(spy).entryPublisher(any(), any(), any(), anyLong(), any(), anyInt(), any()); } }
34,335
48.834543
131
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/CacheNotifierImplTest.java
package org.infinispan.notifications.cachelistener; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.Collections; import java.util.Map; import org.infinispan.cache.impl.EncoderCache; import org.infinispan.commands.CommandsFactory; import org.infinispan.commons.marshall.StreamingMarshaller; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.ImmortalCacheEntry; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.impl.InternalEntryFactory; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.NonTxInvocationContext; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.encoding.DataConversion; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.KnownComponentNames; import org.infinispan.factories.impl.BasicComponentRegistry; import org.infinispan.factories.impl.MockBasicComponentRegistry; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.cachelistener.cluster.ClusterEventManager; import org.infinispan.notifications.cachelistener.event.CacheEntriesEvictedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryExpiredEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryPassivatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.notifications.cachelistener.event.Event.Type; import org.infinispan.notifications.cachelistener.event.TransactionCompletedEvent; import org.infinispan.notifications.cachelistener.event.TransactionRegisteredEvent; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestInternalCacheEntryFactory; import org.infinispan.transaction.xa.GlobalTransaction; import org.infinispan.util.concurrent.BlockingManager; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.util.concurrent.WithinThreadExecutor; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(groups = "unit", testName = "notifications.cachelistener.CacheNotifierImplTest") public class CacheNotifierImplTest extends AbstractInfinispanTest { CacheNotifierImpl n; EncoderCache mockCache; CacheListener cl; InvocationContext ctx; @BeforeMethod public void setUp() { n = new CacheNotifierImpl(); mockCache = mock(EncoderCache.class); EmbeddedCacheManager cacheManager = mock(EmbeddedCacheManager.class); when(mockCache.getCacheManager()).thenReturn(cacheManager); when(mockCache.getAdvancedCache()).thenReturn(mockCache); when(mockCache.getKeyDataConversion()).thenReturn(DataConversion.IDENTITY_KEY); when(mockCache.getValueDataConversion()).thenReturn(DataConversion.IDENTITY_VALUE); when(mockCache.getStatus()).thenReturn(ComponentStatus.INITIALIZING); ComponentRegistry componentRegistry = mock(ComponentRegistry.class); when(mockCache.getComponentRegistry()).thenReturn(componentRegistry); MockBasicComponentRegistry mockRegistry = new MockBasicComponentRegistry(); when(componentRegistry.getComponent(BasicComponentRegistry.class)).thenReturn(mockRegistry); mockRegistry.registerMocks(RpcManager.class, CommandsFactory.class); mockRegistry.registerMock(KnownComponentNames.INTERNAL_MARSHALLER, StreamingMarshaller.class); ClusteringDependentLogic.LocalLogic cdl = new ClusteringDependentLogic.LocalLogic(); Configuration config = new ConfigurationBuilder().build(); cdl.init(null, config, mock(KeyPartitioner.class)); ClusterEventManager cem = mock(ClusterEventManager.class); when(cem.sendEvents(any())).thenReturn(CompletableFutures.completedNull()); BlockingManager handler = mock(BlockingManager.class); when(handler.continueOnNonBlockingThread(any(), any())).thenReturn(CompletableFutures.completedNull()); TestingUtil.inject(n, mockCache, cdl, config, mockRegistry, mock(InternalEntryFactory.class), cem, mock(KeyPartitioner.class), new FakeEncoderRegistry(), TestingUtil.named(KnownComponentNames.ASYNC_NOTIFICATION_EXECUTOR, new WithinThreadExecutor()), handler); cl = new CacheListener(); n.start(); addListener(); ctx = new NonTxInvocationContext(null); } protected void addListener() { n.addListener(cl); } protected Object getExpectedEventValue(Object key, Object val, Type t) { return val; } public void testNotifyCacheEntryCreated() { n.notifyCacheEntryCreated("k", "v1", null, true, ctx, null); n.notifyCacheEntryCreated("k", "v1", null, false, ctx, null); assertTrue(cl.isReceivedPost()); assertTrue(cl.isReceivedPre()); assertEquals(2, cl.getInvocationCount()); assertEquals(mockCache, cl.getEvents().get(0).getCache()); assertEquals(Event.Type.CACHE_ENTRY_CREATED, cl.getEvents().get(0).getType()); assertEquals("k", ((CacheEntryCreatedEvent) cl.getEvents().get(0)).getKey()); assertEquals(getExpectedEventValue("k", null, Event.Type.CACHE_ENTRY_CREATED), ((CacheEntryEvent) cl.getEvents().get(0)).getValue()); assertEquals(mockCache, cl.getEvents().get(1).getCache()); assertEquals(Event.Type.CACHE_ENTRY_CREATED, cl.getEvents().get(1).getType()); assertEquals("k", ((CacheEntryCreatedEvent) cl.getEvents().get(1)).getKey()); assertEquals(getExpectedEventValue("k", "v1", Event.Type.CACHE_ENTRY_CREATED), ((CacheEntryEvent) cl.getEvents().get(1)).getValue()); } public void testNotifyCacheEntryModified() { n.notifyCacheEntryModified("k", "v2", null, "v1", null, true, ctx, null); n.notifyCacheEntryModified("k", "v2", null, "v1", null, false, ctx, null); assertTrue(cl.isReceivedPost()); assertTrue(cl.isReceivedPre()); assertEquals(2, cl.getInvocationCount()); assertEquals(mockCache, cl.getEvents().get(0).getCache()); assertEquals(Event.Type.CACHE_ENTRY_MODIFIED, cl.getEvents().get(0).getType()); assertEquals("k", ((CacheEntryModifiedEvent) cl.getEvents().get(0)).getKey()); assertEquals(getExpectedEventValue("k", "v1", Event.Type.CACHE_ENTRY_MODIFIED), ((CacheEntryEvent) cl.getEvents().get(0)).getValue()); assertTrue(!((CacheEntryModifiedEvent) cl.getEvents().get(0)).isCreated()); assertEquals(mockCache, cl.getEvents().get(1).getCache()); assertEquals(Event.Type.CACHE_ENTRY_MODIFIED, cl.getEvents().get(1).getType()); assertEquals("k", ((CacheEntryModifiedEvent) cl.getEvents().get(1)).getKey()); assertEquals(getExpectedEventValue("k", "v2", Event.Type.CACHE_ENTRY_MODIFIED), ((CacheEntryEvent) cl.getEvents().get(1)).getValue()); assertTrue(!((CacheEntryModifiedEvent) cl.getEvents().get(1)).isCreated()); } public void testNotifyCacheEntryRemoved() { n.notifyCacheEntryRemoved("k", "v", null, true, ctx, null); n.notifyCacheEntryRemoved("k", "v", null, false, ctx, null); assertTrue(cl.isReceivedPost()); assertTrue(cl.isReceivedPre()); assertEquals(2, cl.getInvocationCount()); assertEquals(mockCache, cl.getEvents().get(0).getCache()); assertEquals(Event.Type.CACHE_ENTRY_REMOVED, cl.getEvents().get(0).getType()); assertEquals("k", ((CacheEntryRemovedEvent) cl.getEvents().get(0)).getKey()); assertEquals(getExpectedEventValue("k", "v", Event.Type.CACHE_ENTRY_REMOVED), ((CacheEntryEvent) cl.getEvents().get(0)).getValue()); assertEquals("v", ((CacheEntryRemovedEvent) cl.getEvents().get(0)).getOldValue()); assertEquals(mockCache, cl.getEvents().get(1).getCache()); assertEquals(Event.Type.CACHE_ENTRY_REMOVED, cl.getEvents().get(1).getType()); assertEquals("k", ((CacheEntryRemovedEvent) cl.getEvents().get(1)).getKey()); assertEquals(getExpectedEventValue("k", null, Event.Type.CACHE_ENTRY_REMOVED), ((CacheEntryEvent) cl.getEvents().get(1)).getValue()); assertEquals("v", ((CacheEntryRemovedEvent) cl.getEvents().get(1)).getOldValue()); } public void testNotifyCacheEntryVisited() { n.notifyCacheEntryVisited("k", "v", true, ctx, null); n.notifyCacheEntryVisited("k", "v", false, ctx, null); assertTrue(cl.isReceivedPost()); assertTrue(cl.isReceivedPre()); assertEquals(2, cl.getInvocationCount()); assertEquals(mockCache, cl.getEvents().get(0).getCache()); assertEquals(Event.Type.CACHE_ENTRY_VISITED, cl.getEvents().get(0).getType()); assertEquals("k", ((CacheEntryEvent) cl.getEvents().get(0)).getKey()); assertEquals(getExpectedEventValue("k", "v", Event.Type.CACHE_ENTRY_VISITED), ((CacheEntryEvent) cl.getEvents().get(0)).getValue()); assertEquals(mockCache, cl.getEvents().get(1).getCache()); assertEquals(Event.Type.CACHE_ENTRY_VISITED, cl.getEvents().get(1).getType()); assertEquals("k", ((CacheEntryEvent) cl.getEvents().get(1)).getKey()); assertEquals(getExpectedEventValue("k", "v", Event.Type.CACHE_ENTRY_VISITED), ((CacheEntryEvent) cl.getEvents().get(1)).getValue()); } public void testNotifyCacheEntryEvicted() { n.notifyCacheEntriesEvicted(Collections.singleton(new ImmortalCacheEntry("k", "v")), null, null); assertTrue(cl.isReceivedPost()); assertEquals(1, cl.getInvocationCount()); assertEquals(mockCache, cl.getEvents().get(0).getCache()); assertEquals(Event.Type.CACHE_ENTRY_EVICTED, cl.getEvents().get(0).getType()); Map<Object, Object> entries = ((CacheEntriesEvictedEvent) cl.getEvents().get(0)).getEntries(); Map.Entry<Object, Object> entry = entries.entrySet().iterator().next(); assertEquals("k", entry.getKey()); assertEquals("v", entry.getValue()); } public void testNotifyCacheEntriesEvicted() { InternalCacheEntry ice = TestInternalCacheEntryFactory.create("k", "v"); n.notifyCacheEntriesEvicted(Collections.singleton(ice), null, null); assertTrue(cl.isReceivedPost()); assertEquals(1, cl.getInvocationCount()); assertEquals(mockCache, cl.getEvents().get(0).getCache()); assertEquals(Event.Type.CACHE_ENTRY_EVICTED, cl.getEvents().get(0).getType()); Map<Object, Object> entries = ((CacheEntriesEvictedEvent) cl.getEvents().get(0)).getEntries(); Map.Entry<Object, Object> entry = entries.entrySet().iterator().next(); assertEquals("k", entry.getKey()); assertEquals("v", entry.getValue()); } public void testNotifyCacheEntryExpired() { n.notifyCacheEntryExpired("k", "v", null, null); assertTrue(cl.isReceivedPost()); assertEquals(cl.getInvocationCount(), 1); assertEquals(cl.getEvents().get(0).getCache(), mockCache); assertEquals(cl.getEvents().get(0).getType(), Event.Type.CACHE_ENTRY_EXPIRED); CacheEntryExpiredEvent expiredEvent = ((CacheEntryExpiredEvent) cl.getEvents().get(0)); assertEquals(expiredEvent.getKey(), "k"); assertEquals(getExpectedEventValue("k", "v", Event.Type.CACHE_ENTRY_EXPIRED), ((CacheEntryEvent) cl.getEvents().get(0)).getValue()); } public void testNotifyCacheEntryInvalidated() { n.notifyCacheEntryInvalidated("k", "v", null, true, ctx, null); n.notifyCacheEntryInvalidated("k", "v", null, false, ctx, null); assertTrue(cl.isReceivedPost()); assertTrue(cl.isReceivedPre()); assertEquals(2, cl.getInvocationCount()); assertEquals(mockCache, cl.getEvents().get(0).getCache()); assertEquals(Event.Type.CACHE_ENTRY_INVALIDATED, cl.getEvents().get(0).getType()); assertEquals("k", ((CacheEntryEvent) cl.getEvents().get(0)).getKey()); assertEquals(getExpectedEventValue("k", "v", Event.Type.CACHE_ENTRY_INVALIDATED), ((CacheEntryEvent) cl.getEvents().get(0)).getValue()); assertEquals(mockCache, cl.getEvents().get(1).getCache()); assertEquals(Event.Type.CACHE_ENTRY_INVALIDATED, cl.getEvents().get(1).getType()); assertEquals("k", ((CacheEntryEvent) cl.getEvents().get(1)).getKey()); assertEquals(getExpectedEventValue("k", "v", Event.Type.CACHE_ENTRY_INVALIDATED), ((CacheEntryEvent) cl.getEvents().get(1)).getValue()); } public void testNotifyCacheEntryLoaded() { n.notifyCacheEntryLoaded("k", "v", true, ctx, null); n.notifyCacheEntryLoaded("k", "v", false, ctx, null); assertTrue(cl.isReceivedPost()); assertTrue(cl.isReceivedPre()); assertEquals(2, cl.getInvocationCount()); assertEquals(mockCache, cl.getEvents().get(0).getCache()); assertEquals(Event.Type.CACHE_ENTRY_LOADED, cl.getEvents().get(0).getType()); assertEquals("k", ((CacheEntryEvent) cl.getEvents().get(0)).getKey()); assertEquals(getExpectedEventValue("k", "v", Event.Type.CACHE_ENTRY_LOADED), ((CacheEntryEvent) cl.getEvents().get(0)).getValue()); assertEquals(mockCache, cl.getEvents().get(1).getCache()); assertEquals(Event.Type.CACHE_ENTRY_LOADED, cl.getEvents().get(1).getType()); assertEquals("k", ((CacheEntryEvent) cl.getEvents().get(1)).getKey()); assertEquals(getExpectedEventValue("k", "v", Event.Type.CACHE_ENTRY_LOADED), ((CacheEntryEvent) cl.getEvents().get(1)).getValue()); } public void testNotifyCacheEntryActivated() { n.notifyCacheEntryActivated("k", "v", true, ctx, null); n.notifyCacheEntryActivated("k", "v", false, ctx, null); assertTrue(cl.isReceivedPost()); assertTrue(cl.isReceivedPre()); assertEquals(2, cl.getInvocationCount()); assertEquals(mockCache, cl.getEvents().get(0).getCache()); assertEquals(Event.Type.CACHE_ENTRY_ACTIVATED, cl.getEvents().get(0).getType()); assertEquals("k", ((CacheEntryEvent) cl.getEvents().get(0)).getKey()); assertEquals(getExpectedEventValue("k", "v", Event.Type.CACHE_ENTRY_ACTIVATED), ((CacheEntryEvent) cl.getEvents().get(0)).getValue()); assertEquals(mockCache, cl.getEvents().get(1).getCache()); assertEquals(Event.Type.CACHE_ENTRY_ACTIVATED, cl.getEvents().get(1).getType()); assertEquals("k", ((CacheEntryEvent) cl.getEvents().get(1)).getKey()); assertEquals(getExpectedEventValue("k", "v", Event.Type.CACHE_ENTRY_ACTIVATED), ((CacheEntryEvent) cl.getEvents().get(1)).getValue()); } public void testNotifyCacheEntryPassivated() { n.notifyCacheEntryPassivated("k", "v", true, null, null); n.notifyCacheEntryPassivated("k", "v", false, null, null); assertTrue(cl.isReceivedPost()); assertTrue(cl.isReceivedPre()); assertEquals(2, cl.getInvocationCount()); assertEquals(mockCache, cl.getEvents().get(0).getCache()); assertEquals(Event.Type.CACHE_ENTRY_PASSIVATED, cl.getEvents().get(0).getType()); CacheEntryPassivatedEvent event = (CacheEntryPassivatedEvent) cl.getEvents().get(0); assertEquals("k", event.getKey()); assertEquals(getExpectedEventValue("k", "v", Event.Type.CACHE_ENTRY_PASSIVATED), ((CacheEntryEvent) cl.getEvents().get(0)).getValue()); assertEquals(mockCache, cl.getEvents().get(1).getCache()); assertEquals(Event.Type.CACHE_ENTRY_PASSIVATED, cl.getEvents().get(1).getType()); event = (CacheEntryPassivatedEvent) cl.getEvents().get(1); assertEquals("k", event.getKey()); assertEquals(getExpectedEventValue("k", "v", Event.Type.CACHE_ENTRY_PASSIVATED), ((CacheEntryEvent) cl.getEvents().get(1)).getValue()); } public void testNotifyTransactionCompleted() { GlobalTransaction tx = mock(GlobalTransaction.class); n.notifyTransactionCompleted(tx, true, ctx); n.notifyTransactionCompleted(tx, false, ctx); assertEquals(2, cl.getInvocationCount()); assertEquals(mockCache, cl.getEvents().get(0).getCache()); assertEquals(Event.Type.TRANSACTION_COMPLETED, cl.getEvents().get(0).getType()); assertTrue(((TransactionCompletedEvent) cl.getEvents().get(0)).isTransactionSuccessful()); assertEquals(((TransactionCompletedEvent) cl.getEvents().get(0)).getGlobalTransaction(), tx); assertEquals(mockCache, cl.getEvents().get(1).getCache()); assertEquals(Event.Type.TRANSACTION_COMPLETED, cl.getEvents().get(1).getType()); assertTrue(!((TransactionCompletedEvent) cl.getEvents().get(1)).isTransactionSuccessful()); assertEquals(((TransactionCompletedEvent) cl.getEvents().get(1)).getGlobalTransaction(), tx); } public void testNotifyTransactionRegistered() { GlobalTransaction tx = mock(GlobalTransaction.class); n.notifyTransactionRegistered(tx, false); n.notifyTransactionRegistered(tx, false); assertEquals(2, cl.getInvocationCount()); assertEquals(mockCache, cl.getEvents().get(0).getCache()); assertEquals(Event.Type.TRANSACTION_REGISTERED, cl.getEvents().get(0).getType()); assertEquals(((TransactionRegisteredEvent) cl.getEvents().get(0)).getGlobalTransaction(), tx); assertEquals(mockCache, cl.getEvents().get(1).getCache()); assertEquals(Event.Type.TRANSACTION_REGISTERED, cl.getEvents().get(1).getType()); assertEquals(((TransactionRegisteredEvent) cl.getEvents().get(1)).getGlobalTransaction(), tx); } }
18,163
54.042424
120
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/CacheListenerVisibilityTest.java
package org.infinispan.notifications.cachelistener; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.annotations.Test; /** * Tests visibility of effects of cache operations on a separate thread once * a cache listener event has been consumed for the corresponding cache * operation. * * @author Galder Zamarreño * @since 5.1 */ @Test(groups = "functional", testName = "notifications.cachelistener.CacheListenerVisibilityTest") @CleanupAfterMethod public class CacheListenerVisibilityTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.createCacheManager(false); } public void testSizeVisibility() throws Exception { updateCache(Visibility.SIZE); } public void testGetVisibility() throws Exception { updateCache(Visibility.GET); } public void testGetVisibilityWithinEntryCreatedListener() throws Exception { updateCacheAssertInListener( new EntryCreatedWithAssertListener(new CountDownLatch(1))); } public void testGetVisibilityWithinEntryModifiedListener() throws Exception { updateCacheAssertInListener( new EntryModifiedWithAssertListener(new CountDownLatch(1))); } public void testRemoveVisibility() throws Exception { cache.put(1, "v1"); final CountDownLatch after = new CountDownLatch(1); final CountDownLatch afterContinue = new CountDownLatch(1); final CountDownLatch before = new CountDownLatch(1); cache.addListener(new EntryListener(before, afterContinue, after)); assertEquals("v1", cache.get(1)); Future<Void> ignore = fork(new Callable<Void>() { @Override public Void call() throws Exception { cache.remove(1); return null; } }); // With removes, there's a before/after event acknowledgment, so verify it // Evicts on the other hand only emit a single event, after boolean signalled = before.await(30, TimeUnit.SECONDS); assertTrue("Timed out while waiting for before listener notification", signalled); assertEquals("v1", cache.get(1)); // Let the isPre=false callback continue afterContinue.countDown(); signalled = after.await(30, TimeUnit.SECONDS); assertTrue("Timed out while waiting for after listener notification", signalled); assertEquals(null, cache.get(1)); ignore.get(5, TimeUnit.SECONDS); } public void testEvictOnCacheEntryEvictedVisibility() throws Exception { checkEvictVisibility(false); } public void testEvictOnCacheEntriesEvictedVisibility() throws Exception { checkEvictVisibility(true); } private void checkEvictVisibility(boolean isCacheEntriesEvicted) throws Exception { cache.put(1, "v1"); final CountDownLatch after = new CountDownLatch(1); Object listener = isCacheEntriesEvicted ? new EntriesEvictedListener(after) : new EntryListener(null, null, after); cache.addListener(listener); assertEquals("v1", cache.get(1)); Future<Void> ignore = fork(new Callable<Void>() { @Override public Void call() throws Exception { cache.evict(1); return null; } }); boolean signalled = after.await(30, TimeUnit.SECONDS); assertTrue("Timed out while waiting for after listener notification", signalled); assertEquals(null, cache.get(1)); ignore.get(5, TimeUnit.SECONDS); } public void testClearVisibility() throws Exception { cache.put(1, "v1"); cache.put(2, "v1"); cache.put(3, "v1"); final CyclicBarrier after = new CyclicBarrier(2); final CountDownLatch afterContinue = new CountDownLatch(1); final CountDownLatch before = new CountDownLatch(1); cache.addListener(new CacheClearListener(before, afterContinue, after)); assertEquals("v1", cache.get(1)); assertEquals("v1", cache.get(2)); assertEquals("v1", cache.get(3)); Future<Void> ignore = fork(new Callable<Void>() { @Override public Void call() throws Exception { cache.clear(); return null; } }); boolean signalled = before.await(30, TimeUnit.SECONDS); assertTrue("Timed out while waiting for before listener notification", signalled); assertEquals("v1", cache.get(1)); assertEquals("v1", cache.get(2)); assertEquals("v1", cache.get(3)); // Let the isPre=false callback continue afterContinue.countDown(); // Wait for isPre=false remove notification for k=1 after.await(30, TimeUnit.SECONDS); assertEquals(null, cache.get(1)); // Wait for isPre=false remove notification for k=2 after.await(30, TimeUnit.SECONDS); assertEquals(null, cache.get(2)); // Wait for isPre=false remove notification for k=3 after.await(30, TimeUnit.SECONDS); assertEquals(null, cache.get(3)); assertTrue(cache.isEmpty()); ignore.get(5, TimeUnit.SECONDS); } private void updateCacheAssertInListener(WithAssertListener listener) throws Exception { cache.addListener(listener); Future<Void> ignore = fork(new Callable<Void>() { @Override public Void call() throws Exception { cache.put("k", "v"); return null; } }); listener.latch.await(30, TimeUnit.SECONDS); assert listener.assertNotNull; assert listener.assertValue; ignore.get(5, TimeUnit.SECONDS); } private void updateCache(Visibility visibility) throws Exception { final String key = "k-" + visibility; final String value = "k-" + visibility; final CountDownLatch after = new CountDownLatch(1); final CountDownLatch afterContinue = new CountDownLatch(1); final CountDownLatch before = new CountDownLatch(1); cache.addListener(new EntryListener(before, afterContinue, after)); switch (visibility) { case SIZE: assertEquals(0, cache.size()); break; case GET: assertNull(cache.get(key)); break; } Future<Void> ignore = fork(new Callable<Void>() { @Override public Void call() throws Exception { cache.put(key, value); return null; } }); boolean signalled = before.await(30, TimeUnit.SECONDS); assertTrue("Timed out while waiting for before listener notification", signalled); switch (visibility) { case SIZE: assertEquals(0, cache.size()); break; case GET: assertNull(cache.get(key)); break; } // Let the isPre=false callback continue afterContinue.countDown(); signalled = after.await(30, TimeUnit.SECONDS); assertTrue("Timed out while waiting for after listener notification", signalled); switch (visibility) { case SIZE: assertEquals(1, cache.size()); break; case GET: Object retVal = cache.get(key); assertNotNull(retVal); assertEquals(retVal, value); break; } ignore.get(5, TimeUnit.SECONDS); } @Listener public static class EntriesEvictedListener { // Use a different listener class for @CacheEntriesEvicted vs // @CacheEntryEvicted to tests both callbacks separately Log log = LogFactory.getLog(EntriesEvictedListener.class); final CountDownLatch after; public EntriesEvictedListener(CountDownLatch after) { this.after = after; } @CacheEntriesEvicted @SuppressWarnings("unused") public void entryEvicted(Event e) { log.info("Cache entries evicted, now check in different thread"); after.countDown(); // Force a bit of delay in the listener so that lack of visibility // of changes in container can be appreciated more easily TestingUtil.sleepThread(1000); } } @Listener public static class CacheClearListener { Log log = LogFactory.getLog(CacheClearListener.class); final CyclicBarrier after; final CountDownLatch before; final CountDownLatch afterContinue; public CacheClearListener(CountDownLatch before, CountDownLatch afterContinue, CyclicBarrier after) { this.before = before; this.after = after; this.afterContinue = afterContinue; } @CacheEntryRemoved @SuppressWarnings("unused") public void entryTouched(Event e) { if (!e.isPre()) { log.infof("Cache entry removed, event is: %s", e); try { after.await(30, TimeUnit.SECONDS); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } catch (BrokenBarrierException e1) { throw new IllegalStateException(e1); } catch (TimeoutException e1) { throw new IllegalStateException(e1); } // Force a bit of delay in the listener so that lack of visibility // of changes in container can be appreciated more easily TestingUtil.sleepThread(1000); } else { before.countDown(); try { boolean signalled = afterContinue.await(30, TimeUnit.SECONDS); assertTrue("Timed out while waiting for post listener event to execute", signalled); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } } } } @Listener public static class EntryListener { Log log = LogFactory.getLog(EntryListener.class); final CountDownLatch after; final CountDownLatch before; final CountDownLatch afterContinue; public EntryListener(CountDownLatch before, CountDownLatch afterContinue, CountDownLatch after) { this.before = before; this.after = after; this.afterContinue = afterContinue; } @CacheEntriesEvicted @SuppressWarnings("unused") public void entryEvicted(Event e) { log.info("Cache entry evicted, now check in different thread"); after.countDown(); // Force a bit of delay in the listener so that lack of visibility // of changes in container can be appreciated more easily TestingUtil.sleepThread(1000); } @CacheEntryCreated @CacheEntryRemoved @SuppressWarnings("unused") public void entryTouched(Event e) { if (!e.isPre()) { log.info("Cache entry touched, now check in different thread"); after.countDown(); // Force a bit of delay in the listener so that lack of visibility // of changes in container can be appreciated more easily TestingUtil.sleepThread(1000); } else { before.countDown(); try { boolean signalled = afterContinue.await(30, TimeUnit.SECONDS); assertTrue("Timed out while waiting for post listener event to execute", signalled); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } } } } public static abstract class WithAssertListener { Log log = LogFactory.getLog(WithAssertListener.class); final CountDownLatch latch; volatile boolean assertNotNull; volatile boolean assertValue; protected WithAssertListener(CountDownLatch latch) { this.latch = latch; } protected void assertCacheContents(CacheEntryEvent e) { if (!e.isPre()) { log.info("Cache entry created, now check cache contents"); Object value = e.getCache().get("k"); if (value == null) { assertNotNull = false; assertValue = false; } else { assertNotNull = true; assertValue = value.equals("v"); } // Force a bit of delay in the listener latch.countDown(); } } } @Listener public static class EntryCreatedWithAssertListener extends WithAssertListener { protected EntryCreatedWithAssertListener(CountDownLatch latch) { super(latch); } @CacheEntryCreated @SuppressWarnings("unused") public void entryCreated(CacheEntryEvent e) { assertCacheContents(e); } } @Listener public static class EntryModifiedWithAssertListener extends WithAssertListener { protected EntryModifiedWithAssertListener(CountDownLatch latch) { super(latch); } @CacheEntryCreated @CacheEntryModified @SuppressWarnings("unused") public void entryCreated(CacheEntryEvent e) { assertCacheContents(e); } } private enum Visibility { SIZE, GET } }
14,529
31.004405
98
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/FilterListenerTest.java
package org.infinispan.notifications.cachelistener; import java.io.IOException; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.filter.CacheEventFilter; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.Test; import static org.testng.AssertJUnit.assertEquals; @Test(groups = "functional", testName = "notifications.cachelistener.FilterListenerTest") public class FilterListenerTest extends AbstractInfinispanTest { public void testLocal() throws IOException { this.test(false); } public void testSimple() throws IOException { this.test(true); } private void test(boolean simple) throws IOException { GlobalConfiguration global = new GlobalConfigurationBuilder().nonClusteredDefault().build(); Configuration local = new ConfigurationBuilder().clustering().cacheMode(CacheMode.LOCAL).simpleCache(simple).build(); try (EmbeddedCacheManager manager = new DefaultCacheManager(global)) { manager.defineConfiguration("local", local); Cache<Object, Object> cache = manager.getCache("local"); TestListener listener = new TestListener(); cache.addListener(listener, listener, null); cache.put("foo", "bar"); cache.put(1, 2); try { assertEquals(1, listener.events.size()); assertEquals("foo", listener.events.remove()); } finally { cache.removeListener(listener); cache.stop(); } } } @Listener public static class TestListener implements CacheEventFilter<Object, Object> { private final Queue<Object> events = new LinkedBlockingQueue<>(); @CacheEntryCreated public void onEvent(CacheEntryCreatedEvent<Object, Object> event) { if (!event.isPre()) { this.events.add(event.getKey()); } } @Override public boolean accept(Object key, Object oldValue, Metadata oldMetadata, Object newValue, Metadata newMetadata, EventType eventType) { return key instanceof String; } } }
2,901
37.693333
140
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/CacheNotifierImplInitialTransferLocalTest.java
package org.infinispan.notifications.cachelistener; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.Test; @Test(groups = "unit", testName = "notifications.cachelistener.CacheNotifierImplInitialTransferLocalTest") public class CacheNotifierImplInitialTransferLocalTest extends BaseCacheNotifierImplInitialTransferTest { protected CacheNotifierImplInitialTransferLocalTest() { super(CacheMode.LOCAL); } }
453
33.923077
106
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/TransactionSuspendedCacheNotifierTest.java
package org.infinispan.notifications.cachelistener; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntriesEvicted; import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryInvalidated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryLoaded; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.annotation.CacheEntryVisited; import org.infinispan.notifications.cachelistener.annotation.TransactionCompleted; import org.infinispan.notifications.cachelistener.annotation.TransactionRegistered; import org.infinispan.notifications.cachelistener.event.Event; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.annotations.Test; /** * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "notifications.cachelistener.TransactionSuspendedCacheNotifierTest") @CleanupAfterMethod public class TransactionSuspendedCacheNotifierTest extends SingleCacheManagerTest { public void testTransactionSuspended() throws Exception { TestListener listener = new TestListener(); cache.getAdvancedCache().addListener(listener); assertTrue(cache.isEmpty()); //created cache.put("key", "value"); assertEquals("value", cache.get("key")); //modified cache.put("key", "new-value"); assertEquals("new-value", cache.get("key")); tm().begin(); assertEquals("new-value", cache.get("key")); tm().commit(); //removed cache.remove("key"); assertNull(cache.get("key")); cache.clear(); assertTrue(cache.isEmpty()); if (listener.list.size() > 0) { for (Throwable throwable : listener.list) { log.error("Error in listener...", throwable); } fail("Listener catch some errors"); } } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(true); return TestCacheManagerFactory.createCacheManager(builder); } @Listener(sync = true) public static class TestListener { private final Log log = LogFactory.getLog(TestListener.class); private final List<Throwable> list = Collections.synchronizedList(new ArrayList<Throwable>(2)); @CacheEntryActivated @CacheEntryCreated @CacheEntriesEvicted @CacheEntryInvalidated @CacheEntryLoaded @CacheEntryModified @CacheEntryPassivated @CacheEntryRemoved @CacheEntryVisited @TransactionCompleted @TransactionRegistered public void handle(Event e) { try { Object value = e.getCache().getAdvancedCache().withFlags(Flag.SKIP_LISTENER_NOTIFICATION).get("key"); log.debugf("Event=%s, value=%s", e, value); } catch (Throwable throwable) { list.add(throwable); } } } }
3,968
35.412844
113
java
null
infinispan-main/core/src/test/java/org/infinispan/notifications/cachelistener/CacheNotifierImplWithConverterTest.java
package org.infinispan.notifications.cachelistener; import java.util.Set; import org.infinispan.commons.util.Util; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.event.Event; import org.testng.annotations.Test; @Test(groups = "unit", testName = "notifications.cachelistener.CacheNotifierImplWithConverterTest") public class CacheNotifierImplWithConverterTest extends CacheNotifierImplTest { @Override protected void addListener() { // Installing a listener with converter Set<Class> filterAnnotations = Util.asSet(CacheEntryCreated.class, CacheEntryModified.class, CacheEntryRemoved.class, CacheEntryExpired.class); n.addFilteredListener(cl, null, (key, oldValue, oldMetadata, newValue, newMetadata, eventType) -> "custom event for test (" + eventType.getType().name() + "," + key + "," + newValue + ")", filterAnnotations); } @Override protected Object getExpectedEventValue(Object key, Object val, Event.Type t) { // the converter (see lambda above) returns a string with format: // "custom event for test (CACHE_ENTRY_<event_type>,<key>,<value>)" return "custom event for test (" + t.name() + "," + key + "," + val + ")"; } }
1,566
45.088235
103
java