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/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/stress/ClientEventStressTest.java
|
package org.infinispan.client.hotrod.stress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.event.ClientEvent;
import org.infinispan.client.hotrod.logging.Log;
import org.infinispan.client.hotrod.logging.LogFactory;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.commons.test.TestResourceTracker;
import org.testng.annotations.Test;
@Test(groups = "stress", testName = "client.hotrod.event.ClientEventStressTest", timeOut = 15*60*1000)
public class ClientEventStressTest extends SingleCacheManagerTest {
private static final Log log = LogFactory.getLog(ClientEventStressTest.class);
static int NUM_CLIENTS = 3;
static int NUM_THREADS_PER_CLIENT = 10;
static final int NUM_OPERATIONS = 10_000;
static final int NUM_EVENTS = NUM_OPERATIONS * NUM_THREADS_PER_CLIENT * NUM_CLIENTS * NUM_CLIENTS;
static ExecutorService EXEC = Executors.newCachedThreadPool();
HotRodServer hotrodServer;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
return TestCacheManagerFactory.createCacheManager();
}
@Override
protected void setup() throws Exception {
super.setup();
hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
}
RemoteCacheManager getRemoteCacheManager(int port) {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(port);
return new InternalRemoteCacheManager(builder.build());
}
public void testStressEvents() {
TestResourceTracker.testThreadStarted(this.getTestName());
CyclicBarrier barrier = new CyclicBarrier((NUM_CLIENTS * NUM_THREADS_PER_CLIENT) + 1);
List<Future<Void>> futures = new ArrayList<>(NUM_CLIENTS * NUM_THREADS_PER_CLIENT);
List<ClientEntryListener> listeners = new ArrayList<>(NUM_CLIENTS);
RemoteCacheManager[] remotecms = new RemoteCacheManager[NUM_CLIENTS];
for (int i = 0; i < NUM_CLIENTS; i++)
remotecms[i] = getRemoteCacheManager(hotrodServer.getPort());
for (RemoteCacheManager remotecm : remotecms) {
RemoteCache<Integer, Integer> remote = remotecm.getCache();
ClientEntryListener listener = new ClientEntryListener();
listeners.add(listener);
remote.addClientListener(listener);
for (int i = 0; i < NUM_THREADS_PER_CLIENT; i++) {
Callable<Void> call = new Put(barrier, remote);
futures.add(EXEC.submit(call));
}
}
barrierAwait(barrier); // wait for all threads to be ready
barrierAwait(barrier); // wait for all threads to finish
for (Future<Void> f : futures)
futureGet(f);
log.debugf("Put operations completed, wait for events...");
eventuallyEquals(NUM_EVENTS, () -> countEvents(listeners));
}
int countEvents(List<ClientEntryListener> listeners) {
Integer count = listeners.stream().reduce(0, (acc, l) -> acc + l.count.get(), (x, y) -> x + y);
log.debugf("Event count is %d, target %d%n", (int) count, NUM_EVENTS);
return count;
}
static class Put implements Callable<Void> {
static final ThreadLocalRandom R = ThreadLocalRandom.current();
final CyclicBarrier barrier;
final RemoteCache<Integer, Integer> remote;
public Put(CyclicBarrier barrier, RemoteCache<Integer, Integer> remote) {
this.barrier = barrier;
this.remote = remote;
}
@Override
public Void call() throws Exception {
barrierAwait(barrier);
try {
for (int i = 0; i < NUM_OPERATIONS; i++) {
int value = R.nextInt(Integer.MAX_VALUE);
remote.put(value, value); // TODO: Consider using async puts
}
return null;
} finally {
barrierAwait(barrier);
}
}
}
@ClientListener
static class ClientEntryListener {
final AtomicInteger count = new AtomicInteger();
@ClientCacheEntryCreated
@ClientCacheEntryModified
@SuppressWarnings("unused")
public void handleClientEvent(ClientEvent event) {
int countSoFar;
if ((countSoFar = count.incrementAndGet()) % 100 == 0) {
log.debugf("Reached %s", countSoFar);
}
}
}
static int barrierAwait(CyclicBarrier barrier) {
try {
return barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
throw new AssertionError(e);
}
}
<T> T futureGet(Future<T> future) {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
throw new AssertionError(e);
}
}
}
| 5,855
| 35.830189
| 102
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/stress/near/EagerNearCacheStressTest.java
|
package org.infinispan.client.hotrod.stress.near;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManagers;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withRemoteCacheManager;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.configuration.NearCacheMode;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.client.hotrod.test.RemoteCacheManagerCallable;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
/**
* Manual test, requires external Hot Rod server.
*/
@Test(groups = "manual", testName = "client.hotrod.stress.near.EagerNearCacheStressTest")
public class EagerNearCacheStressTest {
static int NUM_CLIENTS = 3;
static int NUM_THREADS_PER_CLIENT = 10;
static ExecutorService EXEC = Executors.newCachedThreadPool();
static final int NUM_OPERATIONS = 10_000_000;
static final int NUM_KEYS_PRELOAD = 1_000;
static final int KEY_RANGE = 1_000;
@AfterClass
public static void shutdownExecutor() {
EXEC.shutdown();
}
EmbeddedCacheManager createCacheManager() {
return TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration());
}
RemoteCacheManager getRemoteCacheManager(int port) {
return getRemoteCacheManager(port, NearCacheMode.DISABLED, -1);
}
RemoteCacheManager getRemoteCacheManager(int port, NearCacheMode nearCacheMode, int maxEntries) {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.nearCache().mode(nearCacheMode).maxEntries(maxEntries);
builder.addServer().host("127.0.0.1").port(port);
return new InternalRemoteCacheManager(builder.build());
}
public void testLocalPreloadAndGetPut10to1() {
runPreloadAndOps(NearCacheMode.INVALIDATED, -1, 0.90);
}
void runPreloadAndOps(NearCacheMode nearCacheMode, int maxEntries, double getRatio) {
EmbeddedCacheManager cm = createCacheManager();
//HotRodServer server = createHotRodServer(cm);
int port = 11222;
preloadData(port);
RemoteCacheManager[] remotecms = new RemoteCacheManager[NUM_CLIENTS];
for (int i = 0; i < NUM_CLIENTS; i++)
remotecms[i] = getRemoteCacheManager(port, nearCacheMode, maxEntries);
try {
ops(remotecms, getRatio);
} finally {
killRemoteCacheManagers(remotecms);
//killServers(server);
TestingUtil.killCacheManagers(cm);
}
}
void ops(RemoteCacheManager[] remotecms, double getRatio) {
CyclicBarrier barrier = new CyclicBarrier((NUM_CLIENTS * NUM_THREADS_PER_CLIENT) + 1);
List<Future<Void>> futures = new ArrayList<>(NUM_CLIENTS * NUM_THREADS_PER_CLIENT);
for (RemoteCacheManager remotecm : remotecms) {
RemoteCache<Integer, String> remote = remotecm.getCache();
for (int i = 0; i < NUM_THREADS_PER_CLIENT; i++) {
Callable<Void> call = new Main(barrier, remote, getRatio);
futures.add(EXEC.submit(call));
}
}
barrierAwait(barrier); // wait for all threads to be ready
barrierAwait(barrier); // wait for all threads to finish
for (Future<Void> f : futures)
futureGet(f);
}
void preloadData(int port) {
// Preload data
withRemoteCacheManager(new RemoteCacheManagerCallable(getRemoteCacheManager(port)) {
@Override
public void call() {
RemoteCache<Integer, String> remote = rcm.getCache();
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < NUM_KEYS_PRELOAD; ++i)
map.put(i, TestingUtil.generateRandomString(512));
remote.putAll(map);
}
});
}
static abstract class Runner implements Callable<Void> {
final CyclicBarrier barrier;
final RemoteCache<Integer, String> remote;
final double getRatio;
Runner(CyclicBarrier barrier, RemoteCache<Integer, String> remote, double getRatio) {
this.barrier = barrier;
this.remote = remote;
this.getRatio = getRatio;
}
@Override
public Void call() throws Exception {
barrierAwait(barrier);
try {
run();
return null;
} finally {
barrierAwait(barrier);
}
}
abstract void run();
}
final static class Main extends Runner {
static final ThreadLocalRandom R = ThreadLocalRandom.current();
Main(CyclicBarrier barrier, RemoteCache<Integer, String> remote, double getRatio) {
super(barrier, remote, getRatio);
}
@Override
void run() {
double maxGetKey = KEY_RANGE * getRatio;
for (int i = 0; i < NUM_OPERATIONS; i++) {
int key = R.nextInt(KEY_RANGE);
if (key < maxGetKey) {
String value = remote.get(key);
assertNotNull(value);
} else {
String prev = remote.put(key, TestingUtil.generateRandomString(512));
assertNull(prev);
}
}
}
}
static int barrierAwait(CyclicBarrier barrier) {
try {
return barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
throw new AssertionError(e);
}
}
<T> T futureGet(Future<T> future) {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
throw new AssertionError(e);
}
}
}
| 6,568
| 34.128342
| 100
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/configuration/SSLClassPathConfigurationTest.java
|
package org.infinispan.client.hotrod.configuration;
import static org.testng.Assert.assertNotNull;
import javax.net.ssl.SSLContext;
import org.infinispan.commons.test.security.TestCertificates;
import org.infinispan.commons.util.SslContextFactory;
import org.testng.annotations.Test;
@Test(testName = "client.hotrod.configuration.SSLClassPathConfigurationTest", groups = "functional")
public class SSLClassPathConfigurationTest {
public void testLoadTrustStore() {
String keyStoreFileName = TestCertificates.certificate("client");
String truststoreFileName = "classpath:ca.pfx";
SSLContext context =
new SslContextFactory()
.keyStoreFileName(keyStoreFileName)
.keyStoreType(TestCertificates.KEYSTORE_TYPE)
.keyStorePassword(TestCertificates.KEY_PASSWORD)
.trustStoreFileName(truststoreFileName)
.trustStoreType(TestCertificates.KEYSTORE_TYPE)
.trustStorePassword(TestCertificates.KEY_PASSWORD).getContext();
assertNotNull(context);
}
}
| 1,094
| 34.322581
| 100
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/configuration/ConfigurationTest.java
|
package org.infinispan.client.hotrod.configuration;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.ASYNC_EXECUTOR_FACTORY;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.AUTH_CALLBACK_HANDLER;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.AUTH_CLIENT_SUBJECT;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.AUTH_PASSWORD;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.AUTH_REALM;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.AUTH_SERVER_NAME;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.AUTH_USERNAME;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CLUSTER_PROPERTIES_PREFIX;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CONNECTION_POOL_EXHAUSTED_ACTION;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CONNECTION_POOL_MAX_ACTIVE;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CONNECTION_POOL_MAX_PENDING_REQUESTS;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CONNECTION_POOL_MAX_WAIT;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CONNECTION_POOL_MIN_IDLE;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.CONNECT_TIMEOUT;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.HASH_FUNCTION_PREFIX;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.JAVA_SERIAL_ALLOWLIST;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.JMX;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.JMX_DOMAIN;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.JMX_NAME;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.KEY_SIZE_ESTIMATE;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.KEY_STORE_CERTIFICATE_PASSWORD;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.KEY_STORE_FILE_NAME;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.KEY_STORE_PASSWORD;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.MAX_RETRIES;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.NEAR_CACHE_MAX_ENTRIES;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.NEAR_CACHE_MODE;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.NEAR_CACHE_NAME_PATTERN;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.PROTOCOL_VERSION;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.REQUEST_BALANCING_STRATEGY;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SASL_MECHANISM;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SASL_PROPERTIES_PREFIX;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SERVER_LIST;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SNI_HOST_NAME;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SO_TIMEOUT;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SSL_CONTEXT;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SSL_PROTOCOL;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.STATISTICS;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TCP_KEEP_ALIVE;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TCP_NO_DELAY;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TRACING_PROPAGATION_ENABLED;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TRUST_STORE_FILE_NAME;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TRUST_STORE_PASSWORD;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.USE_AUTH;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.USE_SSL;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.VALUE_SIZE_ESTIMATE;
import static org.infinispan.commons.test.Exceptions.expectException;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;
import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.regex.Pattern;
import javax.net.ssl.SSLContext;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.infinispan.client.hotrod.ProtocolVersion;
import org.infinispan.client.hotrod.SomeAsyncExecutorFactory;
import org.infinispan.client.hotrod.SomeCustomConsistentHashV2;
import org.infinispan.client.hotrod.SomeRequestBalancingStrategy;
import org.infinispan.client.hotrod.impl.ConfigurationProperties;
import org.infinispan.client.hotrod.impl.HotRodURI;
import org.infinispan.client.hotrod.security.BasicCallbackHandler;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.transaction.lookup.RemoteTransactionManagerLookup;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.marshall.JavaSerializationMarshaller;
import org.infinispan.commons.marshall.ProtoStreamMarshaller;
import org.infinispan.commons.marshall.UTF8StringMarshaller;
import org.infinispan.commons.util.FileLookupFactory;
import org.infinispan.test.AbstractInfinispanTest;
import org.testng.annotations.Test;
@Test(testName = "client.hotrod.configuration.ConfigurationTest", groups = "functional")
public class ConfigurationTest extends AbstractInfinispanTest {
static final Map<String, Function<Configuration, ?>> OPTIONS = new HashMap<>();
static final Map<Class<?>, Function<Object, Object>> TYPES = new HashMap<>();
static {
OPTIONS.put(ASYNC_EXECUTOR_FACTORY, c -> c.asyncExecutorFactory().factoryClass());
OPTIONS.put(REQUEST_BALANCING_STRATEGY, c -> c.balancingStrategyFactory().get().getClass());
OPTIONS.put("maxActive", c -> c.connectionPool().maxActive());
OPTIONS.put(CONNECTION_POOL_MAX_ACTIVE, c -> c.connectionPool().maxActive());
OPTIONS.put("maxWait", c -> c.connectionPool().maxWait());
OPTIONS.put(CONNECTION_POOL_MAX_WAIT, c -> c.connectionPool().maxWait());
OPTIONS.put("minIdle", c -> c.connectionPool().minIdle());
OPTIONS.put(CONNECTION_POOL_MIN_IDLE, c -> c.connectionPool().minIdle());
OPTIONS.put("exhaustedAction", c -> c.connectionPool().exhaustedAction());
OPTIONS.put(CONNECTION_POOL_EXHAUSTED_ACTION, c -> c.connectionPool().exhaustedAction());
OPTIONS.put("minEvictableIdleTimeMillis", c -> c.connectionPool().minEvictableIdleTime());
OPTIONS.put(CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME, c -> c.connectionPool().minEvictableIdleTime());
OPTIONS.put(CONNECTION_POOL_MAX_PENDING_REQUESTS, c -> c.connectionPool().maxPendingRequests());
OPTIONS.put(CONNECT_TIMEOUT, Configuration::connectionTimeout);
OPTIONS.put(PROTOCOL_VERSION, Configuration::version);
OPTIONS.put(SO_TIMEOUT, Configuration::socketTimeout);
OPTIONS.put(TCP_NO_DELAY, Configuration::tcpNoDelay);
OPTIONS.put(TCP_KEEP_ALIVE, Configuration::tcpKeepAlive);
OPTIONS.put(KEY_SIZE_ESTIMATE, Configuration::keySizeEstimate);
OPTIONS.put(VALUE_SIZE_ESTIMATE, Configuration::valueSizeEstimate);
OPTIONS.put(MAX_RETRIES, Configuration::maxRetries);
OPTIONS.put(USE_SSL, c -> c.security().ssl().enabled());
OPTIONS.put(KEY_STORE_FILE_NAME, c -> c.security().ssl().keyStoreFileName());
OPTIONS.put(SNI_HOST_NAME, c -> c.security().ssl().sniHostName());
OPTIONS.put(KEY_STORE_PASSWORD, c -> new String(c.security().ssl().keyStorePassword()));
OPTIONS.put(KEY_STORE_CERTIFICATE_PASSWORD, c -> new String(c.security().ssl().keyStoreCertificatePassword()));
OPTIONS.put(TRUST_STORE_FILE_NAME, c -> c.security().ssl().trustStoreFileName());
OPTIONS.put(TRUST_STORE_PASSWORD, c -> new String(c.security().ssl().trustStorePassword()));
OPTIONS.put(SSL_PROTOCOL, c -> c.security().ssl().protocol());
OPTIONS.put(SSL_CONTEXT, c -> c.security().ssl().sslContext());
OPTIONS.put(USE_AUTH, c -> c.security().authentication().enabled());
OPTIONS.put(SASL_MECHANISM, c -> c.security().authentication().saslMechanism());
OPTIONS.put(AUTH_CALLBACK_HANDLER, c -> c.security().authentication().callbackHandler());
OPTIONS.put(AUTH_SERVER_NAME, c -> c.security().authentication().serverName());
OPTIONS.put(AUTH_CLIENT_SUBJECT, c -> c.security().authentication().clientSubject());
OPTIONS.put(SASL_PROPERTIES_PREFIX + ".A", c -> c.security().authentication().saslProperties().get("A"));
OPTIONS.put(SASL_PROPERTIES_PREFIX + ".B", c -> c.security().authentication().saslProperties().get("B"));
OPTIONS.put(SASL_PROPERTIES_PREFIX + ".C", c -> c.security().authentication().saslProperties().get("C"));
OPTIONS.put(JAVA_SERIAL_ALLOWLIST, Configuration::serialAllowList);
OPTIONS.put(NEAR_CACHE_MODE, c -> c.nearCache().mode());
OPTIONS.put(NEAR_CACHE_MAX_ENTRIES, c -> c.nearCache().maxEntries());
OPTIONS.put(NEAR_CACHE_NAME_PATTERN, c -> c.nearCache().cacheNamePattern().pattern());
TYPES.put(Boolean.class, b -> Boolean.toString((Boolean) b));
TYPES.put(ExhaustedAction.class, e -> e.toString());
TYPES.put(Class.class, c -> ((Class<?>) c).getName());
TYPES.put(Integer.class, Object::toString);
TYPES.put(Long.class, Object::toString);
TYPES.put(String.class, Function.identity());
TYPES.put(SSLContext.class, Function.identity());
TYPES.put(MyCallbackHandler.class, Function.identity());
TYPES.put(Subject.class, Function.identity());
TYPES.put(ProtocolVersion.class, p -> p.toString());
TYPES.put(NearCacheMode.class, p -> p.toString());
TYPES.put(mkClass(), l -> String.join(",", (List<String>) l));
TYPES.put(Pattern.class, Function.identity());
}
private static Class<?> mkClass() {
try {
return Class.forName("java.util.Arrays$ArrayList");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
CallbackHandler callbackHandler = new MyCallbackHandler();
public static class MyCallbackHandler implements CallbackHandler {
@Override
public void handle(Callback[] callbacks) {
}
}
Subject clientSubject = new Subject();
public void testConfiguration() {
Map<String, String> saslProperties = new HashMap<>();
saslProperties.put("A", "1");
saslProperties.put("B", "2");
saslProperties.put("C", "3");
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder
.statistics().enable().jmxEnable().jmxDomain("jmxInfinispanDomain").jmxName("jmxInfinispan")
.addServer()
.host("host1")
.port(11222)
.addServer()
.host("host2")
.port(11222)
.asyncExecutorFactory()
.factoryClass(SomeAsyncExecutorFactory.class)
.balancingStrategy(SomeRequestBalancingStrategy.class)
.connectionPool()
.maxActive(100)
.maxWait(1000)
.minIdle(10)
.minEvictableIdleTime(12000)
.exhaustedAction(ExhaustedAction.WAIT)
.maxPendingRequests(12)
.connectionTimeout(100)
.version(ProtocolVersion.PROTOCOL_VERSION_29)
.consistentHashImpl(2, SomeCustomConsistentHashV2.class)
.socketTimeout(100)
.tcpNoDelay(false)
.keySizeEstimate(128)
.valueSizeEstimate(1024)
.maxRetries(0)
.tcpKeepAlive(true)
.security()
.ssl()
.enable()
.keyStoreFileName("my-key-store.file")
.keyStorePassword("my-key-store.password".toCharArray())
.keyStoreCertificatePassword("my-key-store-certificate.password".toCharArray())
.trustStoreFileName("my-trust-store.file")
.trustStorePassword("my-trust-store.password".toCharArray())
.protocol("TLSv1.1")
.security()
.authentication()
.enable()
.saslMechanism("my-sasl-mechanism")
.callbackHandler(callbackHandler)
.serverName("my-server-name")
.clientSubject(clientSubject)
.saslProperties(saslProperties)
.addJavaSerialAllowList(".*Person.*", ".*Employee.*")
.nearCache()
.mode(NearCacheMode.INVALIDATED)
.maxEntries(10_000)
.cacheNamePattern("near.*")
.addCluster("siteA")
.addClusterNode("hostA1", 11222)
.addClusterNode("hostA2", 11223)
.addCluster("siteB")
.addClusterNodes("hostB1:11222; hostB2:11223");
Configuration configuration = builder.build();
validateConfiguration(configuration);
ConfigurationBuilder newBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
newBuilder.read(configuration);
Configuration newConfiguration = newBuilder.build();
validateConfiguration(newConfiguration);
}
public void testWithProperties() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
Properties p = new Properties();
p.setProperty(SERVER_LIST, "host1:11222; host2:11222");
p.setProperty(ASYNC_EXECUTOR_FACTORY, "org.infinispan.client.hotrod.SomeAsyncExecutorFactory");
p.setProperty(REQUEST_BALANCING_STRATEGY, "org.infinispan.client.hotrod.SomeRequestBalancingStrategy");
p.setProperty(HASH_FUNCTION_PREFIX + "." + 2, "org.infinispan.client.hotrod.SomeCustomConsistentHashV2");
p.setProperty(CONNECTION_POOL_MAX_ACTIVE, "100");
p.setProperty("maxTotal", "150");
p.setProperty(CONNECTION_POOL_MAX_WAIT, "1000");
p.setProperty("maxIdle", "20");
p.setProperty(CONNECTION_POOL_MIN_IDLE, "10");
p.setProperty(CONNECTION_POOL_EXHAUSTED_ACTION, ExhaustedAction.WAIT.name());
p.setProperty("numTestsPerEvictionRun", "5");
p.setProperty("timeBetweenEvictionRunsMillis", "15000");
p.setProperty(CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME, "12000");
p.setProperty(CONNECTION_POOL_MAX_PENDING_REQUESTS, "12");
p.setProperty("testOnBorrow", "true");
p.setProperty("testOnReturn", "true");
p.setProperty("testWhileIdle", "false");
p.setProperty(CONNECT_TIMEOUT, "100");
p.setProperty(PROTOCOL_VERSION, "2.9");
p.setProperty(SO_TIMEOUT, "100");
p.setProperty(TCP_NO_DELAY, "false");
p.setProperty(TCP_KEEP_ALIVE, "true");
p.setProperty(KEY_SIZE_ESTIMATE, "128");
p.setProperty(VALUE_SIZE_ESTIMATE, "1024");
p.setProperty(MAX_RETRIES, "0");
p.setProperty(USE_SSL, "true");
p.setProperty(KEY_STORE_FILE_NAME, "my-key-store.file");
p.setProperty(KEY_STORE_PASSWORD, "my-key-store.password");
p.setProperty(KEY_STORE_CERTIFICATE_PASSWORD, "my-key-store-certificate.password");
p.setProperty(TRUST_STORE_FILE_NAME, "my-trust-store.file");
p.setProperty(TRUST_STORE_PASSWORD, "my-trust-store.password");
p.setProperty(SSL_PROTOCOL, "TLSv1.1");
p.setProperty(USE_AUTH, "true");
p.setProperty(SASL_MECHANISM, "my-sasl-mechanism");
p.put(AUTH_CALLBACK_HANDLER, callbackHandler);
p.setProperty(AUTH_SERVER_NAME, "my-server-name");
p.put(AUTH_CLIENT_SUBJECT, clientSubject);
p.setProperty(SASL_PROPERTIES_PREFIX + ".A", "1");
p.setProperty(SASL_PROPERTIES_PREFIX + ".B", "2");
p.setProperty(SASL_PROPERTIES_PREFIX + ".C", "3");
p.setProperty(JAVA_SERIAL_ALLOWLIST, ".*Person.*,.*Employee.*");
p.setProperty(NEAR_CACHE_MODE, NearCacheMode.INVALIDATED.name());
p.setProperty(NEAR_CACHE_MAX_ENTRIES, "10000");
p.setProperty(NEAR_CACHE_NAME_PATTERN, "near.*");
p.setProperty(CLUSTER_PROPERTIES_PREFIX + ".siteA", "hostA1:11222; hostA2:11223");
p.setProperty(CLUSTER_PROPERTIES_PREFIX + ".siteB", "hostB1:11222; hostB2:11223");
p.setProperty(STATISTICS, "true");
p.setProperty(JMX, "true");
p.setProperty(JMX_NAME, "jmxInfinispan");
p.setProperty(JMX_DOMAIN, "jmxInfinispanDomain");
p.setProperty(TRACING_PROPAGATION_ENABLED, "false");
Configuration configuration = builder.withProperties(p).build();
validateConfiguration(configuration);
ConfigurationBuilder newBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
newBuilder.read(configuration, Combine.DEFAULT);
Configuration newConfiguration = newBuilder.build();
validateConfiguration(newConfiguration);
p.setProperty(PROTOCOL_VERSION, "auto");
configuration = new ConfigurationBuilder().withProperties(p).build();
assertEquals(ProtocolVersion.PROTOCOL_VERSION_AUTO, configuration.version());
assertFalse(configuration.tracingPropagationEnabled());
}
public void testSSLContext() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.security()
.ssl()
.enable()
.sslContext(getSSLContext());
Configuration configuration = builder.build();
validateSSLContextConfiguration(configuration);
ConfigurationBuilder newBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
newBuilder.read(configuration, Combine.DEFAULT);
Configuration newConfiguration = newBuilder.build();
validateSSLContextConfiguration(newConfiguration);
}
public void testSni() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.security()
.ssl()
.enable()
.sslContext(getSSLContext())
.sniHostName("sni");
Configuration configuration = builder.build();
validateSniContextConfiguration(configuration);
ConfigurationBuilder newBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
newBuilder.read(configuration, Combine.DEFAULT);
Configuration newConfiguration = newBuilder.build();
validateSniContextConfiguration(newConfiguration);
}
public void testWithPropertiesSSLContext() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
Properties p = new Properties();
p.put(SSL_CONTEXT, getSSLContext());
Configuration configuration = builder.withProperties(p).build();
validateSSLContextConfiguration(configuration);
ConfigurationBuilder newBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
newBuilder.read(configuration, Combine.DEFAULT);
Configuration newConfiguration = newBuilder.build();
validateSSLContextConfiguration(newConfiguration);
}
public void testWithPropertiesSni() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
Properties p = new Properties();
p.put(TRUST_STORE_FILE_NAME, "my-trust-store.file");
p.put(TRUST_STORE_PASSWORD, "my-trust-store.password");
p.put(SNI_HOST_NAME, "sni");
Configuration configuration = builder.withProperties(p).build();
validateSniContextConfiguration(configuration);
ConfigurationBuilder newBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
newBuilder.read(configuration, Combine.DEFAULT);
Configuration newConfiguration = newBuilder.build();
validateSniContextConfiguration(newConfiguration);
}
public void testWithPropertiesAuthCallbackHandlerFQN() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
Properties p = new Properties();
p.setProperty(AUTH_CALLBACK_HANDLER, MyCallbackHandler.class.getName());
Configuration configuration = builder.withProperties(p).build();
assertTrue(OPTIONS.get(AUTH_CALLBACK_HANDLER).apply(configuration) instanceof MyCallbackHandler);
}
public void testParseServerAddresses() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServers("1.1.1.1:9999");
builder.addServers("2.2.2.2");
builder.addServers("[fe80::290:bff:fe1b:5762]:7777");
builder.addServers("[ff01::1]");
builder.addServers("localhost");
builder.addServers("localhost:8382");
Configuration cfg = builder.build();
assertServer("1.1.1.1", 9999, cfg.servers().get(0));
assertServer("2.2.2.2", ConfigurationProperties.DEFAULT_HOTROD_PORT, cfg.servers().get(1));
assertServer("fe80::290:bff:fe1b:5762", 7777, cfg.servers().get(2));
assertServer("ff01::1", ConfigurationProperties.DEFAULT_HOTROD_PORT, cfg.servers().get(3));
assertServer("localhost", ConfigurationProperties.DEFAULT_HOTROD_PORT, cfg.servers().get(4));
assertServer("localhost", 8382, cfg.servers().get(5));
}
public void testPropertyReplacement() throws IOException, UnsupportedCallbackException {
System.setProperty("test.property.server_list", "myhost:12345");
System.setProperty("test.property.marshaller", "org.infinispan.commons.marshall.ProtoStreamMarshaller");
System.setProperty("test.property.tcp_no_delay", "false");
System.setProperty("test.property.tcp_keep_alive", "true");
System.setProperty("test.property.key_size_estimate", "128");
System.setProperty("test.property.value_size_estimate", "256");
System.setProperty("test.property.maxTotal", "79");
System.setProperty("test.property.maxActive", "78");
System.setProperty("test.property.maxIdle", "77");
System.setProperty("test.property.minIdle", "76");
System.setProperty("test.property.timeBetweenEvictionRunsMillis", "1000");
System.setProperty("test.property.minEvictableIdleTimeMillis", "2000");
System.setProperty("test.property.testWhileIdle", "true");
System.setProperty("test.property.use_auth", "true");
System.setProperty("test.property.auth_username", "testuser");
System.setProperty("test.property.auth_password", "testpassword");
System.setProperty("test.property.auth_realm", "testrealm");
System.setProperty("test.property.sasl_mechanism", "PLAIN");
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
Properties p = new Properties();
InputStream inputStream = FileLookupFactory.newInstance().lookupFile("hotrod-client-replacement.properties", this.getClass().getClassLoader());
p.load(inputStream);
builder.withProperties(p);
Configuration cfg = builder.build();
assertServer("myhost", 12345, cfg.servers().get(0));
assertEquals(ProtoStreamMarshaller.class, cfg.marshallerClass());
assertFalse(cfg.tcpNoDelay());
assertTrue(cfg.tcpKeepAlive());
assertEquals(128, cfg.keySizeEstimate());
assertEquals(256, cfg.valueSizeEstimate());
assertEquals(78, cfg.connectionPool().maxActive());
assertEquals(76, cfg.connectionPool().minIdle());
assertEquals(2000, cfg.connectionPool().minEvictableIdleTime());
assertTrue(cfg.security().authentication().enabled());
assertEquals("PLAIN", cfg.security().authentication().saslMechanism());
CallbackHandler callbackHandler = cfg.security().authentication().callbackHandler();
assertEquals(BasicCallbackHandler.class, callbackHandler.getClass());
NameCallback nameCallback = new NameCallback("name");
callbackHandler.handle(new Callback[]{nameCallback});
assertEquals("testuser", nameCallback.getName());
}
@Test(expectedExceptions = CacheConfigurationException.class,
expectedExceptionsMessageRegExp = "ISPN(\\d)*: Invalid max_retries \\(value=-1\\). " +
"Value should be greater or equal than zero.")
public void testNegativeRetriesPerServer() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.maxRetries(-1);
builder.build();
}
@Test(expectedExceptions = CacheConfigurationException.class)
public void testMissingClusterNameDefinition() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addCluster(null);
builder.build();
}
@Test(expectedExceptions = CacheConfigurationException.class)
public void testMissingHostDefinition() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addCluster("test").addClusterNode(null, 1234);
builder.build();
}
@Test(expectedExceptions = CacheConfigurationException.class)
public void testMissingClusterServersDefinition() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addCluster("test");
builder.build();
}
@Test(expectedExceptions = CacheConfigurationException.class)
public void testDuplicateClusterDefinition() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addCluster("test").addClusterNode("host1", 1234);
builder.addCluster("test").addClusterNode("host1", 5678);
builder.build();
}
@Test(expectedExceptions = CacheConfigurationException.class)
public void testInvalidAuthenticationConfig() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.security().authentication().enable().saslMechanism("PLAIN");
builder.build();
}
public void testValidAuthenticationSubjectNoCBH() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.security().authentication().enable().saslMechanism("PLAIN").clientSubject(new Subject());
builder.build();
}
public void testValidAuthenticationCBHNoSubject() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.security().authentication().enable().saslMechanism("PLAIN").callbackHandler(callbacks -> {
});
builder.build();
}
public void testClusters() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServers("1.1.1.1:9999");
builder.addCluster("my-cluster").addClusterNode("localhost", 8382);
Configuration cfg = builder.build();
assertEquals(1, cfg.servers().size());
assertServer("1.1.1.1", 9999, cfg.servers().get(0));
assertEquals(1, cfg.clusters().size());
assertEquals(1, cfg.clusters().get(0).getCluster().size());
assertServer("localhost", 8382, cfg.clusters().get(0).getCluster().get(0));
}
public void testNoTransactionOverwrite() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.remoteCache("tx-cache")
.transactionMode(TransactionMode.FULL_XA)
.transactionManagerLookup(RemoteTransactionManagerLookup.getInstance());
builder.transactionTimeout(1234, TimeUnit.MILLISECONDS);
Properties p = new Properties();
p.setProperty(SERVER_LIST, "host1:11222; host2:11222");
p.setProperty(AUTH_USERNAME, "admin");
p.setProperty(AUTH_PASSWORD, "password");
p.setProperty(AUTH_REALM, "default");
p.setProperty(SASL_MECHANISM, "SCRAM-SHA-512");
builder.withProperties(p);
Configuration config = builder.build();
assertEquals(TransactionMode.FULL_XA, config.remoteCaches().get("tx-cache").transactionMode());
assertEquals(RemoteTransactionManagerLookup.getInstance(), config.remoteCaches().get("tx-cache").transactionManagerLookup());
assertEquals(1234, config.transactionTimeout());
assertEquals(2, config.servers().size());
assertServer("host1", 11222, config.servers().get(0));
assertServer("host2", 11222, config.servers().get(1));
assertEquals("SCRAM-SHA-512", config.security().authentication().saslMechanism());
CallbackHandler ch = config.security().authentication().callbackHandler();
assertEquals(BasicCallbackHandler.class, ch.getClass());
BasicCallbackHandler bch = (BasicCallbackHandler) ch;
assertEquals("admin", bch.getUsername());
assertArrayEquals("password".toCharArray(), bch.getPassword());
assertEquals("default", bch.getRealm());
}
public void testNoTransactionOverwriteWithProperties() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
Properties p = new Properties();
p.setProperty("infinispan.client.hotrod.cache.tx-cache.transaction.transaction_mode", "FULL_XA");
p.setProperty("infinispan.client.hotrod.cache.tx-cache.transaction.transaction_manager_lookup", RemoteTransactionManagerLookup.class.getName());
p.setProperty("infinispan.client.hotrod.transaction.timeout", "1234");
builder.withProperties(p);
Configuration config = builder.build();
assertEquals(TransactionMode.FULL_XA, config.remoteCaches().get("tx-cache").transactionMode());
assertEquals(RemoteTransactionManagerLookup.getInstance(), config.remoteCaches().get("tx-cache").transactionManagerLookup());
assertEquals(1234, config.transactionTimeout());
}
private void assertServer(String host, int port, ServerConfiguration serverCfg) {
assertEquals(host, serverCfg.host());
assertEquals(port, serverCfg.port());
}
private void validateConfiguration(Configuration configuration) {
assertEquals(2, configuration.servers().size());
for (int i = 0; i < configuration.servers().size(); i++) {
assertEquals(String.format("host%d", i + 1), configuration.servers().get(i).host());
assertEquals(11222, configuration.servers().get(i).port());
}
assertEqualsConfig(SomeAsyncExecutorFactory.class, ASYNC_EXECUTOR_FACTORY, configuration);
assertEqualsConfig(SomeRequestBalancingStrategy.class, REQUEST_BALANCING_STRATEGY, configuration);
assertEquals(null, configuration.consistentHashImpl(1));
assertEquals(SomeCustomConsistentHashV2.class, configuration.consistentHashImpl(2));
assertEqualsConfig(100, "maxActive", configuration);
assertEqualsConfig(100, CONNECTION_POOL_MAX_ACTIVE, configuration);
assertEqualsConfig(1000L, "maxWait", configuration);
assertEqualsConfig(1000L, CONNECTION_POOL_MAX_WAIT, configuration);
assertEqualsConfig(10, "minIdle", configuration);
assertEqualsConfig(10, CONNECTION_POOL_MIN_IDLE, configuration);
assertEqualsConfig(ExhaustedAction.WAIT, CONNECTION_POOL_EXHAUSTED_ACTION, configuration);
assertEqualsConfig(12000L, "minEvictableIdleTimeMillis", configuration);
assertEqualsConfig(12000L, CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME, configuration);
assertEqualsConfig(12, CONNECTION_POOL_MAX_PENDING_REQUESTS, configuration);
assertEqualsConfig(100, CONNECT_TIMEOUT, configuration);
assertEqualsConfig(100, SO_TIMEOUT, configuration);
assertEqualsConfig(false, TCP_NO_DELAY, configuration);
assertEqualsConfig(true, TCP_KEEP_ALIVE, configuration);
assertEqualsConfig(128, KEY_SIZE_ESTIMATE, configuration);
assertEqualsConfig(1024, VALUE_SIZE_ESTIMATE, configuration);
assertEqualsConfig(0, MAX_RETRIES, configuration);
assertEqualsConfig(true, USE_SSL, configuration);
assertEqualsConfig("my-key-store.file", KEY_STORE_FILE_NAME, configuration);
assertEqualsConfig("my-key-store.password", KEY_STORE_PASSWORD, configuration);
assertEqualsConfig("my-key-store-certificate.password", KEY_STORE_CERTIFICATE_PASSWORD, configuration);
assertEqualsConfig("my-trust-store.file", TRUST_STORE_FILE_NAME, configuration);
assertEqualsConfig("my-trust-store.password", TRUST_STORE_PASSWORD, configuration);
assertEqualsConfig("TLSv1.1", SSL_PROTOCOL, configuration);
assertEqualsConfig(true, USE_AUTH, configuration);
assertEqualsConfig("my-sasl-mechanism", SASL_MECHANISM, configuration);
assertEqualsConfig(callbackHandler, AUTH_CALLBACK_HANDLER, configuration);
assertEqualsConfig("my-server-name", AUTH_SERVER_NAME, configuration);
assertEqualsConfig(clientSubject, AUTH_CLIENT_SUBJECT, configuration);
assertEqualsConfig("1", SASL_PROPERTIES_PREFIX + ".A", configuration);
assertEqualsConfig("2", SASL_PROPERTIES_PREFIX + ".B", configuration);
assertEqualsConfig("3", SASL_PROPERTIES_PREFIX + ".C", configuration);
assertEqualsConfig(ProtocolVersion.PROTOCOL_VERSION_29, PROTOCOL_VERSION, configuration);
assertEqualsConfig(Arrays.asList(".*Person.*", ".*Employee.*"), JAVA_SERIAL_ALLOWLIST, configuration);
assertEqualsConfig(NearCacheMode.INVALIDATED, NEAR_CACHE_MODE, configuration);
assertEqualsConfig(10_000, NEAR_CACHE_MAX_ENTRIES, configuration);
assertEqualsConfig("near.*", NEAR_CACHE_NAME_PATTERN, configuration);
assertEquals(2, configuration.clusters().size());
assertEquals("siteA", configuration.clusters().get(0).getClusterName());
assertEquals("hostA1", configuration.clusters().get(0).getCluster().get(0).host());
assertEquals(11222, configuration.clusters().get(0).getCluster().get(0).port());
assertEquals("hostA2", configuration.clusters().get(0).getCluster().get(1).host());
assertEquals(11223, configuration.clusters().get(0).getCluster().get(1).port());
assertEquals("siteB", configuration.clusters().get(1).getClusterName());
assertEquals("hostB1", configuration.clusters().get(1).getCluster().get(0).host());
assertEquals(11222, configuration.clusters().get(1).getCluster().get(0).port());
assertEquals("hostB2", configuration.clusters().get(1).getCluster().get(1).host());
assertEquals(11223, configuration.clusters().get(1).getCluster().get(1).port());
assertTrue(configuration.statistics().enabled());
assertTrue(configuration.statistics().jmxEnabled());
assertEquals("jmxInfinispan", configuration.statistics().jmxName());
assertEquals("jmxInfinispanDomain", configuration.statistics().jmxDomain());
}
private void validateSSLContextConfiguration(Configuration configuration) {
assertEqualsConfig(getSSLContext(), SSL_CONTEXT, configuration);
}
private void validateSniContextConfiguration(Configuration configuration) {
assertEqualsConfig("sni", SNI_HOST_NAME, configuration);
}
private SSLContext getSSLContext() {
try {
return SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private static void assertEqualsConfig(Object expected, String propertyName, Configuration cfg) {
assertEquals(expected, OPTIONS.get(propertyName).apply(cfg));
assertEquals(TYPES.get(expected.getClass()).apply(expected), cfg.properties().get(propertyName));
}
public void testMixOfConfiguration1() {
ConfigurationBuilder cb = HotRodURI.create("hotrod://host1?client_intelligence=BASIC").toConfigurationBuilder();
Properties properties = new Properties();
properties.setProperty(ConfigurationProperties.DEFAULT_EXECUTOR_FACTORY_POOL_SIZE, "1");
cb.asyncExecutorFactory().withExecutorProperties(properties);
Configuration configuration = cb.build();
assertEquals(ClientIntelligence.BASIC, configuration.clientIntelligence());
}
public void testMixOfConfiguration2() {
ConfigurationBuilder configurationBuilder = HotRodURI.create("hotrod://host1?client_intelligence=BASIC").toConfigurationBuilder();
configurationBuilder.maxRetries(1);
Configuration configuration = configurationBuilder.build();
assertEquals(ClientIntelligence.BASIC, configuration.clientIntelligence());
assertEquals(1, configuration.maxRetries());
configurationBuilder = new ConfigurationBuilder();
configurationBuilder.maxRetries(1);
configurationBuilder.socketTimeout(123);
configurationBuilder = configurationBuilder.uri("hotrod://host?client_intelligence=BASIC&socket_timeout=456");
configurationBuilder.batchSize(1000);
configuration = configurationBuilder.build();
assertEquals(1, configuration.maxRetries());
assertEquals(ClientIntelligence.BASIC, configuration.clientIntelligence());
assertEquals(1000, configuration.batchSize());
assertEquals(456, configuration.socketTimeout());
}
public void testMixOfConfiguration3() {
Properties properties = new Properties();
properties.setProperty(ConfigurationProperties.DEFAULT_EXECUTOR_FACTORY_POOL_SIZE, "1");
properties.setProperty(ConfigurationProperties.URI, "hotrod://host1?client_intelligence=BASIC");
ConfigurationBuilder cb = new ConfigurationBuilder().withProperties(properties);
Configuration configuration = cb.build();
assertEquals(ClientIntelligence.BASIC, configuration.clientIntelligence());
}
public void testConfigurationViaURI() {
Configuration configuration = HotRodURI.create("hotrod://host1").toConfigurationBuilder().build();
assertEquals(1, configuration.servers().size());
assertFalse(configuration.security().ssl().enabled());
assertFalse(configuration.security().authentication().enabled());
configuration = HotRodURI.create("hotrod://host1?socket_timeout=5000&connect_timeout=1000").toConfigurationBuilder().build();
assertEquals(1, configuration.servers().size());
assertFalse(configuration.security().ssl().enabled());
assertFalse(configuration.security().authentication().enabled());
assertEquals(5000, configuration.socketTimeout());
assertEquals(1000, configuration.connectionTimeout());
configuration = HotRodURI.create("hotrod://host2:11322").toConfigurationBuilder().build();
assertEquals(1, configuration.servers().size());
assertEquals("host2", configuration.servers().get(0).host());
assertEquals(11322, configuration.servers().get(0).port());
assertFalse(configuration.security().ssl().enabled());
assertFalse(configuration.security().authentication().enabled());
configuration = HotRodURI.create("hotrod://user:password@host1:11222").toConfigurationBuilder().build();
assertEquals(1, configuration.servers().size());
assertFalse(configuration.security().ssl().enabled());
assertTrue(configuration.security().authentication().enabled());
BasicCallbackHandler callbackHandler = (BasicCallbackHandler) configuration.security().authentication().callbackHandler();
assertEquals("user", callbackHandler.getUsername());
assertArrayEquals("password".toCharArray(), callbackHandler.getPassword());
configuration = HotRodURI.create("hotrod://host1:11222,host2:11322,host3").toConfigurationBuilder().build();
assertEquals(3, configuration.servers().size());
assertEquals("host1", configuration.servers().get(0).host());
assertEquals(11222, configuration.servers().get(0).port());
assertEquals("host2", configuration.servers().get(1).host());
assertEquals(11322, configuration.servers().get(1).port());
assertEquals("host3", configuration.servers().get(2).host());
assertEquals(11222, configuration.servers().get(2).port());
assertFalse(configuration.security().ssl().enabled());
configuration = HotRodURI.create("hotrods://user:password@host1:11222,host2:11322?trust_store_path=cert.pem").toConfigurationBuilder().build();
assertEquals(2, configuration.servers().size());
assertEquals("host1", configuration.servers().get(0).host());
assertEquals(11222, configuration.servers().get(0).port());
assertEquals("host2", configuration.servers().get(1).host());
assertEquals(11322, configuration.servers().get(1).port());
assertTrue(configuration.security().ssl().enabled());
assertTrue(configuration.security().authentication().enabled());
callbackHandler = (BasicCallbackHandler) configuration.security().authentication().callbackHandler();
assertEquals("user", callbackHandler.getUsername());
assertArrayEquals("password".toCharArray(), callbackHandler.getPassword());
expectException(IllegalArgumentException.class, "ISPN004095:.*", () -> HotRodURI.create("http://host1"));
expectException(IllegalArgumentException.class, "ISPN004096:.*", () -> HotRodURI.create("hotrod://host1?property"));
}
public void testCacheNames() throws IOException {
Properties properties = new Properties();
try (InputStream is = this.getClass().getResourceAsStream("/hotrod-client-percache.properties")) {
properties.load(is);
}
Configuration configuration = new ConfigurationBuilder().withProperties(properties).build();
assertEquals(3, configuration.remoteCaches().size());
assertTrue(configuration.remoteCaches().containsKey("mycache"));
RemoteCacheConfiguration cache = configuration.remoteCaches().get("mycache");
assertEquals("org.infinispan.DIST_SYNC", cache.templateName());
assertTrue(cache.forceReturnValues());
assertTrue(configuration.remoteCaches().containsKey("org.infinispan.yourcache"));
cache = configuration.remoteCaches().get("org.infinispan.yourcache");
assertEquals("org.infinispan.DIST_ASYNC", cache.templateName());
assertEquals(NearCacheMode.INVALIDATED, cache.nearCacheMode());
assertTrue(configuration.remoteCaches().containsKey("org.infinispan.*"));
cache = configuration.remoteCaches().get("org.infinispan.*");
assertEquals("org.infinispan.REPL_SYNC", cache.templateName());
assertEquals(TransactionMode.NON_XA, cache.transactionMode());
}
@Test
public void testPerCacheMarshallerConfig() throws IOException {
Properties properties = new Properties();
try (InputStream is = this.getClass().getResourceAsStream("/hotrod-client-percache.properties")) {
properties.load(is);
}
Configuration configuration = new ConfigurationBuilder().withProperties(properties).build();
assertEquals(JavaSerializationMarshaller.class, configuration.remoteCaches().get("mycache").marshallerClass());
assertEquals(UTF8StringMarshaller.class, configuration.remoteCaches().get("org.infinispan.yourcache").marshallerClass());
Properties props = configuration.properties();
assertEquals(JavaSerializationMarshaller.class.getName(), props.getProperty("infinispan.client.hotrod.cache.mycache.marshaller"));
assertEquals(UTF8StringMarshaller.class.getName(), props.getProperty("infinispan.client.hotrod.cache.org.infinispan.yourcache.marshaller"));
}
}
| 43,722
| 55.489664
| 150
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/near/AvoidStaleNearCacheReadsTest.java
|
package org.infinispan.client.hotrod.near;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
import java.util.stream.IntStream;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.VersionedValue;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.configuration.NearCacheConfigurationBuilder;
import org.infinispan.client.hotrod.configuration.NearCacheMode;
import org.infinispan.client.hotrod.impl.InternalRemoteCache;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.util.concurrent.CompletionStages;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.near.AvoidStaleNearCacheReadsTest")
public class AvoidStaleNearCacheReadsTest extends SingleHotRodServerTest {
private int entryCount;
private boolean bloomFilter;
@AfterMethod(alwaysRun=true)
@Override
protected void clearContent() {
super.clearContent();
RemoteCache<?, ?> remoteCache = remoteCacheManager.getCache();
remoteCache.clear(); // Clear the near cache too
if (bloomFilter) {
CompletionStages.join(((InternalRemoteCache) remoteCache).updateBloomFilter());
}
}
@Override
protected RemoteCacheManager getRemoteCacheManager() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(hotrodServer.getPort());
NearCacheConfigurationBuilder nearCacheConfigurationBuilder = builder.nearCache()
.mode(NearCacheMode.INVALIDATED)
.maxEntries(entryCount)
.bloomFilter(bloomFilter);
if (bloomFilter) {
builder.connectionPool().maxActive(1);
}
return new RemoteCacheManager(builder.build());
}
AvoidStaleNearCacheReadsTest entryCount(int entryCount) {
this.entryCount = entryCount;
return this;
}
AvoidStaleNearCacheReadsTest bloomFilter(boolean bloomFilter) {
this.bloomFilter = bloomFilter;
return this;
}
@Factory
public Object[] factory() {
return new Object[]{
new AvoidStaleNearCacheReadsTest().entryCount(-1),
new AvoidStaleNearCacheReadsTest().entryCount(20).bloomFilter(false),
new AvoidStaleNearCacheReadsTest().entryCount(20).bloomFilter(true),
};
}
@Override
protected String parameters() {
return "maxEntries=" + entryCount + ", bloomFilter=" + bloomFilter;
}
public void testAvoidStaleReadsAfterPutRemove() {
repeated((i, remote) -> {
String value = "v" + i;
remote.put(1, value);
assertEquals(value, remote.get(1));
remote.remove(1);
assertNull(remote.get(1));
});
}
public void testAvoidStaleReadsAfterPutAll() {
repeated((i, remote) -> {
String value = "v" + i;
Map<Integer, String> map = new HashMap<>();
map.put(1, value);
remote.putAll(map);
assertEquals(value, remote.get(1));
});
}
public void testAvoidStaleReadsAfterReplace() {
repeated((i, remote) -> {
String value = "v" + i;
remote.replace(1, value);
VersionedValue<String> versioned = remote.getWithMetadata(1);
assertEquals(value, versioned.getValue());
});
}
public void testAvoidStaleReadsAfterReplaceWithVersion() {
repeated((i, remote) -> {
String value = "v" + i;
VersionedValue<String> versioned = remote.getWithMetadata(1);
remote.replaceWithVersion(1, value, versioned.getVersion());
assertEquals(value, remote.get(1));
});
}
public void testAvoidStaleReadsAfterPutAsyncRemoveVersioned() {
repeated((i, remote) -> {
String value = "v" + i;
await(remote.putAsync(1, value));
VersionedValue<String> versioned = remote.getWithMetadata(1);
assertEquals(value, versioned.getValue());
remote.removeWithVersion(1, versioned.getVersion());
assertNull(remote.get(1));
});
}
private void repeated(BiConsumer<Integer, RemoteCache<Integer, String>> c) {
RemoteCache<Integer, String> remote = remoteCacheManager.getCache();
remote.putIfAbsent(1, "v0");
IntStream.range(1, 1000).forEach(i -> {
c.accept(i, remote);
});
}
static <T> T await(Future<T> f) {
try {
return f.get(10000, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e ) {
throw new AssertionError(e);
}
}
}
| 5,149
| 33.333333
| 93
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/near/AssertsNearCache.java
|
package org.infinispan.client.hotrod.near;
import static org.infinispan.client.hotrod.near.MockNearCacheService.MockClearEvent;
import static org.infinispan.client.hotrod.near.MockNearCacheService.MockEvent;
import static org.infinispan.client.hotrod.near.MockNearCacheService.MockGetEvent;
import static org.infinispan.client.hotrod.near.MockNearCacheService.MockPutEvent;
import static org.infinispan.client.hotrod.near.MockNearCacheService.MockPutIfAbsentEvent;
import static org.infinispan.client.hotrod.near.MockNearCacheService.MockRemoveEvent;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.entryVersion;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
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.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.MetadataValue;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.configuration.NearCacheConfiguration;
import org.infinispan.client.hotrod.configuration.NearCacheMode;
import org.infinispan.client.hotrod.impl.InternalRemoteCache;
class AssertsNearCache<K, V> {
final InternalRemoteCache<K, V> remote;
final Cache<byte[], ?> server;
final BlockingQueue<MockEvent> events;
final RemoteCacheManager manager;
final NearCacheMode nearCacheMode;
final AtomicReference<NearCacheService<K, V>> nearCacheService;
private AssertsNearCache(RemoteCacheManager manager, Cache<byte[], ?> server, BlockingQueue<MockEvent> events,
AtomicReference<NearCacheService<K, V>> nearCacheService) {
this.manager = manager;
this.remote = (InternalRemoteCache<K, V>) manager.getCache();
this.server = server;
this.events = events;
this.nearCacheMode = manager.getConfiguration().nearCache().mode();
this.nearCacheService = nearCacheService;
}
static <K, V> AssertsNearCache<K, V> create(Cache<byte[], ?> server, ConfigurationBuilder builder) {
final BlockingQueue<MockEvent> events = new ArrayBlockingQueue<>(128);
AtomicReference<NearCacheService<K, V>> nearCacheServiceRef = new AtomicReference<>();
RemoteCacheManager manager = new RemoteCacheManager(builder.build()) {
@Override
protected <KK, VV> NearCacheService<KK, VV> createNearCacheService(String cacheName, NearCacheConfiguration cfg) {
MockNearCacheService nearCacheService = new MockNearCacheService<>(cfg, events, listenerNotifier);
nearCacheServiceRef.set(nearCacheService);
return nearCacheService;
}
};
return new AssertsNearCache<K, V>(manager, server, events, nearCacheServiceRef);
}
AssertsNearCache<K, V> get(K key, V expected) {
assertEquals(expected, remote.get(key));
return this;
}
AssertsNearCache<K, V> getAsync(K key, V expected) throws ExecutionException, InterruptedException {
assertEquals(expected, remote.getAsync(key).get());
return this;
}
AssertsNearCache<K, V> getWithMetadata(K key, V expected) {
MetadataValue<V> entry = remote.getWithMetadata(key);
assertEquals(expected, entry == null ? null : entry.getValue());
return this;
}
AssertsNearCache<K, V> getWithMetadataAsync(K key, V expected) throws ExecutionException, InterruptedException {
MetadataValue<V> entry = remote.getWithMetadataAsync(key).get();
assertEquals(expected, entry == null ? null : entry.getValue());
return this;
}
AssertsNearCache<K, V> put(K key, V value) {
remote.put(key, value);
return this;
}
AssertsNearCache<K, V> putAsync(K key, V value) throws ExecutionException, InterruptedException {
remote.putAsync(key, value).get();
return this;
}
AssertsNearCache<K, V> putAsync(K key, V value, long time, TimeUnit timeUnit) throws ExecutionException, InterruptedException {
remote.putAsync(key, value, time, timeUnit).get();
return this;
}
AssertsNearCache<K, V> putAsync(K key, V value, long time, TimeUnit timeUnit, long idle, TimeUnit idleTimeUnit) throws ExecutionException, InterruptedException {
remote.putAsync(key, value, time, timeUnit, idle, idleTimeUnit).get();
return this;
}
AssertsNearCache<K, V> remove(K key) {
remote.remove(key);
return this;
}
AssertsNearCache<K, V> removeAsync(K key) throws ExecutionException, InterruptedException {
remote.removeAsync(key).get();
return this;
}
AssertsNearCache<K, V> expectNoNearEvents() {
assertEquals(events.toString(), 0, events.size());
return this;
}
AssertsNearCache<K, V> expectNoNearEvents(long time, TimeUnit timeUnit) throws InterruptedException {
MockEvent event = events.poll(time, timeUnit);
assertNull("Event was: " + event, event);
return this;
}
AssertsNearCache<K, V> expectNearGetValueVersion(K key, V value) {
MockGetEvent get = assertGetKeyValue(key, value);
if (value != null) {
long serverVersion = entryVersion(server.getAdvancedCache().withStorageMediaType(), key);
assertEquals(serverVersion, get.value.getVersion());
}
return this;
}
AssertsNearCache<K, V> expectNearGetValue(K key, V value) {
assertGetKeyValue(key, value);
return this;
}
AssertsNearCache<K, V> expectNearGetNull(K key) {
MockGetEvent get = assertGetKey(key);
assertNull(get.value);
return this;
}
@SafeVarargs
final AssertsNearCache<K, V> expectNearPut(K key, V value, AssertsNearCache<K, V>... affected) {
expectNearPutInClient(this, key, value);
for (AssertsNearCache<K, V> client : affected)
expectNearPutInClient(client, key, value);
return this;
}
private static <K, V> void expectNearPutInClient(AssertsNearCache<K, V> client, K key, V value) {
MockPutEvent put = pollEvent(client.events);
assertEquals(key, put.key);
assertEquals(value, put.value.getValue());
}
AssertsNearCache<K, V> expectNearPutIfAbsent(K key, V value) {
MockPutIfAbsentEvent put = pollEvent(events);
assertEquals(key, put.key);
assertEquals(value, put.value.getValue());
return this;
}
public AssertsNearCache<K, V> expectNearPreemptiveRemove(K key) {
// Preemptive remove
MockRemoveEvent preemptiveRemove = pollEvent(events);
assertEquals(key, preemptiveRemove.key);
expectNoNearEvents();
return this;
}
public AssertsNearCache<K, V> expectNearPreemptiveRemove(K key, AssertsNearCache<K, V>... affected) {
// Preemptive remove
MockRemoveEvent preemptiveRemove = pollEvent(events);
assertEquals(key, preemptiveRemove.key);
expectNoNearEvents();
for (AssertsNearCache<K, V> client : affected)
expectRemoteNearRemoveInClient(client, key);
return this;
}
@SafeVarargs
final AssertsNearCache<K, V> expectNearRemove(K key, AssertsNearCache<K, V>... affected) {
expectLocalNearRemoveInClient(this, key);
for (AssertsNearCache<K, V> client : affected)
expectRemoteNearRemoveInClient(client, key);
return this;
}
@SafeVarargs
final AssertsNearCache<K, V> expectNearClear(AssertsNearCache<K, V>... affected) {
expectNearClearInClient(this);
for (AssertsNearCache<K, V> client : affected)
expectNearClearInClient(client);
return this;
}
void expectNearClearInClient(AssertsNearCache<K, V> client) {
MockEvent clear = pollEvent(client.events);
assertTrue("Unexpected event: " + clear, clear instanceof MockClearEvent);
}
void resetEvents() {
events.clear();
}
void stop() {
killRemoteCacheManager(manager);
}
private static <K, V> void expectLocalNearRemoveInClient(AssertsNearCache<K, V> client, K key) {
// Preemptive remove
MockRemoveEvent preemptiveRemove = pollEvent(client.events);
assertEquals(key, preemptiveRemove.key);
// Remote event remove
MockRemoveEvent remoteRemove = pollEvent(client.events);
assertEquals(key, remoteRemove.key);
}
private static <K, V> void expectRemoteNearRemoveInClient(AssertsNearCache<K, V> client, K key) {
// Remote event remove
MockRemoveEvent remoteRemove = pollEvent(client.events);
assertEquals(key, remoteRemove.key);
}
private static <E extends MockEvent> E pollEvent(BlockingQueue<MockEvent> events) {
try {
@SuppressWarnings("unchecked")
E event = (E) events.poll(10, TimeUnit.SECONDS);
assertNotNull(event);
return event;
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}
private MockGetEvent assertGetKey(K key) {
MockGetEvent get = pollEvent(events);
assertEquals(key, get.key);
return get;
}
private MockGetEvent assertGetKeyValue(K key, V value) {
MockGetEvent get = assertGetKey(key);
assertEquals(value, get.value == null ? null : get.value.getValue());
return get;
}
public boolean isNearCacheConnected() {
return this.nearCacheService.get().isConnected();
}
public int nearCacheSize() {
return this.nearCacheService.get().size();
}
}
| 9,757
| 36.102662
| 164
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/near/EvictInvalidatedNearCacheTest.java
|
package org.infinispan.client.hotrod.near;
import static org.testng.AssertJUnit.assertEquals;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.configuration.NearCacheConfigurationBuilder;
import org.infinispan.client.hotrod.configuration.NearCacheMode;
import org.infinispan.client.hotrod.impl.InternalRemoteCache;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.util.concurrent.CompletionStages;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.near.EvictInvalidatedNearCacheTest")
public class EvictInvalidatedNearCacheTest extends SingleHotRodServerTest {
private int entryCount;
private boolean bloomFilter;
AssertsNearCache<Integer, String> assertClient;
EvictInvalidatedNearCacheTest entryCount(int entryCount) {
this.entryCount = entryCount;
return this;
}
EvictInvalidatedNearCacheTest bloomFilter(boolean bloomFilter) {
this.bloomFilter = bloomFilter;
return this;
}
@Factory
public Object[] factory() {
return new Object[]{
new EvictInvalidatedNearCacheTest().entryCount(1).bloomFilter(false),
new EvictInvalidatedNearCacheTest().entryCount(1).bloomFilter(true),
new EvictInvalidatedNearCacheTest().entryCount(20).bloomFilter(false),
new EvictInvalidatedNearCacheTest().entryCount(20).bloomFilter(true),
};
}
@Override
protected String parameters() {
return "maxEntries=" + entryCount + ", bloomFilter=" + bloomFilter;
}
@Override
protected void teardown() {
if (assertClient != null) {
assertClient.stop();
assertClient = null;
}
super.teardown();
}
@AfterMethod(alwaysRun=true)
@Override
protected void clearContent() {
super.clearContent();
RemoteCache<?, ?> remoteCache = remoteCacheManager.getCache();
remoteCache.clear(); // Clear the near cache too
if (bloomFilter) {
CompletionStages.join(((InternalRemoteCache) remoteCache).updateBloomFilter());
}
}
protected RemoteCacheManager getRemoteCacheManager() {
assertClient = createClient();
return assertClient.manager;
}
protected <K, V> AssertsNearCache<K, V> createClient() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(hotrodServer.getPort());
NearCacheConfigurationBuilder nearCacheConfigurationBuilder = builder.nearCache().mode(getNearCacheMode())
.maxEntries(entryCount);
if (bloomFilter) {
builder.connectionPool().maxActive(1);
nearCacheConfigurationBuilder.bloomFilter(true);
}
return AssertsNearCache.create(cache(), builder);
}
protected NearCacheMode getNearCacheMode() {
return NearCacheMode.INVALIDATED;
}
public void testEvictAfterReachingMax() {
assertClient.expectNoNearEvents();
for (int i = 0; i < entryCount; ++i) {
assertClient.put(i, "v1").expectNearPreemptiveRemove(i);
assertClient.get(i, "v1").expectNearGetNull(i).expectNearPutIfAbsent(i, "v1");
}
int extraKey = entryCount + 1;
assertClient.put(extraKey, "v1").expectNearPreemptiveRemove(extraKey);
assertClient.get(extraKey, "v1").expectNearGetNull(extraKey).expectNearPutIfAbsent(extraKey, "v1");
// Caffeine is not deterministic as to which one it evicts - so we just verify size
assertEquals(entryCount, assertClient.nearCacheSize());
}
}
| 3,883
| 34.962963
| 112
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/near/InvalidatedFailoverNearCacheTest.java
|
package org.infinispan.client.hotrod.near;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.findServerAndKill;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import java.util.ArrayList;
import java.util.List;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.NearCacheMode;
import org.infinispan.client.hotrod.event.StickyServerLoadBalancingStrategy;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.server.hotrod.HotRodServer;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.near.InvalidatedFailoverNearCacheTest")
public class InvalidatedFailoverNearCacheTest extends MultiHotRodServersTest {
List<AssertsNearCache<Integer, String>> assertClients = new ArrayList<>(2);
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(2, getCacheConfiguration());
}
@AfterClass(alwaysRun = true)
@Override
protected void destroy() {
assertClients.forEach(AssertsNearCache::stop);
assertClients.clear();
super.destroy();
}
private ConfigurationBuilder getCacheConfiguration() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
builder.clustering().hash().numOwners(2);
return hotRodCacheConfiguration(builder);
}
@Override
protected RemoteCacheManager createClient(int i) {
AssertsNearCache<Integer, String> asserts = createStickyAssertClient();
assertClients.add(asserts);
return asserts.manager;
}
protected <K, V> AssertsNearCache<K, V> createStickyAssertClient() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
for (HotRodServer server : servers)
clientBuilder.addServer().host(server.getHost()).port(server.getPort());
clientBuilder.balancingStrategy(StickyServerLoadBalancingStrategy.class);
clientBuilder.nearCache().mode(getNearCacheMode()).maxEntries(-1);
return AssertsNearCache.create(this.cache(0), clientBuilder);
}
protected NearCacheMode getNearCacheMode() {
return NearCacheMode.INVALIDATED;
}
public void testNearCacheClearedUponFailover() {
AssertsNearCache<Integer, String> stickyClient = createStickyAssertClient();
try {
stickyClient.put(1, "v1").expectNearPreemptiveRemove(1);
stickyClient.get(1, "v1").expectNearGetNull(1).expectNearPutIfAbsent(1, "v1");
stickyClient.put(2, "v1").expectNearPreemptiveRemove(2);
stickyClient.get(2, "v1").expectNearGetNull(2).expectNearPutIfAbsent(2, "v1");
stickyClient.put(3, "v1").expectNearPreemptiveRemove(3);
stickyClient.get(3, "v1").expectNearGetNull(3).expectNearPutIfAbsent(3, "v1");
boolean headClientClear = isClientListenerAttachedToSameServer(headClient(), stickyClient);
boolean tailClientClear = isClientListenerAttachedToSameServer(tailClient(), stickyClient);
killServerForClient(stickyClient);
// The clear will be executed when the connection to the server is closed from the listener.
stickyClient.expectNearClear();
// Also make sure the near cache is fully connected so the events will work deterministically
eventually(stickyClient::isNearCacheConnected);
stickyClient.get(1, "v1")
.expectNearGetNull(1)
.expectNearPutIfAbsent(1, "v1");
stickyClient.expectNoNearEvents();
if (headClientClear) {
headClient().expectNearClear();
}
headClient().get(2, "v1").expectNearGetNull(2).expectNearPutIfAbsent(2, "v1");
headClient().expectNoNearEvents();
if (tailClientClear) {
tailClient().expectNearClear();
}
tailClient().get(3, "v1").expectNearGetNull(3).expectNearPutIfAbsent(3, "v1");
tailClient().expectNoNearEvents();
} finally {
stickyClient.stop();
}
}
protected boolean isClientListenerAttachedToSameServer(AssertsNearCache<Integer, String> client1,
AssertsNearCache<Integer, String> client2) {
return true;
}
protected void killServerForClient(AssertsNearCache<Integer, String> stickyClient) {
findServerAndKill(stickyClient.manager, servers, cacheManagers);
}
protected AssertsNearCache<Integer, String> tailClient() {
return assertClients.get(1);
}
protected AssertsNearCache<Integer, String> headClient() {
return assertClients.get(0);
}
}
| 5,003
| 39.682927
| 102
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/near/InvalidatedFailoverNearCacheBloomTest.java
|
package org.infinispan.client.hotrod.near;
import static org.testng.AssertJUnit.assertTrue;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import org.infinispan.client.hotrod.configuration.NearCacheMode;
import org.infinispan.client.hotrod.impl.InvalidatedNearRemoteCache;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.near.InvalidatedFailoverNearCacheBloomTest")
public class InvalidatedFailoverNearCacheBloomTest extends InvalidatedFailoverNearCacheTest {
@Override
protected <K, V> AssertsNearCache<K, V> createStickyAssertClient() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
for (HotRodServer server : servers)
clientBuilder.addServer().host("127.0.0.1").port(server.getPort());
clientBuilder.connectionPool().maxActive(1);
clientBuilder.nearCache().mode(NearCacheMode.INVALIDATED)
.maxEntries(4)
.bloomFilter(true);
return AssertsNearCache.create(cache(0), clientBuilder);
}
@Override
protected void killServerForClient(AssertsNearCache<Integer, String> stickyClient) {
boolean stoppedAServer = false;
SocketAddress socketAddress = ((InvalidatedNearRemoteCache) stickyClient.remote).getBloomListenerAddress();
for (HotRodServer server : servers) {
int serverPort = server.getAddress().getPort();
if (serverPort == ((InetSocketAddress) socketAddress).getPort()) {
HotRodClientTestingUtil.killServers(server);
TestingUtil.killCacheManagers(server.getCacheManager());
cacheManagers.remove(server.getCacheManager());
TestingUtil.blockUntilViewsReceived(50000, false, cacheManagers);
stoppedAServer = true;
break;
}
}
assertTrue("Could not find a server that mapped to " + socketAddress, stoppedAServer);
}
@Override
protected boolean isClientListenerAttachedToSameServer(AssertsNearCache<Integer, String> client1, AssertsNearCache<Integer, String> client2) {
SocketAddress client1Address = ((InvalidatedNearRemoteCache) client1.remote).getBloomListenerAddress();
SocketAddress client2Address = ((InvalidatedNearRemoteCache) client2.remote).getBloomListenerAddress();
return client1Address.equals(client2Address);
}
}
| 2,590
| 44.45614
| 145
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/near/InvalidatedNearCacheBloomTest.java
|
package org.infinispan.client.hotrod.near;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.configuration.NearCacheMode;
import org.infinispan.client.hotrod.impl.InvalidatedNearRemoteCache;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.commons.util.BloomFilter;
import org.infinispan.commons.util.MurmurHash3BloomFilter;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.util.concurrent.CompletionStages;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.near.InvalidatedNearCacheBloomTest")
public class InvalidatedNearCacheBloomTest extends SingleHotRodServerTest {
private static final int NEAR_CACHE_SIZE = 4;
private StorageType storageType;
private AssertsNearCache<Integer, String> assertClient;
private final BloomFilter<byte[]> bloomFilter = MurmurHash3BloomFilter.createFilter(NEAR_CACHE_SIZE << 2);
private InvalidatedNearCacheBloomTest storageType(StorageType storageType) {
this.storageType = storageType;
return this;
}
@Factory
public Object[] factory() {
return new Object[]{
new InvalidatedNearCacheBloomTest().storageType(StorageType.OBJECT),
new InvalidatedNearCacheBloomTest().storageType(StorageType.BINARY),
new InvalidatedNearCacheBloomTest().storageType(StorageType.OFF_HEAP),
};
}
@BeforeMethod
void beforeMethod() {
assertClient.expectNoNearEvents();
// All tests rely upon having the bits set for the key 1
bloomFilter.addToFilter(assertClient.remote.keyToBytes(1));
}
@AfterMethod
void resetBloomFilter() throws InterruptedException {
assertClient.expectNoNearEvents(50, TimeUnit.MILLISECONDS);
((InvalidatedNearRemoteCache) assertClient.remote).clearNearCache();
CompletionStages.join(((InvalidatedNearRemoteCache) assertClient.remote).updateBloomFilter());
// Don't let the clear leak
assertClient.events.clear();
}
@Override
protected String parameters() {
return "[storageType-" + storageType + "]";
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
org.infinispan.configuration.cache.ConfigurationBuilder cb = hotRodCacheConfiguration();
cb.memory().storageType(storageType);
return TestCacheManagerFactory.createCacheManager(cb);
}
@Override
protected RemoteCacheManager getRemoteCacheManager() {
assertClient = createAssertClient();
return assertClient.manager;
}
private <K, V> AssertsNearCache<K, V> createAssertClient() {
ConfigurationBuilder builder = clientConfiguration();
builder.connectionPool().maxActive(1);
return AssertsNearCache.create(this.cache(), builder);
}
private ConfigurationBuilder clientConfiguration() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(hotrodServer.getPort());
builder.nearCache().mode(NearCacheMode.INVALIDATED)
.maxEntries(NEAR_CACHE_SIZE)
.bloomFilter(true);
return builder;
}
public void testSingleKeyFilter() {
assertClient.put(1, "v1").expectNearPreemptiveRemove(1);
assertClient.put(1, "v2").expectNearPreemptiveRemove(1);
assertClient.get(1, "v2").expectNearGetNull(1).expectNearPutIfAbsent(1, "v2");
assertClient.get(1, "v2").expectNearGetValue(1, "v2");
assertClient.remove(1).expectNearRemove(1);
assertClient.get(1, null).expectNearGetNull(1);
}
public void testMultipleKeyFilterConflictButNoRead() {
assertClient.put(1, "v1").expectNearPreemptiveRemove(1);
int conflictKey = findNextKey(bloomFilter, 1, true);
assertClient.put(conflictKey, "v1").expectNearPreemptiveRemove(conflictKey);
assertClient.put(conflictKey, "v2").expectNearPreemptiveRemove(conflictKey);
}
public void testMultipleKeyFilterConflict() {
assertClient.put(1, "v1").expectNearPreemptiveRemove(1);
assertClient.get(1, "v1").expectNearGetNull(1).expectNearPutIfAbsent(1, "v1");
int conflictKey = findNextKey(bloomFilter, 1, true);
// This is a create thus no remove is sent
assertClient.put(conflictKey, "v1").expectNearPreemptiveRemove(conflictKey);
// This conflicts with our original key thus it will send a remove despite nothing being removed
assertClient.put(conflictKey, "v2").expectNearRemove(conflictKey);
assertClient.get(1, "v1").expectNearGetValue(1, "v1");
}
public void testMultipleKeyFilterNoConflict() {
assertClient.put(1, "v1").expectNearPreemptiveRemove(1);
assertClient.get(1, "v1").expectNearGetNull(1).expectNearPutIfAbsent(1, "v1");
int nonConflictKey = findNextKey(bloomFilter, 1, false);
// Both of the following never send a remove event back as the key wasn't present in bloom filter
assertClient.put(nonConflictKey, "v1").expectNearPreemptiveRemove(nonConflictKey);
assertClient.put(nonConflictKey, "v2").expectNearPreemptiveRemove(nonConflictKey);
}
public void testServerBloomFilterUpdate() throws InterruptedException {
assertClient.put(1, "v1").expectNearPreemptiveRemove(1);
assertClient.get(1, "v1").expectNearGetNull(1).expectNearPutIfAbsent(1, "v1");
int nonConflictKey = findNextKey(bloomFilter, 1, false);
assertClient.put(nonConflictKey, "v1").expectNearPreemptiveRemove(nonConflictKey);
assertClient.get(nonConflictKey, "v1").expectNearGetNull(nonConflictKey)
.expectNearPutIfAbsent(nonConflictKey, "v1");
boolean serverBloomFilterUpdated = false;
for (int i = 0; i < 10; ++i) {
assertClient.put(nonConflictKey, "v1");
// The cache will always preemptively invalidate the value if necessary
MockNearCacheService.MockEvent event = assertClient.events.poll(10, TimeUnit.SECONDS);
assertNotNull(event);
assertTrue(event instanceof MockNearCacheService.MockRemoveEvent);
assertEquals(nonConflictKey, ((MockNearCacheService.MockRemoveEvent<?>) event).key);
// Eventually this be null - which means our cache has been updated on the server side
event = assertClient.events.poll(100, TimeUnit.MILLISECONDS);
if (event == null) {
serverBloomFilterUpdated = true;
break;
}
assertTrue(event instanceof MockNearCacheService.MockRemoveEvent);
assertEquals(nonConflictKey, ((MockNearCacheService.MockRemoveEvent<?>) event).key);
Thread.sleep(10);
}
assertTrue("The server bloom filter was never updated and we got remove events every time",
serverBloomFilterUpdated);
}
int findNextKey(BloomFilter<byte[]> filter, int originalValue, boolean present) {
while (true) {
byte[] testKey = assertClient.remote.keyToBytes(++originalValue);
if (present == filter.possiblyPresent(testKey)) {
return originalValue;
}
}
}
}
| 7,796
| 41.375
| 109
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/near/MockNearCacheService.java
|
package org.infinispan.client.hotrod.near;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.function.BiConsumer;
import org.infinispan.client.hotrod.MetadataValue;
import org.infinispan.client.hotrod.configuration.NearCacheConfiguration;
import org.infinispan.client.hotrod.event.impl.ClientListenerNotifier;
public class MockNearCacheService<K, V> extends NearCacheService<K, V> {
final BlockingQueue<MockEvent> events;
MockNearCacheService(NearCacheConfiguration cfg, BlockingQueue<MockEvent> events, ClientListenerNotifier listenerNotifier) {
super(cfg, listenerNotifier);
this.events = events;
}
@Override
protected NearCache<K, V> createNearCache(NearCacheConfiguration config, BiConsumer<K, MetadataValue<V>> biConsumer) {
NearCache<K, V> delegate = super.createNearCache(config, biConsumer);
return new MockNearCache<>(delegate, events);
}
static abstract class MockEvent {}
static abstract class MockKeyValueEvent<K, V> extends MockEvent {
final K key;
final MetadataValue<V> value;
MockKeyValueEvent(K key, MetadataValue<V> value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return this.getClass().getName() + "{" + "key=" + key + ", value=" + value +'}';
}
}
static class MockNearCache<K, V> implements NearCache<K, V> {
final NearCache<K, V> delegate;
final BlockingQueue<MockEvent> events;
MockNearCache(NearCache<K, V> delegate, BlockingQueue<MockEvent> events) {
this.delegate = delegate;
this.events = events;
}
@Override
public void put(K key, MetadataValue<V> value) {
delegate.put(key, value);
events.add(new MockPutEvent<>(key, value));
}
@Override
public void putIfAbsent(K key, MetadataValue<V> value) {
delegate.putIfAbsent(key, value);
events.add(new MockPutIfAbsentEvent<>(key, value));
}
@Override
public boolean remove(K key) {
boolean removed = delegate.remove(key);
events.add(new MockRemoveEvent<>(key));
return removed;
}
@Override
public MetadataValue<V> get(K key) {
MetadataValue<V> value = delegate.get(key);
events.add(new MockGetEvent<>(key, value));
return value;
}
@Override
public void clear() {
delegate.clear();
events.clear();
events.add(new MockClearEvent());
}
@Override
public int size() {
return delegate.size();
}
@Override
public Iterator<Map.Entry<K, MetadataValue<V>>> iterator() {
return delegate.iterator();
}
}
static class MockPutEvent<K, V> extends MockKeyValueEvent<K, V> {
MockPutEvent(K key, MetadataValue<V> value) {
super(key, value);
}
}
static class MockPutIfAbsentEvent<K, V> extends MockKeyValueEvent<K, V> {
MockPutIfAbsentEvent(K key, MetadataValue<V> value) {
super(key, value);
}
}
static class MockGetEvent<K, V> extends MockKeyValueEvent<K, V> {
MockGetEvent(K key, MetadataValue<V> value) {
super(key, value);
}
}
static class MockRemoveEvent<K> extends MockEvent {
final K key;
MockRemoveEvent(K key) {
this.key = key;
}
@Override
public String toString() {
return "MockRemoveEvent{key=" + key + '}';
}
}
static class MockClearEvent extends MockEvent {}
}
| 3,612
| 28.614754
| 127
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/near/ClusterInvalidatedNearCacheTest.java
|
package org.infinispan.client.hotrod.near;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import java.util.ArrayList;
import java.util.List;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.NearCacheMode;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.server.hotrod.HotRodServer;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.near.ClusterInvalidatedNearCacheTest")
public class ClusterInvalidatedNearCacheTest extends MultiHotRodServersTest {
List<AssertsNearCache<Integer, String>> assertClients = new ArrayList<>(2);
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(2, getCacheConfiguration());
}
@AfterClass(alwaysRun = true)
@Override
protected void destroy() {
assertClients.forEach(AssertsNearCache::stop);
assertClients.clear();
super.destroy();
}
private ConfigurationBuilder getCacheConfiguration() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
builder.clustering().hash().numOwners(1);
return hotRodCacheConfiguration(builder);
}
@Override
protected RemoteCacheManager createClient(int i) {
AssertsNearCache<Integer, String> asserts = createAssertClient();
assertClients.add(asserts);
return asserts.manager;
}
private <K, V> AssertsNearCache<K, V> createAssertClient() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
for (HotRodServer server : servers)
clientBuilder.addServer().host("127.0.0.1").port(server.getPort());
clientBuilder.nearCache().mode(getNearCacheMode()).maxEntries(-1);
return AssertsNearCache.create(this.<byte[], Object>cache(0), clientBuilder);
}
public void testNearCacheUpdatesSeenByAllClients() {
Integer key0 = HotRodClientTestingUtil.getIntKeyForServer(server(0));
Integer key1 = HotRodClientTestingUtil.getIntKeyForServer(server(1));
expectNearCacheUpdates(headClient(), key0, tailClient());
expectNearCacheUpdates(tailClient(), key1, headClient());
}
private AssertsNearCache<Integer, String> tailClient() {
return assertClients.get(1);
}
private AssertsNearCache<Integer, String> headClient() {
return assertClients.get(0);
}
protected NearCacheMode getNearCacheMode() {
return NearCacheMode.INVALIDATED;
}
protected void expectNearCacheUpdates(AssertsNearCache<Integer, String> producer,
Integer key, AssertsNearCache<Integer, String> consumer) {
producer.get(key, null).expectNearGetNull(key);
producer.put(key, "v1").expectNearPreemptiveRemove(key);
producer.get(key, "v1").expectNearGetNull(key).expectNearPutIfAbsent(key, "v1");
producer.put(key, "v2").expectNearRemove(key, consumer);
producer.get(key, "v2").expectNearGetNull(key).expectNearPutIfAbsent(key, "v2");
producer.remove(key).expectNearRemove(key, consumer);
producer.get(key, null).expectNearGetNull(key);
}
}
| 3,496
| 37.428571
| 96
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/near/ClusterInvalidatedNearCacheBloomTest.java
|
package org.infinispan.client.hotrod.near;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.NearCacheMode;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.util.concurrent.CompletionStages;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.near.ClusterInvalidatedNearCacheBloomTest")
public class ClusterInvalidatedNearCacheBloomTest extends MultiHotRodServersTest {
private static final int CLUSTER_MEMBERS = 3;
private static final int NEAR_CACHE_SIZE = 4;
List<AssertsNearCache<Integer, String>> assertClients = new ArrayList<>(CLUSTER_MEMBERS);
AssertsNearCache<Integer, String> client0;
AssertsNearCache<Integer, String> client1;
AssertsNearCache<Integer, String> client2;
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(CLUSTER_MEMBERS, getCacheConfiguration());
client0 = assertClients.get(0);
client1 = assertClients.get(1);
client2 = assertClients.get(2);
}
@BeforeMethod
void beforeMethod() {
assertClients.forEach(AssertsNearCache::expectNoNearEvents);
assertClients.forEach(ac -> CompletionStages.join(ac.remote.updateBloomFilter()));
}
@AfterMethod
void afterMethod() {
caches().forEach(Cache::clear);
}
@AfterClass(alwaysRun = true)
@Override
protected void destroy() {
for (AssertsNearCache<Integer, String> assertsNearCache : assertClients) {
try {
assertsNearCache.expectNoNearEvents(50, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}
assertClients.forEach(AssertsNearCache::stop);
assertClients.clear();
super.destroy();
}
private ConfigurationBuilder getCacheConfiguration() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
builder.clustering().hash().numOwners(1);
return hotRodCacheConfiguration(builder);
}
@Override
protected RemoteCacheManager createClient(int i) {
AssertsNearCache<Integer, String> asserts = createAssertClient();
assertClients.add(asserts);
return asserts.manager;
}
private <K, V> AssertsNearCache<K, V> createAssertClient() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
for (HotRodServer server : servers)
clientBuilder.addServer().host("127.0.0.1").port(server.getPort());
clientBuilder.connectionPool().maxActive(1);
clientBuilder.nearCache().mode(NearCacheMode.INVALIDATED)
.maxEntries(NEAR_CACHE_SIZE)
.bloomFilter(true);
return AssertsNearCache.create(cache(0), clientBuilder);
}
public void testInvalidationFromOtherClientModification() {
int key = 0;
client1.get(key, null).expectNearGetNull(key);
client2.get(key, null).expectNearGetNull(key);
String value = "v1";
client1.put(key, value).expectNearPreemptiveRemove(key);
client2.expectNoNearEvents();
client2.get(key, value).expectNearGetNull(key).expectNearPutIfAbsent(key, value);
client2.get(key, value).expectNearGetValue(key, value);
// Client 1 should only get a preemptive remove as it never cached the value locally
// However client 2 should get a remove as it had it cached
client1.remove(key).expectNearPreemptiveRemove(key, client2);
}
public void testClientsBothCachedAndCanUpdate() {
int key = 0;
String value = "v1";
client1.put(key, value).expectNearPreemptiveRemove(key);
client1.get(key, value).expectNearGetNull(key).expectNearPutIfAbsent(key, value);
client2.get(key, value).expectNearGetNull(key).expectNearPutIfAbsent(key, value);
String value2 = "v2";
client1.put(key, value2).expectNearRemove(key, client2);
// Even though our near cache is emptied - the bloom filter hasn't yet been updated so we will still be hit
client2.put(key, value).expectNearRemove(key, client1);
// Force the clients to update the bloom filters on the servers so now we won't see the writes
CompletionStages.join(client1.remote.updateBloomFilter());
CompletionStages.join(client2.remote.updateBloomFilter());
client2.put(key, value).expectNearPreemptiveRemove(key);
client1.put(key, value).expectNearPreemptiveRemove(key);
}
}
| 5,163
| 36.151079
| 113
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/near/InvalidatedNearCacheTest.java
|
package org.infinispan.client.hotrod.near;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withRemoteCacheManager;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import org.infinispan.client.hotrod.MetadataValue;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.configuration.NearCacheConfiguration;
import org.infinispan.client.hotrod.configuration.NearCacheMode;
import org.infinispan.client.hotrod.impl.InvalidatedNearRemoteCache;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.RemoteCacheManagerCallable;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
@Test(groups = {"functional", "smoke"}, testName = "client.hotrod.near.InvalidatedNearCacheTest")
public class InvalidatedNearCacheTest extends SingleHotRodServerTest {
private StorageType storageType;
private AssertsNearCache<Integer, String> assertClient;
private InvalidatedNearCacheTest storageType(StorageType storageType) {
this.storageType = storageType;
return this;
}
@Factory
public Object[] factory() {
return new Object[]{
new InvalidatedNearCacheTest().storageType(StorageType.OBJECT),
new InvalidatedNearCacheTest().storageType(StorageType.BINARY),
new InvalidatedNearCacheTest().storageType(StorageType.OFF_HEAP),
};
}
@Override
protected String parameters() {
return "[storageType-" + storageType + "]";
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
org.infinispan.configuration.cache.ConfigurationBuilder cb = hotRodCacheConfiguration();
cb.memory().storageType(storageType);
return TestCacheManagerFactory.createCacheManager(cb);
}
@Override
protected void teardown() {
if (assertClient != null) {
assertClient.stop();
assertClient = null;
}
super.teardown();
}
@Override
protected RemoteCacheManager getRemoteCacheManager() {
assertClient = createAssertClient();
return assertClient.manager;
}
private <K, V> AssertsNearCache<K, V> createAssertClient() {
ConfigurationBuilder builder = clientConfiguration();
return AssertsNearCache.create(this.cache(), builder);
}
private ConfigurationBuilder clientConfiguration() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(hotrodServer.getPort());
builder.nearCache().mode(getNearCacheMode()).maxEntries(-1);
return builder;
}
private NearCacheMode getNearCacheMode() {
return NearCacheMode.INVALIDATED;
}
public void testGetNearCacheAfterConnect() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(hotrodServer);
builder.nearCache().mode(getNearCacheMode()).maxEntries(-1);
RemoteCacheManager manager = new RemoteCacheManager(builder.build());
try {
RemoteCache<Integer, String> cache = manager.getCache();
cache.put(1, "one");
cache.put(2, "two");
} finally {
HotRodClientTestingUtil.killRemoteCacheManager(manager);
}
AssertsNearCache<Integer, String> newAssertClient = AssertsNearCache.create(cache(), builder);
try {
assertEquals(2, newAssertClient.remote.size());
newAssertClient.expectNoNearEvents();
newAssertClient.get(1, "one").expectNearGetValue(1, null).expectNearPutIfAbsent(1, "one");
newAssertClient.get(2, "two").expectNearGetValue(2, null).expectNearPutIfAbsent(2, "two");
newAssertClient.remove(1).expectNearRemove(1, assertClient);
newAssertClient.remove(2).expectNearRemove(2, assertClient);
} finally {
newAssertClient.stop();
}
assertClient.expectNoNearEvents();
}
public void testGetNearCache() {
assertClient.expectNoNearEvents();
assertClient.get(1, null).expectNearGetNull(1);
assertClient.put(1, "v1").expectNearPreemptiveRemove(1);
assertClient.get(1, "v1").expectNearGetNull(1).expectNearPutIfAbsent(1, "v1");
assertClient.get(1, "v1").expectNearGetValue(1, "v1");
assertClient.remove(1).expectNearRemove(1);
assertClient.get(1, null).expectNearGetNull(1);
}
public void testGetAsyncNearCache() throws ExecutionException, InterruptedException {
assertClient.expectNoNearEvents();
assertClient.getAsync(1, null).expectNearGetNull(1);
assertClient.putAsync(1, "v1").expectNearPreemptiveRemove(1);
assertClient.getAsync(1, "v1").expectNearGetNull(1).expectNearPutIfAbsent(1, "v1");
assertClient.getAsync(1, "v1").expectNearGetValue(1, "v1");
assertClient.removeAsync(1).expectNearRemove(1);
assertClient.getAsync(1, null).expectNearGetNull(1);
}
public void testGetWithMetadataNearCache() {
assertClient.expectNoNearEvents();
assertClient.getWithMetadata(1, null).expectNearGetNull(1);
assertClient.put(1, "v1").expectNearPreemptiveRemove(1);
assertClient.getWithMetadata(1, "v1").expectNearGetNull(1).expectNearPutIfAbsent(1, "v1");
assertClient.getWithMetadata(1, "v1").expectNearGetValueVersion(1, "v1");
assertClient.remove(1).expectNearRemove(1);
assertClient.getWithMetadata(1, null).expectNearGetNull(1);
}
public void testGetWithMetadataAsyncNearCache() throws ExecutionException, InterruptedException {
assertClient.expectNoNearEvents();
assertClient.getWithMetadataAsync(1, null).expectNearGetNull(1);
assertClient.putAsync(1, "v1").expectNearPreemptiveRemove(1);
assertClient.getWithMetadataAsync(1, "v1").expectNearGetNull(1).expectNearPutIfAbsent(1, "v1");
assertClient.getWithMetadataAsync(1, "v1").expectNearGetValueVersion(1, "v1");
assertClient.removeAsync(1).expectNearRemove(1);
assertClient.getWithMetadataAsync(1, null).expectNearGetNull(1);
}
public void testUpdateNearCache() {
assertClient.expectNoNearEvents();
assertClient.put(1, "v1").expectNearPreemptiveRemove(1);
assertClient.put(1, "v2").expectNearRemove(1);
assertClient.get(1, "v2").expectNearGetNull(1).expectNearPutIfAbsent(1, "v2");
assertClient.get(1, "v2").expectNearGetValue(1, "v2");
assertClient.put(1, "v3").expectNearRemove(1);
assertClient.remove(1).expectNearRemove(1);
}
public void testUpdateAsyncNearCache() throws ExecutionException, InterruptedException {
assertClient.expectNoNearEvents();
assertClient.putAsync(1, "v1").expectNearPreemptiveRemove(1);
assertClient.putAsync(1, "v2").expectNearRemove(1);
assertClient.getAsync(1, "v2").expectNearGetNull(1).expectNearPutIfAbsent(1, "v2");
assertClient.getAsync(1, "v2").expectNearGetValue(1, "v2");
assertClient.putAsync(1, "v3").expectNearRemove(1);
assertClient.removeAsync(1).expectNearRemove(1);
assertClient.putAsync(1, "v4", 3, TimeUnit.SECONDS).expectNearPreemptiveRemove(1);
assertClient.putAsync(1, "v5", 3, TimeUnit.SECONDS, 3, TimeUnit.SECONDS).expectNearRemove(1);
}
public void testGetUpdatesNearCache() {
assertClient.expectNoNearEvents();
assertClient.put(1, "v1").expectNearPreemptiveRemove(1);
final AssertsNearCache<Integer, String> newAsserts = createAssertClient();
withRemoteCacheManager(new RemoteCacheManagerCallable(newAsserts.manager) {
@Override
public void call() {
newAsserts.expectNoNearEvents();
newAsserts.get(1, "v1").expectNearGetNull(1).expectNearPutIfAbsent(1, "v1");
}
});
}
public void testGetAsyncUpdatesNearCache() throws ExecutionException, InterruptedException {
assertClient.expectNoNearEvents();
assertClient.putAsync(1, "v1").expectNearPreemptiveRemove(1);
final AssertsNearCache<Integer, String> newAsserts = createAssertClient();
withRemoteCacheManager(new RemoteCacheManagerCallable(newAsserts.manager) {
@Override
public void call() {
newAsserts.expectNoNearEvents();
try {
newAsserts.getAsync(1, "v1").expectNearGetNull(1).expectNearPutIfAbsent(1, "v1");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
@Test(expectedExceptions = CacheConfigurationException.class,
expectedExceptionsMessageRegExp = ".*When enabling near caching, number of max entries must be configured.*")
public void testConfigurationWithoutMaxEntries() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(hotrodServer);
builder.nearCache().mode(getNearCacheMode());
new RemoteCacheManager(builder.build());
}
public void testNearCacheNamePattern() {
cacheManager.defineConfiguration("nearcache", new org.infinispan.configuration.cache.ConfigurationBuilder().build());
ConfigurationBuilder builder = clientConfiguration();
builder.nearCache().cacheNamePattern("near.*");
RemoteCacheManager manager = new RemoteCacheManager(builder.build());
try {
RemoteCache<?, ?> nearcache = manager.getCache("nearcache");
assertTrue(nearcache instanceof InvalidatedNearRemoteCache);
RemoteCache<?, ?> cache = manager.getCache();
assertFalse(cache instanceof InvalidatedNearRemoteCache);
} finally {
HotRodClientTestingUtil.killRemoteCacheManager(manager);
}
}
public void testNearCachePerCache() {
cacheManager.defineConfiguration("ncpc", new org.infinispan.configuration.cache.ConfigurationBuilder().build());
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(hotrodServer.getPort());
builder.remoteCache("ncpc").nearCacheMode(NearCacheMode.INVALIDATED);
RemoteCacheManager manager = new RemoteCacheManager(builder.build());
try {
RemoteCache<?, ?> nearcache = manager.getCache("ncpc");
assertTrue(nearcache instanceof InvalidatedNearRemoteCache);
RemoteCache<?, ?> cache = manager.getCache();
assertFalse(cache instanceof InvalidatedNearRemoteCache);
} finally {
HotRodClientTestingUtil.killRemoteCacheManager(manager);
}
}
public void testNearCacheFactory() {
cacheManager.defineConfiguration("ncf", new org.infinispan.configuration.cache.ConfigurationBuilder().build());
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(hotrodServer.getPort());
TestNearCacheFactory testNearCacheFactory = new TestNearCacheFactory();
builder.nearCache().mode(NearCacheMode.INVALIDATED).nearCacheFactory(testNearCacheFactory).maxEntries(100);
RemoteCacheManager manager = new RemoteCacheManager(builder.build());
try {
RemoteCache<String, String> nearcache = manager.getCache("ncf");
assertTrue(nearcache instanceof InvalidatedNearRemoteCache);
assertEquals(0, testNearCacheFactory.cache.size());
nearcache.put("k1", "v1");
nearcache.get("k1");
assertEquals(1, testNearCacheFactory.cache.size());
} finally {
HotRodClientTestingUtil.killRemoteCacheManager(manager);
}
}
public void testNearCacheFactoryPerCache() {
cacheManager.defineConfiguration("ncfpc", new org.infinispan.configuration.cache.ConfigurationBuilder().build());
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(hotrodServer.getPort());
TestNearCacheFactory testNearCacheFactory = new TestNearCacheFactory();
builder.remoteCache("ncfpc").nearCacheMode(NearCacheMode.INVALIDATED).nearCacheFactory(testNearCacheFactory);
RemoteCacheManager manager = new RemoteCacheManager(builder.build());
try {
RemoteCache<String, String> nearcache = manager.getCache("ncfpc");
assertTrue(nearcache instanceof InvalidatedNearRemoteCache);
assertEquals(0, testNearCacheFactory.cache.size());
nearcache.put("k1", "v1");
nearcache.get("k1");
assertEquals(1, testNearCacheFactory.cache.size());
} finally {
HotRodClientTestingUtil.killRemoteCacheManager(manager);
}
}
public static class TestNearCacheFactory implements NearCacheFactory {
final ConcurrentMap<Object, Object> cache = new ConcurrentHashMap<>();
@Override
public <K, V> NearCache<K, V> createNearCache(NearCacheConfiguration config, BiConsumer<K, MetadataValue<V>> removedConsumer) {
return new NearCache<K, V>() {
@Override
public void put(K key, MetadataValue<V> value) {
cache.put(key, value);
}
@Override
public void putIfAbsent(K key, MetadataValue<V> value) {
cache.putIfAbsent(key, value);
}
@Override
public boolean remove(K key) {
return cache.remove(key) != null;
}
@Override
public MetadataValue<V> get(K key) {
return (MetadataValue<V>) cache.get(key);
}
@Override
public void clear() {
cache.clear();
}
@Override
public int size() {
return cache.size();
}
@Override
public Iterator<Map.Entry<K, MetadataValue<V>>> iterator() {
ConcurrentMap<K, MetadataValue<V>> c = (ConcurrentMap<K, MetadataValue<V>>) (ConcurrentMap<?, ?>) cache;
return c.entrySet().iterator();
}
};
}
}
}
| 14,842
| 42.527859
| 133
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/evolution/IndexSchemaNoDowntimeUpgradeTest.java
|
package org.infinispan.client.hotrod.evolution;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.Search;
import org.infinispan.client.hotrod.annotation.model.Model;
import org.infinispan.client.hotrod.evolution.model.BaseEntityWithNonAnalyzedNameFieldEntity.BaseEntityWithNonAnalyzedNameFieldEntitySchema;
import org.infinispan.client.hotrod.evolution.model.BaseModelEntity.BaseModelEntitySchema;
import org.infinispan.client.hotrod.evolution.model.BaseModelIndexAttributesChangedEntity;
import org.infinispan.client.hotrod.evolution.model.BaseModelIndexAttributesEntity;
import org.infinispan.client.hotrod.evolution.model.BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity;
import org.infinispan.client.hotrod.evolution.model.BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity.BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntitySchema;
import org.infinispan.client.hotrod.evolution.model.BaseModelWithNameFieldAnalyzedEntity.BaseModelWithNameFieldAnalyzedEntitySchema;
import org.infinispan.client.hotrod.evolution.model.BaseModelWithNameFieldAnalyzedEntityOldAnnotations.BaseModelWithNameFieldAnalyzedEntityOldAnnotationsSchema;
import org.infinispan.client.hotrod.evolution.model.BaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntity;
import org.infinispan.client.hotrod.evolution.model.BaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntity.BaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntitySchema;
import org.infinispan.client.hotrod.evolution.model.BaseModelWithNameFieldIndexedEntity.BaseModelWithNameFieldIndexedEntitySchema;
import org.infinispan.client.hotrod.evolution.model.BaseModelWithNameIndexedAndNameFieldEntity;
import org.infinispan.client.hotrod.evolution.model.BaseModelWithNameIndexedAndNameFieldEntity.BaseModelWithNameIndexedAndNameFieldEntitySchema;
import org.infinispan.client.hotrod.evolution.model.BaseModelWithNameIndexedFieldEntity.BaseModelWithNameIndexedFieldEntitySchema;
import org.infinispan.client.hotrod.evolution.model.BaseModelWithNewIndexedFieldEntity.BaseModelWithNewIndexedFieldEntitySchema;
import org.infinispan.client.hotrod.evolution.model.ModelUtils;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.commons.marshall.ProtoStreamMarshaller;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.protostream.GeneratedSchema;
import org.infinispan.query.dsl.Query;
import org.infinispan.query.dsl.QueryFactory;
import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants;
import org.infinispan.server.core.admin.embeddedserver.EmbeddedServerAdminOperationHandler;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static org.assertj.core.api.Assertions.assertThat;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM_TYPE;
import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP;
/**
* This test class contains use-cases that are necessary in the first phase of Keycloak no-downtime store to work
*
* All of these use-cases are build with an assumption that any field that was or will be used in a query is indexed
* this means
* - If we remove index, we stop using the field in queries or remove field
* - If we add index we didn't use the field in any query, but now we want to
*/
@Test(groups = "functional", testName = "client.hotrod.evolution.IndexSchemaNoDowntimeUpgradeTest")
public class IndexSchemaNoDowntimeUpgradeTest extends SingleHotRodServerTest {
private static final String CACHE_NAME = "models";
private final ProtoStreamMarshaller schemaEvolutionClientMarshaller = new ProtoStreamMarshaller();
/**
* Configure server side (embedded) cache
*
* @return the embedded cache manager
* @throws Exception
*/
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder
.encoding()
.mediaType(APPLICATION_PROTOSTREAM_TYPE)
.indexing()
.enable()
.storage(LOCAL_HEAP)
.addIndexedEntity("evolution.Model");
EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createServerModeCacheManager();
cacheManager.defineConfiguration(CACHE_NAME, builder.build());
return cacheManager;
}
/**
* Configure the server, enabling the admin operations
*
* @return the HotRod server
*/
@Override
protected HotRodServer createHotRodServer() {
HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder();
serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler());
return HotRodClientTestingUtil.startHotRodServer(cacheManager, serverBuilder);
}
@Override
protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(String host, int serverPort) {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer()
.host(host)
.port(serverPort)
.marshaller(schemaEvolutionClientMarshaller);
return builder;
}
private void updateSchemaIndex(GeneratedSchema schema) {
// Register proto schema && entity marshaller on client side
schema.registerSchema(schemaEvolutionClientMarshaller.getSerializationContext());
schema.registerMarshallers(schemaEvolutionClientMarshaller.getSerializationContext());
// Register proto schema on server side
RemoteCache<String, String> metadataCache = remoteCacheManager
.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME);
metadataCache.put(schema.getProtoFileName(), schema.getProtoFile());
// reindexCache would make this test working as well,
// the difference is that with updateIndexSchema the index state (Lucene directories) is not touched,
// if the schema change is not retro-compatible reindexCache is required
remoteCacheManager.administration().updateIndexSchema(CACHE_NAME);
}
@AfterMethod
void clean() {
remoteCacheManager.getCache(CACHE_NAME).clear();
}
/**
* This is used, for example, when a new feature is added
* the field has no meaning in the older version, so there is no migration needed
* once the new feature is used, the field is set including the index
*/
@Test
void testAddNewFieldWithIndex() {
// VERSION 1
updateSchemaIndex(BaseModelEntitySchema.INSTANCE);
RemoteCache<String, Model> cache = remoteCacheManager.getCache(CACHE_NAME);
// Create first version entities
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelEntity(1));
// Check there is only one with 3 in name field
doQuery("FROM evolution.Model WHERE name LIKE '%3%'", cache, 1);
// VERSION 2
updateSchemaIndex(BaseModelWithNewIndexedFieldEntitySchema.INSTANCE);
// Create second version entities
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelWithNewIndexedFieldEntity(2));
// check there are all entities, new and old in the cache
assertThat(cache.size()).isEqualTo(10);
// Only new entities contain the new field, no old entity should be returned
doQuery("FROM evolution.Model WHERE newField LIKE '%3%'", cache, 1);
// Test lowercase normalizer
doQuery("FROM evolution.Model WHERE newField LIKE 'Cool%fiEld%3%' ORDER BY newField", cache, 1);
}
/**
* This example shows addition of an index on existing field that was NOT used in any query in the previous version
*
* This is used when we add some functionality that needs to search entities by field that existed before, but
* was not queried
*
* Currently, all fields, that are included in some query are indexed
*
*/
@Test
void testAddAIndexOnExistingFieldThatWasNotUsedInAnyQueryBefore() {
// VERSION 1
updateSchemaIndex(BaseModelEntitySchema.INSTANCE);
RemoteCache<String, Model> cache = remoteCacheManager.getCache(CACHE_NAME);
// Create VERSION 1 entities
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelEntity(1));
// This is just for testing, the field is not used in any used query in VERSION 1
doQuery("FROM evolution.Model WHERE name LIKE '%3%'", cache, 1);
// VERSION 2 - note in this version we are NOT able to use the functionality that for the reason for adding index
// Update to second schema that adds nameIndexed field
updateSchemaIndex(BaseModelWithNameIndexedAndNameFieldEntitySchema.INSTANCE);
// Create VERSION 2 entities
// Entities created in this version needs to have both name and nameIndexed fields so that VERSION 1 is able to read
// these entities
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelWithNameIndexedAndNameFieldEntity(2));
// This is just to check data were created correctly, VERSION 2 doesn't use name nor nameIndexed in any query
// non-indexed field name should be set on both versions new and old
doQuery("FROM evolution.Model WHERE name LIKE '%3%'", cache, 2);
// indexed field nameIndexed should be present only in entities created by VERSION 2 as no reindexing was done yet
doQuery("FROM evolution.Model WHERE nameAnalyzed : '*3*'", cache, 1);
// In this state we can ask administrator to perform update of all entities to VERSION 2 before migrating to VERSION 3
// The advantage of this approach is:
// 1. Keycloak is fully functional in the meanwhile
// 2. Migration can be postponed to any time the administrator wishes (e.g. midnight)
migrateBaseModelEntityToBaseModelWithNameIndexedAndNameFieldEntity(remoteCacheManager.getCache(CACHE_NAME));
// VERSION 3 - note from this version we are able to use the functionality that was the reason for adding the index
// Update schema to version without name field
updateSchemaIndex(BaseModelWithNameIndexedFieldEntitySchema.INSTANCE);
// Create VERSION 3 entities, entity V3 can't contain name field because BaseModelWithIndexedNameEntity doesn't
// contain it in other words, migrating all entities to V3 removes name field from all entities
// The migration is not necessary though the presence of name field should not interfere normal Keycloak behaviour
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelWithNameIndexedFieldEntity(3));
// It is possible there is an older VERSION 2 node writing/reading to/from the cache, it should work
BaseModelWithNameIndexedAndNameFieldEntitySchema.INSTANCE.registerSchema(schemaEvolutionClientMarshaller.getSerializationContext());
BaseModelWithNameIndexedAndNameFieldEntitySchema.INSTANCE.registerMarshallers(schemaEvolutionClientMarshaller.getSerializationContext());
ModelUtils.createModelEntities(cache, 5, i -> ModelUtils.createBaseModelWithNameIndexedAndNameFieldEntity(2).apply(i + 10)); // Creating entities with ids +10 offset
// This is to check that older version is correctly writing also deprecated name field even though current
// schema present in the Infinispan server doesn't contain it
RemoteCache<String, BaseModelWithNameIndexedAndNameFieldEntity> cacheV2Typed = remoteCacheManager.getCache(CACHE_NAME);
BaseModelWithNameIndexedAndNameFieldEntity BaseModelWithNameIndexedAndNameFieldEntity = cacheV2Typed.get("300013");
assertThat(BaseModelWithNameIndexedAndNameFieldEntity.name).isEqualTo("modelD # 13");
// Query on nameIndexed should work with all entities >= 2 (e.g. all in the storage
// because we did the migration `migrateBaseModelEntityToBaseModelWithIndexedAndNonIndexedNameField`)
doQuery("FROM evolution.Model WHERE nameAnalyzed : '*3*'", cache, 4);
}
/**
* This example shows how an index can be removed
*
* In this example we assume the reason for removing the index is that it is no longer used in any query anymore
*/
@Test
void testRemoveIndexWhenNoLongerUsedInQueryInNewerVersion() {
// VERSION 1
updateSchemaIndex(BaseModelWithNameFieldIndexedEntitySchema.INSTANCE);
RemoteCache<String, Model> cache = remoteCacheManager.getCache(CACHE_NAME);
// Create VERSION 1 entities
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelWithNameFieldIndexedEntity(1));
// VERSION 1 uses name in a query
doQuery("FROM evolution.Model WHERE name LIKE '%3%'", cache, 1);
// VERSION 2
// In this version we cannot remove the index as node of VERSION 1 can still make a query with name in it
// The important part of this version is to remove all occurrences of the name field in queries
// VERSION 3
// In this version we can be sure there is no query with name in it, therefore we can remove the index
// Update schema to not include index on name
// Note: If the reason for removal is removal of field completely, the process would be the same with the difference,
// that this schema does not contain the field
updateSchemaIndex(BaseModelEntitySchema.INSTANCE);
// Create entities without index
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelEntity(2));
// Try query with field that has the index in both versions
doQuery("FROM evolution.Model WHERE entityVersion >= 1", cache, 10);
}
@Test
void testMigrateAnalyzedFieldToNonAnalyzed() {
// VERSION 1
updateSchemaIndex(BaseModelWithNameFieldAnalyzedEntitySchema.INSTANCE);
RemoteCache<String, Model> cache = remoteCacheManager.getCache(CACHE_NAME);
// Create VERSION 1 entities with analyzed index
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelWithNameFieldAnalyzedEntity(1));
doQuery("FROM evolution.Model WHERE nameAnalyzed : '*3*'", cache, 1);
// Update schema to VERSION 2 that contains both analyzed and non-analyzed field
updateSchemaIndex(BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntitySchema.INSTANCE);
// Create VERSION 2 entities with both indexes
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity(2));
// We need to do queries that are backward compatible
doQuery("FROM evolution.Model WHERE (entityVersion < 2 AND nameAnalyzed : '*3*') OR (entityVersion >= 2 AND nameNonAnalyzed LIKE '%3%')", cache, 2);
// In this version we request administrator to migrate to VERSION 2 all entities
migrateBaseModelWithNameFieldAnalyzedEntitySchemaToBaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity(remoteCacheManager.getCache(CACHE_NAME));
// VERSION 3
// In this version we can stop using query that uses both old and new field because we know that all entities
// in the storage are upgraded to VERSION 2
doQuery("FROM evolution.Model WHERE nameNonAnalyzed LIKE '%3%'", cache, 2);
// VERSION 4
// Now we can remove deprecated name field
updateSchemaIndex(BaseEntityWithNonAnalyzedNameFieldEntitySchema.INSTANCE);
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseEntityWithNonAnalyzedNameFieldEntity(3));
doQuery("FROM evolution.Model WHERE nameNonAnalyzed LIKE '%3%'", cache, 3);
}
@Test
void testMigrateNonAnalyzedFieldToAnalyzed() {
// VERSION 1
updateSchemaIndex(BaseModelWithNameFieldIndexedEntitySchema.INSTANCE);
RemoteCache<String, Model> cache = remoteCacheManager.getCache(CACHE_NAME);
// Create VERSION 1 entities with non-analyzed index
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelWithNameFieldIndexedEntity(1));
doQuery("FROM evolution.Model WHERE name LIKE '%3%'", cache, 1);
// VERSION 2
// Update schema to VERSION 2 that contains both non-analyzed and analyzed field
updateSchemaIndex(BaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntitySchema.INSTANCE);
// Create VERSION 2 entities with both indexes
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntity(2));
// We need to do queries that are backward compatible
doQuery("FROM evolution.Model WHERE (entityVersion < 2 AND name LIKE '%3%') OR (entityVersion >= 2 AND nameAnalyzed : '*3*')", cache, 2);
// In this version we request administrator to migrate to VERSION 2 entities
migrateBaseModelWithNameFieldIndexedEntityToBaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntity(remoteCacheManager.getCache(CACHE_NAME));
// VERSION 3
// In this version we can stop using query that uses both old and new field because we know that all entities
// in the storage are upgraded to VERSION 2
doQuery("FROM evolution.Model WHERE nameAnalyzed : '*3*'", cache, 2);
// VERSION 4
// Now we can remove deprecated name field
updateSchemaIndex(BaseModelWithNameIndexedFieldEntitySchema.INSTANCE);
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelWithNameIndexedFieldEntity(3));
doQuery("FROM evolution.Model WHERE nameAnalyzed : '*3*'", cache, 3);
}
@Test
void testMigrateOldAnnotationToNewOne() {
// VERSION 1
updateSchemaIndex(BaseModelWithNameFieldAnalyzedEntityOldAnnotationsSchema.INSTANCE);
RemoteCache<String, Model> cache = remoteCacheManager.getCache(CACHE_NAME);
// Create VERSION 1 entities
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelWithNameFieldAnalyzedEntityOldAnnotations(1));
// VERSION 1 uses name in a query
doQuery("FROM evolution.Model WHERE nameAnalyzed : '*3*'", cache, 1);
// VERSION 2
updateSchemaIndex(BaseModelWithNameFieldAnalyzedEntitySchema.INSTANCE);
// No update/reindexing needed as ModelB and ModelJ should be equivalent
// Create entities without index
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelWithNameFieldAnalyzedEntity(2));
// Try query with field that has the index in both versions
doQuery("FROM evolution.Model WHERE nameAnalyzed : '*3*'", cache, 2);
}
/**
* This is the same usecase as {@link IndexSchemaNoDowntimeUpgradeTest#testAddAIndexOnExistingFieldThatWasNotUsedInAnyQueryBefore}
*
* The difference is, that it seems for non-analyzed fields it could be possible to do the migration in one step
* on the other hand, I am not sure whether this works correctly as currently I don't know how to check whether
* the query used the index or not
*/
@Test
void testAddNonAnalyzedIndexOnExistingField() {
// VERSION 1
updateSchemaIndex(BaseModelEntitySchema.INSTANCE);
RemoteCache<String, Model> cache = remoteCacheManager.getCache(CACHE_NAME);
// Create VERSION 1 entities
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelEntity(1));
// Check there is only one with 3 in name field (Query that doesn't use index)
doQuery("FROM evolution.Model WHERE name LIKE '%3%'", cache, 1);
// VERSION 2
updateSchemaIndex(BaseModelWithNameFieldIndexedEntitySchema.INSTANCE);
// Create second version entities
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelWithNameFieldIndexedEntity(2));
// check there are two entities with 3 in name field
doQuery("FROM evolution.Model WHERE name LIKE '%3%'", cache, 2);
}
@Test
void testRemoveIndexAttribute() {
// VERSION 1
updateSchemaIndex(BaseModelIndexAttributesEntity.BaseModelIndexAttributesEntitySchema.INSTANCE);
RemoteCache<String, Model> cache = remoteCacheManager.getCache(CACHE_NAME);
// Create VERSION 1 entities
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelIndexAttributesEntity(1));
// VERSION 1
// projectable = true
assertThat(doQuery("SELECT e.entityVersion FROM evolution.Model e", cache)
.map(o -> ((Object[]) o)[0])).containsExactlyInAnyOrder(1, 1, 1, 1, 1);
// sortable = true
assertThat(doQuery("SELECT e.id FROM evolution.Model e ORDER BY e.id", cache).
map(o -> ((Object[]) o)[0])).containsExactly("800000", "800001", "800002", "800003", "800004");
// aggregable = true
Object[][] expected = Stream.generate(() -> new Object[2]).limit(5).toArray(Object[][]::new);
for (int i = 0; i < 5; i++) { expected[i][0] = i; expected[i][1] = 1L; }
assertThat(doQuery("SELECT e.number, COUNT(e.number) FROM evolution.Model e WHERE e.number <= 10 GROUP BY e.number", cache))
.containsExactlyInAnyOrder(expected[0], expected[1], expected[2], expected[3], expected[4]);
// Change attributes on indexes
updateSchemaIndex(BaseModelIndexAttributesChangedEntity.BaseModelIndexAttributesChangedEntitySchema.INSTANCE);
// Create VERSION 2 entities
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelIndexAttributesChangedEntity(2));
// VERSION 2
// aggregable = false
for (int i = 0; i < 5; i++) { expected[i][0] = i; expected[i][1] = 2L; }
assertThat(doQuery("SELECT e.number, COUNT(e.number) FROM evolution.Model e WHERE e.number <= 10 GROUP BY e.number", cache))
.containsExactlyInAnyOrder(expected[0], expected[1], expected[2], expected[3], expected[4]);
// projectable = false
try {
assertThat(doQuery("SELECT e.entityVersion FROM evolution.Model e", cache)
.map(o -> ((Object[]) o)[0])).containsExactlyInAnyOrder(1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
} catch (AssertionError ex) {
// changing projectable = true to false causes that newly added entities don't have projectable fields
// cache reindex won't help
}
// sortable = false
try {
assertThat(doQuery("SELECT e.id FROM evolution.Model e ORDER BY e.id", cache).
map(o -> ((Object[]) o)[0])).containsExactly("800000", "800001", "800002", "800003", "800004",
"900000", "900001", "900002", "900003", "900004");
} catch (RuntimeException ex) {
// changing sortable = true to false causes java.lang.IllegalStateException: unexpected docvalues type NONE for field 'id' (expected one of [SORTED, SORTED_SET]). Re-index with correct docvalues type.
// cache reindex won't help
}
}
@Test
void testAddIndexAttribute() {
// VERSION 1
updateSchemaIndex(BaseModelIndexAttributesEntity.BaseModelIndexAttributesEntitySchema.INSTANCE);
RemoteCache<String, Model> cache = remoteCacheManager.getCache(CACHE_NAME);
// Create VERSION 1 entities
ModelUtils.createModelEntities(cache, 3, ModelUtils.createBaseModelIndexAttributesEntity(1));
// VERSION 1
// projectable = false
assertThat(doQuery("SELECT e.name FROM evolution.Model e", cache)
.map(o -> ((Object[]) o)[0])).containsExactlyInAnyOrder("modelK # 0", "modelK # 1", "modelK # 2");
// sortable = false
assertThat(doQuery("SELECT e.name FROM evolution.Model e ORDER BY e.name", cache).
map(o -> ((Object[]) o)[0])).containsExactly("modelK # 0", "modelK # 1", "modelK # 2");
// aggregable = false
Object[][] expected = Stream.generate(() -> new Object[2]).limit(6).toArray(Object[][]::new);
for (int i = 0; i < 3; i++) { expected[i][0] = "modelK # " + i; expected[i][1] = 1L; }
assertThat(doQuery("SELECT e.name, COUNT(e.name) FROM evolution.Model e WHERE e.name LIKE '%model%' GROUP BY e.name", cache))
.containsExactlyInAnyOrder(expected[0], expected[1], expected[2]);
// Change attributes on indexes
updateSchemaIndex(BaseModelIndexAttributesChangedEntity.BaseModelIndexAttributesChangedEntitySchema.INSTANCE);
// Create VERSION 2 entities
ModelUtils.createModelEntities(cache, 3, ModelUtils.createBaseModelIndexAttributesChangedEntity(2));
// VERSION 2
// aggregable = true
for (int i = 0; i < 3; i++) { expected[i][0] = "modelK # " + i; expected[i][1] = 1L;
expected[i+3][0] = "modelL # " + i; expected[i+3][1] = 1L; }
assertThat(doQuery("SELECT e.name, COUNT(e.name) FROM evolution.Model e WHERE e.name LIKE '%model%' GROUP BY e.name", cache))
.containsExactlyInAnyOrder(expected[0], expected[1], expected[2], expected[3], expected[4], expected[5]);
// projectable = true
assertThat(doQuery("SELECT e.name FROM evolution.Model e", cache)
.map(o -> ((Object[]) o)[0])).containsExactlyInAnyOrder("modelK # 0", "modelK # 1", "modelK # 2",
"modelL # 0", "modelL # 1", "modelL # 2");
// sortable = true
assertThat(doQuery("SELECT e.name FROM evolution.Model e ORDER BY e.name", cache).
map(o -> ((Object[]) o)[0])).containsExactly("modelK # 0", "modelK # 1", "modelK # 2",
"modelL # 0", "modelL # 1", "modelL # 2");
}
@Test
void testMigrateNormalizerAnalyzer() {
// VERSION 1
updateSchemaIndex(BaseModelIndexAttributesEntity.BaseModelIndexAttributesEntitySchema.INSTANCE);
RemoteCache<String, Model> cache = remoteCacheManager.getCache(CACHE_NAME);
// Create VERSION 1 entities
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelIndexAttributesEntity(1));
// VERSION 1
// lowercase normalizer
doQuery("FROM evolution.Model e WHERE e.normalizedField LIKE '%normalized%'", cache, 5);
// standard analyzer => nothing found because standard analyzer takes whitespace as a delimiter when creating tokens
doQuery("FROM evolution.Model e WHERE e.analyzedField : '*analyzed field*'", cache, 0);
// Change attributes on indexes
updateSchemaIndex(BaseModelIndexAttributesChangedEntity.BaseModelIndexAttributesChangedEntitySchema.INSTANCE);
// Create VERSION 2 entities
ModelUtils.createModelEntities(cache, 5, ModelUtils.createBaseModelIndexAttributesChangedEntity(2));
// VERSION 2 - without reindex only newly added entries are recognized (5)
// lowercase normalizer removed => the query is case-sensitive, only newly added entries are found
doQuery("FROM evolution.Model e WHERE e.normalizedField LIKE '%NORMALIZED%'", cache, 5);
// standard analyzer => case-sensitive, whole text as one token, only newly added entries are found
doQuery("FROM evolution.Model e WHERE e.analyzedField : '*ANALYZED field*'", cache, 5);
remoteCacheManager.administration().reindexCache(CACHE_NAME);
// VERSION 2 - after reindex all entries are recognized (10)
// lowercase normalizer removed => the query is case-sensitive, also old entries are found
doQuery("FROM evolution.Model e WHERE e.normalizedField LIKE '%NORMALIZED%'", cache, 10);
// keyword analyzer => case-sensitive, whole text as one token, also old entries are found
doQuery("FROM evolution.Model e WHERE e.analyzedField : '*ANALYZED field*'", cache, 10);
}
private <T> void doQuery(String query, RemoteCache<String, T> messageCache, int expectedResults) {
QueryFactory queryFactory = Search.getQueryFactory(messageCache);
Query<T> infinispanObjectEntities = queryFactory.create(query);
List<T> result = StreamSupport.stream(infinispanObjectEntities.spliterator(), false)
.collect(Collectors.toList());
assertThat(result).hasSize(expectedResults);
}
private Stream doQuery(String query, RemoteCache<String, Model> messageCache) {
QueryFactory queryFactory = Search.getQueryFactory(messageCache);
Query<Object[]> infinispanObjectEntities = queryFactory.create(query);
return StreamSupport.stream(infinispanObjectEntities.spliterator(), false);
}
private void migrateBaseModelEntityToBaseModelWithNameIndexedAndNameFieldEntity(final RemoteCache<String, BaseModelWithNameIndexedAndNameFieldEntity> cache) {
new HashSet<>(cache.keySet())
.forEach(e -> {
BaseModelWithNameIndexedAndNameFieldEntity BaseModelWithNameIndexedAndNameFieldEntity = cache.get(e);
if (BaseModelWithNameIndexedAndNameFieldEntity.entityVersion == 1) {
BaseModelWithNameIndexedAndNameFieldEntity.nameAnalyzed = BaseModelWithNameIndexedAndNameFieldEntity.name;
BaseModelWithNameIndexedAndNameFieldEntity.name = null; // TODO: Cannot be null for backward compatibility
BaseModelWithNameIndexedAndNameFieldEntity.entityVersion = 2;
cache.put(BaseModelWithNameIndexedAndNameFieldEntity.id, BaseModelWithNameIndexedAndNameFieldEntity);
}
});
}
private void migrateBaseModelWithNameFieldAnalyzedEntitySchemaToBaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity(final RemoteCache<String, BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity> cache) {
new HashSet<>(cache.keySet())
.forEach(e -> {
BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity = cache.get(e);
if (BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity.entityVersion == 1) {
BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity.nameNonAnalyzed = BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity.nameAnalyzed;
BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity.nameAnalyzed = null;
BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity.entityVersion = 2;
cache.put(BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity.id, BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity);
}
});
}
private void migrateBaseModelWithNameFieldIndexedEntityToBaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntity(final RemoteCache<String, BaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntity> cache) {
new HashSet<>(cache.keySet())
.forEach(e -> {
BaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntity ModelG = cache.get(e);
if (ModelG.entityVersion == 1) {
ModelG.nameAnalyzed = ModelG.name;
ModelG.name = null;
ModelG.entityVersion = 2;
cache.put(ModelG.id, ModelG);
}
});
}
}
| 32,082
| 53.842735
| 213
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/evolution/model/BaseModelIndexAttributesEntity.java
|
package org.infinispan.client.hotrod.evolution.model;
import org.infinispan.api.annotations.indexing.Basic;
import org.infinispan.api.annotations.indexing.Indexed;
import org.infinispan.api.annotations.indexing.Keyword;
import org.infinispan.api.annotations.indexing.Text;
import org.infinispan.client.hotrod.annotation.model.Model;
import org.infinispan.protostream.GeneratedSchema;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
@Indexed
@ProtoName("Model") // K
public class BaseModelIndexAttributesEntity implements Model {
@ProtoField(number = 1)
@Basic(projectable = true)
public Integer entityVersion;
@ProtoField(number = 2)
@Basic(sortable = true)
public String id;
@ProtoField(number = 3)
@Basic(aggregable = true)
public Integer number;
@ProtoField(number = 4)
@Basic()
public String name;
@ProtoField(number = 5)
@Keyword(normalizer = "lowercase")
public String normalizedField;
@ProtoField(number = 6)
@Text()
public String analyzedField;
@Override
public String getId() {
return id;
}
@AutoProtoSchemaBuilder(includeClasses = BaseModelIndexAttributesEntity.class, schemaFileName = "evolution-schema.proto", schemaPackageName = "evolution")
public interface BaseModelIndexAttributesEntitySchema extends GeneratedSchema {
BaseModelIndexAttributesEntitySchema INSTANCE = new BaseModelIndexAttributesEntitySchemaImpl();
}
}
| 1,594
| 30.27451
| 158
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/evolution/model/BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity.java
|
package org.infinispan.client.hotrod.evolution.model;
import org.infinispan.api.annotations.indexing.Basic;
import org.infinispan.api.annotations.indexing.Indexed;
import org.infinispan.api.annotations.indexing.Text;
import org.infinispan.client.hotrod.annotation.model.Model;
import org.infinispan.protostream.GeneratedSchema;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
@Indexed
@ProtoName("Model") // G
public class BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity implements Model {
@ProtoField(number = 1)
@Basic(projectable = true)
public Integer entityVersion;
@ProtoField(number = 2)
public String id;
@ProtoField(number = 3)
@Deprecated
@Text()
public String nameAnalyzed;
@ProtoField(number = 4)
@Basic(projectable = true)
public String nameNonAnalyzed;
@Override
public String getId() {
return id;
}
@AutoProtoSchemaBuilder(includeClasses = BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity.class, schemaFileName = "evolution-schema.proto", schemaPackageName = "evolution")
public interface BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntitySchema extends GeneratedSchema {
BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntitySchema INSTANCE = new BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntitySchemaImpl();
}
}
| 1,485
| 34.380952
| 182
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/evolution/model/BaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntity.java
|
package org.infinispan.client.hotrod.evolution.model;
import org.infinispan.api.annotations.indexing.Basic;
import org.infinispan.api.annotations.indexing.Indexed;
import org.infinispan.api.annotations.indexing.Text;
import org.infinispan.client.hotrod.annotation.model.Model;
import org.infinispan.protostream.GeneratedSchema;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
@Indexed
@ProtoName("Model") // I
public class BaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntity implements Model {
@ProtoField(number = 1)
@Basic(projectable = true)
public Integer entityVersion;
@ProtoField(number = 2)
public String id;
@ProtoField(number = 3)
@Basic(projectable = true, sortable = true)
public String name;
@ProtoField(number = 4)
@Text()
public String nameAnalyzed;
@Override
public String getId() {
return id;
}
@AutoProtoSchemaBuilder(includeClasses = BaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntity.class, schemaFileName = "evolution-schema.proto", schemaPackageName = "evolution")
public interface BaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntitySchema extends GeneratedSchema {
BaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntitySchema INSTANCE = new BaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntitySchemaImpl();
}
}
| 1,480
| 35.121951
| 183
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/evolution/model/BaseModelWithNameFieldIndexedEntity.java
|
package org.infinispan.client.hotrod.evolution.model;
import org.infinispan.api.annotations.indexing.Basic;
import org.infinispan.api.annotations.indexing.Indexed;
import org.infinispan.client.hotrod.annotation.model.Model;
import org.infinispan.protostream.GeneratedSchema;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
@Indexed
@ProtoName("Model") // B
public class BaseModelWithNameFieldIndexedEntity implements Model {
@ProtoField(number = 1)
@Basic(projectable = true)
public Integer entityVersion;
@ProtoField(number = 2)
public String id;
@ProtoField(number = 3)
@Basic(projectable = true, sortable = true)
public String name;
@Override
public String getId() {
return id;
}
@AutoProtoSchemaBuilder(includeClasses = BaseModelWithNameFieldIndexedEntity.class, schemaFileName = "evolution-schema.proto", schemaPackageName = "evolution")
public interface BaseModelWithNameFieldIndexedEntitySchema extends GeneratedSchema {
BaseModelWithNameFieldIndexedEntitySchema INSTANCE = new BaseModelWithNameFieldIndexedEntitySchemaImpl();
}
}
| 1,254
| 33.861111
| 163
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/evolution/model/BaseModelWithNewIndexedFieldEntity.java
|
package org.infinispan.client.hotrod.evolution.model;
import org.infinispan.api.annotations.indexing.Basic;
import org.infinispan.api.annotations.indexing.Indexed;
import org.infinispan.api.annotations.indexing.Keyword;
import org.infinispan.client.hotrod.annotation.model.Model;
import org.infinispan.protostream.GeneratedSchema;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
@Indexed
@ProtoName("Model") // E
public class BaseModelWithNewIndexedFieldEntity implements Model {
@ProtoField(number = 1)
@Basic(projectable = true)
public Integer entityVersion;
@ProtoField(number = 2)
public String id;
@ProtoField(number = 3)
@Deprecated
public String name;
@ProtoField(number = 4)
@Keyword(normalizer = "lowercase")
public String newField;
@Override
public String getId() {
return id;
}
@AutoProtoSchemaBuilder(includeClasses = BaseModelWithNewIndexedFieldEntity.class, schemaFileName = "evolution-schema.proto", schemaPackageName = "evolution")
public interface BaseModelWithNewIndexedFieldEntitySchema extends GeneratedSchema {
BaseModelWithNewIndexedFieldEntitySchema INSTANCE = new BaseModelWithNewIndexedFieldEntitySchemaImpl();
}
}
| 1,369
| 32.414634
| 162
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/evolution/model/BaseModelIndexAttributesChangedEntity.java
|
package org.infinispan.client.hotrod.evolution.model;
import org.infinispan.api.annotations.indexing.Basic;
import org.infinispan.api.annotations.indexing.Indexed;
import org.infinispan.api.annotations.indexing.Keyword;
import org.infinispan.api.annotations.indexing.Text;
import org.infinispan.client.hotrod.annotation.model.Model;
import org.infinispan.protostream.GeneratedSchema;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
@Indexed
@ProtoName("Model") // L
public class BaseModelIndexAttributesChangedEntity implements Model {
@ProtoField(number = 1)
@Basic
public Integer entityVersion;
@ProtoField(number = 2)
@Basic
public String id;
@ProtoField(number = 3)
@Basic
public Integer number;
@ProtoField(number = 4)
@Basic(projectable = true, sortable = true, aggregable = true)
public String name;
@ProtoField(number = 5)
@Keyword
public String normalizedField;
@ProtoField(number = 6)
@Text(analyzer = "keyword")
public String analyzedField;
@Override
public String getId() {
return id;
}
@AutoProtoSchemaBuilder(includeClasses = BaseModelIndexAttributesChangedEntity.class, schemaFileName = "evolution-schema.proto", schemaPackageName = "evolution")
public interface BaseModelIndexAttributesChangedEntitySchema extends GeneratedSchema {
BaseModelIndexAttributesChangedEntitySchema INSTANCE = new BaseModelIndexAttributesChangedEntitySchemaImpl();
}
}
| 1,621
| 30.803922
| 165
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/evolution/model/BaseModelWithNameFieldAnalyzedEntityOldAnnotations.java
|
package org.infinispan.client.hotrod.evolution.model;
import org.infinispan.api.annotations.indexing.Indexed;
import org.infinispan.client.hotrod.annotation.model.Model;
import org.infinispan.protostream.GeneratedSchema;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoDoc;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
@Indexed // Uses the old annotations so we can test that migration from the old annotations to new ones
@ProtoName("Model") // J
public class BaseModelWithNameFieldAnalyzedEntityOldAnnotations implements Model {
@ProtoField(number = 1)
// Uses the old annotations so we can test that migration from the old annotations to new ones
@ProtoDoc("@Field(index = Index.YES, store = Store.YES)")
public Integer entityVersion;
@ProtoField(number = 2)
public String id;
@ProtoField(number = 3)
// Uses the old annotations so we can test that migration from the old annotations to new ones
@ProtoDoc("@Field(index = Index.YES, store = Store.YES, analyze = Analyze.YES, analyzer = @Analyzer(definition = \"standard\"))")
public String nameAnalyzed;
@Override
public String getId() {
return id;
}
@AutoProtoSchemaBuilder(includeClasses = BaseModelWithNameFieldAnalyzedEntityOldAnnotations.class, schemaFileName = "evolution-schema.proto", schemaPackageName = "evolution")
public interface BaseModelWithNameFieldAnalyzedEntityOldAnnotationsSchema extends GeneratedSchema {
BaseModelWithNameFieldAnalyzedEntityOldAnnotationsSchema INSTANCE = new BaseModelWithNameFieldAnalyzedEntityOldAnnotationsSchemaImpl();
}
}
| 1,748
| 45.026316
| 178
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/evolution/model/BaseModelEntity.java
|
package org.infinispan.client.hotrod.evolution.model;
import org.infinispan.api.annotations.indexing.Basic;
import org.infinispan.api.annotations.indexing.Indexed;
import org.infinispan.client.hotrod.annotation.model.Model;
import org.infinispan.protostream.GeneratedSchema;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
@Indexed
@ProtoName("Model") // A
public class BaseModelEntity implements Model {
@ProtoField(number = 1)
@Basic(projectable = true)
public Integer entityVersion;
@ProtoField(number = 2)
public String id;
@ProtoField(number = 3)
public String name;
@Override
public String getId() {
return id;
}
@AutoProtoSchemaBuilder(includeClasses = BaseModelEntity.class, schemaFileName = "evolution-schema.proto", schemaPackageName = "evolution")
public interface BaseModelEntitySchema extends GeneratedSchema {
BaseModelEntitySchema INSTANCE = new BaseModelEntitySchemaImpl();
}
}
| 1,106
| 30.628571
| 143
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/evolution/model/BaseEntityWithNonAnalyzedNameFieldEntity.java
|
package org.infinispan.client.hotrod.evolution.model;
import org.infinispan.api.annotations.indexing.Basic;
import org.infinispan.api.annotations.indexing.Indexed;
import org.infinispan.client.hotrod.annotation.model.Model;
import org.infinispan.protostream.GeneratedSchema;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
@Indexed
@ProtoName("Model") // H
public class BaseEntityWithNonAnalyzedNameFieldEntity implements Model {
@ProtoField(number = 1)
@Basic(projectable = true)
public Integer entityVersion;
@ProtoField(number = 2)
public String id;
@ProtoField(number = 4)
@Basic(projectable = true)
public String nameNonAnalyzed;
@Override
public String getId() {
return id;
}
@AutoProtoSchemaBuilder(includeClasses = BaseEntityWithNonAnalyzedNameFieldEntity.class, schemaFileName = "evolution-schema.proto", schemaPackageName = "evolution")
public interface BaseEntityWithNonAnalyzedNameFieldEntitySchema extends GeneratedSchema {
BaseEntityWithNonAnalyzedNameFieldEntitySchema INSTANCE = new BaseEntityWithNonAnalyzedNameFieldEntitySchemaImpl();
}
}
| 1,272
| 34.361111
| 168
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/evolution/model/BaseModelWithNameFieldAnalyzedEntity.java
|
package org.infinispan.client.hotrod.evolution.model;
import org.infinispan.api.annotations.indexing.Basic;
import org.infinispan.api.annotations.indexing.Indexed;
import org.infinispan.api.annotations.indexing.Text;
import org.infinispan.client.hotrod.annotation.model.Model;
import org.infinispan.protostream.GeneratedSchema;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
@Indexed
@ProtoName("Model") // C
public class BaseModelWithNameFieldAnalyzedEntity implements Model {
@ProtoField(number = 1)
@Basic(projectable = true)
public Integer entityVersion;
@ProtoField(number = 2)
public String id;
@ProtoField(number = 3)
@Text()
public String nameAnalyzed;
@Override
public String getId() {
return id;
}
@AutoProtoSchemaBuilder(includeClasses = BaseModelWithNameFieldAnalyzedEntity.class, schemaFileName = "evolution-schema.proto", schemaPackageName = "evolution")
public interface BaseModelWithNameFieldAnalyzedEntitySchema extends GeneratedSchema {
BaseModelWithNameFieldAnalyzedEntitySchema INSTANCE = new BaseModelWithNameFieldAnalyzedEntitySchemaImpl();
}
}
| 1,284
| 33.72973
| 164
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/evolution/model/BaseModelWithNameIndexedFieldEntity.java
|
package org.infinispan.client.hotrod.evolution.model;
import org.infinispan.api.annotations.indexing.Basic;
import org.infinispan.api.annotations.indexing.Indexed;
import org.infinispan.api.annotations.indexing.Text;
import org.infinispan.client.hotrod.annotation.model.Model;
import org.infinispan.protostream.GeneratedSchema;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
@Indexed
@ProtoName("Model") // F
public class BaseModelWithNameIndexedFieldEntity implements Model {
@ProtoField(number = 1)
@Basic(projectable = true)
public Integer entityVersion;
@ProtoField(number = 2)
public String id;
@ProtoField(number = 4)
@Text()
public String nameAnalyzed;
@Override
public String getId() {
return id;
}
@AutoProtoSchemaBuilder(includeClasses = BaseModelWithNameIndexedFieldEntity.class, schemaFileName = "evolution-schema.proto", schemaPackageName = "evolution")
public static interface BaseModelWithNameIndexedFieldEntitySchema extends GeneratedSchema {
BaseModelWithNameIndexedFieldEntitySchema INSTANCE = new BaseModelWithNameIndexedFieldEntitySchemaImpl();
}
}
| 1,286
| 33.783784
| 163
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/evolution/model/ModelUtils.java
|
package org.infinispan.client.hotrod.evolution.model;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.annotation.model.Model;
import java.util.function.Function;
public class ModelUtils {
private static int ID_VERSION_OFFSET = 100000;
public static Function<Integer, Model> createBaseModelEntity(int version) {
return i -> {
BaseModelEntity m = new BaseModelEntity();
m.entityVersion = version;
m.id = String.valueOf(i);
m.name = "modelA # " + i;
return m;
};
}
public static Function<Integer, Model> createBaseModelWithNameFieldIndexedEntity(int version) {
return i -> {
BaseModelWithNameFieldIndexedEntity m = new BaseModelWithNameFieldIndexedEntity();
m.entityVersion = version;
m.id = String.valueOf(ID_VERSION_OFFSET + i);
m.name = "modelB # " + i;
return m;
};
}
public static Function<Integer, Model> createBaseModelWithNameFieldAnalyzedEntity(int version) {
return i -> {
BaseModelWithNameFieldAnalyzedEntity m = new BaseModelWithNameFieldAnalyzedEntity();
m.entityVersion = version;
m.id = String.valueOf((2 * ID_VERSION_OFFSET) + i);
m.nameAnalyzed = "modelC # " + i;
return m;
};
}
public static Function<Integer, Model> createBaseModelWithNameIndexedAndNameFieldEntity(int version) {
return i -> {
BaseModelWithNameIndexedAndNameFieldEntity m = new BaseModelWithNameIndexedAndNameFieldEntity();
m.entityVersion = version;
m.id = String.valueOf((3 * ID_VERSION_OFFSET) + i);
m.name = "modelD # " + i;
m.nameAnalyzed = "modelD # " + i;
return m;
};
}
public static Function<Integer, Model> createBaseModelWithNewIndexedFieldEntity(int version) {
return i -> {
BaseModelWithNewIndexedFieldEntity m = new BaseModelWithNewIndexedFieldEntity();
m.entityVersion = version;
m.id = String.valueOf((4 * ID_VERSION_OFFSET) + i);
m.name = "modelE # " + i;
m.newField = "cOoLNewField-" + i;
return m;
};
}
public static Function<Integer, Model> createBaseModelWithNameIndexedFieldEntity(int version) {
return i -> {
BaseModelWithNameIndexedFieldEntity m = new BaseModelWithNameIndexedFieldEntity();
m.entityVersion = version;
m.id = String.valueOf((5 * ID_VERSION_OFFSET) + i);
m.nameAnalyzed = "modelF # " + i;
return m;
};
}
public static Function<Integer, Model> createBaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity(int version) {
return i -> {
BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity m = new BaseModelWithNameAnalyzedAndNameNonAnalyzedFieldEntity();
m.entityVersion = version;
m.id = String.valueOf((6 * ID_VERSION_OFFSET) + i);
m.nameAnalyzed = "modelG # " + i;
m.nameNonAnalyzed = m.nameAnalyzed;
return m;
};
}
public static Function<Integer, Model> createBaseEntityWithNonAnalyzedNameFieldEntity(int version) {
return i -> {
BaseEntityWithNonAnalyzedNameFieldEntity m = new BaseEntityWithNonAnalyzedNameFieldEntity();
m.entityVersion = version;
m.id = String.valueOf((7 * ID_VERSION_OFFSET) + i);
m.nameNonAnalyzed = "modelH # " + i;
return m;
};
}
public static Function<Integer, Model> createBaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntity(int version) {
return i -> {
BaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntity m = new BaseModelWithNameFieldIndexedAndNameAnalyzedFieldEntity();
m.entityVersion = version;
m.id = String.valueOf((7 * ID_VERSION_OFFSET) + i);
m.nameAnalyzed = "modelI # " + i;
m.name = "modelI # " + i;
return m;
};
}
public static Function<Integer, Model> createBaseModelWithNameFieldAnalyzedEntityOldAnnotations(int version) {
return i -> {
BaseModelWithNameFieldAnalyzedEntityOldAnnotations m = new BaseModelWithNameFieldAnalyzedEntityOldAnnotations();
m.entityVersion = version;
m.id = String.valueOf(i);
m.nameAnalyzed = "modelJ # " + i;
return m;
};
}
public static Function<Integer, Model> createBaseModelIndexAttributesEntity(int version) {
return i -> {
BaseModelIndexAttributesEntity m = new BaseModelIndexAttributesEntity();
m.entityVersion = version;
m.id = String.valueOf((8 * ID_VERSION_OFFSET) + i);
m.number = i;
m.name = "modelK # " + i;
m.normalizedField = "modelK # lowercase NORMALIZED field " + i;
m.analyzedField = "modelK # standard ANALYZED field " + i;
return m;
};
}
public static Function<Integer, Model> createBaseModelIndexAttributesChangedEntity(int version) {
return i -> {
BaseModelIndexAttributesChangedEntity m = new BaseModelIndexAttributesChangedEntity();
m.entityVersion = version;
m.id = String.valueOf((9 * ID_VERSION_OFFSET) + i);
m.number = i;
m.name = "modelL # " + i;
m.normalizedField = "modelL # NORMALIZED field " + i;
m.analyzedField = "modelL # keyword ANALYZED field " + i;
return m;
};
}
public static void createModelEntities(RemoteCache<String, Model> cache, int number, Function<Integer, Model> modelProducer) {
for (int i = 0; i < number; i++) {
Model m = modelProducer.apply(i);
cache.put(m.getId(), m);
}
}
}
| 5,977
| 36.597484
| 134
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/evolution/model/BaseModelWithNameIndexedAndNameFieldEntity.java
|
package org.infinispan.client.hotrod.evolution.model;
import org.infinispan.api.annotations.indexing.Basic;
import org.infinispan.api.annotations.indexing.Indexed;
import org.infinispan.api.annotations.indexing.Text;
import org.infinispan.client.hotrod.annotation.model.Model;
import org.infinispan.protostream.GeneratedSchema;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
@Indexed
@ProtoName("Model") // D
public class BaseModelWithNameIndexedAndNameFieldEntity implements Model {
@ProtoField(number = 1)
@Basic(projectable = true)
public Integer entityVersion;
@ProtoField(number = 2)
public String id;
@ProtoField(number = 3)
@Deprecated
public String name;
@ProtoField(number = 4)
@Text()
public String nameAnalyzed;
@Override
public String getId() {
return id;
}
@AutoProtoSchemaBuilder(includeClasses = BaseModelWithNameIndexedAndNameFieldEntity.class, schemaFileName = "evolution-schema.proto", schemaPackageName = "evolution")
public interface BaseModelWithNameIndexedAndNameFieldEntitySchema extends GeneratedSchema {
BaseModelWithNameIndexedAndNameFieldEntitySchema INSTANCE = new BaseModelWithNameIndexedAndNameFieldEntitySchemaImpl();
}
}
| 1,383
| 32.756098
| 170
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/test/HotRodClientTestingUtil.java
|
package org.infinispan.client.hotrod.test;
import static org.infinispan.client.hotrod.impl.ConfigurationProperties.DEFAULT_EXECUTOR_FACTORY_THREADNAME_PREFIX;
import static org.infinispan.commons.test.CommonsTestingUtil.loadFileAsString;
import static org.infinispan.distribution.DistributionTestHelper.isFirstOwner;
import static org.infinispan.server.core.test.ServerTestingUtil.findFreePort;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Random;
import java.util.function.Consumer;
import javax.management.ObjectName;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.FailoverRequestBalancingStrategy;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheContainer;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.configuration.StatisticsConfiguration;
import org.infinispan.client.hotrod.event.RemoteCacheSupplier;
import org.infinispan.client.hotrod.impl.protocol.HotRodConstants;
import org.infinispan.client.hotrod.impl.transaction.TransactionTable;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory;
import org.infinispan.client.hotrod.logging.Log;
import org.infinispan.commons.api.BasicCache;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.marshall.ProtoStreamMarshaller;
import org.infinispan.commons.test.TestResourceTracker;
import org.infinispan.commons.util.Util;
import org.infinispan.container.versioning.NumericVersion;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.metadata.Metadata;
import org.infinispan.scripting.ScriptingManager;
import org.infinispan.server.core.test.ServerTestingUtil;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder;
import org.infinispan.server.hotrod.test.HotRodTestingUtil;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.logging.LogFactory;
import org.testng.AssertJUnit;
/**
* Utility methods for the Hot Rod client
*
* @author Galder Zamarreño
* @since 5.1
*/
public class HotRodClientTestingUtil {
private static final Log log = LogFactory.getLog(HotRodClientTestingUtil.class, Log.class);
public static HotRodServer startHotRodServer(EmbeddedCacheManager cacheManager, HotRodServerConfigurationBuilder builder) {
return startHotRodServer(cacheManager, findFreePort(), builder);
}
public static HotRodServer startHotRodServer(EmbeddedCacheManager cacheManager, int port, HotRodServerConfigurationBuilder builder) {
return ServerTestingUtil.startProtocolServer(port, p -> HotRodTestingUtil.startHotRodServer(cacheManager, p, builder));
}
public static HotRodServer startHotRodServer(EmbeddedCacheManager cacheManager) {
return startHotRodServer(cacheManager, new HotRodServerConfigurationBuilder());
}
/**
* Kills a remote cache manager.
*
* @param rcm the remote cache manager instance to kill
*/
public static void killRemoteCacheManager(RemoteCacheContainer rcm) {
try {
if (rcm != null) rcm.stop();
} catch (Throwable t) {
log.warn("Error stopping remote cache manager", t);
}
}
/**
* Kills a group of remote cache managers.
*
* @param rcms the remote cache manager instances to kill
*/
public static void killRemoteCacheManagers(RemoteCacheManager... rcms) {
if (rcms != null) {
for (RemoteCacheManager rcm : rcms) {
try {
if (rcm != null)
rcm.stop();
} catch (Throwable t) {
log.warn("Error stopping remote cache manager", t);
}
}
}
}
/**
* Kills a group of Hot Rod servers.
*
* @param servers the group of Hot Rod servers to kill
*/
public static void killServers(HotRodServer... servers) {
if (servers != null) {
for (HotRodServer server : servers) {
try {
if (server != null) server.stop();
} catch (Throwable t) {
log.warn("Error stopping Hot Rod server", t);
}
}
}
}
/**
* Invoke a task using a remote cache manager. This method guarantees that
* the remote manager used in the task will be cleaned up after the task has
* completed, regardless of the task outcome.
*
* @param c task to execute
* @throws Exception if the task fails somehow
*/
public static void withRemoteCacheManager(RemoteCacheManagerCallable c) {
try {
c.call();
} finally {
killRemoteCacheManager(c.rcm);
}
}
public static <K, V> void withClientListener(
RemoteCacheSupplier<K> l, Consumer<RemoteCache<K, V>> cons) {
l.get().addClientListener(l);
try {
cons.accept(l.get());
} finally {
l.get().removeClientListener(l);
}
}
public static <K, V> void withClientListener(RemoteCacheSupplier<K> listener,
Object[] fparams, Object[] cparams, Consumer<RemoteCache<K, V>> cons) {
listener.get().addClientListener(listener, fparams, cparams);
try {
cons.accept(listener.get());
} finally {
listener.get().removeClientListener(listener);
}
}
public static <K> long entryVersion(Cache<byte[], ?> cache, K key) {
byte[] lookupKey;
try {
lookupKey = toBytes(key);
} catch (Exception e) {
throw new AssertionError(e);
}
Metadata meta = cache.getAdvancedCache().getCacheEntry(lookupKey).getMetadata();
return ((NumericVersion) meta.version()).getVersion();
}
public static byte[] toBytes(Object key) {
try {
return new ProtoStreamMarshaller().objectToByteBuffer(key);
} catch (Exception e) {
throw new AssertionError(e);
}
}
public static String getServersString(HotRodServer... servers) {
StringBuilder builder = new StringBuilder();
for (HotRodServer server : servers) {
builder.append("localhost").append(':').append(server.getPort()).append(";");
}
return builder.toString();
}
public static RemoteCacheManager getRemoteCacheManager(HotRodServer server) {
ConfigurationBuilder builder = newRemoteConfigurationBuilder(server);
return new InternalRemoteCacheManager(builder.build());
}
public static ConfigurationBuilder newRemoteConfigurationBuilder() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.asyncExecutorFactory()
.addExecutorProperty(DEFAULT_EXECUTOR_FACTORY_THREADNAME_PREFIX,
TestResourceTracker.getCurrentTestShortName() + "-Client-Async");
return builder;
}
public static ConfigurationBuilder newRemoteConfigurationBuilder(HotRodServer server) {
ConfigurationBuilder builder = newRemoteConfigurationBuilder();
builder.addServer()
.host(server.getHost())
.port(server.getPort());
return builder;
}
public static byte[] getKeyForServer(HotRodServer primaryOwner) {
return getKeyForServer(primaryOwner, null);
}
public static byte[] getKeyForServer(HotRodServer primaryOwner, String cacheName) {
Marshaller marshaller = new ProtoStreamMarshaller();
Cache<?, ?> cache = cacheName != null
? primaryOwner.getCacheManager().getCache(cacheName)
: primaryOwner.getCacheManager().getCache();
Random r = new Random();
byte[] dummy = new byte[8];
int attemptsLeft = 1000;
try {
do {
r.nextBytes(dummy);
attemptsLeft--;
} while (!isFirstOwner(cache, marshaller.objectToByteBuffer(dummy)) && attemptsLeft >= 0);
} catch (IOException e) {
throw new AssertionError(e);
} catch (InterruptedException e) {
throw new AssertionError(e);
}
if (attemptsLeft < 0)
throw new IllegalStateException("Could not find any key owned by " + primaryOwner);
log.infof("Binary key %s hashes to [cluster=%s,hotrod=%s]",
Util.printArray(dummy, false), primaryOwner.getCacheManager().getAddress(),
primaryOwner.getAddress());
return dummy;
}
public static Integer getIntKeyForServer(HotRodServer primaryOwner) {
return getIntKeyForServer(primaryOwner, null);
}
public static Integer getIntKeyForServer(HotRodServer primaryOwner, String cacheName) {
Cache<?, ?> cache = cacheName != null
? primaryOwner.getCacheManager().getCache(cacheName)
: primaryOwner.getCacheManager().getCache();
Random r = new Random();
byte[] dummy;
Integer dummyInt;
int attemptsLeft = 1000;
do {
dummyInt = r.nextInt();
dummy = toBytes(dummyInt);
attemptsLeft--;
} while (!isFirstOwner(cache, dummy) && attemptsLeft >= 0);
if (attemptsLeft < 0)
throw new IllegalStateException("Could not find any key owned by " + primaryOwner);
log.infof("Integer key %s hashes to [cluster=%s,hotrod=%s]",
dummyInt, primaryOwner.getCacheManager().getAddress(),
primaryOwner.getAddress());
return dummyInt;
}
/**
* Get a split-personality key, whose POJO version hashes to the primary
* owner passed in, but it's binary version does not.
*/
public static Integer getSplitIntKeyForServer(HotRodServer primaryOwner, HotRodServer binaryOwner, String cacheName) {
Cache<?, ?> cache = cacheName != null
? primaryOwner.getCacheManager().getCache(cacheName)
: primaryOwner.getCacheManager().getCache();
Cache<?, ?> binaryOwnerCache = cacheName != null
? binaryOwner.getCacheManager().getCache(cacheName)
: binaryOwner.getCacheManager().getCache();
Random r = new Random();
byte[] dummy;
Integer dummyInt;
int attemptsLeft = 1000;
boolean primaryOwnerFound = false;
boolean binaryOwnerFound = false;
do {
dummyInt = r.nextInt();
dummy = toBytes(dummyInt);
attemptsLeft--;
primaryOwnerFound = isFirstOwner(cache, dummyInt);
binaryOwnerFound = isFirstOwner(binaryOwnerCache, dummy);
} while (!(primaryOwnerFound && binaryOwnerFound) && attemptsLeft >= 0);
if (attemptsLeft < 0)
throw new IllegalStateException("Could not find any key owned by " + primaryOwner);
log.infof("Integer key [pojo=%s,bytes=%s] hashes to [cluster=%s,hotrod=%s], but the binary version's owner is [cluster=%s,hotrod=%s]",
Util.toHexString(dummy), dummyInt,
primaryOwner.getCacheManager().getAddress(), primaryOwner.getAddress(),
binaryOwner.getCacheManager().getAddress(), binaryOwner.getAddress());
return dummyInt;
}
public static <T extends FailoverRequestBalancingStrategy> T getLoadBalancer(RemoteCacheManager client) {
ChannelFactory channelFactory;
if (client instanceof InternalRemoteCacheManager) {
channelFactory = ((InternalRemoteCacheManager) client).getChannelFactory();
} else {
channelFactory = TestingUtil.extractField(client, "channelFactory");
}
return (T) channelFactory.getBalancer(HotRodConstants.DEFAULT_CACHE_NAME_BYTES);
}
public static void findServerAndKill(RemoteCacheManager client,
Collection<HotRodServer> servers, Collection<EmbeddedCacheManager> cacheManagers) {
InetSocketAddress addr = (InetSocketAddress) getLoadBalancer(client).nextServer(null);
for (HotRodServer server : servers) {
if (server.getPort() == addr.getPort()) {
HotRodClientTestingUtil.killServers(server);
TestingUtil.killCacheManagers(server.getCacheManager());
cacheManagers.remove(server.getCacheManager());
TestingUtil.blockUntilViewsReceived(50000, false, cacheManagers);
}
}
}
public static void withScript(EmbeddedCacheManager cm, String scriptPath, Consumer<String> f) {
ScriptingManager scriptingManager = cm.getGlobalComponentRegistry().getComponent(ScriptingManager.class);
String scriptName = scriptPath.replaceAll("\\/", "");
try {
loadScript(scriptName, scriptingManager, scriptPath);
f.accept(scriptName);
} finally {
scriptingManager.removeScript(scriptName);
}
}
public static String loadScript(String scriptName, ScriptingManager scriptingManager, String fileName) {
try (InputStream is = HotRodClientTestingUtil.class.getResourceAsStream(fileName)) {
String script = loadFileAsString(is);
scriptingManager.addScript(scriptName, script);
return scriptName;
} catch (IOException e) {
throw new AssertionError(e);
}
}
public static void withScript(BasicCache<String, String> scriptCache, String scriptPath, Consumer<String> f) {
String scriptName = scriptPath.replaceAll("\\/", "");
try {
loadScript(scriptName, scriptCache, scriptPath);
f.accept(scriptName);
} finally {
scriptCache.remove(scriptName);
}
}
public static String loadScript(String scriptName, BasicCache<String, String> scriptCache, String fileName) {
try (InputStream is = HotRodClientTestingUtil.class.getResourceAsStream(fileName)) {
String script = loadFileAsString(is);
scriptCache.put(scriptName, script);
return scriptName;
} catch (IOException e) {
throw new AssertionError(e);
}
}
public static void assertNoTransaction(Collection<RemoteCacheManager> cacheManagers) {
cacheManagers.forEach(HotRodClientTestingUtil::assertNoTransaction);
}
public static void assertNoTransaction(RemoteCacheManager cacheManager) {
for (String tableName : Arrays.asList("syncTransactionTable", "xaTransactionTable")) {
TransactionTable table = TestingUtil.extractField(cacheManager, tableName);
Map<?, ?> txs = TestingUtil.extractField(table, "registeredTransactions");
log.tracef("Pending Transactions in %s: %s", cacheManager, txs.keySet());
AssertJUnit.assertEquals(0, txs.size());
}
}
public static ObjectName remoteCacheManagerObjectName(RemoteCacheManager rcm) throws Exception {
StatisticsConfiguration cfg = rcm.getConfiguration().statistics();
return new ObjectName(String.format("%s:type=HotRodClient,name=%s", cfg.jmxDomain(), cfg.jmxName()));
}
public static ObjectName remoteCacheObjectName(RemoteCacheManager rcm, String cacheName) throws Exception {
StatisticsConfiguration cfg = rcm.getConfiguration().statistics();
return new ObjectName(String.format("%s:type=HotRodClient,name=%s,cache=%s", cfg.jmxDomain(), cfg.jmxName(), cacheName));
}
}
| 15,231
| 37.659898
| 140
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/test/RemoteCacheManagerCallable.java
|
package org.infinispan.client.hotrod.test;
import org.infinispan.client.hotrod.RemoteCacheManager;
/**
* A task that executes operations against a given remote cache manager.
*
* @author Galder Zamarreño
* @since 5.2
*/
public class RemoteCacheManagerCallable {
protected final RemoteCacheManager rcm;
public RemoteCacheManagerCallable(RemoteCacheManager rcm) {
this.rcm = rcm;
}
public void call() {
// No-op
}
}
| 452
| 17.875
| 72
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/test/FixedServerBalancing.java
|
package org.infinispan.client.hotrod.test;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Collection;
import java.util.Set;
import org.infinispan.client.hotrod.FailoverRequestBalancingStrategy;
import org.infinispan.server.hotrod.HotRodServer;
/**
* @since 9.4
*/
public class FixedServerBalancing implements FailoverRequestBalancingStrategy {
private final HotRodServer server;
public FixedServerBalancing(HotRodServer server) {
this.server = server;
}
@Override
public void setServers(Collection<SocketAddress> servers1) {
}
@Override
public SocketAddress nextServer(Set<SocketAddress> failedServers) {
return InetSocketAddress.createUnresolved(server.getHost(), server.getPort());
}
}
| 771
| 24.733333
| 84
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/test/MultiHotRodServersTest.java
|
package org.infinispan.client.hotrod.test;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.test.TestingUtil.blockUntilCacheStatusAchieved;
import static org.infinispan.test.TestingUtil.blockUntilViewReceived;
import static org.infinispan.test.TestingUtil.killCacheManagers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.configuration.internal.PrivateGlobalConfigurationBuilder;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder;
import org.infinispan.server.hotrod.test.HotRodTestingUtil;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
/**
* Base test class for Hot Rod tests.
*
* @author Galder Zamarreño
* @since 5.0
*/
public abstract class MultiHotRodServersTest extends MultipleCacheManagersTest {
protected final List<HotRodServer> servers = new ArrayList<>();
protected final List<RemoteCacheManager> clients = new ArrayList<>();
protected boolean testReplay = true;
protected void createHotRodServers(int num, ConfigurationBuilder defaultBuilder) {
// Start Hot Rod servers
for (int i = 0; i < num; i++) addHotRodServer(defaultBuilder);
// Verify that default caches should be started
for (int i = 0; i < num; i++) assert manager(i).getCache() != null;
// Block until views have been received
blockUntilViewReceived(manager(0).getCache(), num);
// Verify that caches running
for (int i = 0; i < num; i++) {
blockUntilCacheStatusAchieved(
manager(i).getCache(), ComponentStatus.RUNNING, 10000);
}
for (int i = 0; i < num; i++) {
clients.add(createClient(i));
}
}
protected RemoteCacheManager createClient(int i) {
return new InternalRemoteCacheManager(testReplay, createHotRodClientConfigurationBuilder(server(i)).build());
}
protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(HotRodServer server) {
return createHotRodClientConfigurationBuilder(server.getHost(), server.getPort());
}
protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(String host, int serverPort) {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer()
.host(host)
.port(serverPort)
.maxRetries(maxRetries())
.addContextInitializers(contextInitializers().toArray(new SerializationContextInitializer[0]));
return clientBuilder;
}
protected SerializationContextInitializer contextInitializer() {
return null;
}
protected List<SerializationContextInitializer> contextInitializers() {
SerializationContextInitializer sci = contextInitializer();
return sci == null ? Collections.emptyList() : Collections.singletonList(sci);
}
protected int maxRetries() {
return 0;
}
@AfterMethod(alwaysRun = true)
protected void clearContent() throws Throwable {
// Do not clear content to allow servers
// to stop gracefully and catch any issues there.
}
@AfterClass(alwaysRun = true)
@Override
protected void destroy() {
try {
for (RemoteCacheManager client : clients) {
HotRodClientTestingUtil.killRemoteCacheManager(client);
}
// Correct order is to stop servers first
for (HotRodServer server : servers) {
HotRodClientTestingUtil.killServers(server);
}
} finally {
// And then the caches and cache managers
servers.clear();
clients.clear();
super.destroy();
}
}
protected HotRodServer addHotRodServer(ConfigurationBuilder builder) {
GlobalConfigurationBuilder globalConfigurationBuilder = getServerModeGlobalConfigurationBuilder();
modifyGlobalConfiguration(globalConfigurationBuilder);
EmbeddedCacheManager cm = addClusterEnabledCacheManager(globalConfigurationBuilder, builder);
HotRodServer server = HotRodClientTestingUtil.startHotRodServer(cm);
servers.add(server);
return server;
}
private GlobalConfigurationBuilder getServerModeGlobalConfigurationBuilder() {
GlobalConfigurationBuilder globalConfigurationBuilder = new GlobalConfigurationBuilder();
globalConfigurationBuilder.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true);
globalConfigurationBuilder.transport().defaultTransport();
return globalConfigurationBuilder;
}
protected HotRodServer addHotRodServer(ConfigurationBuilder builder, int port) {
GlobalConfigurationBuilder globalConfigurationBuilder = getServerModeGlobalConfigurationBuilder();
EmbeddedCacheManager cm = addClusterEnabledCacheManager(globalConfigurationBuilder, builder);
HotRodServer server = HotRodTestingUtil.startHotRodServer(cm, port, new HotRodServerConfigurationBuilder());
servers.add(server);
return server;
}
protected HotRodServer addHotRodServerAndClient(ConfigurationBuilder builder) {
int index = servers.size();
HotRodServer server = addHotRodServer(builder);
// Block until views have been received
blockUntilViewReceived(manager(index).getCache(), servers.size());
blockUntilCacheStatusAchieved(manager(index).getCache(), ComponentStatus.RUNNING, 10000);
clients.add(createClient(index));
return server;
}
protected HotRodServer server(int i) {
return servers.get(i);
}
protected void killAll() {
while (clients.size() > 0) {
clients.get(0).stop();
clients.remove(0);
}
while (servers.size() > 0) {
killServer(0);
}
}
protected void killServer(int i) {
HotRodServer server = servers.get(i);
killServers(server);
servers.remove(i);
killCacheManagers(cacheManagers.get(i));
cacheManagers.remove(i);
}
protected RemoteCacheManager client(int i) {
return clients.get(i);
}
protected void defineInAll(String cacheName, ConfigurationBuilder builder) {
for (HotRodServer server : servers) {
defineCache(server, cacheName, builder);
}
}
protected void defineCache(HotRodServer server, String cacheName, ConfigurationBuilder builder) {
server.getCacheManager().defineConfiguration(cacheName, builder.build());
Cache<?, ?> cache = server.getCacheManager().getCache(cacheName);
blockUntilCacheStatusAchieved(cache, ComponentStatus.RUNNING, 10000);
}
protected void modifyGlobalConfiguration(GlobalConfigurationBuilder builder) {
List<SerializationContextInitializer> scis = contextInitializers();
if (scis != null)
builder.serialization().addContextInitializers(scis);
}
}
| 7,500
| 38.067708
| 146
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/test/NoopChannelOperation.java
|
package org.infinispan.client.hotrod.test;
import java.net.SocketAddress;
import java.util.concurrent.CompletableFuture;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelOperation;
import io.netty.channel.Channel;
public class NoopChannelOperation extends CompletableFuture<Channel> implements ChannelOperation {
@Override
public void invoke(Channel channel) {
complete(channel);
}
@Override
public void cancel(SocketAddress address, Throwable cause) {
completeExceptionally(cause);
}
}
| 537
| 24.619048
| 98
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/test/SingleHotRodServerTest.java
|
package org.infinispan.client.hotrod.test;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
/**
* @author Galder Zamarreño
*/
public abstract class SingleHotRodServerTest extends SingleCacheManagerTest {
protected HotRodServer hotrodServer;
protected RemoteCacheManager remoteCacheManager;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
return TestCacheManagerFactory.createCacheManager(contextInitializer(), hotRodCacheConfiguration());
}
@Override
protected void setup() throws Exception {
super.setup();
hotrodServer = createHotRodServer();
remoteCacheManager = getRemoteCacheManager();
remoteCacheManager.getCache(); // start the cache
}
protected HotRodServer createHotRodServer() {
return HotRodClientTestingUtil.startHotRodServer(cacheManager);
}
protected RemoteCacheManager getRemoteCacheManager() {
ConfigurationBuilder builder = createHotRodClientConfigurationBuilder("127.0.0.1", hotrodServer.getPort());
return new InternalRemoteCacheManager(builder.build());
}
protected ConfigurationBuilder createHotRodClientConfigurationBuilder(String host, int serverPort) {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer()
.host(host)
.port(serverPort);
SerializationContextInitializer sci = contextInitializer();
if (sci != null)
builder.addContextInitializer(sci);
return builder;
}
protected SerializationContextInitializer contextInitializer() {
return null;
}
@Override
protected void teardown() {
killRemoteCacheManager(remoteCacheManager);
killServers(hotrodServer);
hotrodServer = null;
remoteCacheManager = null;
super.teardown();
}
}
| 2,486
| 34.028169
| 113
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/test/InternalRemoteCacheManager.java
|
package org.infinispan.client.hotrod.test;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.Configuration;
import org.infinispan.client.hotrod.impl.protocol.CodecHolder;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory;
import org.infinispan.client.hotrod.impl.transport.netty.TestChannelFactory;
/**
* RemoteCacheManager that exposes internal components such as transportFactory.
*
* This class serves testing purposes and is NOT part of public API.
*
* @author Martin Gencur
*/
public class InternalRemoteCacheManager extends RemoteCacheManager {
private final boolean testReplay;
private ChannelFactory customChannelFactory;
public InternalRemoteCacheManager(boolean testReplay, Configuration configuration) {
super(configuration, true);
this.testReplay = testReplay;
}
public InternalRemoteCacheManager(Configuration configuration) {
super(configuration, true);
this.testReplay = true;
}
public InternalRemoteCacheManager(Configuration configuration, ChannelFactory customChannelFactory) {
this(configuration, false);
this.customChannelFactory = customChannelFactory;
}
public InternalRemoteCacheManager(Configuration configuration, boolean start) {
super(configuration, start);
this.testReplay = true;
}
public InternalRemoteCacheManager(boolean start) {
super(start);
this.testReplay = true;
}
public InternalRemoteCacheManager() {
this(true);
}
public ChannelFactory getChannelFactory() {
return channelFactory;
}
@Override
public ChannelFactory createChannelFactory() {
if (customChannelFactory != null) return customChannelFactory;
if (testReplay) return new TestChannelFactory(new CodecHolder(getConfiguration().version().getCodec()));
return super.createChannelFactory();
}
}
| 1,931
| 30.672131
| 110
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/ClientListenerFailoverBusyTest.java
|
package org.infinispan.client.hotrod.retry;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.infinispan.AdvancedCache;
import org.infinispan.client.hotrod.ProtocolVersion;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.event.ClientCacheEntryModifiedEvent;
import org.infinispan.client.hotrod.impl.protocol.Codec25;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelRecord;
import org.infinispan.client.hotrod.test.NoopChannelOperation;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commons.test.annotation.TestForIssue;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.InvocationContext;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.util.concurrent.AggregateCompletionStage;
import org.infinispan.util.concurrent.CompletionStages;
import org.testng.annotations.Test;
import io.netty.channel.Channel;
@TestForIssue(jiraKey = "ISPN-14846")
@CleanupAfterMethod
@Test(groups = "functional", testName = "client.hotrod.retry.ClientListenerFailoverBusyTest")
public class ClientListenerFailoverBusyTest extends AbstractRetryTest {
private static final int MAX_PENDING_REQUESTS = 10;
{
nbrOfServers = 1;
}
@Override
protected ConfigurationBuilder getCacheConfig() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
return hotRodCacheConfiguration(builder);
}
@Override
protected RemoteCacheManager createClient() {
RemoteCacheManager rcm = super.createClient();
rcm.getChannelFactory().setNegotiatedCodec(new Codec25());
return rcm;
}
@Override
protected void amendRemoteCacheManagerConfiguration(org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder) {
builder.version(ProtocolVersion.PROTOCOL_VERSION_25)
// We need maxActive=2 because protocol version is 2.5.
// The listener never releases its channel to the pool.
.connectionPool().maxActive(2)
// Necessary so the listener reuses the channel.
.maxPendingRequests(MAX_PENDING_REQUESTS + 1);
}
public void testWithASingleOperation() throws Exception {
testListenerWithSlowServer(1);
}
public void testWithMultipleOperations() throws Exception {
testListenerWithSlowServer(MAX_PENDING_REQUESTS);
}
private void testListenerWithSlowServer(int numberOfOperations) throws Exception {
AdvancedCache<?, ?> cache = cacheToHit(1);
InetSocketAddress address = InetSocketAddress.createUnresolved(hotRodServer1.getHost(), hotRodServer1.getPort());
// We acquire the channel. This will be the same channel for the listener.
Channel channel = channelFactory.fetchChannelAndInvoke(address, new NoopChannelOperation()).get(10, TimeUnit.SECONDS);
// Release channel back to the pool so listener can use it.
ChannelRecord.of(channel).release(channel);
Listener listener = new Listener();
remoteCache.addClientListener(listener);
ExecutorService executor = Executors.newScheduledThreadPool(numberOfOperations);
CyclicBarrier barrier = new CyclicBarrier(numberOfOperations + 1);
CountDownLatch latch = new CountDownLatch(1);
DelayedInterceptor interceptor = new DelayedInterceptor(latch, barrier, executor);
cache.getAsyncInterceptorChain().addInterceptor(interceptor, 1);
// We issue all of these operations which do not complete until the latch is released.
AggregateCompletionStage<?> operations = CompletionStages.aggregateCompletionStage();
for (int i = 0; i < numberOfOperations; i++) {
operations.dependsOn(remoteCache.putAsync(1, "v" + i));
}
// Await all the operations reach the interceptor.
barrier.await(10, TimeUnit.SECONDS);
int eventsBeforeFailover = listener.getReceived();
// Now close the listener channel, so it failover to the channel with put operations.
channel.close().awaitUninterruptibly();
eventually(() -> channelFactory.getNumActive() == 1);
try {
// We release the latch so operations complete, in the same channel the listener is using.
latch.countDown();
operations.freeze().toCompletableFuture().get(10, TimeUnit.SECONDS);
// If numberOfOperations == 1 we only create the entry, we do not generate events from updates.
if (numberOfOperations > 1)
eventually(() -> listener.getReceived() > eventsBeforeFailover);
} finally {
cache.getAsyncInterceptorChain().removeInterceptor(DelayedInterceptor.class);
executor.shutdown();
}
}
@ClientListener
private static class Listener {
private final AtomicInteger count = new AtomicInteger(0);
@ClientCacheEntryModified
public void handleModifiedEvent(ClientCacheEntryModifiedEvent<?> ignore) {
count.incrementAndGet();
}
int getReceived() {
return count.intValue();
}
}
public static class DelayedInterceptor extends DDAsyncInterceptor {
private final CountDownLatch latch;
private final CyclicBarrier barrier;
private final ExecutorService executor;
public DelayedInterceptor(CountDownLatch latch, CyclicBarrier barrier, ExecutorService executor) {
this.latch = latch;
this.barrier = barrier;
this.executor = executor;
}
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
CompletableFuture<Object> cf = new CompletableFuture<>();
executor.submit(() -> {
try {
barrier.await();
latch.await();
cf.complete(super.visitPutKeyValueCommand(ctx, command));
} catch (Throwable e) {
cf.completeExceptionally(e);
}
});
return asyncValue(cf);
}
}
}
| 6,686
| 38.105263
| 129
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/StableControlledConsistentHashFactory.java
|
package org.infinispan.client.hotrod.retry;
import java.util.List;
import org.infinispan.distribution.ch.impl.DefaultConsistentHash;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.BaseControlledConsistentHashFactory;
/**
* Consistent hash factory implementation keeping segments stable as nodes are stopped:
*
* <ol>
* <li>0 -> A, 1 -> B, 2 -> C
* <li>When A is stopped: 0, 1 -> B, 2 -> C
* <li>When B is also stopped: 0, 1, 2 -> C
* </ol>
*/
public class StableControlledConsistentHashFactory
extends BaseControlledConsistentHashFactory<DefaultConsistentHash> {
public StableControlledConsistentHashFactory() {
super(new DefaultTrait(), 3);
}
@Override
protected int[][] assignOwners(int numSegments, List<Address> members) {
switch (members.size()) {
case 1:
return new int[][]{{0}, {0}, {0}};
case 2:
return new int[][]{{0}, {0}, {1}};
default:
return new int[][]{{0}, {1}, {2}};
}
}
@AutoProtoSchemaBuilder(
includeClasses = {StableControlledConsistentHashFactory.class},
schemaFileName = "test.client.CompleteShutdownDistRetryTest.proto",
schemaFilePath = "proto/generated",
schemaPackageName = "org.infinispan.test.client.CompleteShutdownDistRetryTest"
)
public interface SCI extends SerializationContextInitializer {
}
}
| 1,558
| 32.170213
| 87
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/SocketTimeoutFailureRetryTest.java
|
package org.infinispan.client.hotrod.retry;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicReference;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.commands.read.GetCacheEntryCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.InvocationContext;
import org.infinispan.interceptors.BaseCustomAsyncInterceptor;
import org.infinispan.interceptors.impl.EntryWrappingInterceptor;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterTest;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.retry.SocketTimeoutFailureRetryTest")
@CleanupAfterTest
public class SocketTimeoutFailureRetryTest extends AbstractRetryTest {
@Override
protected ConfigurationBuilder getCacheConfig() {
ConfigurationBuilder builder = hotRodCacheConfiguration(
getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
return builder;
}
@Override
protected RemoteCacheManager createRemoteCacheManager(int port) {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder
.connectionTimeout(2_000)
.socketTimeout(2_000)
.maxRetries(1)
//.connectionPool().maxActive(1) //this ensures that only one server is active at a time
.addServer().host("127.0.0.1").port(port);
return new InternalRemoteCacheManager(builder.build());
}
protected void addInterceptors(Cache<?, ?> cache) {
super.addInterceptors(cache);
TestingUtil.extractInterceptorChain(cache)
.addInterceptorAfter(new DelayingInterceptor(), EntryWrappingInterceptor.class);
}
public void testRetrySocketTimeout() {
Integer key = 1;
remoteCache.put(key, "v1");
assertEquals("v1", remoteCache.get(1));
AdvancedCache<?, ?> nextCache = cacheToHit(key);
DelayingInterceptor interceptor = TestingUtil.extractInterceptorChain(nextCache)
.findInterceptorExtending(DelayingInterceptor.class);
CompletableFuture<Void> delay = new CompletableFuture<>();
interceptor.delayNextRequest(delay);
assertEquals(0, remoteCacheManager.getChannelFactory().getRetries());
int connectionsBefore = channelFactory.getNumActive() + channelFactory.getNumIdle();
assertEquals("v1", remoteCache.get(key));
assertEquals(1, remoteCacheManager.getChannelFactory().getRetries());
assertEquals(connectionsBefore, channelFactory.getNumActive() + channelFactory.getNumIdle());
delay.complete(null);
}
public static class DelayingInterceptor extends BaseCustomAsyncInterceptor {
static volatile AtomicReference<CompletionStage<Void>> delayNextRequest = new AtomicReference<>();
public void delayNextRequest(CompletionStage<Void> delayStage) {
delayNextRequest.set(delayStage);
}
@Override
public Object visitGetCacheEntryCommand(InvocationContext ctx, GetCacheEntryCommand command) {
// Delay just one invocation, then reset to null
CompletionStage<Void> delay = delayNextRequest.getAndSet(null);
return asyncInvokeNext(ctx, command, delay);
}
}
}
| 3,849
| 41.777778
| 104
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/GetAllRetryTest.java
|
package org.infinispan.client.hotrod.retry;
import static java.util.stream.IntStream.range;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import java.util.Map;
import java.util.stream.Collectors;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
@Test(testName = "client.hotrod.retry.GetAllRetryTest", groups = "functional")
public class GetAllRetryTest extends MultiHotRodServersTest {
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(3, getCacheConfiguration());
}
private ConfigurationBuilder getCacheConfiguration() {
return hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
}
@Override
protected int maxRetries() {
return 10;
}
@Test
public void testFailOver() throws InterruptedException {
RemoteCache<Integer, String> remoteCache = clients.get(0).getCache();
int size = 1000;
range(0, size).forEach(num -> remoteCache.put(num, "value" + num));
Map<Integer, String> firstBatch = remoteCache.getAll(range(0, size / 2).boxed().collect(Collectors.toSet()));
HotRodClientTestingUtil.killServers(servers.get(0));
Map<Integer, String> secondBatch = remoteCache.getAll(range(size / 2, size).boxed().collect(Collectors.toSet()));
assertEquals(size, firstBatch.size() + secondBatch.size());
}
}
| 1,753
| 32.730769
| 119
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/CompleteShutdownDistRetryTest.java
|
package org.infinispan.client.hotrod.retry;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.fail;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.infinispan.client.hotrod.HitsAwareCacheManagersTest;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.exceptions.TransportException;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.server.hotrod.HotRodServer;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.retry.CompleteShutdownDistRetryTest")
public class CompleteShutdownDistRetryTest extends HitsAwareCacheManagersTest {
List<SocketAddress> addrs;
List<byte[]> keys;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = getConfiguration();
createHotRodServers(3, builder);
}
@Override
protected GlobalConfigurationBuilder defaultGlobalConfigurationBuilder() {
GlobalConfigurationBuilder gcb = GlobalConfigurationBuilder.defaultClusteredBuilder();
gcb.serialization().addContextInitializer(new SCIImpl());
return gcb;
}
@Override
protected void assertOnlyServerHit(SocketAddress serverAddress) {
super.assertOnlyServerHit(serverAddress);
resetStats(); // reset stats after checking that only server got hit
}
public void testRetryAfterCompleteShutdown() {
RemoteCache<byte[], String> client = client(0).getCache();
int initialServerPort = addr2hrServer.values().iterator().next().getPort();
addrs = getSocketAddressList();
keys = genKeys();
assertNoHits();
assertPutAndGet(client, 0, "zero");
assertPutAndGet(client, 1, "one");
assertPutAndGet(client, 2, "two");
killServer();
killServer();
assertNull(client.get(keys.get(0))); // data gone
assertNull(client.get(keys.get(1))); // data gone
resetStats();
assertEquals("two", client.get(keys.get(2)));
assertOnlyServerHit(addrs.get(2));
killServer();
try {
assertEquals("two", client.get(keys.get(2)));
fail("Should have thrown exception");
} catch (TransportException e) {
// Ignore, expected
}
resetStats();
addHotRodServer(getConfiguration(), initialServerPort);
addHotRodServer(getConfiguration());
addHotRodServer(getConfiguration());
addInterceptors();
keys = genKeys();
addrs = getSocketAddressList();
assertNoHits();
assertPutAndGet(client, 0, "zero");
assertPutAndGet(client, 1, "one");
assertPutAndGet(client, 2, "two");
}
private void assertPutAndGet(RemoteCache<byte[], String> client, int nodeIndex, String value) {
client.put(keys.get(nodeIndex), value);
assertOnlyServerHit(addrs.get(nodeIndex));
assertEquals(value, client.get(keys.get(nodeIndex)));
assertOnlyServerHit(addrs.get(nodeIndex));
}
private List<byte[]> genKeys() {
List<byte[]> keys = new ArrayList<>();
for (Map.Entry<SocketAddress, HotRodServer> entry : addr2hrServer.entrySet()) {
keys.add(HotRodClientTestingUtil.getKeyForServer(entry.getValue()));
}
return keys;
}
private List<SocketAddress> getSocketAddressList() {
return new ArrayList<>(addr2hrServer.keySet());
}
private ConfigurationBuilder getConfiguration() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
builder.clustering().hash().numSegments(3).numOwners(1);
builder.clustering().hash().consistentHashFactory(new StableControlledConsistentHashFactory());
return hotRodCacheConfiguration(builder);
}
}
| 4,161
| 33.683333
| 101
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/ReplicationHitsTest.java
|
package org.infinispan.client.hotrod.retry;
import static org.testng.AssertJUnit.assertEquals;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.remoting.rpc.RpcManagerImpl;
import org.testng.annotations.Test;
/**
* @author Dan Berindei
* @since 8.1
*/
@Test (testName = "client.hotrod.retry.ReplicationHitsTest", groups = "functional")
public class ReplicationHitsTest extends AbstractRetryTest {
public static final int NUM_WRITES = 100;
public void testPut() {
resetStats();
assertNoHits();
for (Cache c : caches()) {
((RpcManagerImpl) c.getAdvancedCache().getRpcManager()).setStatisticsEnabled(true);
}
for (int i = 0; i < NUM_WRITES; i++) {
remoteCache.put("k" + i, "v1");
}
int totalReplications = 0;
for (Cache c : caches()) {
totalReplications += ((RpcManagerImpl) c.getAdvancedCache().getRpcManager()).getReplicationCount();
}
assertEquals(NUM_WRITES, totalReplications);
}
@Override
protected ConfigurationBuilder getCacheConfig() {
ConfigurationBuilder config =
getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false);
config.clustering().hash().numSegments(60);
return config;
}
}
| 1,361
| 27.978723
| 108
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/PutAllRetryTest.java
|
package org.infinispan.client.hotrod.retry;
import static java.util.stream.IntStream.range;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import java.util.TreeMap;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
@Test(testName = "client.hotrod.retry.PutAllRetryTest", groups = "functional")
public class PutAllRetryTest extends MultiHotRodServersTest {
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(3, getCacheConfiguration());
}
private ConfigurationBuilder getCacheConfiguration() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
builder.clustering().hash().numOwners(2);
return hotRodCacheConfiguration(builder);
}
@Override
protected int maxRetries() {
return 10;
}
@Test
public void testFailOver() throws InterruptedException {
RemoteCache<Integer, String> remoteCache = clients.get(0).getCache();
int size = 1000;
TreeMap<Integer, String> dataMap = new TreeMap<>();
range(0, size).forEach(num -> dataMap.put(num, "value" + num));
remoteCache.putAll(dataMap.subMap(0, size / 2));
HotRodClientTestingUtil.killServers(servers.get(0));
remoteCache.putAll(dataMap.subMap(size / 2, size));
assertEquals(size, remoteCache.size());
}
}
| 1,726
| 30.981481
| 96
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/AbstractRetryTest.java
|
package org.infinispan.client.hotrod.retry;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.getLoadBalancer;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.marshall;
import java.net.SocketAddress;
import org.infinispan.AdvancedCache;
import org.infinispan.client.hotrod.HitsAwareCacheManagersTest;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.impl.RemoteCacheImpl;
import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHash;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory;
import org.infinispan.client.hotrod.impl.transport.tcp.RoundRobinBalancingStrategy;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
public abstract class AbstractRetryTest extends HitsAwareCacheManagersTest {
protected HotRodServer hotRodServer1;
protected HotRodServer hotRodServer2;
protected HotRodServer hotRodServer3;
protected int nbrOfServers = 3;
protected RemoteCacheImpl<Object, Object> remoteCache;
protected RemoteCacheManager remoteCacheManager;
protected ChannelFactory channelFactory;
protected ConfigurationBuilder config;
protected RoundRobinBalancingStrategy strategy;
public AbstractRetryTest() {
cleanup = CleanupPhase.AFTER_METHOD;
}
@Override
protected void createCacheManagers() throws Throwable {
assert nbrOfServers > 0 && nbrOfServers <= 3 : "nbrOfServers must be between 1 and 3";
config = hotRodCacheConfiguration(getCacheConfig());
EmbeddedCacheManager cm1 = TestCacheManagerFactory.createClusteredCacheManager(config);
registerCacheManager(cm1);
hotRodServer1 = createStartHotRodServer(manager(0));
addr2hrServer.put(getAddress(hotRodServer1), hotRodServer1);
if (nbrOfServers > 1) {
EmbeddedCacheManager cm2 = TestCacheManagerFactory.createClusteredCacheManager(config);
registerCacheManager(cm2);
hotRodServer2 = createStartHotRodServer(manager(1));
addr2hrServer.put(getAddress(hotRodServer2), hotRodServer2);
}
if (nbrOfServers > 2) {
EmbeddedCacheManager cm3 = TestCacheManagerFactory.createClusteredCacheManager(config);
registerCacheManager(cm3);
hotRodServer3 = createStartHotRodServer(manager(2));
addr2hrServer.put(getAddress(hotRodServer3), hotRodServer3);
}
waitForClusterToForm();
remoteCacheManager = createRemoteCacheManager(hotRodServer1.getPort());
remoteCache = (RemoteCacheImpl) remoteCacheManager.getCache();
channelFactory = remoteCacheManager.getChannelFactory();
strategy = getLoadBalancer(remoteCacheManager);
addInterceptors();
assert super.cacheManagers.size() == nbrOfServers;
}
protected RemoteCacheManager createRemoteCacheManager(int port) {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder
.forceReturnValues(true)
.connectionTimeout(5)
.connectionPool().maxActive(1); //this ensures that only one server is active at a time
amendRemoteCacheManagerConfiguration(builder);
builder.addServer().host("127.0.0.1").port(port);
return new InternalRemoteCacheManager(builder.build());
}
protected void amendRemoteCacheManagerConfiguration(org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder) {
// no-op
}
protected HotRodServer createStartHotRodServer(EmbeddedCacheManager manager) {
return HotRodClientTestingUtil.startHotRodServer(manager);
}
@AfterMethod(alwaysRun = true)
@Override
protected void clearContent() throws Throwable {
if (cleanupAfterMethod()) {
HotRodClientTestingUtil.killRemoteCacheManagers(remoteCacheManager);
remoteCacheManager = null;
HotRodClientTestingUtil.killServers(hotRodServer1, hotRodServer2, hotRodServer3);
hotRodServer1 = null;
hotRodServer2 = null;
hotRodServer3 = null;
}
super.clearContent();
}
@AfterClass(alwaysRun = true)
@Override
protected void destroy() {
if (cleanupAfterTest()) {
HotRodClientTestingUtil.killRemoteCacheManagers(remoteCacheManager);
remoteCacheManager = null;
HotRodClientTestingUtil.killServers(hotRodServer1, hotRodServer2, hotRodServer3);
hotRodServer1 = null;
hotRodServer2 = null;
hotRodServer3 = null;
}
super.destroy();
}
protected abstract ConfigurationBuilder getCacheConfig();
protected AdvancedCache<?, ?> cacheToHit(Object key) {
ConsistentHash consistentHash = channelFactory.getConsistentHash(RemoteCacheManager.cacheNameBytes());
SocketAddress expectedServer = consistentHash.getServer(marshall(key));
return addr2hrServer.get(expectedServer).getCacheManager().getCache().getAdvancedCache();
}
}
| 5,515
| 38.971014
| 129
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/CompleteShutdownReplRetryTest.java
|
package org.infinispan.client.hotrod.retry;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.fail;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.exceptions.TransportException;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.retry.CompleteShutdownReplRetryTest")
public class CompleteShutdownReplRetryTest extends MultiHotRodServersTest {
@Override
protected void createCacheManagers() throws Throwable {
// Empty
}
@Override
protected int maxRetries() {
return 1;
}
public void testRetryAfterCompleteShutdown() {
ConfigurationBuilder builder = hotRodCacheConfiguration(
getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false));
createHotRodServers(3, builder);
try {
int initialServerPort = server(0).getPort();
assertClusterSize("Cluster should be formed", 3);
RemoteCache<Integer, String> client = client(0).getCache();
client.put(1, "one");
assertEquals("one", client.get(1));
killServer(0);
assertEquals("one", client.get(1));
killServer(0);
assertEquals("one", client.get(1));
killServer(0);
try {
assertEquals("one", client.get(1));
fail("Should have thrown exception");
} catch (TransportException e) {
// Ignore, expected
}
addHotRodServer(builder, initialServerPort);
client.put(1, "one");
assertEquals("one", client.get(1));
} finally {
destroy();
}
}
}
| 1,937
| 30.770492
| 92
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/SecureServerFailureRetryTest.java
|
package org.infinispan.client.hotrod.retry;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.core.security.simple.SimpleSaslAuthenticator;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder;
import org.infinispan.server.hotrod.test.TestCallbackHandler;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.retry.SecureServerFailureRetryTest")
public class SecureServerFailureRetryTest extends ServerFailureRetryTest {
@Override
protected HotRodServer createStartHotRodServer(EmbeddedCacheManager manager) {
HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder();
SimpleSaslAuthenticator sap = new SimpleSaslAuthenticator();
sap.addUser("user", "realm", "password".toCharArray(), null);
serverBuilder.authentication()
.enable()
.sasl()
.serverName("localhost")
.addAllowedMech("CRAM-MD5")
.authenticator(sap);
return HotRodClientTestingUtil.startHotRodServer(manager, serverBuilder);
}
@Override
protected RemoteCacheManager createRemoteCacheManager(int port) {
ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder
.security().authentication()
.enable()
.saslMechanism("CRAM-MD5")
.callbackHandler(new TestCallbackHandler("user", "realm", "password".toCharArray()))
.forceReturnValues(true)
.connectionTimeout(5)
.connectionPool().maxActive(1)
.addServer().host("127.0.0.1").port(port);
return new InternalRemoteCacheManager(clientBuilder.build());
}
}
| 2,073
| 43.12766
| 99
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/ServerFailureRetryTest.java
|
package org.infinispan.client.hotrod.retry;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.InvocationContext;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.remoting.transport.jgroups.SuspectException;
import org.jgroups.SuspectedException;
import org.testng.annotations.Test;
/**
* Test different server error situations and check how clients behave under
* those circumstances. Also verify whether failover is happening accordingly.
*
* @author Galder Zamarreño
* @since 4.2
*/
@Test(groups = "functional", testName = "client.hotrod.retry.ServerFailureRetryTest")
public class ServerFailureRetryTest extends AbstractRetryTest {
@Override
protected ConfigurationBuilder getCacheConfig() {
return hotRodCacheConfiguration(
getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false));
}
public void testRetryWithInfinispanSuspectException() {
retryExceptions(false);
}
public void testRetryWithJGroupsSuspectedException() {
retryExceptions(true);
}
private void retryExceptions(boolean throwJGroupsException) {
AdvancedCache<?, ?> nextCache = cacheToHit(1);
ErrorInducingInterceptor interceptor = new ErrorInducingInterceptor(throwJGroupsException);
nextCache.getAsyncInterceptorChain().addInterceptor(interceptor, 1);
try {
remoteCache.put(1, "v1");
assertTrue(interceptor.suspectExceptionThrown);
assertEquals("v1", remoteCache.get(1));
} finally {
nextCache.getAsyncInterceptorChain().removeInterceptor(ErrorInducingInterceptor.class);
}
}
public void testRetryCacheStopped() {
// Put data in any of the cluster's default cache
remoteCache.put(1, "v1");
assertEquals("v1", remoteCache.get(1));
// Find out what next cluster cache to be hit and stop it
Cache<?, ?> cache = cacheToHit(2);
try {
cache.stop();
remoteCache.put(2, "v2");
assertEquals("v2", remoteCache.get(2));
} finally {
cache.start();
}
}
// Listener callbacks can happen in the main thread or remote thread
// depending on primary owner considerations, even for replicated caches.
// Using an interceptor gives more flexibility by being able to put it
// at the top of the interceptor stack, before remote/local separation
public static class ErrorInducingInterceptor extends DDAsyncInterceptor {
volatile boolean suspectExceptionThrown;
boolean throwJGroupsException;
public ErrorInducingInterceptor(boolean throwJGroupsException) {
this.throwJGroupsException = throwJGroupsException;
}
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
if (ctx.isOriginLocal()) {
suspectExceptionThrown = true;
throw throwJGroupsException ?
new SuspectedException("Simulated suspicion")
: new SuspectException("Simulated suspicion");
}
return super.visitPutKeyValueCommand(ctx, command);
}
}
}
| 3,553
| 36.410526
| 113
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/ReplicationRetryTest.java
|
package org.infinispan.client.hotrod.retry;
import static org.testng.Assert.assertEquals;
import java.net.SocketAddress;
import java.util.Iterator;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.VersionedValue;
import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHash;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.test.HotRodTestingUtil;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test (testName = "client.hotrod.retry.ReplicationRetryTest", groups = "functional")
public class ReplicationRetryTest extends AbstractRetryTest {
public void testGet() {
validateSequenceAndStopServer();
//now make sure that next call won't fail
resetStats();
for (int i = 0; i < 100; i++) {
assert remoteCache.get("k").equals("v");
}
}
public void testPut() {
validateSequenceAndStopServer();
resetStats();
assertEquals(remoteCache.put("k", "v0"), "v");
for (int i = 1; i < 100; i++) {
assertEquals("v" + (i-1), remoteCache.put("k", "v"+i));
}
}
public void testRemove() {
validateSequenceAndStopServer();
resetStats();
assertEquals("v", remoteCache.remove("k"));
}
public void testContains() {
validateSequenceAndStopServer();
resetStats();
assertEquals(true, remoteCache.containsKey("k"));
}
public void testGetWithMetadata() {
validateSequenceAndStopServer();
resetStats();
VersionedValue value = remoteCache.getWithMetadata("k");
assertEquals("v", value.getValue());
}
public void testPutIfAbsent() {
validateSequenceAndStopServer();
resetStats();
assertEquals(null, remoteCache.putIfAbsent("noSuchKey", "someValue"));
assertEquals("someValue", remoteCache.get("noSuchKey"));
}
public void testReplace() {
validateSequenceAndStopServer();
resetStats();
assertEquals("v", remoteCache.replace("k", "v2"));
}
public void testReplaceIfUnmodified() {
validateSequenceAndStopServer();
resetStats();
assertEquals(false, remoteCache.replaceWithVersion("k", "v2", 12));
}
public void testRemoveIfUnmodified() {
validateSequenceAndStopServer();
resetStats();
assertEquals(false, remoteCache.removeWithVersion("k", 12));
}
public void testClear() {
validateSequenceAndStopServer();
resetStats();
remoteCache.clear();
assertEquals(false, remoteCache.containsKey("k"));
}
private void validateSequenceAndStopServer() {
ConsistentHash consistentHash = channelFactory.getConsistentHash(RemoteCacheManager.cacheNameBytes());
SocketAddress expectedServer;
resetStats();
assertNoHits();
expectedServer = consistentHash.getServer(HotRodTestingUtil.marshall("k"));
assertNoHits();
remoteCache.put("k","v");
assert strategy.getServers().length == 3;
assertOnlyServerHit(expectedServer);
resetStats();
expectedServer = consistentHash.getServer(HotRodTestingUtil.marshall("k2"));
remoteCache.put("k2","v2");
assertOnlyServerHit(expectedServer);
resetStats();
expectedServer = consistentHash.getServer(HotRodTestingUtil.marshall("k3"));
remoteCache.put("k3","v3");
assertOnlyServerHit(expectedServer);
resetStats();
expectedServer = consistentHash.getServer(HotRodTestingUtil.marshall("k"));
assertEquals("v", remoteCache.put("k","v"));
assertOnlyServerHit(expectedServer);
//this would be the next server to be shutdown
expectedServer = consistentHash.getServer(HotRodTestingUtil.marshall("k"));
HotRodServer toStop = addr2hrServer.get(expectedServer);
toStop.stop();
for (Iterator<EmbeddedCacheManager> ecmIt = cacheManagers.iterator(); ecmIt.hasNext();) {
if (ecmIt.next().getAddress().equals(expectedServer)) ecmIt.remove();
}
TestingUtil.waitForNoRebalance(caches());
}
@Override
protected ConfigurationBuilder getCacheConfig() {
return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false);
}
}
| 4,450
| 30.567376
| 108
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/ServerFailureRetrySingleOwnerTest.java
|
package org.infinispan.client.hotrod.retry;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import org.infinispan.client.hotrod.VersionedValue;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
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.CacheEntryEvent;
import org.infinispan.remoting.transport.jgroups.SuspectException;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.util.ControlledConsistentHashFactory;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.Test;
/**
* Tests that force operations to be directed to a server that applies the
* change locally but fails to send it to other nodes. The failover mechanism
* in the Hot Rod client will determine a different server and retry.
*/
@Test(groups = "functional", testName = "client.hotrod.retry.ServerFailureRetrySingleOwnerTest")
public class ServerFailureRetrySingleOwnerTest extends AbstractRetryTest {
public ServerFailureRetrySingleOwnerTest() {
cleanup = CleanupPhase.AFTER_TEST;
}
@Override
protected ConfigurationBuilder getCacheConfig() {
ConfigurationBuilder builder = hotRodCacheConfiguration(
getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
builder.clustering().hash().numOwners(1).numSegments(1)
.consistentHashFactory(new ControlledConsistentHashFactory.Default(0))
.transaction().transactionMode(TransactionMode.TRANSACTIONAL).useSynchronization(true)
.locking().isolationLevel(IsolationLevel.READ_COMMITTED);
return builder;
}
public void testRetryReplaceWithVersion() {
final ErrorInducingListener listener = new ErrorInducingListener();
final byte[] key = HotRodClientTestingUtil.getKeyForServer(hotRodServer1);
assertNull(remoteCache.putIfAbsent(key, 1));
final VersionedValue versioned = remoteCache.getWithMetadata(key);
assertEquals(1, versioned.getValue());
withListener(listener, () -> {
assertFalse(listener.errorInduced);
assertEquals(true, remoteCache.replaceWithVersion(key, 2, versioned.getVersion()));
assertTrue(listener.errorInduced);
assertEquals(2, remoteCache.get(key));
});
}
public void testRetryRemoveWithVersion() {
final ErrorInducingListener listener = new ErrorInducingListener();
final byte[] key = HotRodClientTestingUtil.getKeyForServer(hotRodServer1);
assertNull(remoteCache.putIfAbsent(key, 1));
final VersionedValue versioned = remoteCache.getWithMetadata(key);
assertEquals(1, versioned.getValue());
withListener(listener, () -> {
assertFalse(listener.errorInduced);
assertEquals(true, remoteCache.removeWithVersion(key, versioned.getVersion()));
assertTrue(listener.errorInduced);
assertNull(remoteCache.get(key));
});
}
public void testRetryRemove() {
final ErrorInducingListener listener = new ErrorInducingListener();
final byte[] key = HotRodClientTestingUtil.getKeyForServer(hotRodServer1);
assertNull(remoteCache.putIfAbsent(key, 1));
withListener(listener, () -> {
assertFalse(listener.errorInduced);
assertEquals(1, remoteCache.remove(key));
assertTrue(listener.errorInduced);
assertNull(remoteCache.get(key));
});
}
public void testRetryReplace() {
final ErrorInducingListener listener = new ErrorInducingListener();
final byte[] key = HotRodClientTestingUtil.getKeyForServer(hotRodServer1);
assertNull(remoteCache.putIfAbsent(key, 1));
withListener(listener, () -> {
assertFalse(listener.errorInduced);
assertEquals(1, remoteCache.replace(key, 2));
assertTrue(listener.errorInduced);
assertEquals(2, remoteCache.get(key));
});
}
public void testRetryPutIfAbsent() {
final ErrorInducingListener listener = new ErrorInducingListener();
final byte[] key = HotRodClientTestingUtil.getKeyForServer(hotRodServer1);
withListener(listener, () -> {
assertFalse(listener.errorInduced);
assertNull(remoteCache.putIfAbsent(key, 1));
assertTrue(listener.errorInduced);
assertEquals(1, remoteCache.get(key));
});
}
public void testRetryPutOnNonEmpty() {
final ErrorInducingListener listener = new ErrorInducingListener();
final byte[] key = HotRodClientTestingUtil.getKeyForServer(hotRodServer1);
assertNull(remoteCache.put(key, 1));
withListener(listener, () -> {
assertFalse(listener.errorInduced);
assertEquals(1, remoteCache.put(key, 2));
assertTrue(listener.errorInduced);
assertEquals(2, remoteCache.get(key));
});
}
public void testRetryPutOnEmpty() {
final ErrorInducingListener listener = new ErrorInducingListener();
final byte[] key = HotRodClientTestingUtil.getKeyForServer(hotRodServer1);
withListener(listener, () -> {
assertFalse(listener.errorInduced);
assertNull(remoteCache.put(key, 1));
assertTrue(listener.errorInduced);
assertEquals(1, remoteCache.get(key));
});
}
private void withListener(Object listener, Runnable r) {
hotRodServer1.getCacheManager().getCache().addListener(listener);
try {
r.run();
} finally {
hotRodServer1.getCacheManager().getCache().removeListener(listener);
}
}
@Listener
public static class ErrorInducingListener {
boolean errorInduced;
@CacheEntryCreated
@CacheEntryModified
@CacheEntryRemoved
@SuppressWarnings("unused")
public void handleEvent(CacheEntryEvent event) throws Exception {
if (!event.isPre() && event.isOriginLocal()) {
errorInduced = true;
throw new SuspectException("Simulated suspicion");
}
}
}
}
| 6,579
| 40.125
| 98
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/RetryOnFailureUnitTest.java
|
package org.infinispan.client.hotrod.retry;
import static org.infinispan.client.hotrod.impl.Util.await;
import static org.testng.AssertJUnit.assertEquals;
import java.net.SocketAddress;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.infinispan.client.hotrod.exceptions.HotRodClientException;
import org.infinispan.client.hotrod.exceptions.RemoteNodeSuspectException;
import org.infinispan.client.hotrod.impl.ConfigurationProperties;
import org.infinispan.client.hotrod.impl.operations.RetryOnFailureOperation;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory;
import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.test.AbstractInfinispanTest;
import org.mockito.Mockito;
import org.testng.annotations.Test;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
/**
* Tests the number of retries.
*
* @author Pedro Ruivo
* @since 7.0
*/
@Test(groups = "unit", testName = "client.hotrod.retry.RetryOnFailureUnitTest")
public class RetryOnFailureUnitTest extends AbstractInfinispanTest {
private final Channel mockChannel = Mockito.mock(Channel.class);
public void testNoRetryOnTransportFailure() {
doRetryTest(0, true);
}
public void testNoRetryOnExecuteFailure() {
doRetryTest(0, false);
}
public void testSingleRetryOnTransportFailure() {
doRetryTest(1, true);
}
public void testSingleRetryOnExecuteFailure() {
doRetryTest(1, false);
}
public void testMultipleRetryOnTransportFailure() {
doRetryTest(ConfigurationProperties.DEFAULT_MAX_RETRIES, true);
}
public void testMultipleRetryOnExecuteFailure() {
doRetryTest(ConfigurationProperties.DEFAULT_MAX_RETRIES, false);
}
private void doRetryTest(int maxRetry, boolean failOnTransport) {
ChannelFactory mockTransport = Mockito.mock(ChannelFactory.class);
Mockito.when(mockTransport.getMaxRetries()).thenReturn(maxRetry);
TestOperation testOperation = new TestOperation(mockTransport, failOnTransport);
Exceptions.expectExceptionNonStrict(HotRodClientException.class, () -> await(testOperation.execute(), 10000));
if (failOnTransport) {
// Number of retries doubles as a result of dealing with complete shutdown recoveries
assertEquals("Wrong getChannel() invocation.", maxRetry + 1, testOperation.channelInvocationCount.get());
assertEquals("Wrong execute() invocation.", 0, testOperation.executeInvocationCount.get());
} else {
assertEquals("Wrong getChannel() invocation.", maxRetry + 1, testOperation.channelInvocationCount.get());
assertEquals("Wrong execute() invocation.", maxRetry + 1, testOperation.executeInvocationCount.get());
}
}
private class TestOperation extends RetryOnFailureOperation<Void> {
private final AtomicInteger channelInvocationCount;
private final AtomicInteger executeInvocationCount;
private final boolean failOnTransport;
TestOperation(ChannelFactory channelFactory, boolean failOnTransport) {
super(ILLEGAL_OP_CODE, ILLEGAL_OP_CODE, null, channelFactory, null, null, 0,
HotRodClientTestingUtil.newRemoteConfigurationBuilder().build(), null, null);
this.failOnTransport = failOnTransport;
channelInvocationCount = new AtomicInteger(0);
executeInvocationCount = new AtomicInteger(0);
}
@Override
protected void fetchChannelAndInvoke(int retryCount, Set<SocketAddress> failedServers) {
channelInvocationCount.incrementAndGet();
if (failOnTransport) {
cancel(null, new RemoteNodeSuspectException("Induced Failure", 1L, (short) 1));
} else {
invoke(mockChannel);
}
}
@Override
protected void executeOperation(Channel channel) {
executeInvocationCount.incrementAndGet();
if (!failOnTransport) {
exceptionCaught(null, new RemoteNodeSuspectException("Induced Failure", 1L, (short) 1));
} else {
//we can return null since it is not used
complete(null);
}
}
@Override
public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) {
throw new UnsupportedOperationException();
}
}
}
| 4,468
| 36.554622
| 116
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/DistributionRetryTest.java
|
package org.infinispan.client.hotrod.retry;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.infinispan.Cache;
import org.infinispan.affinity.KeyAffinityService;
import org.infinispan.affinity.KeyAffinityServiceFactory;
import org.infinispan.affinity.KeyGenerator;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.VersionedValue;
import org.infinispan.client.hotrod.exceptions.TransportException;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.client.hotrod.test.NoopChannelOperation;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.marshall.ProtoStreamMarshaller;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.testng.annotations.Test;
import io.netty.channel.Channel;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@CleanupAfterMethod
@Test(testName = "client.hotrod.retry.DistributionRetryTest", groups = "functional")
public class DistributionRetryTest extends AbstractRetryTest {
private int retries = 0;
@Override
protected ConfigurationBuilder getCacheConfig() {
ConfigurationBuilder builder = hotRodCacheConfiguration(
getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
builder.clustering().hash().numOwners(1);
return builder;
}
@Override
protected void amendRemoteCacheManagerConfiguration(org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder) {
builder.maxRetries(retries);
}
private boolean nextOperationShouldFail() {
return retries == 0;
}
private void assertOperationFailsWithTransport(Object key) {
Exceptions.expectException(TransportException.class, ".*", () -> remoteCache.get(key));
}
public void testGet() throws Exception {
Object key = generateKeyAndShutdownServer();
log.info("Starting actual test");
if (nextOperationShouldFail()) assertOperationFailsWithTransport(key);
//now make sure that next call won't fail
resetStats();
assertEquals(remoteCache.get(key), "v");
}
public void testPut() throws Exception {
Object key = generateKeyAndShutdownServer();
log.info("Here it starts");
if (nextOperationShouldFail()) assertOperationFailsWithTransport(key);
assertEquals(remoteCache.put(key, "v0"), "v");
}
public void testRemove() throws Exception {
Object key = generateKeyAndShutdownServer();
if (nextOperationShouldFail()) assertOperationFailsWithTransport(key);
assertEquals("v", remoteCache.remove(key));
}
public void testContains() throws Exception {
Object key = generateKeyAndShutdownServer();
if (nextOperationShouldFail()) assertOperationFailsWithTransport(key);
resetStats();
assertEquals(true, remoteCache.containsKey(key));
}
public void testGetWithMetadata() throws Exception {
Object key = generateKeyAndShutdownServer();
if (nextOperationShouldFail()) assertOperationFailsWithTransport(key);
resetStats();
VersionedValue value = remoteCache.getWithMetadata(key);
assertEquals("v", value.getValue());
}
public void testPutIfAbsent() throws Exception {
Object key = generateKeyAndShutdownServer();
if (nextOperationShouldFail()) assertOperationFailsWithTransport(key);
assertEquals(null, remoteCache.putIfAbsent("noSuchKey", "someValue"));
assertEquals("someValue", remoteCache.get("noSuchKey"));
}
public void testReplace() throws Exception {
Object key = generateKeyAndShutdownServer();
if (nextOperationShouldFail()) assertOperationFailsWithTransport(key);
assertEquals("v", remoteCache.replace(key, "v2"));
}
public void testReplaceIfUnmodified() throws Exception {
Object key = generateKeyAndShutdownServer();
if (nextOperationShouldFail()) assertOperationFailsWithTransport(key);
assertEquals(false, remoteCache.replaceWithVersion(key, "v2", 12));
}
public void testRemoveIfUnmodified() throws Exception {
Object key = generateKeyAndShutdownServer();
if (nextOperationShouldFail()) assertOperationFailsWithTransport(key);
resetStats();
assertEquals(false, remoteCache.removeWithVersion(key, 12));
}
public void testClear() throws Exception {
Object key = generateKeyAndShutdownServer();
if (nextOperationShouldFail()) assertOperationFailsWithTransport(key);
resetStats();
remoteCache.clear();
assertEquals(false, remoteCache.containsKey(key));
}
private Object generateKeyAndShutdownServer() throws IOException, ClassNotFoundException, InterruptedException {
resetStats();
Cache<Object,Object> cache = manager(1).getCache();
ExecutorService ex = Executors.newSingleThreadExecutor(getTestThreadFactory("KeyGenerator"));
KeyAffinityService kaf = KeyAffinityServiceFactory.newKeyAffinityService(cache, ex, new ByteKeyGenerator(), 2, true);
Address address = cache.getAdvancedCache().getRpcManager().getTransport().getAddress();
byte[] keyBytes = (byte[]) kaf.getKeyForAddress(address);
String key = ByteKeyGenerator.getStringObject(keyBytes);
ex.shutdownNow();
kaf.stop();
remoteCache.put(key, "v");
assertOnlyServerHit(getAddress(hotRodServer2));
ChannelFactory channelFactory = ((InternalRemoteCacheManager) remoteCacheManager).getChannelFactory();
Marshaller m = new ProtoStreamMarshaller();
Channel channel = channelFactory.fetchChannelAndInvoke(m.objectToByteBuffer(key, 64), null, RemoteCacheManager.cacheNameBytes(), new NoopChannelOperation()).join();
try {
assertEquals(channel.remoteAddress(), new InetSocketAddress(hotRodServer2.getHost(), hotRodServer2.getPort()));
} finally {
channelFactory.releaseChannel(channel);
}
log.info("About to stop Hot Rod server 2");
HotRodClientTestingUtil.killServers(hotRodServer2);
eventually(() -> !channel.isActive());
return key;
}
public static class ByteKeyGenerator implements KeyGenerator<Object> {
Random r = new Random();
@Override
public byte[] getKey() {
String result = String.valueOf(r.nextLong());
try {
return new ProtoStreamMarshaller().objectToByteBuffer(result, 64);
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
public static String getStringObject(byte[] bytes) {
try {
return (String) new ProtoStreamMarshaller().objectFromByteBuffer(bytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private DistributionRetryTest withRetries(int retries) {
this.retries = retries;
return this;
}
@Override
protected String parameters() {
return "[retries=" + retries + "]";
}
@Override
public Object[] factory() {
return new Object[] {
new DistributionRetryTest().withRetries(0),
new DistributionRetryTest().withRetries(10),
};
}
}
| 7,779
| 36.76699
| 170
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/retry/ClientListenerRetryTest.java
|
package org.infinispan.client.hotrod.retry;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import java.io.IOException;
import java.net.SocketAddress;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.IntStream;
import org.infinispan.client.hotrod.DataFormat;
import org.infinispan.client.hotrod.ProtocolVersion;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.event.ClientCacheEntryCreatedEvent;
import org.infinispan.client.hotrod.event.impl.AbstractClientEvent;
import org.infinispan.client.hotrod.exceptions.TransportException;
import org.infinispan.client.hotrod.impl.protocol.Codec25;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.configuration.ClassAllowList;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
import io.netty.buffer.ByteBuf;
/**
* Tests for a client with a listener when connection to the server drops.
*/
@Test(groups = "functional", testName = "client.hotrod.retry.ClientListenerRetryTest")
@SuppressWarnings("unused")
public class ClientListenerRetryTest extends MultiHotRodServersTest {
private final AtomicInteger counter = new AtomicInteger(0);
private final FailureInducingCodec failureInducingCodec = new FailureInducingCodec();
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(2, getCacheConfiguration());
clients.forEach(rcm -> rcm.getChannelFactory().setNegotiatedCodec(failureInducingCodec));
}
@Override
protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(String host, int serverPort) {
// disable protocol negotiation since we want to use FailureInducingCodec
return super.createHotRodClientConfigurationBuilder(host, serverPort).version(ProtocolVersion.PROTOCOL_VERSION_25).socketTimeout(60_000);
}
private ConfigurationBuilder getCacheConfiguration() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
return hotRodCacheConfiguration(builder);
}
@Test
public void testConnectionDrop() {
RemoteCache<Integer, String> remoteCache = client(0).getCache();
Listener listener = new Listener();
remoteCache.addClientListener(listener);
assertListenerActive(remoteCache, listener);
failureInducingCodec.induceFailure();
addItems(remoteCache, 10);
failureInducingCodec.resetFailure();
assertListenerActive(remoteCache, listener);
}
private void addItems(RemoteCache<Integer, String> cache, int items) {
IntStream.range(0, items).forEach(i -> cache.put(counter.incrementAndGet(), "value"));
}
private void assertListenerActive(RemoteCache<Integer, String> cache, Listener listener) {
int received = listener.getReceived();
eventually(() -> {
cache.put(counter.incrementAndGet(), "value");
return listener.getReceived() > received;
});
}
@ClientListener
private static class Listener {
private final AtomicInteger count = new AtomicInteger(0);
@ClientCacheEntryCreated
public void handleCreatedEvent(ClientCacheEntryCreatedEvent<?> e) {
count.incrementAndGet();
}
int getReceived() {
return count.intValue();
}
}
@Override
protected int maxRetries() {
return 10;
}
private static class FailureInducingCodec extends Codec25 {
private volatile boolean failure;
private final IOException failWith = new IOException("Connection reset by peer");
@Override
public AbstractClientEvent readCacheEvent(ByteBuf buf, Function<byte[], DataFormat> listenerDataFormat, short eventTypeId, ClassAllowList allowList, SocketAddress serverAddress) {
if (failure) {
throw new TransportException(failWith, serverAddress);
}
return super.readCacheEvent(buf, listenerDataFormat, eventTypeId, allowList, serverAddress);
}
private void induceFailure() {
failure = true;
}
private void resetFailure() {
failure = false;
}
}
}
| 4,499
| 34.433071
| 185
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/multimap/RemoteMultimapStateTransferTest.java
|
package org.infinispan.client.hotrod.multimap;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.server.hotrod.HotRodServer;
import org.testng.annotations.Test;
/**
* State transfer test for multimap to ensure the Bucket class is properly sent.
*
* @author Pedro Ruivo
* @since 12.0
*/
@Test(groups = "functional", testName = "client.hotrod.multimap.RemoteMultimapStateTransferTest")
public class RemoteMultimapStateTransferTest extends MultiHotRodServersTest {
private static final int NODES = 2;
private static final int VALUES = 4;
private static final String CACHE_NAME = "multimap";
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cacheBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
createHotRodServers(NODES, new ConfigurationBuilder());
defineInAll(CACHE_NAME, cacheBuilder);
}
public void testStateTransfer() {
RemoteMultimapCache<String, String> mc = multimapCache(0);
List<String> values1 = createValues();
String key1 = Util.threadLocalRandomUUID().toString();
storeValues(mc, key1, values1);
List<String> values2 = createValues();
String key2 = Util.threadLocalRandomUUID().toString();
storeValues(mc, key2, values2);
for (int i = 0; i < NODES; ++i) {
assertData(i, key1, values1);
assertData(i, key2, values2);
}
HotRodServer server = addHotRodServerAndClient(new ConfigurationBuilder());
defineCache(server, CACHE_NAME, getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
for (int i = 0; i < NODES + 1; ++i) {
assertData(i, key1, values1);
assertData(i, key2, values2);
}
}
private RemoteMultimapCache<String, String> multimapCache(int index) {
MultimapCacheManager<String, String> mcm = RemoteMultimapCacheManagerFactory.from(client(index));
return mcm.get(CACHE_NAME);
}
private void assertData(int index, String key, List<String> values) {
RemoteMultimapCache<String, String> mc = multimapCache(index);
Collection<String> data = mc.get(key).join();
assertEquals(values.size(), data.size());
for (String v : values) {
assertTrue(data.contains(v));
}
}
private static void storeValues(RemoteMultimapCache<String, String> rmc, String key, List<String> values) {
for (String v : values) {
rmc.put(key, v).join();
}
}
private static List<String> createValues() {
List<String> values = new ArrayList<>(VALUES);
for (int i = 0; i < VALUES; ++i) {
values.add(Util.threadLocalRandomUUID().toString());
}
return values;
}
}
| 3,086
| 32.193548
| 110
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/multimap/RemoteMultimapCacheAPITWithDuplicatesTest.java
|
package org.infinispan.client.hotrod.multimap;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Collection;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.RemoteMultimapCacheAPITWithDuplicatesTest")
public class RemoteMultimapCacheAPITWithDuplicatesTest extends SingleHotRodServerTest {
private static final String TEST_CACHE_NAME = RemoteMultimapCacheAPITWithDuplicatesTest.class.getSimpleName();
private RemoteMultimapCache<String, String> multimapCache;
@Override
protected RemoteCacheManager getRemoteCacheManager() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
// Do not retry when the server response cannot be parsed, see ISPN-12596
builder.forceReturnValues(isForceReturnValuesViaConfiguration()).maxRetries(0);
builder.addServer().host("127.0.0.1").port(hotrodServer.getPort());
return new InternalRemoteCacheManager(builder.build());
}
@Override
protected void setup() throws Exception {
cacheManager = createCacheManager();
hotrodServer = createHotRodServer();
remoteCacheManager = getRemoteCacheManager();
remoteCacheManager.start();
cacheManager.defineConfiguration(TEST_CACHE_NAME, new org.infinispan.configuration.cache.ConfigurationBuilder().build() );
MultimapCacheManager<String, String> rmc = RemoteMultimapCacheManagerFactory.from(remoteCacheManager);
this.multimapCache = rmc.get(TEST_CACHE_NAME, true);
}
protected boolean isForceReturnValuesViaConfiguration() {
return true;
}
public void testSupportsDuplicates() {
assertTrue(multimapCache.supportsDuplicates());
}
public void testPut() {
multimapCache.put("k", "a").join();
multimapCache.put("k", "a").join();
multimapCache.put("k", "a").join();
Collection<String> kValues = multimapCache.get("k").join();
assertEquals(3, kValues.size());
assertTrue(kValues.contains("a"));
}
public void testGetWithMetadata() throws Exception {
multimapCache.put("k", "a").join();
multimapCache.put("k", "a").join();
multimapCache.put("k", "c").join();
MetadataCollection<String> metadataCollection = multimapCache.getWithMetadata("k").join();
assertEquals(3, metadataCollection.getCollection().size());
assertTrue(metadataCollection.getCollection().contains("a"));
assertEquals(-1, metadataCollection.getLifespan());
assertEquals(0, metadataCollection.getVersion());
}
public void testRemoveKeyValue() {
multimapCache.put("k", "a").join();
multimapCache.put("k", "a").join();
multimapCache.put("k", "c").join();
Collection<String> kValues = multimapCache.get("k").join();
assertEquals(3, kValues.size());
assertTrue(multimapCache.remove("k", "a").join());
assertEquals(1, multimapCache.get("k").join().size());
}
}
| 3,430
| 38.895349
| 130
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/multimap/RemoteMultimapCacheAPITest.java
|
package org.infinispan.client.hotrod.multimap;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.testng.annotations.Test;
/**
* Multimap Cache Remote test
*
* @author karesti@redhat.com
* @since 9.2
*/
@Test(groups = "functional", testName = "client.hotrod.RemoteMultimapCacheAPITest")
public class RemoteMultimapCacheAPITest extends SingleHotRodServerTest {
private RemoteMultimapCache<String, String> multimapCache;
@Override
protected RemoteCacheManager getRemoteCacheManager() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
// Do not retry when the server response cannot be parsed, see ISPN-12596
builder.forceReturnValues(isForceReturnValuesViaConfiguration()).maxRetries(0);
builder.addServer().host("127.0.0.1").port(hotrodServer.getPort());
return new InternalRemoteCacheManager(builder.build());
}
@Override
protected void setup() throws Exception {
cacheManager = createCacheManager();
hotrodServer = createHotRodServer();
remoteCacheManager = getRemoteCacheManager();
remoteCacheManager.start();
MultimapCacheManager<String, String> rmc = RemoteMultimapCacheManagerFactory.from(remoteCacheManager);
// TODO: Avoid conflict names with a namespace or configuration between cache and multimap cache
this.multimapCache = rmc.get("");
}
protected boolean isForceReturnValuesViaConfiguration() {
return true;
}
public void testGetNotExist() {
Collection<String> kValues = multimapCache.get("k").join();
assertEquals(0, kValues.size());
}
public void testGetWithMetadataNotExist() {
CompletableFuture<MetadataCollection<String>> k = multimapCache.getWithMetadata("k");
assertEquals(0, k.join().getCollection().size());
}
public void testPut() throws Exception {
multimapCache.put("k", "a").join();
multimapCache.put("k", "b").join();
multimapCache.put("k", "c").join();
Collection<String> kValues = multimapCache.get("k").join();
assertEquals(3, kValues.size());
assertTrue(kValues.contains("a"));
assertTrue(kValues.contains("b"));
assertTrue(kValues.contains("c"));
}
public void testPutWithDuplicates() {
multimapCache.put("k", "a").join();
multimapCache.put("k", "a").join();
multimapCache.put("k", "a").join();
Collection<String> kValues = multimapCache.get("k").join();
assertEquals(1, kValues.size());
assertTrue(kValues.contains("a"));
}
public void testGetWithMetadata() throws Exception {
multimapCache.put("k", "a").join();
MetadataCollection<String> metadataCollection = multimapCache.getWithMetadata("k").join();
assertEquals(1, metadataCollection.getCollection().size());
assertTrue(metadataCollection.getCollection().contains("a"));
assertEquals(-1, metadataCollection.getLifespan());
assertEquals(0, metadataCollection.getVersion());
}
public void testRemoveKey() {
multimapCache.put("k", "a").join();
Collection<String> kValues = multimapCache.get("k").join();
assertEquals(1, kValues.size());
assertTrue(kValues.contains("a"));
assertTrue(multimapCache.remove("k").join());
assertEquals(0, multimapCache.get("k").join().size());
assertFalse(multimapCache.remove("k").join());
}
public void testRemoveKeyValue() {
multimapCache.put("k", "a").join();
multimapCache.put("k", "b").join();
multimapCache.put("k", "c").join();
Collection<String> kValues = multimapCache.get("k").join();
assertEquals(3, kValues.size());
assertTrue(multimapCache.remove("k", "a").join());
assertEquals(2, multimapCache.get("k").join().size());
}
public void testSize() throws Exception {
assertEquals(Long.valueOf(0), multimapCache.size().join());
multimapCache.put("k", "a").join();
assertEquals(Long.valueOf(1), multimapCache.size().join());
multimapCache.put("k", "b").join();
assertEquals(Long.valueOf(2), multimapCache.size().join());
}
public void testContainsEntry() {
multimapCache.put("k", "a").join();
assertTrue(multimapCache.containsEntry("k", "a").join());
assertFalse(multimapCache.containsEntry("k", "b").join());
}
public void testContainsKey() {
multimapCache.put("k", "a").join();
assertTrue(multimapCache.containsKey("k").join());
assertFalse(multimapCache.containsKey("l").join());
}
public void testContainsValue() {
multimapCache.put("k", "a").join();
assertTrue(multimapCache.containsValue("a").join());
assertFalse(multimapCache.containsValue("b").join());
}
}
| 5,257
| 35.262069
| 108
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/tx/RecoveryTest.java
|
package org.infinispan.client.hotrod.tx;
import static org.infinispan.test.TestingUtil.extractGlobalComponent;
import static org.infinispan.test.TestingUtil.replaceComponent;
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.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import jakarta.transaction.TransactionManager;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.configuration.TransactionMode;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.client.hotrod.transaction.lookup.RemoteTransactionManagerLookup;
import org.infinispan.client.hotrod.transaction.manager.RemoteTransactionManager;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.tx.TransactionImpl;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.tx.table.GlobalTxTable;
import org.infinispan.commons.test.ExceptionRunnable;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.util.ControlledTimeService;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.Test;
/**
* Tests Hot Rod client recovery
*
* @author Pedro Ruivo
* @since 9.4
*/
@Test(groups = "functional", testName = "client.hotrod.tx.RecoveryTest")
public class RecoveryTest extends MultiHotRodServersTest {
private static final AtomicInteger XID_GENERATOR = new AtomicInteger(1);
private final ControlledTimeService timeService = new ControlledTimeService();
private static DummyXid newXid() {
return new DummyXid((byte) XID_GENERATOR.getAndIncrement());
}
private static void assertNoTxException(ExceptionRunnable runnable) throws Exception {
assertXaException(runnable, XAException.XAER_NOTA);
}
private static void assertInvalidException(ExceptionRunnable runnable) throws Exception {
assertXaException(runnable, XAException.XAER_INVAL);
}
private static void assertXaException(ExceptionRunnable runnable, int errorCode) throws Exception {
try {
runnable.run();
fail();
} catch (XAException e) {
assertEquals(errorCode, e.errorCode);
}
}
public void testXaResourceReUse() throws Exception {
XAResource xaResource = xaResource(0);
DummyXid xid = newXid();
assertNoTxException(() -> xaResource.start(xid, XAResource.TMJOIN));
assertNoTxException(() -> xaResource.start(xid, XAResource.TMRESUME));
assertNoTxException(() -> xaResource.end(xid, XAResource.TMNOFLAGS));
assertNoTxException(() -> xaResource.prepare(xid));
assertNoTxException(() -> xaResource.commit(xid, false));
assertNoTxException(() -> xaResource.rollback(xid));
Xid[] actual = xaResource.recover(XAResource.TMSTARTRSCAN);
assertEquals(0, actual.length);
actual = xaResource.recover(XAResource.TMNOFLAGS);
assertEquals(0, actual.length);
actual = xaResource.recover(XAResource.TMENDRSCAN);
assertEquals(0, actual.length);
//no-op
xaResource.forget(xid);
}
public void testStartAndFinishScan() throws Exception {
doStartAndFinishScanTest(this::xaResource);
}
public void testStartAndFinishScanWithRecoverableXaResource() throws Exception {
doStartAndFinishScanTest(this::recoverableXaResource);
}
public void testRecoveryIteration() throws Exception {
doRecoveryIterationTest(this::xaResource);
}
public void testRecoveryIterationWithRecoverableXaResource() throws Exception {
doRecoveryIterationTest(this::recoverableXaResource);
}
public void testXaResourceEnlistAfterRecoverable(Method method) throws Exception {
String key = method.getName();
RemoteCache<String, String> cache = remoteCache(0);
TransactionManager tm = remoteTM(0);
tm.begin();
TransactionImpl tx = (TransactionImpl) tm.getTransaction();
assertEquals(0, tx.getEnlistedResources().size());
tx.enlistResource(recoverableXaResource(0));
assertEquals(1, tx.getEnlistedResources().size());
cache.put(key, "value");
assertEquals(2, tx.getEnlistedResources().size());
tm.suspend();
//lets make sure the put is in the transaction. if it is, the key's value in server is null
assertNull(cache.get(key));
tm.resume(tx);
tm.commit(); //we should commit
assertEquals("value", cache.get(key));
}
public void testRecoverableAfterXaResource(Method method) throws Exception {
String key = method.getName();
RemoteCache<String, String> cache = remoteCache(0);
TransactionManager tm = remoteTM(0);
tm.begin();
TransactionImpl tx = (TransactionImpl) tm.getTransaction();
assertEquals(0, tx.getEnlistedResources().size());
cache.put(key, "value");
assertEquals(1, tx.getEnlistedResources().size());
tx.enlistResource(recoverableXaResource(0));
assertEquals(2, tx.getEnlistedResources().size());
tm.commit();
assertEquals("value", cache.get(key));
}
protected String cacheName() {
return "recovery-test-cache";
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cacheBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
cacheBuilder.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup());
cacheBuilder.transaction().lockingMode(LockingMode.PESSIMISTIC);
cacheBuilder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ);
createHotRodServers(numberOfNodes(), new ConfigurationBuilder());
for (EmbeddedCacheManager cm : cacheManagers) {
//use the same time service in all managers
replaceComponent(cm, TimeService.class, timeService, true);
//stop reaper. we are going to trigger it manually
extractGlobalComponent(cm, GlobalTxTable.class).stop();
}
defineInAll(cacheName(), cacheBuilder);
}
@Override
protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(
String host, int serverPort) {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = super
.createHotRodClientConfigurationBuilder(host, serverPort);
clientBuilder.forceReturnValues(false);
clientBuilder.remoteCache(cacheName())
.transactionManagerLookup(RemoteTransactionManagerLookup.getInstance())
.transactionMode(TransactionMode.FULL_XA);
clientBuilder.transactionTimeout(10, TimeUnit.SECONDS);
return clientBuilder;
}
private void doStartAndFinishScanTest(XaResourceSupplier xaResourceSupplier) throws Exception {
XAResource xaResource = xaResourceSupplier.get(0);
assertInvalidException(() -> xaResource.recover(XAResource.TMENDRSCAN));
//2 start in a row should fail
xaResource.recover(XAResource.TMSTARTRSCAN);
assertInvalidException(() -> xaResource.recover(XAResource.TMSTARTRSCAN));
xaResource.recover(XAResource.TMENDRSCAN);
//start and end together is fine!
xaResource.recover(XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN);
//no iteration in progress
assertInvalidException(() -> xaResource.recover(XAResource.TMNOFLAGS));
}
private void doRecoveryIterationTest(XaResourceSupplier xaResourceSupplier) throws Exception {
XAResource xaResource0 = xaResourceSupplier.get(0);
XAResource xaResource1 = xaResourceSupplier.get(1);
//2 prepared transactions
remoteTM(0).begin();
remoteCache(0).put("k0", "v");
Xid xid0 = xid(0);
prepare(0);
remoteTM(1).begin();
remoteCache(1).put("k1", "v");
Xid xid1 = xid(1);
prepare(1);
timeService.advance(9000); //9 seconds, below the 10 second configured
assertBeforeTimeoutRecoveryIteration(xaResource0, xid0);
assertBeforeTimeoutRecoveryIteration(xaResource1, xid1);
timeService.advance(2000); //2 seconds, remote transaction will be include in recovery
assertRecoveryIteration(xaResource0, xid0, xid1);
assertRecoveryIteration(xaResource1, xid1, xid0);
//resource1 if finished and it should be able to commit the xid0 transaction
xaResource1.commit(xid0, false);
xaResource1.rollback(xid1);
assertEquals("v", remoteCache(0).get("k0"));
assertNull(remoteCache(0).get("k1"));
xaResource0.forget(xid0);
xaResource1.forget(xid1);
}
private void assertRecoveryIteration(XAResource xaResource, Xid local, Xid remote) throws Exception {
Xid[] actual = xaResource.recover(XAResource.TMSTARTRSCAN);
assertTrue(actual.length != 0);
if (actual.length == 1) {
//it returned only the local transaction
assertEquals(local, actual[0]);
actual = xaResource.recover(XAResource.TMENDRSCAN);
assertEquals(1, actual.length); //other client transaction
assertEquals(remote, actual[0]);
} else {
//the server replied quick enough
assertEquals(local, actual[0]);
assertEquals(remote, actual[1]);
actual = xaResource.recover(XAResource.TMENDRSCAN);
assertEquals(0, actual.length);
}
}
private void assertBeforeTimeoutRecoveryIteration(XAResource xaResource, Xid local) throws Exception {
Xid[] actual = xaResource.recover(XAResource.TMSTARTRSCAN);
assertEquals(1, actual.length);
assertEquals(local, actual[0]);
actual = xaResource.recover(XAResource.TMENDRSCAN);
assertEquals(0, actual.length);
}
private void prepare(int index) throws Exception {
RemoteTransactionManager tm = remoteTM(index);
TransactionImpl tx = (TransactionImpl) tm.getTransaction();
tm.suspend();
assertTrue(tx.runPrepare());
}
private Xid xid(int index) {
TransactionImpl tx = (TransactionImpl) remoteTM(index).getTransaction();
return tx.getXid();
}
private XAResource xaResource(int index) throws Exception {
RemoteTransactionManager tm = remoteTM(index);
tm.begin();
RemoteCache<String, String> cache = remoteCache(index);
cache.put("_k_", "_v_");
TransactionImpl tx = (TransactionImpl) tm.getTransaction();
XAResource xaResource = tx.getEnlistedResources().iterator().next();
tm.commit();
xaResource.forget(tx.getXid());
return xaResource;
}
private XAResource recoverableXaResource(int index) {
return client(index).getXaResource();
}
private <K, V> RemoteCache<K, V> remoteCache(int index) {
return client(index).getCache(cacheName());
}
private RemoteTransactionManager remoteTM(int index) {
return (RemoteTransactionManager) remoteCache(index).getTransactionManager();
}
private int numberOfNodes() {
return 3;
}
@FunctionalInterface
private interface XaResourceSupplier {
XAResource get(int index) throws Exception;
}
private static class DummyXid extends XidImpl {
DummyXid(byte id) {
super(-1234, new byte[]{id}, new byte[]{id});
}
}
}
| 11,729
| 35.542056
| 116
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/tx/TxFunctionalTest.java
|
package org.infinispan.client.hotrod.tx;
import static org.infinispan.client.hotrod.configuration.TransactionMode.NONE;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.assertNoTransaction;
import static org.infinispan.client.hotrod.tx.util.KeyValueGenerator.BYTE_ARRAY_GENERATOR;
import static org.infinispan.client.hotrod.tx.util.KeyValueGenerator.GENERIC_ARRAY_GENERATOR;
import static org.infinispan.client.hotrod.tx.util.KeyValueGenerator.STRING_GENERATOR;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Stream;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.TransactionMode;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.client.hotrod.tx.util.KeyValueGenerator;
import org.infinispan.client.hotrod.tx.util.TransactionSetup;
import org.infinispan.commons.marshall.JavaSerializationMarshaller;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Simple Functional test.
*
* @author Pedro Ruivo
* @since 9.3
*/
@Test(groups = "functional", testName = "client.hotrod.tx.TxFunctionalTest")
public class TxFunctionalTest<K, V> extends MultiHotRodServersTest {
private KeyValueGenerator<K, V> kvGenerator;
private TransactionMode transactionMode;
private boolean useJavaSerialization;
public TxFunctionalTest<K, V> keyValueGenerator(KeyValueGenerator<K, V> kvGenerator) {
this.kvGenerator = kvGenerator;
return this;
}
@Override
public Object[] factory() {
return Arrays.stream(TransactionMode.values())
.filter(tMode -> tMode != NONE)
.flatMap(txMode -> Arrays.stream(LockingMode.values())
.flatMap(lockingMode -> Stream.builder()
.add(new TxFunctionalTest<byte[], byte[]>()
.keyValueGenerator(BYTE_ARRAY_GENERATOR)
.transactionMode(txMode)
.lockingMode(lockingMode))
.add(new TxFunctionalTest<String, String>()
.keyValueGenerator(STRING_GENERATOR)
.transactionMode(txMode)
.lockingMode(lockingMode))
.add(new TxFunctionalTest<Object[], Object[]>()
.keyValueGenerator(GENERIC_ARRAY_GENERATOR).javaSerialization()
.transactionMode(txMode)
.lockingMode(lockingMode))
.build())).toArray();
}
@AfterMethod(alwaysRun = true)
@Override
protected void clearContent() throws Throwable {
assertNoTransaction(clients);
super.clearContent();
}
public TxFunctionalTest<K, V> transactionMode(TransactionMode transactionMode) {
this.transactionMode = transactionMode;
return this;
}
public TxFunctionalTest<K, V> javaSerialization() {
useJavaSerialization = true;
return this;
}
@BeforeClass(alwaysRun = true)
public void printParameters() {
log.debugf("Parameters: %s", super.parameters());
}
public void testSimpleTransaction(Method method) throws Exception {
final K k1 = kvGenerator.generateKey(method, 1);
final K k2 = kvGenerator.generateKey(method, 2);
final V v1 = kvGenerator.generateValue(method, 1);
final V v2 = kvGenerator.generateValue(method, 2);
RemoteCache<K, V> remoteCache = remoteCache(0);
final TransactionManager tm = remoteCache.getTransactionManager();
//test with tx
tm.begin();
kvGenerator.assertValueEquals(null, remoteCache.put(k1, v1));
kvGenerator.assertValueEquals(null, remoteCache.put(k2, v1));
tm.commit();
assertEntryInAllClients(k1, v1);
assertEntryInAllClients(k2, v1);
//test without tx
remoteCache.put(k1, v2);
remoteCache.put(k2, v2);
assertEntryInAllClients(k1, v2);
assertEntryInAllClients(k2, v2);
}
public void testTransactionIsolation(Method method) throws Exception {
final K k1 = kvGenerator.generateKey(method, 1);
final K k2 = kvGenerator.generateKey(method, 2);
final V v1 = kvGenerator.generateValue(method, 1);
final V v2 = kvGenerator.generateValue(method, 2);
RemoteCache<K, V> remoteCache = remoteCache(0);
final TransactionManager tm = remoteCache.getTransactionManager();
//test with tx
tm.begin();
kvGenerator.assertValueEquals(null, remoteCache.put(k1, v1));
kvGenerator.assertValueEquals(null, remoteCache.put(k2, v1));
kvGenerator.assertValueEquals(v1, remoteCache.get(k1));
kvGenerator.assertValueEquals(v1, remoteCache.get(k2));
final Transaction tx1 = tm.suspend();
assertEntryInAllClients(k1, null);
assertEntryInAllClients(k2, null);
tm.begin();
remoteCache.put(k1, v2);
remoteCache.put(k2, v2);
kvGenerator.assertValueEquals(v2, remoteCache.get(k1));
kvGenerator.assertValueEquals(v2, remoteCache.get(k2));
tm.commit();
assertEntryInAllClients(k1, v2);
assertEntryInAllClients(k2, v2);
tm.resume(tx1);
//it shouldn't see the other transaction updates!
kvGenerator.assertValueEquals(v1, remoteCache.get(k1));
kvGenerator.assertValueEquals(v1, remoteCache.get(k2));
tm.commit();
assertEntryInAllClients(k1, v1);
assertEntryInAllClients(k2, v1);
}
public void testRollback(Method method) throws Exception {
final K k1 = kvGenerator.generateKey(method, 1);
final K k2 = kvGenerator.generateKey(method, 2);
final V v1 = kvGenerator.generateValue(method, 1);
RemoteCache<K, V> remoteCache = remoteCache(0);
final TransactionManager tm = remoteCache.getTransactionManager();
//test with tx
tm.begin();
kvGenerator.assertValueEquals(null, remoteCache.put(k1, v1));
kvGenerator.assertValueEquals(null, remoteCache.put(k2, v1));
kvGenerator.assertValueEquals(v1, remoteCache.get(k1));
kvGenerator.assertValueEquals(v1, remoteCache.get(k2));
tm.rollback();
assertEntryInAllClients(k1, null);
assertEntryInAllClients(k2, null);
}
public void testSetAsRollback(Method method) throws Exception {
final K k1 = kvGenerator.generateKey(method, 1);
final K k2 = kvGenerator.generateKey(method, 2);
final V v1 = kvGenerator.generateValue(method, 1);
RemoteCache<K, V> remoteCache = remoteCache(0);
final TransactionManager tm = remoteCache.getTransactionManager();
//test with tx
tm.begin();
kvGenerator.assertValueEquals(null, remoteCache.put(k1, v1));
kvGenerator.assertValueEquals(null, remoteCache.put(k2, v1));
kvGenerator.assertValueEquals(v1, remoteCache.get(k1));
kvGenerator.assertValueEquals(v1, remoteCache.get(k2));
tm.setRollbackOnly();
Exceptions.expectException(RollbackException.class, tm::commit);
assertEntryInAllClients(k1, null);
assertEntryInAllClients(k2, null);
}
public void testConflictWithUpdateNonExisting(Method method) throws Exception {
final K k1 = kvGenerator.generateKey(method, 1);
final K k2 = kvGenerator.generateKey(method, 2);
final V v1 = kvGenerator.generateValue(method, 1);
final V v2 = kvGenerator.generateValue(method, 2);
RemoteCache<K, V> remoteCache = remoteCacheWithForceReturnValue();
final TransactionManager tm = remoteCache.getTransactionManager();
//test with tx
tm.begin();
kvGenerator.assertValueEquals(null, remoteCache.put(k1, v1));
kvGenerator.assertValueEquals(null, remoteCache.put(k2, v1));
kvGenerator.assertValueEquals(v1, remoteCache.get(k1));
kvGenerator.assertValueEquals(v1, remoteCache.get(k2));
final Transaction tx1 = tm.suspend();
assertEntryInAllClients(k1, null);
assertEntryInAllClients(k2, null);
remoteCache.put(k1, v2);
assertEntryInAllClients(k1, v2);
assertEntryInAllClients(k2, null);
tm.resume(tx1);
kvGenerator.assertValueEquals(v1, remoteCache.get(k1));
kvGenerator.assertValueEquals(v1, remoteCache.get(k2));
Exceptions.expectException(RollbackException.class, tm::commit);
assertEntryInAllClients(k1, v2);
assertEntryInAllClients(k2, null);
}
public void testConflictWithTxUpdateNonExisting(Method method) throws Exception {
final K k1 = kvGenerator.generateKey(method, 1);
final K k2 = kvGenerator.generateKey(method, 2);
final V v1 = kvGenerator.generateValue(method, 1);
final V v2 = kvGenerator.generateValue(method, 2);
RemoteCache<K, V> remoteCache = remoteCacheWithForceReturnValue();
final TransactionManager tm = remoteCache.getTransactionManager();
//test with tx
tm.begin();
kvGenerator.assertValueEquals(null, remoteCache.put(k1, v1));
kvGenerator.assertValueEquals(null, remoteCache.put(k2, v1));
kvGenerator.assertValueEquals(v1, remoteCache.get(k1));
kvGenerator.assertValueEquals(v1, remoteCache.get(k2));
final Transaction tx1 = tm.suspend();
assertEntryInAllClients(k1, null);
assertEntryInAllClients(k2, null);
tm.begin();
remoteCache.put(k1, v2);
tm.commit();
assertEntryInAllClients(k1, v2);
assertEntryInAllClients(k2, null);
tm.resume(tx1);
kvGenerator.assertValueEquals(v1, remoteCache.get(k1));
kvGenerator.assertValueEquals(v1, remoteCache.get(k2));
Exceptions.expectException(RollbackException.class, tm::commit);
assertEntryInAllClients(k1, v2);
assertEntryInAllClients(k2, null);
}
public void testConflictWithUpdate(Method method) throws Exception {
final K k1 = kvGenerator.generateKey(method, 1);
final K k2 = kvGenerator.generateKey(method, 2);
final V v1 = kvGenerator.generateValue(method, 1);
final V v2 = kvGenerator.generateValue(method, 2);
RemoteCache<K, V> remoteCache = remoteCacheWithForceReturnValue();
final TransactionManager tm = remoteCache.getTransactionManager();
remoteCache.put(k1, v1);
//test with tx
tm.begin();
kvGenerator.assertValueEquals(v1, remoteCache.put(k1, v2));
kvGenerator.assertValueEquals(null, remoteCache.put(k2, v2));
kvGenerator.assertValueEquals(v2, remoteCache.get(k1));
kvGenerator.assertValueEquals(v2, remoteCache.get(k2));
final Transaction tx1 = tm.suspend();
assertEntryInAllClients(k1, v1);
assertEntryInAllClients(k2, null);
remoteCache.put(k1, v1);
assertEntryInAllClients(k1, v1);
assertEntryInAllClients(k2, null);
tm.resume(tx1);
kvGenerator.assertValueEquals(v2, remoteCache.get(k1));
kvGenerator.assertValueEquals(v2, remoteCache.get(k2));
Exceptions.expectException(RollbackException.class, tm::commit);
assertEntryInAllClients(k1, v1);
assertEntryInAllClients(k2, null);
}
public void testConflictWithTxUpdate(Method method) throws Exception {
final K k1 = kvGenerator.generateKey(method, 1);
final K k2 = kvGenerator.generateKey(method, 2);
final V v1 = kvGenerator.generateValue(method, 1);
final V v2 = kvGenerator.generateValue(method, 2);
RemoteCache<K, V> remoteCache = remoteCacheWithForceReturnValue();
final TransactionManager tm = remoteCache.getTransactionManager();
remoteCache.put(k1, v1);
//test with tx
tm.begin();
kvGenerator.assertValueEquals(v1, remoteCache.put(k1, v2));
kvGenerator.assertValueEquals(null, remoteCache.put(k2, v2));
kvGenerator.assertValueEquals(v2, remoteCache.get(k1));
kvGenerator.assertValueEquals(v2, remoteCache.get(k2));
final Transaction tx1 = tm.suspend();
assertEntryInAllClients(k1, v1);
assertEntryInAllClients(k2, null);
tm.begin();
remoteCache.put(k1, v1);
tm.commit();
assertEntryInAllClients(k1, v1);
assertEntryInAllClients(k2, null);
tm.resume(tx1);
kvGenerator.assertValueEquals(v2, remoteCache.get(k1));
kvGenerator.assertValueEquals(v2, remoteCache.get(k2));
Exceptions.expectException(RollbackException.class, tm::commit);
assertEntryInAllClients(k1, v1);
assertEntryInAllClients(k2, null);
}
public void testConflictWithRemove(Method method) throws Exception {
final K k1 = kvGenerator.generateKey(method, 1);
final K k2 = kvGenerator.generateKey(method, 2);
final V v1 = kvGenerator.generateValue(method, 1);
final V v2 = kvGenerator.generateValue(method, 2);
RemoteCache<K, V> remoteCache = remoteCacheWithForceReturnValue();
final TransactionManager tm = remoteCache.getTransactionManager();
remoteCache.put(k1, v1);
//test with tx
tm.begin();
kvGenerator.assertValueEquals(v1, remoteCache.put(k1, v2));
kvGenerator.assertValueEquals(null, remoteCache.put(k2, v2));
kvGenerator.assertValueEquals(v2, remoteCache.get(k1));
kvGenerator.assertValueEquals(v2, remoteCache.get(k2));
final Transaction tx1 = tm.suspend();
assertEntryInAllClients(k1, v1);
assertEntryInAllClients(k2, null);
remoteCache.remove(k1);
assertEntryInAllClients(k1, null);
assertEntryInAllClients(k2, null);
tm.resume(tx1);
kvGenerator.assertValueEquals(v2, remoteCache.get(k1));
kvGenerator.assertValueEquals(v2, remoteCache.get(k2));
Exceptions.expectException(RollbackException.class, tm::commit);
assertEntryInAllClients(k1, null);
assertEntryInAllClients(k2, null);
}
public void testConflictWithTxRemove(Method method) throws Exception {
final K k1 = kvGenerator.generateKey(method, 1);
final K k2 = kvGenerator.generateKey(method, 2);
final V v1 = kvGenerator.generateValue(method, 1);
final V v2 = kvGenerator.generateValue(method, 2);
RemoteCache<K, V> remoteCache = remoteCacheWithForceReturnValue();
final TransactionManager tm = remoteCache.getTransactionManager();
remoteCache.put(k1, v1);
//test with tx
tm.begin();
kvGenerator.assertValueEquals(v1, remoteCache.put(k1, v2));
kvGenerator.assertValueEquals(null, remoteCache.put(k2, v2));
kvGenerator.assertValueEquals(v2, remoteCache.get(k1));
kvGenerator.assertValueEquals(v2, remoteCache.get(k2));
final Transaction tx1 = tm.suspend();
assertEntryInAllClients(k1, v1);
assertEntryInAllClients(k2, null);
tm.begin();
remoteCache.remove(k1);
tm.commit();
assertEntryInAllClients(k1, null);
assertEntryInAllClients(k2, null);
tm.resume(tx1);
kvGenerator.assertValueEquals(v2, remoteCache.get(k1));
kvGenerator.assertValueEquals(v2, remoteCache.get(k2));
Exceptions.expectException(RollbackException.class, tm::commit);
assertEntryInAllClients(k1, null);
assertEntryInAllClients(k2, null);
}
@Override
protected String[] parameterNames() {
return concat(super.parameterNames(), null, null, null);
}
@Override
protected Object[] parameterValues() {
return concat(super.parameterValues(), kvGenerator.toString(), transactionMode, lockingMode);
}
@Override
protected String parameters() {
return "[" + kvGenerator + "/" + transactionMode + "/" + lockingMode + "]";
}
protected String cacheName() {
return "tx-cache";
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cacheBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
cacheBuilder.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup());
cacheBuilder.transaction().lockingMode(lockingMode);
cacheBuilder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ);
createHotRodServers(numberOfNodes(), new ConfigurationBuilder());
defineInAll(cacheName(), cacheBuilder);
}
protected void modifyGlobalConfiguration(GlobalConfigurationBuilder builder) {
builder.serialization().marshaller(new JavaSerializationMarshaller()).allowList().addClasses(Object[].class);
}
protected final RemoteCache<K, V> remoteCache(int index) {
return client(index).getCache(cacheName());
}
@Override
protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(
String host, int serverPort) {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = super
.createHotRodClientConfigurationBuilder(host, serverPort);
clientBuilder.forceReturnValues(false);
TransactionSetup.amendJTA(clientBuilder.remoteCache(cacheName())).transactionMode(transactionMode);
if (useJavaSerialization) {
clientBuilder.marshaller(new JavaSerializationMarshaller()).addJavaSerialAllowList("\\Q[\\ELjava.lang.Object;");
}
return clientBuilder;
}
private int numberOfNodes() {
return 3;
}
private RemoteCache<K, V> remoteCacheWithForceReturnValue() {
return client(0).getCache(cacheName(), true);
}
private void assertEntryInAllClients(K key, V value) {
for (RemoteCacheManager manager : clients) {
RemoteCache<K, V> remoteCache = manager.getCache(cacheName());
kvGenerator.assertValueEquals(value, remoteCache.get(key));
}
}
}
| 18,249
| 36.55144
| 121
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/tx/LCROTest.java
|
package org.infinispan.client.hotrod.tx;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.assertNoTransaction;
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 java.util.Arrays;
import java.util.Collection;
import jakarta.transaction.TransactionManager;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.configuration.TransactionMode;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.client.hotrod.transaction.lookup.RemoteTransactionManagerLookup;
import org.infinispan.client.hotrod.tx.util.KeyValueGenerator;
import org.infinispan.commons.tx.TransactionImpl;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
/**
* Last Resource Commit Optimization test (1PC)
*
* @author Pedro Ruivo
* @since 9.3
*/
@Test(groups = "functional", testName = "client.hotrod.tx.LCROTest")
public class LCROTest extends MultiHotRodServersTest {
private static final String CACHE_A = "lrco-a";
private static final String CACHE_B = "lrco-b";
private static final String CACHE_C = "lrco-c";
private static final KeyValueGenerator<String, String> GENERATOR = KeyValueGenerator.STRING_GENERATOR;
public void testFailureInA(Method method) throws Exception {
doSingleTestFailure(method, CACHE_A);
}
public void testFailureInB(Method method) throws Exception {
doSingleTestFailure(method, CACHE_B);
}
public void testFailureInC(Method method) throws Exception {
doSingleTestFailure(method, CACHE_C);
}
public void testReadOnlyWithWriteInA(Method method) throws Exception {
doReadOnlyWithSingleWriteTest(method, CACHE_A, false);
}
public void testReadOnlyWithFailedWriteInA(Method method) throws Exception {
doReadOnlyWithSingleWriteTest(method, CACHE_A, true);
}
public void testReadOnlyWithWriteInB(Method method) throws Exception {
doReadOnlyWithSingleWriteTest(method, CACHE_B, false);
}
public void testReadOnlyWithFailedWriteInB(Method method) throws Exception {
doReadOnlyWithSingleWriteTest(method, CACHE_B, true);
}
public void testReadOnlyWithWriteInC(Method method) throws Exception {
doReadOnlyWithSingleWriteTest(method, CACHE_C, false);
}
public void testReadOnlyWithFailedWriteInC(Method method) throws Exception {
doReadOnlyWithSingleWriteTest(method, CACHE_C, true);
}
public void testReadOnly(Method method) throws Exception {
final String key = GENERATOR.generateKey(method, 0);
final String value1 = GENERATOR.generateValue(method, 0);
final RemoteCache<String, String> cacheA = client(0).getCache(CACHE_A);
final RemoteCache<String, String> cacheB = client(0).getCache(CACHE_B);
final RemoteCache<String, String> cacheC = client(0).getCache(CACHE_C);
cacheA.put(key, value1);
cacheB.put(key, value1);
cacheC.put(key, value1);
final TransactionManager tm = cacheA.getTransactionManager();
tm.begin();
GENERATOR.assertValueEquals(value1, cacheA.get(key));
GENERATOR.assertValueEquals(value1, cacheB.get(key));
GENERATOR.assertValueEquals(value1, cacheC.get(key));
final TransactionImpl tx = (TransactionImpl) tm.suspend();
XAResource resource = extractXaResource(tx);
//just to be sure that we don't have any NPE or similar exception when there are no writes
resource.commit(tx.getXid(), true); //force 1PC
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cacheBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
cacheBuilder.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup());
cacheBuilder.transaction().lockingMode(LockingMode.PESSIMISTIC);
cacheBuilder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ);
createHotRodServers(3, new ConfigurationBuilder());
defineInAll(CACHE_A, cacheBuilder);
defineInAll(CACHE_B, cacheBuilder);
defineInAll(CACHE_C, cacheBuilder);
}
@Override
protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(
String host, int serverPort) {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = super
.createHotRodClientConfigurationBuilder(host, serverPort);
//force the return value
clientBuilder.forceReturnValues(true);
for (String cacheName : Arrays.asList(CACHE_A, CACHE_B, CACHE_C)) {
clientBuilder.remoteCache(cacheName)
//use our TM to test it to extract the XaResource.
.transactionManagerLookup(RemoteTransactionManagerLookup.getInstance())
//only for XA modes
.transactionMode(TransactionMode.NON_DURABLE_XA);
}
return clientBuilder;
}
@AfterMethod(alwaysRun = true)
@Override
protected void clearContent() throws Throwable {
assertNoTransaction(clients);
super.clearContent();
}
private void doSingleTestFailure(Method method, String conflictCacheName) throws Exception {
final String key = GENERATOR.generateKey(method, 0);
final String value1 = GENERATOR.generateValue(method, 0);
final String value2 = GENERATOR.generateValue(method, 1);
final RemoteCache<String, String> cacheA = client(0).getCache(CACHE_A);
final RemoteCache<String, String> cacheB = client(0).getCache(CACHE_B);
final RemoteCache<String, String> cacheC = client(0).getCache(CACHE_C);
final TransactionManager tm = cacheA.getTransactionManager();
tm.begin();
cacheA.put(key, value1);
cacheB.put(key, value1);
cacheC.put(key, value1);
final TransactionImpl tx = (TransactionImpl) tm.suspend();
client(0).getCache(conflictCacheName).put(key, value2); //creates a conflict with the tx.
XAResource resource = extractXaResource(tx);
try {
resource.commit(tx.getXid(), true); //force 1PC
fail("Rollback is expected");
} catch (XAException e) {
assertEquals(XAException.XA_RBROLLBACK, e.errorCode);
}
GENERATOR.assertValueEquals(CACHE_A.equals(conflictCacheName) ? value2 : null, cacheA.get(key));
GENERATOR.assertValueEquals(CACHE_B.equals(conflictCacheName) ? value2 : null, cacheB.get(key));
GENERATOR.assertValueEquals(CACHE_C.equals(conflictCacheName) ? value2 : null, cacheC.get(key));
}
private void doReadOnlyWithSingleWriteTest(Method method, String writeCache, boolean rollback) throws Exception {
final String key = GENERATOR.generateKey(method, 0);
final String value1 = GENERATOR.generateValue(method, 0);
final String value2 = GENERATOR.generateValue(method, 1);
final String value3 = GENERATOR.generateValue(method, 2);
final RemoteCache<String, String> cacheA = client(0).getCache(CACHE_A);
final RemoteCache<String, String> cacheB = client(0).getCache(CACHE_B);
final RemoteCache<String, String> cacheC = client(0).getCache(CACHE_C);
cacheA.put(key, value1);
cacheB.put(key, value1);
cacheC.put(key, value1);
final TransactionManager tm = cacheA.getTransactionManager();
tm.begin();
GENERATOR.assertValueEquals(value1, cacheA.get(key));
GENERATOR.assertValueEquals(value1, cacheB.get(key));
GENERATOR.assertValueEquals(value1, cacheC.get(key));
client(0).getCache(writeCache).put(key, value2);
final TransactionImpl tx = (TransactionImpl) tm.suspend();
if (rollback) {
client(0).getCache(writeCache).put(key, value3); //creates a conflict with the tx.
}
XAResource resource = extractXaResource(tx);
try {
resource.commit(tx.getXid(), true); //force 1PC
assertFalse(rollback);
} catch (XAException e) {
assertTrue(rollback);
assertEquals(XAException.XA_RBROLLBACK, e.errorCode);
}
GENERATOR.assertValueEquals(CACHE_A.equals(writeCache) ? (rollback ? value3 : value2) : value1, cacheA.get(key));
GENERATOR.assertValueEquals(CACHE_B.equals(writeCache) ? (rollback ? value3 : value2) : value1, cacheB.get(key));
GENERATOR.assertValueEquals(CACHE_C.equals(writeCache) ? (rollback ? value3 : value2) : value1, cacheC.get(key));
}
private XAResource extractXaResource(TransactionImpl tx) {
Collection<XAResource> resources = tx.getEnlistedResources();
assertEquals(1, resources.size());
return resources.iterator().next();
}
}
| 9,166
| 40.292793
| 119
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/tx/APITxTest.java
|
package org.infinispan.client.hotrod.tx;
import static org.infinispan.client.hotrod.configuration.TransactionMode.NONE;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.assertNoTransaction;
import static org.infinispan.client.hotrod.tx.util.KeyValueGenerator.BYTE_ARRAY_GENERATOR;
import static org.infinispan.client.hotrod.tx.util.KeyValueGenerator.GENERIC_ARRAY_GENERATOR;
import static org.infinispan.client.hotrod.tx.util.KeyValueGenerator.STRING_GENERATOR;
import static org.infinispan.commons.test.Exceptions.expectException;
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.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Stream;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.client.hotrod.MetadataValue;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.configuration.TransactionMode;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.client.hotrod.tx.util.KeyValueGenerator;
import org.infinispan.client.hotrod.tx.util.TransactionSetup;
import org.infinispan.commons.marshall.JavaSerializationMarshaller;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.transaction.LockingMode;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
/**
* Tests all the methods, encoding/decoding and transaction isolation.
*
* @author Pedro Ruivo
* @since 9.3
*/
@Test(groups = "functional", testName = "client.hotrod.tx.APITxTest")
public class APITxTest<K, V> extends MultiHotRodServersTest {
private static final int NR_NODES = 2;
private static final String CACHE_NAME = "api-tx-cache";
private KeyValueGenerator<K, V> kvGenerator;
private TransactionMode transactionMode;
private boolean useJavaSerialization;
@Override
public Object[] factory() {
return Arrays.stream(TransactionMode.values())
.filter(tMode -> tMode != NONE)
.flatMap(txMode -> Arrays.stream(LockingMode.values())
.flatMap(lockingMode -> Stream.builder()
.add(new APITxTest<byte[], byte[]>()
.keyValueGenerator(BYTE_ARRAY_GENERATOR)
.transactionMode(txMode)
.lockingMode(lockingMode))
.add(new APITxTest<String, String>()
.keyValueGenerator(STRING_GENERATOR)
.transactionMode(txMode)
.lockingMode(lockingMode))
.add(new APITxTest<Object[], Object[]>()
.keyValueGenerator(GENERIC_ARRAY_GENERATOR).javaSerialization()
.transactionMode(txMode)
.lockingMode(lockingMode))
.build())).toArray();
}
@AfterMethod(alwaysRun = true)
@Override
protected void clearContent() throws Throwable {
assertNoTransaction(clients);
super.clearContent();
}
public void testPut(Method method) throws Exception {
doApiTest(method, this::empty, this::put, this::putDataCheck, this::checkNoKeys, 3, 3, true);
}
public void testPutAsync(Method method) throws Exception {
doApiTest(method, this::empty, this::put, this::putDataCheck, this::checkNoKeys, 3, 3, false);
}
public void testPutIfAbsent(Method method) throws Exception {
doApiTest(method, this::empty, this::putIfAbsent, this::putDataCheck, this::checkNoKeys, 3, 3, true);
}
public void testPutIfAbsentAsync(Method method) throws Exception {
doApiTest(method, this::empty, this::putIfAbsent, this::putDataCheck, this::checkNoKeys, 3, 3, false);
}
public void testPutAll(Method method) throws Exception {
doApiTest(method, this::empty, this::putAll, this::putAllDataCheck, this::checkNoKeys, 6, 6, true);
}
public void testPutAllAsync(Method method) throws Exception {
doApiTest(method, this::empty, this::putAll, this::putAllDataCheck, this::checkNoKeys, 6, 6, false);
}
public void testReplace(Method method) throws Exception {
doApiTest(method, this::initKeys, this::replace, this::secondHalfDataCheck, this::checkInitValue, 6, 12, true);
}
public void testReplaceAsync(Method method) throws Exception {
doApiTest(method, this::initKeys, this::replace, this::secondHalfDataCheck, this::checkInitValue, 6, 12, false);
}
public void testReplaceWithVersion(Method method) throws Exception {
doApiTest(method, this::initKeys, this::replaceWithVersion, this::secondHalfDataCheck, this::checkInitValue, 4, 8,
true);
}
public void testReplaceWithVersionAsync(Method method) throws Exception {
doApiTest(method, this::initKeys, this::replaceWithVersion, this::secondHalfDataCheck, this::checkInitValue, 4, 8,
false);
}
public void testRemove(Method method) throws Exception {
doApiTest(method, this::initKeys, this::remove, this::checkNoKeys, this::checkInitValue, 2, 2, true);
}
public void testRemoveAsync(Method method) throws Exception {
doApiTest(method, this::initKeys, this::remove, this::checkNoKeys, this::checkInitValue, 2, 2, false);
}
public void testRemoveWithVersion(Method method) throws Exception {
doApiTest(method, this::initKeys, this::removeWithVersion, this::checkNoKeys, this::checkInitValue, 1, 1, true);
}
public void testRemoveWithVersionAsync(Method method) throws Exception {
doApiTest(method, this::initKeys, this::removeWithVersion, this::checkNoKeys, this::checkInitValue, 1, 1, false);
}
public void testMerge(Method method) throws Exception {
RemoteCache<K, V> cache = txRemoteCache();
TransactionManager tm = cache.getTransactionManager();
List<K> keys = generateKeys(method, 3);
List<V> values = generateValues(method, 3);
tm.begin();
//merge is throwing UOE for "normal" remote cache. it isn't supported in tx as well
expectException(UnsupportedOperationException.class,
() -> cache.merge(keys.get(0), values.get(0), (v1, v2) -> values.get(0)));
expectException(UnsupportedOperationException.class,
() -> cache.merge(keys.get(0), values.get(0), (v1, v2) -> values.get(0), 1, TimeUnit.MINUTES));
expectException(UnsupportedOperationException.class, () -> cache
.merge(keys.get(0), values.get(0), (v1, v2) -> values.get(0), 2, TimeUnit.MINUTES, 3, TimeUnit.MINUTES));
tm.commit();
}
// Commented out until we properly support compute variants on remote cache
// public void testCompute(Method method) throws Exception {
// doApiTest(method, this::empty, this::compute, this::checkInitValue, this::checkNoKeys, 1, 1, true);
// }
//
// public void testComputeIfAbsent(Method method) throws Exception {
// doApiTest(method, this::empty, this::computeIfAbsent, this::checkInitValue, this::checkNoKeys, 1, 1, true);
// }
//
// public void testComputeIfPresent(Method method) throws Exception {
// doApiTest(method, this::initKeys, this::computeIfPresent,
// (keys, values, inTx) -> checkInitValue(keys, values.subList(1, 2), inTx), this::checkInitValue, 1, 2,
// true);
// }
public void testContainsKeyAndValue(Method method) throws Exception {
RemoteCache<K, V> cache = txRemoteCache();
TransactionManager tm = cache.getTransactionManager();
final K key = kvGenerator.generateKey(method, 0);
final K key1 = kvGenerator.generateKey(method, 1);
final V value = kvGenerator.generateValue(method, 0);
final V value1 = kvGenerator.generateValue(method, 1);
cache.put(key, value);
cache.put(key1, value1);
tm.begin();
assertTrue(cache.containsKey(key));
assertTrue(cache.containsValue(value));
assertTrue(cache.containsKey(key1));
assertTrue(cache.containsValue(value1));
cache.remove(key);
assertFalse(cache.containsKey(key));
assertFalse(cache.containsValue(value));
assertTrue(cache.containsKey(key1));
assertTrue(cache.containsValue(value1));
final Transaction tx = tm.suspend();
//check it didn't leak
assertTrue(cache.containsKey(key));
assertTrue(cache.containsValue(value));
assertTrue(cache.containsKey(key1));
assertTrue(cache.containsValue(value1));
tm.resume(tx);
tm.commit();
tm.begin();
assertFalse(cache.containsKey(key));
assertFalse(cache.containsValue(value));
assertTrue(cache.containsKey(key1));
assertTrue(cache.containsValue(value1));
cache.put(key, value);
assertTrue(cache.containsKey(key));
assertTrue(cache.containsValue(value));
assertTrue(cache.containsKey(key1));
assertTrue(cache.containsValue(value1));
final Transaction tx2 = tm.suspend();
//check it didn't leak
assertFalse(cache.containsKey(key));
assertFalse(cache.containsValue(value));
assertTrue(cache.containsKey(key1));
assertTrue(cache.containsValue(value1));
tm.resume(tx2);
tm.commit();
assertTrue(cache.containsKey(key));
assertTrue(cache.containsValue(value));
assertTrue(cache.containsKey(key1));
assertTrue(cache.containsValue(value1));
}
// Compute is not implemented for tx remote caches
// public void testCompute(Method method) {
// }
public void testComputeIfAbsentMethods(Method method) {
RemoteCache<K, V> cache = txRemoteCache();
final K targetKey = kvGenerator.generateKey(method, 0);
Function<? super K, ? extends V> remappingFunction = key ->
kvGenerator.generateValue(method, 1);
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.computeIfAbsent(targetKey, remappingFunction));
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.computeIfAbsent(targetKey, remappingFunction, 1, TimeUnit.SECONDS));
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.computeIfAbsent(targetKey, remappingFunction, 1, TimeUnit.SECONDS, 10, TimeUnit.SECONDS));
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.computeIfAbsentAsync(targetKey, remappingFunction));
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.computeIfAbsentAsync(targetKey, remappingFunction, 1, TimeUnit.SECONDS));
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.computeIfAbsentAsync(targetKey, remappingFunction, 1, TimeUnit.SECONDS, 10, TimeUnit.SECONDS));
}
public void testComputeIfPresentMethods(Method method) {
RemoteCache<K, V> cache = txRemoteCache();
final K targetKey = kvGenerator.generateKey(method, 0);
BiFunction<? super K, ? super V, ? extends V> remappingFunction = (key, value) ->
kvGenerator.generateValue(method, 1);
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.computeIfPresent(targetKey, remappingFunction));
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.computeIfPresent(targetKey, remappingFunction, 1, TimeUnit.SECONDS));
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.computeIfPresent(targetKey, remappingFunction, 1, TimeUnit.SECONDS, 10, TimeUnit.SECONDS));
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.computeIfPresentAsync(targetKey, remappingFunction));
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.computeIfPresentAsync(targetKey, remappingFunction, 1, TimeUnit.SECONDS));
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.computeIfPresentAsync(targetKey, remappingFunction, 1, TimeUnit.SECONDS, 10, TimeUnit.SECONDS));
}
public void testMergeMethods(Method method) {
RemoteCache<K, V> cache = txRemoteCache();
final K targetKey = kvGenerator.generateKey(method, 0);
V targetValue = kvGenerator.generateValue(method, 0);
BiFunction<? super V, ? super V, ? extends V> remappingFunction = (value1, value2) ->
kvGenerator.generateValue(method, 2);
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.merge(targetKey, targetValue, remappingFunction));
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.merge(targetKey, targetValue, remappingFunction, 1, TimeUnit.SECONDS));
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.merge(targetKey, targetValue, remappingFunction, 1, TimeUnit.SECONDS, 10, TimeUnit.SECONDS));
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.mergeAsync(targetKey, targetValue, remappingFunction));
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.mergeAsync(targetKey, targetValue, remappingFunction, 1, TimeUnit.SECONDS));
Exceptions.expectException(UnsupportedOperationException.class, () -> cache.mergeAsync(targetKey, targetValue, remappingFunction, 1, TimeUnit.SECONDS, 10, TimeUnit.SECONDS));
}
@Override
protected boolean cleanupAfterMethod() {
try {
cleanupTransactions();
} catch (SystemException e) {
log.error("Error cleaning up running transactions", e);
}
return super.cleanupAfterMethod();
}
@Override
protected String[] parameterNames() {
return concat(super.parameterNames(), null, null, null);
}
@Override
protected Object[] parameterValues() {
return concat(super.parameterValues(), kvGenerator.toString(), transactionMode, lockingMode);
}
@Override
protected String parameters() {
return "[" + kvGenerator + "/" + transactionMode + "/" + lockingMode + "]";
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cacheBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
cacheBuilder.transaction().lockingMode(lockingMode);
cacheBuilder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ);
createHotRodServers(NR_NODES, new ConfigurationBuilder());
defineInAll(CACHE_NAME, cacheBuilder);
}
@Override
protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(
String host, int serverPort) {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = super
.createHotRodClientConfigurationBuilder(host, serverPort);
clientBuilder.forceReturnValues(false);
TransactionSetup.amendJTA(clientBuilder.remoteCache(CACHE_NAME)).transactionMode(transactionMode);
if (useJavaSerialization) {
clientBuilder.marshaller(new JavaSerializationMarshaller()).addJavaSerialAllowList("\\Q[\\ELjava.lang.Object;");
}
return clientBuilder;
}
private void cleanupTransactions() throws SystemException {
RemoteCache<K, V> cache = txRemoteCache();
TransactionManager tm = cache.getTransactionManager();
if (tm.getTransaction() != null) {
tm.rollback();
}
}
private APITxTest<K, V> transactionMode(TransactionMode transactionMode) {
this.transactionMode = transactionMode;
return this;
}
private APITxTest<K, V> keyValueGenerator(KeyValueGenerator<K, V> kvGenerator) {
this.kvGenerator = kvGenerator;
return this;
}
public APITxTest<K, V> javaSerialization() {
useJavaSerialization = true;
return this;
}
private void doApiTest(Method method, Step<K, V> init, OperationStep<K, V> op, DataCheck<K, V> dataCheck,
Step<K, V> isolationCheck, int keysCount, int valuesCount, boolean sync)
throws Exception {
RemoteCache<K, V> cache = txRemoteCache();
TransactionManager tm = cache.getTransactionManager();
List<K> keys = generateKeys(method, keysCount);
List<V> values = generateValues(method, valuesCount);
init.execute(keys, values);
tm.begin();
op.execute(keys, values, sync);
dataCheck.execute(keys, values, true);
final Transaction tx = tm.suspend();
//check it didn't leak outside the transaction
isolationCheck.execute(keys, values);
tm.resume(tx);
tm.commit();
dataCheck.execute(keys, values, false);
}
private void empty(List<K> keys, List<V> values) {
}
private void initKeys(List<K> keys, List<V> values) {
RemoteCache<K, V> cache = txRemoteCache();
for (int i = 0; i < keys.size(); ++i) {
cache.put(keys.get(i), values.get(i));
}
}
private void checkNoKeys(List<K> keys, List<V> values) {
checkNoKeys(keys, values, true);
}
private void checkNoKeys(List<K> keys, List<V> values, boolean inTx) {
RemoteCache<K, V> cache = txRemoteCache();
for (K key : keys) {
assertNull(cache.get(key));
}
}
private void checkInitValue(List<K> keys, List<V> values) {
RemoteCache<K, V> cache = txRemoteCache();
for (int i = 0; i < keys.size(); ++i) {
kvGenerator.assertValueEquals(values.get(i), cache.get(keys.get(i)));
}
}
private void secondHalfDataCheck(List<K> keys, List<V> values, boolean inTx) {
putDataCheck(keys, values.subList(keys.size(), values.size()), inTx);
}
private void put(List<K> keys, List<V> values, boolean sync) throws Exception {
assertEquals(3, keys.size());
assertEquals(3, values.size());
RemoteCache<K, V> cache = txRemoteCache();
if (sync) {
cache.put(keys.get(0), values.get(0));
cache.put(keys.get(1), values.get(1), 1, TimeUnit.MINUTES);
cache.put(keys.get(2), values.get(2), 2, TimeUnit.MINUTES, 3, TimeUnit.MINUTES);
} else {
cache.putAsync(keys.get(0), values.get(0)).get();
cache.putAsync(keys.get(1), values.get(1), 1, TimeUnit.MINUTES).get();
cache.putAsync(keys.get(2), values.get(2), 2, TimeUnit.MINUTES, 3, TimeUnit.MINUTES).get();
}
}
private void putIfAbsent(List<K> keys, List<V> values, boolean sync) throws Exception {
assertEquals(3, keys.size());
assertEquals(3, values.size());
RemoteCache<K, V> cache = txRemoteCache();
if (sync) {
cache.putIfAbsent(keys.get(0), values.get(0));
cache.putIfAbsent(keys.get(1), values.get(1), 1, TimeUnit.MINUTES);
cache.putIfAbsent(keys.get(2), values.get(2), 2, TimeUnit.MINUTES, 3, TimeUnit.MINUTES);
} else {
cache.putIfAbsentAsync(keys.get(0), values.get(0)).get();
cache.putIfAbsentAsync(keys.get(1), values.get(1), 1, TimeUnit.MINUTES).get();
cache.putIfAbsentAsync(keys.get(2), values.get(2), 2, TimeUnit.MINUTES, 3, TimeUnit.MINUTES).get();
}
}
private void putDataCheck(List<K> keys, List<V> values, boolean inTx) {
RemoteCache<K, V> cache = txRemoteCache();
kvGenerator.assertValueEquals(values.get(0), cache.get(keys.get(0)));
//max idle is zero. that means to use the default server value
//outside the transaction, it returns -1 for infinite max-idle
assertMetadataValue(values.get(1), cache.getWithMetadata(keys.get(1)), TimeUnit.MINUTES.toSeconds(1),
inTx ? 0 : -1);
assertMetadataValue(values.get(2), cache.getWithMetadata(keys.get(2)), TimeUnit.MINUTES.toSeconds(2),
TimeUnit.MINUTES.toSeconds(3));
}
private void putAll(List<K> keys, List<V> values, boolean sync) throws Exception {
assertEquals(6, keys.size());
assertEquals(6, values.size());
RemoteCache<K, V> cache = txRemoteCache();
if (sync) {
Map<K, V> map = new HashMap<>();
map.put(keys.get(0), values.get(0));
map.put(keys.get(1), values.get(1));
cache.putAll(map);
map.clear();
map.put(keys.get(2), values.get(2));
map.put(keys.get(3), values.get(3));
cache.putAll(map, 1, TimeUnit.MINUTES);
map.clear();
map.put(keys.get(4), values.get(4));
map.put(keys.get(5), values.get(5));
cache.putAll(map, 2, TimeUnit.MINUTES, 3, TimeUnit.MINUTES);
} else {
Map<K, V> map = new HashMap<>();
map.put(keys.get(0), values.get(0));
map.put(keys.get(1), values.get(1));
cache.putAllAsync(map).get();
map.clear();
map.put(keys.get(2), values.get(2));
map.put(keys.get(3), values.get(3));
cache.putAllAsync(map, 1, TimeUnit.MINUTES).get();
map.clear();
map.put(keys.get(4), values.get(4));
map.put(keys.get(5), values.get(5));
cache.putAllAsync(map, 2, TimeUnit.MINUTES, 3, TimeUnit.MINUTES).get();
}
}
private void putAllDataCheck(List<K> keys, List<V> values, boolean inTx) {
RemoteCache<K, V> cache = txRemoteCache();
kvGenerator.assertValueEquals(values.get(0), cache.get(keys.get(0)));
kvGenerator.assertValueEquals(values.get(1), cache.get(keys.get(1)));
//max idle is zero. that means to use the default server value
assertMetadataValue(values.get(2), cache.getWithMetadata(keys.get(2)), TimeUnit.MINUTES.toSeconds(1),
inTx ? 0 : -1);
assertMetadataValue(values.get(3), cache.getWithMetadata(keys.get(3)), TimeUnit.MINUTES.toSeconds(1),
inTx ? 0 : -1);
assertMetadataValue(values.get(4), cache.getWithMetadata(keys.get(4)), TimeUnit.MINUTES.toSeconds(2),
TimeUnit.MINUTES.toSeconds(3));
assertMetadataValue(values.get(5), cache.getWithMetadata(keys.get(5)), TimeUnit.MINUTES.toSeconds(2),
TimeUnit.MINUTES.toSeconds(3));
}
private void replace(List<K> keys, List<V> values, boolean sync) throws Exception {
assertEquals(6, keys.size());
assertEquals(12, values.size());
RemoteCache<K, V> cache = txRemoteCache();
if (sync) {
kvGenerator.assertValueEquals(values.get(0), cache.replace(keys.get(0), values.get(6)));
kvGenerator.assertValueEquals(values.get(1), cache.replace(keys.get(1), values.get(7), 1, TimeUnit.MINUTES));
kvGenerator.assertValueEquals(values.get(2),
cache.replace(keys.get(2), values.get(8), 2, TimeUnit.MINUTES, 3, TimeUnit.MINUTES));
assertTrue(cache.replace(keys.get(3), values.get(3), values.get(9)));
assertTrue(cache.replace(keys.get(4), values.get(4), values.get(10), 4, TimeUnit.MINUTES));
assertTrue(
cache.replace(keys.get(5), values.get(5), values.get(11), 5, TimeUnit.MINUTES, 6, TimeUnit.MINUTES));
} else {
kvGenerator.assertValueEquals(values.get(0), cache.replaceAsync(keys.get(0), values.get(6)).get());
kvGenerator.assertValueEquals(values.get(1),
cache.replaceAsync(keys.get(1), values.get(7), 1, TimeUnit.MINUTES).get());
kvGenerator.assertValueEquals(values.get(2),
cache.replaceAsync(keys.get(2), values.get(8), 2, TimeUnit.MINUTES, 3, TimeUnit.MINUTES).get());
cache.replaceAsync(keys.get(3), values.get(3), values.get(9));
cache.replaceAsync(keys.get(4), values.get(4), values.get(10), 4, TimeUnit.MINUTES);
cache.replaceAsync(keys.get(5), values.get(5), values.get(11), 5, TimeUnit.MINUTES, 6, TimeUnit.MINUTES);
}
}
private void replaceWithVersion(List<K> keys, List<V> values, boolean sync) throws Exception {
assertEquals(4, keys.size());
assertEquals(8, values.size());
RemoteCache<K, V> cache = txRemoteCache();
if (sync) {
MetadataValue<V> value = cache.getWithMetadata(keys.get(0));
assertTrue(cache.replaceWithVersion(keys.get(0), values.get(4), value.getVersion()));
value = cache.getWithMetadata(keys.get(1));
assertTrue(cache.replaceWithVersion(keys.get(1), values.get(5), value.getVersion(), 60));
value = cache.getWithMetadata(keys.get(2));
assertTrue(cache.replaceWithVersion(keys.get(2), values.get(6), value.getVersion(), 120, 180));
value = cache.getWithMetadata(keys.get(3));
assertTrue(cache.replaceWithVersion(keys.get(3), values.get(7), value.getVersion(), 4, TimeUnit.MINUTES, 5,
TimeUnit.MINUTES));
} else {
MetadataValue<V> value = cache.getWithMetadata(keys.get(0));
assertTrue(cache.replaceWithVersionAsync(keys.get(0), values.get(4), value.getVersion()).get());
value = cache.getWithMetadata(keys.get(1));
assertTrue(cache.replaceWithVersionAsync(keys.get(1), values.get(5), value.getVersion(), 60).get());
value = cache.getWithMetadata(keys.get(2));
assertTrue(cache.replaceWithVersionAsync(keys.get(2), values.get(6), value.getVersion(), 120, 180).get());
value = cache.getWithMetadata(keys.get(3));
assertTrue(cache.replaceWithVersion(keys.get(3), values.get(7), value.getVersion(), 4, TimeUnit.MINUTES, 5,
TimeUnit.MINUTES));
}
}
private void remove(List<K> keys, List<V> values, boolean sync) throws Exception {
assertEquals(2, keys.size());
assertEquals(2, values.size());
RemoteCache<K, V> cache = txRemoteCache();
if (sync) {
cache.remove(keys.get(0));
assertTrue(cache.remove(keys.get(1), values.get(1)));
} else {
cache.removeAsync(keys.get(0)).get();
cache.removeAsync(keys.get(1), values.get(1));
}
}
private void removeWithVersion(List<K> keys, List<V> values, boolean sync) throws Exception {
assertEquals(1, keys.size());
assertEquals(1, values.size());
RemoteCache<K, V> cache = txRemoteCache();
MetadataValue<V> value = cache.getWithMetadata(keys.get(0));
if (sync) {
assertTrue(cache.removeWithVersion(keys.get(0), value.getVersion()));
} else {
assertTrue(cache.removeWithVersionAsync(keys.get(0), value.getVersion()).get());
}
}
private void compute(List<K> keys, List<V> values, boolean sync) {
assertEquals(1, keys.size());
assertEquals(1, values.size());
assertTrue(sync);
RemoteCache<K, V> cache = txRemoteCache();
cache.compute(keys.get(0), (k, v) -> values.get(0));
}
private void computeIfAbsent(List<K> keys, List<V> values, boolean sync) {
assertEquals(1, keys.size());
assertEquals(1, values.size());
assertTrue(sync);
RemoteCache<K, V> cache = txRemoteCache();
cache.computeIfAbsent(keys.get(0), k -> values.get(0));
}
private void computeIfPresent(List<K> keys, List<V> values, boolean sync) {
assertEquals(1, keys.size());
assertEquals(2, values.size());
assertTrue(sync);
RemoteCache<K, V> cache = txRemoteCache();
cache.compute(keys.get(0), (k, v) -> values.get(1));
}
private void assertMetadataValue(V expected, MetadataValue<V> value, long lifespan, long maxIdle) {
assertNotNull(value);
kvGenerator.assertValueEquals(expected, value.getValue());
assertEquals(lifespan, value.getLifespan());
assertEquals(maxIdle, value.getMaxIdle());
}
private RemoteCache<K, V> txRemoteCache() {
return client(0).getCache(CACHE_NAME);
}
private List<K> generateKeys(Method method, int count) {
List<K> keys = new ArrayList<>(count);
for (int i = 0; i < count; ++i) {
keys.add(kvGenerator.generateKey(method, i));
}
return keys;
}
private List<V> generateValues(Method method, int count) {
List<V> keys = new ArrayList<>(count);
for (int i = 0; i < count; ++i) {
keys.add(kvGenerator.generateValue(method, i));
}
return keys;
}
private interface DataCheck<K, V> {
void execute(List<K> keys, List<V> values, boolean inTx);
}
private interface Step<K, V> {
void execute(List<K> keys, List<V> values);
}
private interface OperationStep<K, V> {
void execute(List<K> keys, List<V> values, boolean sync) throws Exception;
}
}
| 28,891
| 41.425844
| 181
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/tx/InvalidServerConfigTxTest.java
|
package org.infinispan.client.hotrod.tx;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.assertNoTransaction;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.lang.reflect.Method;
import jakarta.transaction.TransactionManager;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.configuration.TransactionMode;
import org.infinispan.client.hotrod.exceptions.CacheNotTransactionalException;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.transaction.LockingMode;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.Test;
/**
* Checks invalid server configuration.
*
* @author Pedro Ruivo
* @since 9.3
*/
@Test(groups = "functional", testName = "client.hotrod.tx.InvalidServerConfigTxTest")
public class InvalidServerConfigTxTest extends SingleHotRodServerTest {
public void testNonTxCache(Method method) {
ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(false);
cacheManager.defineConfiguration(method.getName(), builder.build());
assertFalse(remoteCacheManager.isTransactional(method.getName()));
Exceptions.expectException(CacheNotTransactionalException.class, "ISPN004084.*",
() -> remoteCacheManager.getCache(method.getName(), TransactionMode.NON_XA));
RemoteCache<String, String> cache = remoteCacheManager.getCache(method.getName(), TransactionMode.NONE);
assertFalse(cache.isTransactional());
}
public void testReadCommitted(Method method) {
ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(true);
builder.locking().isolationLevel(IsolationLevel.READ_COMMITTED);
cacheManager.defineConfiguration(method.getName(), builder.build());
assertFalse(remoteCacheManager.isTransactional(method.getName()));
Exceptions.expectException(CacheNotTransactionalException.class, "ISPN004084.*",
() -> remoteCacheManager.getCache(method.getName(), TransactionMode.NON_XA));
RemoteCache<String, String> cache = remoteCacheManager.getCache(method.getName(), TransactionMode.NONE);
assertFalse(cache.isTransactional());
}
public void testOkConfig(Method method) throws Exception {
ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(true);
builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ);
builder.transaction().lockingMode(LockingMode.PESSIMISTIC);
cacheManager.defineConfiguration(method.getName(), builder.build());
assertTrue(remoteCacheManager.isTransactional(method.getName()));
RemoteCache<String, String> cache = remoteCacheManager.getCache(method.getName(), TransactionMode.NON_XA);
assertTrue(cache.isTransactional());
final TransactionManager tm = cache.getTransactionManager();
tm.begin();
try {
cache.put("k1", "v1");
} finally {
tm.commit();
}
assertEquals("v1", cache.get("k1"));
assertNoTransaction(remoteCacheManager);
}
}
| 3,277
| 41.025641
| 112
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/tx/MultipleCacheTxFunctionalTest.java
|
package org.infinispan.client.hotrod.tx;
import static org.infinispan.client.hotrod.configuration.TransactionMode.NONE;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.assertNoTransaction;
import static org.infinispan.client.hotrod.tx.util.KeyValueGenerator.BYTE_ARRAY_GENERATOR;
import static org.infinispan.client.hotrod.tx.util.KeyValueGenerator.GENERIC_ARRAY_GENERATOR;
import static org.infinispan.client.hotrod.tx.util.KeyValueGenerator.STRING_GENERATOR;
import static org.testng.AssertJUnit.assertSame;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Stream;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.TransactionMode;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.client.hotrod.tx.util.KeyValueGenerator;
import org.infinispan.client.hotrod.tx.util.TransactionSetup;
import org.infinispan.commons.marshall.JavaSerializationMarshaller;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Tests transactions involving multiple {@link RemoteCache}.
*
* @author Pedro Ruivo
* @since 9.3
*/
@Test(groups = "functional", testName = "client.hotrod.tx.MultipleCacheTxFunctionalTest")
public class MultipleCacheTxFunctionalTest<K, V> extends MultiHotRodServersTest {
private static final String CACHE_A = "tx-cache-a";
private static final String CACHE_B = "tx-cache-b";
private static final String CACHE_C = "tx-cache-c";
private KeyValueGenerator<K, V> kvGenerator;
private TransactionMode transactionMode;
private boolean useJavaSerialization;
@Override
public Object[] factory() {
return Arrays.stream(TransactionMode.values())
.filter(tMode -> tMode != NONE)
.flatMap(txMode -> Arrays.stream(LockingMode.values())
.flatMap(lockingMode -> Stream.builder()
.add(new MultipleCacheTxFunctionalTest<byte[], byte[]>()
.keyValueGenerator(BYTE_ARRAY_GENERATOR)
.transactionMode(txMode)
.lockingMode(lockingMode))
.add(new MultipleCacheTxFunctionalTest<String, String>()
.keyValueGenerator(STRING_GENERATOR)
.transactionMode(txMode)
.lockingMode(lockingMode))
.add(new MultipleCacheTxFunctionalTest<Object[], Object[]>()
.keyValueGenerator(GENERIC_ARRAY_GENERATOR).javaSerialization()
.transactionMode(txMode)
.lockingMode(lockingMode))
.build())).toArray();
}
@AfterMethod(alwaysRun = true)
@Override
protected void clearContent() throws Throwable {
assertNoTransaction(clients);
super.clearContent();
}
public void testMultipleCaches(Method method) throws Exception {
final K k1 = kvGenerator.generateKey(method, 1);
final K k2 = kvGenerator.generateKey(method, 2);
final K k3 = kvGenerator.generateKey(method, 3);
final V v1 = kvGenerator.generateValue(method, 1);
final V v2 = kvGenerator.generateValue(method, 2);
final V v3 = kvGenerator.generateValue(method, 3);
RemoteCache<K, V> remoteCacheA = remoteCache(CACHE_A);
RemoteCache<K, V> remoteCacheB = remoteCache(CACHE_B);
RemoteCache<K, V> remoteCacheC = remoteCache(CACHE_C);
assertSame(remoteCacheA.getTransactionManager(), remoteCacheB.getTransactionManager());
assertSame(remoteCacheA.getTransactionManager(), remoteCacheC.getTransactionManager());
final TransactionManager tm = remoteCacheA.getTransactionManager();
tm.begin();
kvGenerator.assertValueEquals(null, remoteCacheA.put(k1, v1));
kvGenerator.assertValueEquals(null, remoteCacheB.put(k2, v2));
kvGenerator.assertValueEquals(null, remoteCacheC.put(k3, v3));
kvGenerator.assertValueEquals(v1, remoteCacheA.get(k1));
kvGenerator.assertValueEquals(v2, remoteCacheB.get(k2));
kvGenerator.assertValueEquals(v3, remoteCacheC.get(k3));
tm.commit();
assertEntryInAllClients(CACHE_A, k1, v1);
assertEntryInAllClients(CACHE_A, k2, null);
assertEntryInAllClients(CACHE_A, k3, null);
assertEntryInAllClients(CACHE_B, k1, null);
assertEntryInAllClients(CACHE_B, k2, v2);
assertEntryInAllClients(CACHE_B, k3, null);
assertEntryInAllClients(CACHE_C, k1, null);
assertEntryInAllClients(CACHE_C, k2, null);
assertEntryInAllClients(CACHE_C, k3, v3);
}
public void testMultipleCacheWithSameKey(Method method) throws Exception {
final K k1 = kvGenerator.generateKey(method, 1);
final V v1 = kvGenerator.generateValue(method, 1);
final V v2 = kvGenerator.generateValue(method, 2);
final V v3 = kvGenerator.generateValue(method, 3);
RemoteCache<K, V> remoteCacheA = remoteCache(CACHE_A);
RemoteCache<K, V> remoteCacheB = remoteCache(CACHE_B);
RemoteCache<K, V> remoteCacheC = remoteCache(CACHE_C);
assertSame(remoteCacheA.getTransactionManager(), remoteCacheB.getTransactionManager());
assertSame(remoteCacheA.getTransactionManager(), remoteCacheC.getTransactionManager());
final TransactionManager tm = remoteCacheA.getTransactionManager();
tm.begin();
kvGenerator.assertValueEquals(null, remoteCacheA.put(k1, v1));
kvGenerator.assertValueEquals(null, remoteCacheB.put(k1, v2));
kvGenerator.assertValueEquals(null, remoteCacheC.put(k1, v3));
kvGenerator.assertValueEquals(v1, remoteCacheA.get(k1));
kvGenerator.assertValueEquals(v2, remoteCacheB.get(k1));
kvGenerator.assertValueEquals(v3, remoteCacheC.get(k1));
tm.commit();
assertEntryInAllClients(CACHE_A, k1, v1);
assertEntryInAllClients(CACHE_B, k1, v2);
assertEntryInAllClients(CACHE_C, k1, v3);
}
public void testMultipleCacheWithConflict(Method method) throws Exception {
final K k1 = kvGenerator.generateKey(method, 1);
final V v1 = kvGenerator.generateValue(method, 1);
final V v2 = kvGenerator.generateValue(method, 2);
final V v3 = kvGenerator.generateValue(method, 3);
final V v4 = kvGenerator.generateValue(method, 4);
RemoteCache<K, V> remoteCacheA = remoteCache(CACHE_A);
RemoteCache<K, V> remoteCacheB = remoteCache(CACHE_B);
RemoteCache<K, V> remoteCacheC = remoteCache(CACHE_C);
assertSame(remoteCacheA.getTransactionManager(), remoteCacheB.getTransactionManager());
assertSame(remoteCacheA.getTransactionManager(), remoteCacheC.getTransactionManager());
final TransactionManager tm = remoteCacheA.getTransactionManager();
tm.begin();
kvGenerator.assertValueEquals(null, remoteCacheA.get(k1));
kvGenerator.assertValueEquals(null, remoteCacheA.put(k1, v1));
kvGenerator.assertValueEquals(null, remoteCacheB.put(k1, v2));
kvGenerator.assertValueEquals(null, remoteCacheC.put(k1, v3));
kvGenerator.assertValueEquals(v1, remoteCacheA.get(k1));
kvGenerator.assertValueEquals(v2, remoteCacheB.get(k1));
kvGenerator.assertValueEquals(v3, remoteCacheC.get(k1));
final Transaction tx = tm.suspend();
client(0).getCache(CACHE_A).put(k1, v4);
tm.resume(tx);
Exceptions.expectException(RollbackException.class, tm::commit);
assertEntryInAllClients(CACHE_A, k1, v4);
assertEntryInAllClients(CACHE_B, k1, null);
assertEntryInAllClients(CACHE_C, k1, null);
}
public void testMultipleCacheRollback(Method method) throws Exception {
final K k1 = kvGenerator.generateKey(method, 1);
final V v1 = kvGenerator.generateValue(method, 1);
final V v2 = kvGenerator.generateValue(method, 2);
final V v3 = kvGenerator.generateValue(method, 3);
RemoteCache<K, V> remoteCacheA = remoteCache(CACHE_A);
RemoteCache<K, V> remoteCacheB = remoteCache(CACHE_B);
RemoteCache<K, V> remoteCacheC = remoteCache(CACHE_C);
assertSame(remoteCacheA.getTransactionManager(), remoteCacheB.getTransactionManager());
assertSame(remoteCacheA.getTransactionManager(), remoteCacheC.getTransactionManager());
final TransactionManager tm = remoteCacheA.getTransactionManager();
tm.begin();
kvGenerator.assertValueEquals(null, remoteCacheA.put(k1, v1));
kvGenerator.assertValueEquals(null, remoteCacheB.put(k1, v2));
kvGenerator.assertValueEquals(null, remoteCacheC.put(k1, v3));
kvGenerator.assertValueEquals(v1, remoteCacheA.get(k1));
kvGenerator.assertValueEquals(v2, remoteCacheB.get(k1));
kvGenerator.assertValueEquals(v3, remoteCacheC.get(k1));
tm.rollback();
assertEntryInAllClients(CACHE_A, k1, null);
assertEntryInAllClients(CACHE_B, k1, null);
assertEntryInAllClients(CACHE_C, k1, null);
}
public void testMultipleCacheSetRollbackOnly(Method method) throws Exception {
final K k1 = kvGenerator.generateKey(method, 1);
final V v1 = kvGenerator.generateValue(method, 1);
final V v2 = kvGenerator.generateValue(method, 2);
final V v3 = kvGenerator.generateValue(method, 3);
RemoteCache<K, V> remoteCacheA = remoteCache(CACHE_A);
RemoteCache<K, V> remoteCacheB = remoteCache(CACHE_B);
RemoteCache<K, V> remoteCacheC = remoteCache(CACHE_C);
assertSame(remoteCacheA.getTransactionManager(), remoteCacheB.getTransactionManager());
assertSame(remoteCacheA.getTransactionManager(), remoteCacheC.getTransactionManager());
final TransactionManager tm = remoteCacheA.getTransactionManager();
tm.begin();
kvGenerator.assertValueEquals(null, remoteCacheA.put(k1, v1));
kvGenerator.assertValueEquals(null, remoteCacheB.put(k1, v2));
kvGenerator.assertValueEquals(null, remoteCacheC.put(k1, v3));
kvGenerator.assertValueEquals(v1, remoteCacheA.get(k1));
kvGenerator.assertValueEquals(v2, remoteCacheB.get(k1));
kvGenerator.assertValueEquals(v3, remoteCacheC.get(k1));
tm.setRollbackOnly();
Exceptions.expectException(RollbackException.class, tm::commit);
assertEntryInAllClients(CACHE_A, k1, null);
assertEntryInAllClients(CACHE_B, k1, null);
assertEntryInAllClients(CACHE_C, k1, null);
}
@BeforeClass(alwaysRun = true)
public void printParameters() {
log.debugf("Parameters: %s", super.parameters());
}
@Override
protected String[] parameterNames() {
return concat(super.parameterNames(), null, null, null);
}
@Override
protected Object[] parameterValues() {
return concat(super.parameterValues(), kvGenerator.toString(), transactionMode, lockingMode);
}
@Override
protected String parameters() {
return "[" + kvGenerator + "/" + transactionMode + "/" + lockingMode + "]";
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cacheBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
cacheBuilder.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup());
cacheBuilder.transaction().lockingMode(lockingMode);
cacheBuilder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ);
createHotRodServers(3, new ConfigurationBuilder());
defineInAll(CACHE_A, cacheBuilder);
defineInAll(CACHE_B, cacheBuilder);
defineInAll(CACHE_C, cacheBuilder);
}
@Override
protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(
String host, int serverPort) {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = super
.createHotRodClientConfigurationBuilder(host, serverPort);
clientBuilder.forceReturnValues(false);
for (String cacheName : Arrays.asList(CACHE_A, CACHE_B, CACHE_C)) {
TransactionSetup.amendJTA(clientBuilder.remoteCache(cacheName)).transactionMode(transactionMode);
}
if (useJavaSerialization) {
clientBuilder.marshaller(new JavaSerializationMarshaller()).addJavaSerialAllowList("\\Q[\\ELjava.lang.Object;");
}
return clientBuilder;
}
private RemoteCache<K, V> remoteCache(String cacheName) {
return client(0).getCache(cacheName);
}
private void assertEntryInAllClients(String cacheName, K key, V value) {
for (RemoteCacheManager manager : clients) {
RemoteCache<K, V> remoteCache = manager.getCache(cacheName);
kvGenerator.assertValueEquals(value, remoteCache.get(key));
}
}
private MultipleCacheTxFunctionalTest<K, V> keyValueGenerator(KeyValueGenerator<K, V> kvGenerator) {
this.kvGenerator = kvGenerator;
return this;
}
private MultipleCacheTxFunctionalTest<K, V> transactionMode(TransactionMode transactionMode) {
this.transactionMode = transactionMode;
return this;
}
private MultipleCacheTxFunctionalTest<K, V> javaSerialization() {
useJavaSerialization = true;
return this;
}
}
| 13,781
| 43.315113
| 121
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/tx/util/TransactionSetup.java
|
package org.infinispan.client.hotrod.tx.util;
import org.infinispan.client.hotrod.configuration.RemoteCacheConfigurationBuilder;
import org.infinispan.client.hotrod.transaction.lookup.RemoteTransactionManagerLookup;
import org.infinispan.commons.tx.lookup.TransactionManagerLookup;
import org.infinispan.commons.util.LegacyKeySupportSystemProperties;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup;
import jakarta.transaction.TransactionManager;
/**
* Setup the {@link TransactionManager} for test classes.
*
* @author Pedro Ruivo
* @since 9.3
*/
public final class TransactionSetup {
private static final String JBOSS_TM = "jbosstm";
private static final String DUMMY_TM = "dummytm";
private static final String JTA = LegacyKeySupportSystemProperties
.getProperty("infinispan.test.jta.tm.hotrod", "infinispan.tm.hotrod");
private static TransactionManagerLookup lookup;
static {
init();
}
private TransactionSetup() {
}
private static void init() {
String property = JTA;
if (DUMMY_TM.equalsIgnoreCase(property)) {
System.out.println("Hot Rod client transaction manager used: Dummy");
lookup = RemoteTransactionManagerLookup.getInstance();
} else {
//use JBossTM as default (as in core)
System.out.println("Hot Rod client transaction manager used: JBossTM");
JBossStandaloneJTAManagerLookup tmLookup = new JBossStandaloneJTAManagerLookup();
tmLookup.init(new GlobalConfigurationBuilder().build());
lookup = tmLookup;
}
}
public static RemoteCacheConfigurationBuilder amendJTA(RemoteCacheConfigurationBuilder builder) {
return builder.transactionManagerLookup(lookup);
}
}
| 1,828
| 34.173077
| 100
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/tx/util/KeyValueGenerator.java
|
package org.infinispan.client.hotrod.tx.util;
import static org.infinispan.test.TestingUtil.k;
import static org.infinispan.test.TestingUtil.v;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;
import java.lang.reflect.Method;
/**
* A key and value generator for Hot Rod testing.
*
* @author Pedro Ruivo
* @since 9.3
*/
public interface KeyValueGenerator<K, V> {
KeyValueGenerator<String, String> STRING_GENERATOR = new KeyValueGenerator<String, String>() {
@Override
public String generateKey(Method method, int index) {
return k(method, index);
}
@Override
public String generateValue(Method method, int index) {
return v(method, index);
}
@Override
public void assertValueEquals(String expected, String actual) {
assertEquals(expected, actual);
}
@Override
public String toString() {
return "STRING";
}
};
KeyValueGenerator<byte[], byte[]> BYTE_ARRAY_GENERATOR = new KeyValueGenerator<byte[], byte[]>() {
@Override
public byte[] generateKey(Method method, int index) {
return k(method, index).getBytes();
}
@Override
public byte[] generateValue(Method method, int index) {
return v(method, index).getBytes();
}
@Override
public void assertValueEquals(byte[] expected, byte[] actual) {
assertArrayEquals(expected, actual);
}
@Override
public String toString() {
return "BYTE_ARRAY";
}
};
KeyValueGenerator<Object[], Object[]> GENERIC_ARRAY_GENERATOR = new KeyValueGenerator<Object[], Object[]>() {
@Override
public Object[] generateKey(Method method, int index) {
return new Object[]{method.getName(), "key", index};
}
@Override
public Object[] generateValue(Method method, int index) {
return new Object[]{method.getName(), "value", index};
}
@Override
public void assertValueEquals(Object[] expected, Object[] actual) {
assertArrayEquals(expected, actual);
}
@Override
public String toString() {
return "GENERIC_ARRAY";
}
};
K generateKey(Method method, int index);
V generateValue(Method method, int index);
void assertValueEquals(V expected, V actual);
}
| 2,410
| 25.206522
| 112
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/maxresult/RemoteDefaultMaxResultTest.java
|
package org.infinispan.client.hotrod.maxresult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.Search;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.commons.test.annotation.TestForIssue;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.query.dsl.Query;
import org.infinispan.query.dsl.QueryFactory;
import org.infinispan.query.dsl.QueryResult;
import org.infinispan.query.model.Game;
import org.infinispan.query.model.NonIndexedGame;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "org.infinispan.client.hotrod.maxresult.RemoteDefaultMaxResultTest")
@TestForIssue(jiraKey = "ISPN-14194")
public class RemoteDefaultMaxResultTest extends SingleHotRodServerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder indexed = new ConfigurationBuilder();
indexed.indexing().enable()
.storage(LOCAL_HEAP)
.addIndexedEntity("Game");
ConfigurationBuilder notIndexed = new ConfigurationBuilder();
EmbeddedCacheManager manager = TestCacheManagerFactory.createServerModeCacheManager();
manager.defineConfiguration("indexed-games", indexed.build());
manager.defineConfiguration("not-indexed-games", notIndexed.build());
return manager;
}
@Override
protected SerializationContextInitializer contextInitializer() {
return Game.GameSchema.INSTANCE;
}
@Test
public void testNonIndexed() {
RemoteCache<Integer, NonIndexedGame> games = remoteCacheManager.getCache("not-indexed-games");
for (int i = 1; i <= 110; i++) {
games.put(i, new NonIndexedGame("Game " + i, "This is the game " + i + "# of a series"));
}
QueryFactory factory = Search.getQueryFactory(games);
Query<NonIndexedGame> query = factory.create("from NonIndexedGame");
QueryResult<NonIndexedGame> result = query.execute();
assertThat(result.count().value()).isEqualTo(110);
assertThat(result.list()).hasSize(100); // use the default
query = factory.create("from NonIndexedGame");
query.maxResults(200); // raise it
result = query.execute();
assertThat(result.count().value()).isEqualTo(110);
assertThat(result.list()).hasSize(110);
}
@Test
public void testIndexed() {
RemoteCache<Integer, Game> games = remoteCacheManager.getCache("indexed-games");
for (int i = 1; i <= 110; i++) {
games.put(i, new Game("Game " + i, "This is the game " + i + "# of a series"));
}
QueryFactory factory = Search.getQueryFactory(games);
Query<Game> query = factory.create("from Game");
QueryResult<Game> result = query.execute();
assertThat(result.count().value()).isEqualTo(110);
assertThat(result.list()).hasSize(100); // use the default
query = factory.create("from Game");
query.maxResults(200); // raise it
result = query.execute();
assertThat(result.count().value()).isEqualTo(110);
assertThat(result.list()).hasSize(110);
}
}
| 3,465
| 37.087912
| 108
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/maxresult/RemoteHitCountAccuracyTest.java
|
package org.infinispan.client.hotrod.maxresult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.Search;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.commons.test.annotation.TestForIssue;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.query.dsl.Query;
import org.infinispan.query.dsl.QueryFactory;
import org.infinispan.query.dsl.QueryResult;
import org.infinispan.query.model.Game;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "org.infinispan.client.hotrod.maxresult.RemoteHitCountAccuracyTest")
@TestForIssue(jiraKey = "ISPN-14195")
public class RemoteHitCountAccuracyTest extends SingleHotRodServerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder indexed = new ConfigurationBuilder();
indexed.indexing().enable()
.storage(LOCAL_HEAP)
.addIndexedEntity("Game");
indexed.query().hitCountAccuracy(10); // lower the default accuracy
EmbeddedCacheManager manager = TestCacheManagerFactory.createServerModeCacheManager();
manager.defineConfiguration("indexed-games", indexed.build());
return manager;
}
@Override
protected SerializationContextInitializer contextInitializer() {
return Game.GameSchema.INSTANCE;
}
@Test
public void overrideHitCountAccuracy() {
RemoteCache<Integer, Game> games = remoteCacheManager.getCache("indexed-games");
for (int i = 1; i <= 5000; i++) {
games.put(i, new Game("Game " + i, "This is the game " + i + "# of a series"));
}
QueryFactory factory = Search.getQueryFactory(games);
Query<Game> query = factory.create("from Game where description : 'game'");
QueryResult<Game> result = query.execute();
// the hit count accuracy does not allow to compute **an exact** hit count
assertThat(result.count().isExact()).isFalse();
query = factory.create("from Game where description : 'game'");
// raise the default accuracy
query.hitCountAccuracy(5_000);
result = query.execute();
assertThat(result.count().isExact()).isTrue();
assertThat(result.count().value()).isEqualTo(5_000);
}
}
| 2,618
| 39.292308
| 108
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/OldClientCustomEventsTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.client.hotrod.ProtocolVersion.PROTOCOL_VERSION_27;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withClientListener;
import org.infinispan.client.hotrod.ProtocolVersion;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.event.CustomEventLogListener.CustomEvent;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.event.OldClientCustomEventsTest")
public class OldClientCustomEventsTest extends SingleHotRodServerTest {
private static final String MAGIC_KEY = "key-42";
private static final ProtocolVersion VERSION = PROTOCOL_VERSION_27;
@Override
protected HotRodServer createHotRodServer() {
HotRodServerConfigurationBuilder builder = new HotRodServerConfigurationBuilder();
HotRodServer server = HotRodClientTestingUtil.startHotRodServer(cacheManager, builder);
server.addCacheEventFilterFactory("static-filter-factory", new EventLogListener.StaticCacheEventFilterFactory<>(MAGIC_KEY));
server.addCacheEventConverterFactory("static-converter-factory", new CustomEventLogListener.StaticConverterFactory());
return server;
}
@Override
protected RemoteCacheManager getRemoteCacheManager() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(hotrodServer.getPort()).version(VERSION)
.addContextInitializer(contextInitializer());
return new InternalRemoteCacheManager(builder.build());
}
@Override
protected SerializationContextInitializer contextInitializer() {
return ClientEventSCI.INSTANCE;
}
public void testFilteredEvents() {
final EventLogListener.StaticFilteredEventLogListener<String> l = new EventLogListener.StaticFilteredEventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, new Object[]{"match"}, new Object[]{}, remote -> {
l.expectNoEvents();
remote.put("key-1", "one");
remote.put("key-2", "two");
remote.put("key-3", "three");
l.expectNoEvents();
remote.put(MAGIC_KEY, "hot key");
l.expectOnlyCreatedEvent(MAGIC_KEY);
});
}
public void testConvertedEvents() {
final CustomEventLogListener.StaticCustomEventLogListener<String> l = new CustomEventLogListener.StaticCustomEventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
remote.put("key-1", "one");
l.expectCreatedEvent(new CustomEvent<>("key-1", "one", 0));
});
}
}
| 3,178
| 45.75
| 165
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/CustomMarshallerEventIT.java
|
package org.infinispan.client.hotrod.event;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import java.io.Serializable;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.io.ByteBuffer;
import org.infinispan.commons.io.ByteBufferFactory;
import org.infinispan.commons.io.ByteBufferFactoryImpl;
import org.infinispan.commons.marshall.AbstractMarshaller;
import org.testng.annotations.Test;
/**
* Tests for remote listeners and custom marshaller.
* The cache is not configured with any media type in particular, but the listener
* should receive events that are to be unmarshalled by a specific user provided marshaller.
*/
@Test(groups = "functional", testName = "client.hotrod.event.CustomMarshallerEventIT")
public class CustomMarshallerEventIT extends SingleHotRodServerTest {
@Override
protected void setup() throws Exception {
super.setup();
// Make the custom marshaller available in the server. In standalone servers, this can done using a deployment jar.
hotrodServer.setMarshaller(new IdMarshaller());
}
@Override
protected RemoteCacheManager getRemoteCacheManager() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(hotrodServer.getPort());
builder.marshaller(new IdMarshaller());
return new RemoteCacheManager(builder.build());
}
@Test
public void testEventReceiveBasic() {
RemoteCache<Id, Id> remoteCache = remoteCacheManager.getCache();
final IdEventListener eventListener = new IdEventListener();
remoteCache.addClientListener(eventListener);
try {
// Created events
remoteCache.put(new Id(1), new Id(11));
ClientCacheEntryCreatedEvent<Id> created = eventListener.pollEvent();
assertEquals(new Id(1), created.getKey());
remoteCache.put(new Id(2), new Id(22));
created = eventListener.pollEvent();
assertEquals(new Id(2), created.getKey());
// Modified events
remoteCache.put(new Id(1), new Id(111));
ClientCacheEntryModifiedEvent<Id> modified = eventListener.pollEvent();
assertEquals(new Id(1), modified.getKey());
// Remove events
remoteCache.remove(new Id(1));
ClientCacheEntryRemovedEvent<Id> removed = eventListener.pollEvent();
assertEquals(new Id(1), removed.getKey());
remoteCache.remove(new Id(2));
removed = eventListener.pollEvent();
assertEquals(new Id(2), removed.getKey());
} finally {
remoteCache.removeClientListener(eventListener);
}
}
@ClientListener
public static class IdEventListener {
BlockingQueue<ClientEvent> events = new ArrayBlockingQueue<>(128);
@ClientCacheEntryCreated
@ClientCacheEntryModified
@ClientCacheEntryRemoved
public void handleCreatedEvent(ClientEvent e) {
events.add(e);
}
public <E extends ClientEvent> E pollEvent() {
try {
E event = (E) events.poll(10, TimeUnit.SECONDS);
assertNotNull(event);
return event;
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}
}
public static class IdMarshaller extends AbstractMarshaller {
@Override
protected ByteBuffer objectToBuffer(Object o, int estimatedSize) {
Id obj = (Id) o;
ByteBufferFactory factory = new ByteBufferFactoryImpl();
return factory.newByteBuffer(new byte[]{obj.id}, 0, 1);
}
@Override
public Object objectFromByteBuffer(byte[] buf, int offset, int length) {
return new Id(buf[0]);
}
@Override
public boolean isMarshallable(Object o) {
return true;
}
@Override
public MediaType mediaType() {
return MediaType.fromString("application/x-custom-id");
}
}
public static class Id implements Serializable {
final byte id;
public Id(int id) {
this.id = (byte) id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Id other = (Id) o;
return id == other.id;
}
@Override
public int hashCode() {
return id;
}
}
}
| 5,194
| 34.101351
| 121
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/ClientListenerRemoveOnStopTest.java
|
package org.infinispan.client.hotrod.event;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Set;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.event.ClientListenerRemoveOnStopTest")
public class ClientListenerRemoveOnStopTest extends SingleHotRodServerTest {
public void testAllListenersRemovedOnStop() {
final RemoteCache<Integer, String> rcache = remoteCacheManager.getCache();
final EventLogListener<Integer> eventListener1 = new EventLogListener<>(rcache);
rcache.addClientListener(eventListener1);
Set<Object> listeners = rcache.getListeners();
assertEquals(1, listeners.size());
assertEquals(eventListener1, listeners.iterator().next());
final EventLogListener<Integer> eventListener2 = new EventLogListener<>(rcache);
rcache.addClientListener(eventListener2);
listeners = rcache.getListeners();
assertEquals(2, listeners.size());
assertTrue(listeners.contains(eventListener1));
assertTrue(listeners.contains(eventListener2));
remoteCacheManager.stop();
listeners = rcache.getListeners();
assertEquals(0, listeners.size());
}
public void testRemoveListenerAfterStopAndRestart() throws Exception {
remoteCacheManager.start();
final RemoteCache<Integer, String> rcache = remoteCacheManager.getCache();
final EventLogListener<Integer> eventListener1 = new EventLogListener<>(rcache);
rcache.addClientListener(eventListener1);
Set<Object> listeners = rcache.getListeners();
assertEquals(1, listeners.size());
assertTrue(listeners.contains(eventListener1));
int port = this.hotrodServer.getPort();
HotRodClientTestingUtil.killServers(this.hotrodServer);
TestingUtil.killCacheManagers(this.cacheManager);
// The listener is removed as soon as the channel is closed
eventuallyEquals(0, () -> rcache.getListeners().size());
this.cacheManager = createCacheManager();
hotrodServer = HotRodClientTestingUtil.startHotRodServer(this.cacheManager, port, new HotRodServerConfigurationBuilder());
rcache.removeClientListener(eventListener1);
listeners = rcache.getListeners();
assertEquals(0, listeners.size());
}
}
| 2,635
| 45.245614
| 128
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/ClientEventsOOMTest.java
|
package org.infinispan.client.hotrod.event;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.filter.NamedFactory;
import org.infinispan.metadata.Metadata;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverterFactory;
import org.infinispan.notifications.cachelistener.filter.EventType;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
import java.io.Serializable;
import java.lang.management.BufferPoolMXBean;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
/**
* A remote listener over a slow channel that requires the initial state can lead to OOME in the server.
* See https://issues.jboss.org/browse/ISPN-6005.
*
* @author anistor@redhat.com
* @since 8.2
*/
@Test(groups = "functional", testName = "client.hotrod.event.ClientEventsOOMTest")
public class ClientEventsOOMTest extends MultiHotRodServersTest {
private static final int NUM_ENTRIES = Integer.getInteger("client.stress.num_entries", 100);
private static final long SLEEP_TIME_MS = Long.getLong("client.stress.sleep_time", 10); // ms
private static final int NUM_NODES = 2;
private static final BufferPoolMXBean DIRECT_POOL = getDirectMemoryPool();
private RemoteCache<Integer, byte[]> remoteCache;
// There is only one Godzilla in heap, but we can use Netty's off-heap pools to multiply them and destroy the world
private static final byte[] GODZILLA = makeGodzilla();
{
testReplay = false;
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfgBuilder = getConfigurationBuilder();
createHotRodServers(NUM_NODES, cfgBuilder);
waitForClusterToForm();
for (int i = 0; i < NUM_NODES; i++) {
server(i).addCacheEventConverterFactory("godzilla-growing-converter-factory", new CustomConverterFactory());
}
remoteCache = client(0).getCache();
}
private ConfigurationBuilder getConfigurationBuilder() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false);
//playing with OOM - weird things might happen when JVM will struggle for life
builder.clustering().remoteTimeout(4, TimeUnit.MINUTES);
return hotRodCacheConfiguration(builder);
}
public void testOOM() throws Throwable {
try {
log.debugf("Max direct memory is: %s%n", humanReadableByteCount(maxDirectMemory0(), false));
logDirectMemory(log);
byte[] babyGodzilla = new byte[]{13};
for (int i = 0; i < NUM_ENTRIES; i++) {
remoteCache.put(i, babyGodzilla);
}
log.debugf("ADDED %d BABY GODZILLAS\n", NUM_ENTRIES);
log.debug("ADDING LISTENER!");
CountDownLatch latch = new CountDownLatch(1);
ClientEntryListener listener = new ClientEntryListener(latch);
logDirectMemory(log);
remoteCache.addClientListener(listener); // the world ends here
log.debug("ADDED LISTENER");
logDirectMemory(log);
latch.await(1, TimeUnit.MINUTES);
remoteCache.removeClientListener(listener);
assertEquals(NUM_ENTRIES, listener.eventCount);
} catch (Throwable t) {
logDirectMemory(log);
log.debug("Exception reported", t);
throw t;
}
}
private static void logDirectMemory(Log log) {
log.debugf("Direct memory: used=%s, capacity=%s%n",
humanReadableByteCount(DIRECT_POOL.getMemoryUsed(), false),
humanReadableByteCount(DIRECT_POOL.getTotalCapacity(), false));
}
private static BufferPoolMXBean getDirectMemoryPool() {
List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
BufferPoolMXBean directPool = null;
for (BufferPoolMXBean pool : pools) {
if (pool.getName().equals("direct")) directPool = pool;
}
return directPool;
}
private static long maxDirectMemory0() {
try {
// Try to get from sun.misc.VM.maxDirectMemory() which should be most accurate.
Class<?> vmClass = Class.forName("sun.misc.VM", true, ClassLoader.getSystemClassLoader());
Method m = vmClass.getDeclaredMethod("maxDirectMemory");
return ((Number) m.invoke(null)).longValue();
} catch (Throwable t) {
// Ignore
return -1;
}
}
private static String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
@ClientListener(converterFactoryName = "godzilla-growing-converter-factory", useRawData = true, includeCurrentState = true)
private static class ClientEntryListener {
private static final Log log = LogFactory.getLog(ClientEntryListener.class);
private final CountDownLatch latch;
int eventCount = 0;
ClientEntryListener(CountDownLatch latch) {
this.latch = latch;
}
@ClientCacheEntryCreated
@SuppressWarnings("unused")
public void handleClientCacheEntryCreatedEvent(ClientCacheEntryCustomEvent event) {
byte[] eventData = (byte[]) event.getEventData();
int length = eventData.length;
eventCount++;
log.debugf("ClientEntryListener.handleClientCacheEntryCreatedEvent eventCount=%d length=%d data=%s\n",
eventCount, length, Util.toStr(eventData));
logDirectMemory(log);
if (eventCount == NUM_ENTRIES) latch.countDown();
try {
Thread.sleep(SLEEP_TIME_MS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
@NamedFactory(name = "godzilla-growing-converter-factory")
private static class CustomConverterFactory implements CacheEventConverterFactory {
@Override
public <K, V, C> CacheEventConverter<K, V, C> getConverter(Object[] params) {
return new CustomConverter<>();
}
static class CustomConverter<K, V, C> implements CacheEventConverter<K, V, C>, Serializable {
@Override
public C convert(Object key, Object previousValue, Metadata previousMetadata, Object value, Metadata metadata, EventType eventType) {
// all baby godzillas get converted to full grown godzillas
return (C) GODZILLA;
}
}
}
private static byte[] makeGodzilla() {
// this will not fit through the keyhole
byte[] godzilla = new byte[1024 * 1024 * 42];
Arrays.fill(godzilla, (byte) 13);
return godzilla;
}
}
| 7,571
| 37.830769
| 142
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/ClientListenerWithIndexingAndProtobufTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB;
import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.query.dsl.embedded.testdomain.User;
import org.testng.annotations.Test;
/**
* @author anistor@redhat.com
* @since 7.2
*/
@Test(groups = "functional", testName = "client.hotrod.event.ClientListenerWithIndexingAndProtobufTest")
public class ClientListenerWithIndexingAndProtobufTest extends MultiHotRodServersTest {
private static final int NUM_NODES = 2;
private RemoteCache<Object, Object> remoteCache;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfgBuilder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
cfgBuilder.indexing().enable()
.storage(LOCAL_HEAP)
.addIndexedEntity("sample_bank_account.User");
createHotRodServers(NUM_NODES, cfgBuilder);
waitForClusterToForm();
remoteCache = client(0).getCache();
}
@Override
protected SerializationContextInitializer contextInitializer() {
return TestDomainSCI.INSTANCE;
}
public void testEventFilter() {
User user1 = new UserPB();
user1.setId(1);
user1.setName("John");
user1.setSurname("Doe");
user1.setGender(User.Gender.MALE);
user1.setAge(22);
NoopEventListener listener = new NoopEventListener();
remoteCache.addClientListener(listener);
expectElementsInQueue(listener.createEvents, 0);
remoteCache.put("user_" + user1.getId(), user1);
assertEquals(1, remoteCache.size());
expectElementsInQueue(listener.createEvents, 1);
remoteCache.removeClientListener(listener);
}
private void expectElementsInQueue(BlockingQueue<?> queue, int numElements) {
for (int i = 0; i < numElements; i++) {
try {
Object e = queue.poll(5, TimeUnit.SECONDS);
assertNotNull("Queue was empty!", e);
} catch (InterruptedException e) {
throw new AssertionError("Interrupted while waiting for condition", e);
}
}
try {
// no more elements expected here
Object e = queue.poll(5, TimeUnit.SECONDS);
assertNull("No more elements expected in queue!", e);
} catch (InterruptedException e) {
throw new AssertionError("Interrupted while waiting for condition", e);
}
}
@ClientListener
private static class NoopEventListener {
public final BlockingQueue<ClientCacheEntryCreatedEvent> createEvents = new LinkedBlockingQueue<>();
@ClientCacheEntryCreated
public void handleCreatedEvent(ClientCacheEntryCreatedEvent<?> e) {
createEvents.add(e);
}
}
}
| 3,722
| 34.457143
| 125
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/RemoteContinuousQueryLeavingRemoteCacheManagerTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.Search;
import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB;
import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.time.TimeService;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.query.api.continuous.ContinuousQuery;
import org.infinispan.query.api.continuous.ContinuousQueryListener;
import org.infinispan.query.dsl.Query;
import org.infinispan.query.dsl.QueryFactory;
import org.infinispan.query.dsl.embedded.testdomain.User;
import org.infinispan.query.remote.impl.filter.IckleContinuousQueryProtobufCacheEventFilterConverterFactory;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.ControlledTimeService;
import org.infinispan.util.KeyValuePair;
import org.testng.annotations.Test;
/**
* Test remote continuous query with removing a cache manager
*
* @author anistor@redhat.com
* @author wburns@redhat.com
* @since 10.0
*/
@Test(groups = "functional", testName = "client.hotrod.event.RemoteContinuousQueryLeavingRemoteCacheManagerTest")
public class RemoteContinuousQueryLeavingRemoteCacheManagerTest extends MultiHotRodServersTest {
private final int NUM_NODES = 1;
private RemoteCache<String, User> remoteCache;
private final ControlledTimeService timeService = new ControlledTimeService();
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfgBuilder = getConfigurationBuilder();
createHotRodServers(NUM_NODES, cfgBuilder);
waitForClusterToForm();
// Register the filter/converter factory. This should normally be discovered by the server via class path instead
// of being added manually here, but this is ok in a test.
IckleContinuousQueryProtobufCacheEventFilterConverterFactory factory = new IckleContinuousQueryProtobufCacheEventFilterConverterFactory();
for (int i = 0; i < NUM_NODES; i++) {
server(i).addCacheEventFilterConverterFactory(IckleContinuousQueryProtobufCacheEventFilterConverterFactory.FACTORY_NAME, factory);
TestingUtil.replaceComponent(server(i).getCacheManager(), TimeService.class, timeService, true);
}
remoteCache = client(0).getCache();
}
protected ConfigurationBuilder getConfigurationBuilder() {
ConfigurationBuilder cfgBuilder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
cfgBuilder.indexing().enable()
.storage(LOCAL_HEAP)
.addIndexedEntity("sample_bank_account.User");
cfgBuilder.expiration().disableReaper();
return cfgBuilder;
}
@Override
protected SerializationContextInitializer contextInitializer() {
return TestDomainSCI.INSTANCE;
}
static class Listener implements ContinuousQueryListener<String, User> {
final BlockingQueue<KeyValuePair<String, User>> joined = new LinkedBlockingQueue<>();
final BlockingQueue<KeyValuePair<String, User>> updated = new LinkedBlockingQueue<>();
final BlockingQueue<String> left = new LinkedBlockingQueue<>();
@Override
public void resultJoining(String key, User value) {
joined.add(new KeyValuePair<>(key, value));
}
@Override
public void resultUpdated(String key, User value) {
updated.add(new KeyValuePair<>(key, value));
}
@Override
public void resultLeaving(String key) {
left.add(key);
}
}
private Listener applyContinuousQuery(RemoteCache<String, User> cacheToUse) {
QueryFactory qf = Search.getQueryFactory(cacheToUse);
Query<User> query = qf.<User>create("FROM sample_bank_account.User WHERE age <= :ageParam")
.setParameter("ageParam", 32);
ContinuousQuery<String, User> continuousQuery = Search.getContinuousQuery(cacheToUse);
Listener listener = new Listener();
continuousQuery.addContinuousQueryListener(query, listener);
return listener;
}
public void testContinuousQueryRemoveRCM() {
// Create an additional remote cache manager that registers the same query
RemoteCacheManager extraRemoteCacheManager = new InternalRemoteCacheManager(createHotRodClientConfigurationBuilder(server(0)).build());
RemoteCache<String, User> extraRemoteCache = extraRemoteCacheManager.getCache();
User user1 = new UserPB();
user1.setId(1);
user1.setName("John");
user1.setSurname("Doe");
user1.setGender(User.Gender.MALE);
user1.setAge(22);
user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2)));
user1.setNotes("Lorem ipsum dolor sit amet");
remoteCache.put("user" + user1.getId(), user1);
Listener listener = applyContinuousQuery(remoteCache);
// Also register the query on the extra remote cache
Listener extraListener = applyContinuousQuery(extraRemoteCache);
expectElementsInQueue(listener.joined, 1, (kv) -> kv.getValue().getAge(), 22);
expectElementsInQueue(extraListener.joined, 1, (kv) -> kv.getValue().getAge(), 22);
expectElementsInQueue(listener.updated, 0);
expectElementsInQueue(extraListener.updated, 0);
expectElementsInQueue(listener.left, 0);
expectElementsInQueue(extraListener.left, 0);
// Now we shut down the extra remote cache
extraRemoteCacheManager.stop();
user1.setAge(23);
remoteCache.put("user" + user1.getId(), user1);
expectElementsInQueue(listener.joined, 0);
expectElementsInQueue(listener.updated, 1, (kv) -> kv.getValue().getAge(), 23);
expectElementsInQueue(listener.left, 0);
}
private <T> void expectElementsInQueue(BlockingQueue<T> queue, int numElements) {
expectElementsInQueue(queue, numElements, null);
}
private <T, R> void expectElementsInQueue(BlockingQueue<T> queue, int numElements, Function<T, R> valueTransformer, Object... expectedValue) {
List<Object> expectedValues;
if (expectedValue.length != 0) {
if (expectedValue.length != numElements) {
throw new IllegalArgumentException("The number of expected values must either match the number of expected elements or no expected values should be specified.");
}
expectedValues = new ArrayList<>(expectedValue.length);
Collections.addAll(expectedValues, expectedValue);
} else {
expectedValues = null;
}
for (int i = 0; i < numElements; i++) {
final T o;
try {
o = queue.poll(5, TimeUnit.SECONDS);
assertNotNull("Queue was empty after reading " + i + " elements!", o);
} catch (InterruptedException e) {
throw new AssertionError("Interrupted while waiting for condition", e);
}
if (expectedValues != null) {
Object v = valueTransformer != null ? valueTransformer.apply(o) : o;
boolean found = expectedValues.remove(v);
assertTrue("Expectation failed on element number " + i + ", unexpected value: " + v, found);
}
}
try {
// no more elements expected here
Object o = queue.poll(100, TimeUnit.MILLISECONDS);
assertNull("No more elements expected in queue!", o);
} catch (InterruptedException e) {
throw new AssertionError("Interrupted while waiting for condition", e);
}
}
}
| 8,449
| 40.831683
| 173
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/ClientClusterExpirationEventsTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withClientListener;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertNull;
import java.util.concurrent.TimeUnit;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.event.CustomEventLogListener.CustomEvent;
import org.infinispan.client.hotrod.event.CustomEventLogListener.FilterConverterFactory;
import org.infinispan.client.hotrod.event.CustomEventLogListener.FilterCustomEventLogListener;
import org.infinispan.client.hotrod.event.CustomEventLogListener.StaticConverterFactory;
import org.infinispan.client.hotrod.event.CustomEventLogListener.StaticCustomEventLogListener;
import org.infinispan.client.hotrod.event.EventLogListener.StaticCacheEventFilterFactory;
import org.infinispan.client.hotrod.event.EventLogListener.StaticFilteredEventLogListener;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.time.TimeService;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.notifications.cachelistener.CacheNotifier;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.ControlledTimeService;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.event.ClientClusterExpirationEventsTest")
public class ClientClusterExpirationEventsTest extends MultiHotRodServersTest {
static final int NUM_SERVERS = 2;
protected ControlledTimeService ts0;
protected ControlledTimeService ts1;
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(NUM_SERVERS, getCacheConfiguration());
injectTimeServices();
}
@Override
protected SerializationContextInitializer contextInitializer() {
return ClientEventSCI.INSTANCE;
}
private ConfigurationBuilder getCacheConfiguration() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
builder.clustering().hash().numOwners(1);
return hotRodCacheConfiguration(builder);
}
protected HotRodServer addHotRodServer(ConfigurationBuilder builder) {
HotRodServer server = super.addHotRodServer(builder);
server.addCacheEventConverterFactory("static-converter-factory", new StaticConverterFactory());
server.addCacheEventFilterConverterFactory("filter-converter-factory", new FilterConverterFactory());
return server;
}
private void injectTimeServices() {
ts0 = new ControlledTimeService();
TestingUtil.replaceComponent(server(0).getCacheManager(), TimeService.class, ts0, true);
ts1 = new ControlledTimeService();
TestingUtil.replaceComponent(server(1).getCacheManager(), TimeService.class, ts1, true);
}
public void testSimpleExpired() {
final Integer key0 = HotRodClientTestingUtil.getIntKeyForServer(server(0));
final EventLogListener<Integer> l = new EventLogListener<>(client(0).getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
remote.put(key0, "one", 10, TimeUnit.MINUTES);
l.expectOnlyCreatedEvent(key0);
ts0.advance(TimeUnit.MINUTES.toMillis(10) + 1);
assertNull(remote.get(key0));
l.expectOnlyExpiredEvent(key0);
});
}
public void testFilteringInCluster() {
// Generate key and add static filter in all servers
final Integer key0 = HotRodClientTestingUtil.getIntKeyForServer(server(0));
final Integer key1 = HotRodClientTestingUtil.getIntKeyForServer(server(1));
for (HotRodServer server : servers)
server.addCacheEventFilterFactory("static-filter-factory", new StaticCacheEventFilterFactory(key1));
// We listen to all events, otherwise events that are filtered out could leak between tests
final EventLogListener<Integer> allEvents = new EventLogListener<>(client(0).getCache());
withClientListener(allEvents, r1 -> {
final StaticFilteredEventLogListener<Integer> l = new StaticFilteredEventLogListener<>(r1);
withClientListener(l, remote -> {
allEvents.expectNoEvents();
l.expectNoEvents();
remote.put(key0, "one", 10, TimeUnit.MINUTES);
allEvents.expectOnlyCreatedEvent(key0);
l.expectNoEvents();
remote.put(key1, "two", 10, TimeUnit.MINUTES);
allEvents.expectOnlyCreatedEvent(key1);
l.expectOnlyCreatedEvent(key1);
// Now expire both
ts0.advance(TimeUnit.MINUTES.toMillis(10) + 1);
ts1.advance(TimeUnit.MINUTES.toMillis(10) + 1);
assertNull(remote.get(key0));
allEvents.expectOnlyExpiredEvent(key0);
l.expectNoEvents();
assertNull(remote.get(key1));
allEvents.expectOnlyExpiredEvent(key1);
l.expectOnlyExpiredEvent(key1);
});
});
}
public void testConversionInCluster() {
final Integer key0 = HotRodClientTestingUtil.getIntKeyForServer(server(0));
final Integer key1 = HotRodClientTestingUtil.getIntKeyForServer(server(1));
final StaticCustomEventLogListener<Integer> l = new StaticCustomEventLogListener<>(client(0).getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
remote.put(key0, "one", 10, TimeUnit.MINUTES);
l.expectCreatedEvent(new CustomEvent(key0, "one", 0));
remote.put(key1, "two", 10, TimeUnit.MINUTES);
l.expectCreatedEvent(new CustomEvent(key1, "two", 0));
// Now expire both
ts0.advance(TimeUnit.MINUTES.toMillis(10) + 1);
ts1.advance(TimeUnit.MINUTES.toMillis(10) + 1);
assertNull(remote.get(key0));
l.expectExpiredEvent(new CustomEvent(key0, "one", 0));
assertNull(remote.get(key1));
l.expectExpiredEvent(new CustomEvent(key1, "two", 0));
});
}
public void testFilterCustomEventsInCluster() {
final Integer key0 = HotRodClientTestingUtil.getIntKeyForServer(server(0));
final Integer key1 = HotRodClientTestingUtil.getIntKeyForServer(server(1));
final FilterCustomEventLogListener<Integer> l = new FilterCustomEventLogListener<>(client(0).getCache());
withClientListener(l, new Object[]{key0}, null, remote -> {
remote.put(key0, "one", 10, TimeUnit.MINUTES);
l.expectCreatedEvent(new CustomEvent(key0, null, 1));
remote.put(key1, "two", 10, TimeUnit.MINUTES);
l.expectCreatedEvent(new CustomEvent(key1, "two", 1));
// Now expire both
ts0.advance(TimeUnit.MINUTES.toMillis(10) + 1);
ts1.advance(TimeUnit.MINUTES.toMillis(10) + 1);
assertNull(remote.get(key0));
l.expectExpiredEvent(new CustomEvent(key0, null, 2));
assertNull(remote.get(key1));
l.expectExpiredEvent(new CustomEvent(key1, "two", 2));
});
}
public void testNullValueMetadataExpiration() {
final Integer key = HotRodClientTestingUtil.getIntKeyForServer(server(0));
final EventLogListener<Integer> l = new EventLogListener<>(client(0).getCache());
withClientListener(l, remote -> {
Cache<Integer, String> cache0 = cache(0);
CacheNotifier notifier = cache0.getAdvancedCache().getComponentRegistry().getComponent(CacheNotifier.class);
byte[] keyBytes = HotRodClientTestingUtil.toBytes(key);
// Note we are manually forcing an expiration event with a null value and metadata
notifier.notifyCacheEntryExpired(keyBytes, null, null, null);
l.expectOnlyExpiredEvent(key);
});
}
}
| 7,967
| 44.531429
| 117
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/JsonKeyValueRawEventsTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM_TYPE;
import static org.testng.Assert.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import java.nio.ByteBuffer;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.DataFormat;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.commons.marshall.UTF8StringMarshaller;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.data.Person;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.util.KeyValuePair;
import org.testng.annotations.Test;
/**
* Test for receiving events in different formats when using a converter.
*
* @since 9.4
*/
@Test(groups = {"functional",}, testName = "client.hotrod.event.JsonKeyValueRawEventsTest")
public class JsonKeyValueRawEventsTest extends SingleHotRodServerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.encoding().key().mediaType(APPLICATION_PROTOSTREAM_TYPE);
builder.encoding().value().mediaType(APPLICATION_PROTOSTREAM_TYPE);
return TestCacheManagerFactory.createCacheManager(contextInitializer(), builder);
}
@Override
protected SerializationContextInitializer contextInitializer() {
return TestDataSCI.INSTANCE;
}
public void testReceiveKeyValuesAsJson() throws InterruptedException {
BlockingQueue<KeyValuePair<String, String>> eventsQueue = new LinkedBlockingQueue<>();
DataFormat jsonValues = DataFormat.builder().valueType(APPLICATION_JSON)
.valueMarshaller(new UTF8StringMarshaller()).build();
RemoteCache<String, Person> cache = remoteCacheManager.getCache();
RemoteCache<String, String> jsonCache = cache.withDataFormat(jsonValues);
jsonCache.addClientListener(new EventListener(eventsQueue, jsonCache.getDataFormat()));
cache.put("1", new Person("John"));
KeyValuePair<String, String> event = eventsQueue.poll(5, TimeUnit.SECONDS);
assertNotNull(event);
assertEquals(event.getKey(), "1");
assertEquals(event.getValue(), "{\"_type\":\"org.infinispan.test.core.Person\",\"name\":\"John\",\"accepted_tos\":false,\"moneyOwned\":1.1,\"moneyOwed\":0.4,\"decimalField\":10.3,\"realField\":4.7}");
}
@ClientListener(converterFactoryName = "___eager-key-value-version-converter", useRawData = true)
static class EventListener {
private final Queue<KeyValuePair<String, String>> eventsQueue;
private final DataFormat dataFormat;
EventListener(Queue<KeyValuePair<String, String>> eventsQueue, DataFormat dataFormat) {
this.eventsQueue = eventsQueue;
this.dataFormat = dataFormat;
}
@ClientCacheEntryCreated
@ClientCacheEntryModified
public void handleCreatedModifiedEvent(ClientCacheEntryCustomEvent<byte[]> event) {
eventsQueue.add(readEvent(event));
}
private KeyValuePair<String, String> readEvent(ClientCacheEntryCustomEvent<byte[]> event) {
byte[] eventData = event.getEventData();
ByteBuffer rawData = ByteBuffer.wrap(eventData);
byte[] rawKey = readElement(rawData);
byte[] rawValue = readElement(rawData);
return new KeyValuePair<>(dataFormat.keyToObj(rawKey, null), dataFormat.valueToObj(rawValue, null));
}
private byte[] readElement(ByteBuffer buffer) {
int length = UnsignedNumeric.readUnsignedInt(buffer);
byte[] element = new byte[length];
buffer.get(element);
return element;
}
}
}
| 4,415
| 40.660377
| 206
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/StickyServerLoadBalancingStrategy.java
|
package org.infinispan.client.hotrod.event;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Collection;
import java.util.Set;
import org.infinispan.client.hotrod.FailoverRequestBalancingStrategy;
import org.infinispan.client.hotrod.impl.transport.tcp.RoundRobinBalancingStrategy;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
public class StickyServerLoadBalancingStrategy implements FailoverRequestBalancingStrategy {
static Log log = LogFactory.getLog(StickyServerLoadBalancingStrategy.class);
private InetSocketAddress stickyServer;
private final RoundRobinBalancingStrategy delegate = new RoundRobinBalancingStrategy();
@Override
public void setServers(Collection<SocketAddress> servers) {
log.info("Set servers: " + servers);
delegate.setServers(servers);
stickyServer = (InetSocketAddress) servers.iterator().next();
}
@Override
public SocketAddress nextServer(Set<SocketAddress> failedServers) {
if (failedServers != null && !failedServers.isEmpty())
return delegate.nextServer(failedServers);
else {
log.info("Select " + stickyServer + " for load balancing");
return stickyServer;
}
}
}
| 1,267
| 34.222222
| 92
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/ClientClusterFailoverEventsTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.findServerAndKill;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.ControlledTimeService;
import org.infinispan.commons.time.TimeService;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.event.ClientClusterFailoverEventsTest")
public class ClientClusterFailoverEventsTest extends MultiHotRodServersTest {
protected ControlledTimeService ts0;
protected ControlledTimeService ts1;
@Override
protected void createCacheManagers() throws Throwable {
// Empty
}
private void injectTimeServices() {
ts0 = new ControlledTimeService();
TestingUtil.replaceComponent(server(0).getCacheManager(), TimeService.class, ts0, true);
ts1 = new ControlledTimeService();
TestingUtil.replaceComponent(server(1).getCacheManager(), TimeService.class, ts1, true);
}
public void testEventReplayWithAndWithoutStateAfterFailover() {
ConfigurationBuilder base = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
//base.clustering().hash().numOwners(1);
ConfigurationBuilder builder = hotRodCacheConfiguration(base);
createHotRodServers(2, builder);
injectTimeServices();
try {
final Integer key00 = HotRodClientTestingUtil.getIntKeyForServer(server(0));
final Integer key10 = HotRodClientTestingUtil.getIntKeyForServer(server(0));
final Integer key11 = HotRodClientTestingUtil.getIntKeyForServer(server(1));
final Integer key21 = HotRodClientTestingUtil.getIntKeyForServer(server(1));
final Integer key31 = HotRodClientTestingUtil.getIntKeyForServer(server(1));
final Integer key41 = HotRodClientTestingUtil.getIntKeyForServer(server(1));
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
HotRodServer server = server(0);
clientBuilder.addServers(server.getHost() + ":" + server.getPort());
clientBuilder.balancingStrategy(StickyServerLoadBalancingStrategy.class);
RemoteCacheManager newClient = new RemoteCacheManager(clientBuilder.build());
try {
RemoteCache<Integer, String> c = newClient.getCache();
WithStateEventLogListener<Integer> statefulListener = new WithStateEventLogListener<>(c);
EventLogListener<Integer> statelessListener = new EventLogListener<>(c);
FailoverEventLogListener<Integer> failoverListener = new FailoverEventLogListener<>(c);
c.addClientListener(statelessListener);
c.addClientListener(statefulListener);
c.addClientListener(failoverListener);
c.put(key00, "zero");
statefulListener.expectOnlyCreatedEvent(key00);
statelessListener.expectOnlyCreatedEvent(key00);
failoverListener.expectOnlyCreatedEvent(key00);
c.put(key10, "one", 1000, TimeUnit.MILLISECONDS);
statefulListener.expectOnlyCreatedEvent(key10);
statelessListener.expectOnlyCreatedEvent(key10);
failoverListener.expectOnlyCreatedEvent(key10);
c.put(key11, "two");
statefulListener.expectOnlyCreatedEvent(key11);
statelessListener.expectOnlyCreatedEvent(key11);
failoverListener.expectOnlyCreatedEvent(key11);
c.put(key41, "three", 1000, TimeUnit.MILLISECONDS);
statefulListener.expectOnlyCreatedEvent(key41);
statelessListener.expectOnlyCreatedEvent(key41);
failoverListener.expectOnlyCreatedEvent(key41);
ts0.advance(1001);
ts1.advance(1001);
findServerAndKill(newClient, servers, cacheManagers);
// The failover is asynchronous, triggered by closing the channels. If we did an operation right
// now we could get this event.
// c.put(key21, "four");
// Failover expectations
statelessListener.expectNoEvents();
statefulListener.expectFailoverEvent();
failoverListener.expectFailoverEvent();
// State expectations
statelessListener.expectNoEvents();
failoverListener.expectNoEvents();
//we should receive CLIENT_CACHE_ENTRY_CREATED only for entries that did not expire
statefulListener.expectUnorderedEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED, key00, key11);
//now there should be no events for key10 and key41 as they expired
statefulListener.expectNoEvents();
c.put(key31, "five");
statefulListener.expectUnorderedEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED, key31);
c.remove(key11);
c.remove(key21);
c.remove(key31);
} finally {
killRemoteCacheManager(newClient);
}
} finally {
destroy();
}
}
@ClientListener(includeCurrentState = true)
public static class WithStateEventLogListener<K> extends FailoverEventLogListener<K> {
public WithStateEventLogListener(RemoteCache<K, ?> remote) {
super(remote);
}
}
}
| 6,005
| 47.829268
| 110
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/CustomEventLogListener.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.test.TestingUtil.assertAnyEquals;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryExpired;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.filter.NamedFactory;
import org.infinispan.metadata.Metadata;
import org.infinispan.notifications.cachelistener.filter.AbstractCacheEventFilterConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverterFactory;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverterFactory;
import org.infinispan.notifications.cachelistener.filter.EventType;
import org.infinispan.protostream.WrappedMessage;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
@ClientListener(converterFactoryName = "test-converter-factory")
public abstract class CustomEventLogListener<K, E> implements RemoteCacheSupplier<K> {
BlockingQueue<E> createdCustomEvents = new ArrayBlockingQueue<>(128);
BlockingQueue<E> modifiedCustomEvents = new ArrayBlockingQueue<>(128);
BlockingQueue<E> removedCustomEvents = new ArrayBlockingQueue<>(128);
BlockingQueue<E> expiredCustomEvents = new ArrayBlockingQueue<>(128);
private final RemoteCache<K, ?> remote;
protected CustomEventLogListener(RemoteCache<K, ?> remote) {
this.remote = remote;
}
@Override
@SuppressWarnings("unchecked")
public <V> RemoteCache<K, V> get() {
return (RemoteCache<K, V>) remote;
}
public E pollEvent(ClientEvent.Type type) {
try {
E event = queue(type).poll(10, TimeUnit.SECONDS);
assertNotNull(event);
return event;
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}
protected BlockingQueue<E> queue(ClientEvent.Type type) {
switch (type) {
case CLIENT_CACHE_ENTRY_CREATED: return createdCustomEvents;
case CLIENT_CACHE_ENTRY_MODIFIED: return modifiedCustomEvents;
case CLIENT_CACHE_ENTRY_REMOVED: return removedCustomEvents;
case CLIENT_CACHE_ENTRY_EXPIRED: return expiredCustomEvents;
default: throw new IllegalArgumentException("Unknown event type: " + type);
}
}
public void expectNoEvents(ClientEvent.Type type) {
assertEquals(0, queue(type).size());
}
public void expectNoEvents() {
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED);
}
public void expectSingleCustomEvent(ClientEvent.Type type, E expected) {
E event = pollEvent(type);
assertAnyEquals(expected, event);
}
public void expectCreatedEvent(E expected) {
expectSingleCustomEvent(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED, expected);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED);
}
public void expectModifiedEvent(E expected) {
expectSingleCustomEvent(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED, expected);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED);
}
public void expectRemovedEvent(E expected) {
expectSingleCustomEvent(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED, expected);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED);
}
public void expectExpiredEvent(E expected) {
expectSingleCustomEvent(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED, expected);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED);
}
@ClientCacheEntryCreated
@SuppressWarnings("unused")
public void handleCustomCreatedEvent(ClientCacheEntryCustomEvent<E> e) {
assertEquals(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED, e.getType());
createdCustomEvents.add(e.getEventData());
}
@ClientCacheEntryModified
@SuppressWarnings("unused")
public void handleCustomModifiedEvent(ClientCacheEntryCustomEvent<E> e) {
assertEquals(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED, e.getType());
modifiedCustomEvents.add(e.getEventData());
}
@ClientCacheEntryRemoved
@SuppressWarnings("unused")
public void handleCustomRemovedEvent(ClientCacheEntryCustomEvent<E> e) {
assertEquals(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED, e.getType());
removedCustomEvents.add(e.getEventData());
}
@ClientCacheEntryExpired
@SuppressWarnings("unused")
public void handleCustomExpiredEvent(ClientCacheEntryCustomEvent<E> e) {
assertEquals(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED, e.getType());
expiredCustomEvents.add(e.getEventData());
}
public static final class CustomEvent<K> {
@ProtoField(1)
final WrappedMessage key;
@ProtoField(2)
final String value;
@ProtoField(number = 3, defaultValue = "-1")
final long timestamp;
@ProtoField(number = 4, defaultValue = "0")
final int counter;
public CustomEvent(K key, String value, int counter) {
this(new WrappedMessage(key), value, System.nanoTime(), counter);
}
@ProtoFactory
CustomEvent(WrappedMessage key, String value, long timestamp, int counter) {
this.key = key;
this.value = value;
this.timestamp = timestamp;
this.counter = counter;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomEvent<?> that = (CustomEvent<?>) o;
if (counter != that.counter) return false;
if (!key.getValue().equals(that.key.getValue())) return false;
return Objects.equals(value, that.value);
}
@Override
public int hashCode() {
int result = key.getValue().hashCode();
result = 31 * result + (value != null ? value.hashCode() : 0);
result = 31 * result + counter;
return result;
}
@Override
public String toString() {
return "CustomEvent{" +
"key=" + key.getValue() +
", value='" + value + '\'' +
", timestamp=" + timestamp +
", counter=" + counter +
'}';
}
}
@ClientListener(converterFactoryName = "static-converter-factory")
public static class StaticCustomEventLogListener<K> extends CustomEventLogListener<K, CustomEvent> {
public StaticCustomEventLogListener(RemoteCache<K, ?> r) { super(r); }
@Override
public void expectSingleCustomEvent(ClientEvent.Type type, CustomEvent expected) {
CustomEvent event = pollEvent(type);
assertNotNull(event.key);
assertNotNull(event.timestamp); // check only custom field, value can be null
assertAnyEquals(expected, event);
}
public void expectOrderedEventQueue(ClientEvent.Type type) {
BlockingQueue<CustomEvent> queue = queue(type);
if (queue.size() < 2)
return;
try {
CustomEvent before = queue.poll(10, TimeUnit.SECONDS);
Iterator<CustomEvent> iter = queue.iterator();
while (iter.hasNext()) {
CustomEvent after = iter.next();
expectTimeOrdered(before, after);
before = after;
}
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}
private void expectTimeOrdered(CustomEvent before, CustomEvent after) {
assertTrue("Before timestamp=" + before.timestamp + ", after timestamp=" + after.timestamp,
before.timestamp < after.timestamp);
}
}
@ClientListener(converterFactoryName = "raw-static-converter-factory", useRawData = true)
public static class RawStaticCustomEventLogListener<K> extends CustomEventLogListener<K, byte[]> {
public RawStaticCustomEventLogListener(RemoteCache<K, ?> r) { super(r); }
}
@ClientListener(converterFactoryName = "static-converter-factory", includeCurrentState = true)
public static class StaticCustomEventLogWithStateListener<K> extends CustomEventLogListener<K, CustomEvent> {
public StaticCustomEventLogWithStateListener(RemoteCache<K, ?> r) { super(r); }
}
@ClientListener(converterFactoryName = "dynamic-converter-factory")
public static class DynamicCustomEventLogListener<K> extends CustomEventLogListener<K, CustomEvent> {
public DynamicCustomEventLogListener(RemoteCache<K, ?> r) { super(r); }
}
@ClientListener(converterFactoryName = "dynamic-converter-factory", includeCurrentState = true)
public static class DynamicCustomEventWithStateLogListener<K> extends CustomEventLogListener<K, CustomEvent> {
public DynamicCustomEventWithStateLogListener(RemoteCache<K, ?> r) { super(r); }
}
@ClientListener(converterFactoryName = "simple-converter-factory")
public static class SimpleListener<K> extends CustomEventLogListener<K, String> {
public SimpleListener(RemoteCache<K, ?> r) {
super(r);
}
}
@NamedFactory(name = "simple-converter-factory")
static class SimpleConverterFactory<K> implements CacheEventConverterFactory {
@Override
@SuppressWarnings("unchecked")
public CacheEventConverter<String, String, CustomEvent> getConverter(Object[] params) {
return new SimpleConverter();
}
@ProtoName("SimpleConverter")
static class SimpleConverter<K> implements CacheEventConverter<K, String, String>, Serializable {
@Override
public String convert(K key, String oldValue, Metadata oldMetadata, String newValue, Metadata newMetadata, EventType eventType) {
if (newValue != null) return newValue;
return oldValue;
}
}
}
@NamedFactory(name = "static-converter-factory")
public static class StaticConverterFactory<K> implements CacheEventConverterFactory {
@Override
public CacheEventConverter<K, String, CustomEvent> getConverter(Object[] params) {
return new StaticConverter<>();
}
@ProtoName("StaticConverter")
static class StaticConverter<K> implements CacheEventConverter<K, String, CustomEvent>, Serializable {
@Override
public CustomEvent convert(K key, String previousValue, Metadata previousMetadata, String value,
Metadata metadata, EventType eventType) {
return new CustomEvent<>(key, value, 0);
}
}
}
@NamedFactory(name = "dynamic-converter-factory")
public static class DynamicConverterFactory<K> implements CacheEventConverterFactory {
@Override
public CacheEventConverter<K, String, CustomEvent> getConverter(final Object[] params) {
return new DynamicConverter<>(params);
}
static class DynamicConverter<K> implements CacheEventConverter<K, String, CustomEvent>, Serializable {
private final Object[] params;
public DynamicConverter(Object[] params) {
this.params = params;
}
@ProtoFactory
DynamicConverter(ArrayList<WrappedMessage> wrappedParams) {
this.params = wrappedParams == null ? null : wrappedParams.stream().map(WrappedMessage::getValue).toArray();
}
@ProtoField(number = 1, collectionImplementation = ArrayList.class)
List<WrappedMessage> getWrappedParams() {
return Arrays.stream(params).map(WrappedMessage::new).collect(Collectors.toList());
}
@Override
public CustomEvent convert(K key, String previousValue, Metadata previousMetadata, String value,
Metadata metadata, EventType eventType) {
if (params[0].equals(key))
return new CustomEvent<>(key, null, 0);
return new CustomEvent<>(key, value, 0);
}
}
}
@NamedFactory(name = "raw-static-converter-factory")
public static class RawStaticConverterFactory implements CacheEventConverterFactory {
@Override
public CacheEventConverter<byte[], byte[], byte[]> getConverter(Object[] params) {
return new RawStaticConverter();
}
@ProtoName("RawStaticConverter")
static class RawStaticConverter implements CacheEventConverter<byte[], byte[], byte[]>, Serializable {
@Override
public byte[] convert(byte[] key, byte[] previousValue, Metadata previousMetadata, byte[] value,
Metadata metadata, EventType eventType) {
return value != null ? concat(key, value) : key;
}
}
}
@NamedFactory(name = "filter-converter-factory")
public static class FilterConverterFactory implements CacheEventFilterConverterFactory {
@Override
public CacheEventFilterConverter<Integer, String, CustomEvent> getFilterConverter(Object[] params) {
return new FilterConverter(params);
}
static class FilterConverter extends AbstractCacheEventFilterConverter<Integer, String, CustomEvent> {
private final Object[] params;
@ProtoField(number = 1, defaultValue = "0")
int count;
FilterConverter(Object[] params) {
this.params = params;
this.count = 0;
}
@ProtoFactory
FilterConverter(List<WrappedMessage> wrappedParams, int count) {
this.params = wrappedParams == null ? null : wrappedParams.stream().map(WrappedMessage::getValue).toArray();
this.count = count;
}
@ProtoField(number = 2, collectionImplementation = ArrayList.class)
List<WrappedMessage> getWrappedParams() {
return Arrays.stream(params).map(WrappedMessage::new).collect(Collectors.toList());
}
@Override
public CustomEvent filterAndConvert(Integer key, String oldValue, Metadata oldMetadata,
String newValue, Metadata newMetadata, EventType eventType) {
count++;
if (params[0].equals(key))
return new CustomEvent<>(key, null, count);
return new CustomEvent<>(key, newValue, count);
}
}
}
@ClientListener(filterFactoryName = "filter-converter-factory", converterFactoryName = "filter-converter-factory")
public static class FilterCustomEventLogListener<K> extends CustomEventLogListener<K, CustomEvent> {
public FilterCustomEventLogListener(RemoteCache<K, ?> r) { super(r); }
}
static byte[] concat(byte[] a, byte[] b) {
int aLen = a.length;
int bLen = b.length;
byte[] ret = new byte[aLen + bLen];
System.arraycopy(a, 0, ret, 0, aLen);
System.arraycopy(b, 0, ret, aLen, bLen);
return ret;
}
}
| 16,364
| 38.817518
| 138
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/EventLogListener.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.test.TestingUtil.assertAnyEquals;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryExpired;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.filter.NamedFactory;
import org.infinispan.metadata.Metadata;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilter;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterFactory;
import org.infinispan.notifications.cachelistener.filter.EventType;
import org.infinispan.protostream.ProtobufUtil;
import org.infinispan.protostream.WrappedMessage;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
@ClientListener
public class EventLogListener<K> implements RemoteCacheSupplier<K> {
public BlockingQueue<ClientCacheEntryCreatedEvent> createdEvents = new ArrayBlockingQueue<>(128);
public BlockingQueue<ClientCacheEntryModifiedEvent> modifiedEvents = new ArrayBlockingQueue<>(128);
public BlockingQueue<ClientCacheEntryRemovedEvent> removedEvents = new ArrayBlockingQueue<>(128);
public BlockingQueue<ClientCacheEntryExpiredEvent> expiredEvents = new ArrayBlockingQueue<>(128);
private final RemoteCache<K, ?> remote;
public EventLogListener(RemoteCache<K, ?> remote) {
this.remote = remote;
}
@Override
@SuppressWarnings("unchecked")
public <V> RemoteCache<K, V> get() {
return (RemoteCache<K, V>) remote;
}
@SuppressWarnings("unchecked")
public <E extends ClientEvent> E pollEvent(ClientEvent.Type type) {
try {
E event = (E) queue(type).poll(10, TimeUnit.SECONDS);
assertNotNull(event);
return event;
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}
@SuppressWarnings("unchecked")
public <E extends ClientEvent> BlockingQueue<E> queue(ClientEvent.Type type) {
switch (type) {
case CLIENT_CACHE_ENTRY_CREATED: return (BlockingQueue<E>) createdEvents;
case CLIENT_CACHE_ENTRY_MODIFIED: return (BlockingQueue<E>) modifiedEvents;
case CLIENT_CACHE_ENTRY_REMOVED: return (BlockingQueue<E>) removedEvents;
case CLIENT_CACHE_ENTRY_EXPIRED: return (BlockingQueue<E>) expiredEvents;
default: throw new IllegalArgumentException("Unknown event type: " + type);
}
}
@ClientCacheEntryCreated
@SuppressWarnings("unused")
public void handleCreatedEvent(ClientCacheEntryCreatedEvent e) {
createdEvents.add(e);
}
@ClientCacheEntryModified @SuppressWarnings("unused")
public void handleModifiedEvent(ClientCacheEntryModifiedEvent e) {
modifiedEvents.add(e);
}
@ClientCacheEntryRemoved @SuppressWarnings("unused")
public void handleRemovedEvent(ClientCacheEntryRemovedEvent e) {
removedEvents.add(e);
}
@ClientCacheEntryExpired @SuppressWarnings("unused")
public void handleExpiredEvent(ClientCacheEntryExpiredEvent e) {
expiredEvents.add(e);
}
public void expectNoEvents() {
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED);
}
public void expectNoEvents(ClientEvent.Type type) {
switch (type) {
case CLIENT_CACHE_ENTRY_CREATED:
assertEquals(createdEvents.toString(), 0, createdEvents.size());
break;
case CLIENT_CACHE_ENTRY_MODIFIED:
assertEquals(modifiedEvents.toString(), 0, modifiedEvents.size());
break;
case CLIENT_CACHE_ENTRY_REMOVED:
assertEquals(removedEvents.toString(), 0, removedEvents.size());
break;
case CLIENT_CACHE_ENTRY_EXPIRED:
assertEquals(expiredEvents.toString(), 0, expiredEvents.size());
break;
}
}
public void expectOnlyCreatedEvent(K key) {
expectSingleEvent(key, ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED);
}
public void expectOnlyModifiedEvent(K key) {
expectSingleEvent(key, ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED);
}
public void expectOnlyRemovedEvent(K key) {
expectSingleEvent(key, ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED);
}
public void expectOnlyExpiredEvent(K key) {
expectSingleEvent(key, ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED);
expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED);
}
public void expectSingleEvent(K key, ClientEvent.Type type) {
switch (type) {
case CLIENT_CACHE_ENTRY_CREATED:
ClientCacheEntryCreatedEvent createdEvent = pollEvent(type);
assertAnyEquals(key, createdEvent.getKey());
assertAnyEquals(serverDataVersion(remote, key), createdEvent.getVersion());
break;
case CLIENT_CACHE_ENTRY_MODIFIED:
ClientCacheEntryModifiedEvent modifiedEvent = pollEvent(type);
assertAnyEquals(key, modifiedEvent.getKey());
assertAnyEquals(serverDataVersion(remote, key), modifiedEvent.getVersion());
break;
case CLIENT_CACHE_ENTRY_REMOVED:
ClientCacheEntryRemovedEvent removedEvent = pollEvent(type);
assertAnyEquals(key, removedEvent.getKey());
break;
case CLIENT_CACHE_ENTRY_EXPIRED:
ClientCacheEntryExpiredEvent expiredEvent = pollEvent(type);
assertAnyEquals(key, expiredEvent.getKey());
break;
}
assertEquals(0, queue(type).size());
}
private long serverDataVersion(RemoteCache<K, ?> cache, K key) {
return cache.getWithMetadata(key).getVersion();
}
public void expectUnorderedEvents(ClientEvent.Type type, K... keys) {
List<K> assertedKeys = new ArrayList<>();
for (int i = 0; i < keys.length; i++) {
ClientEvent event = pollEvent(type);
int initialSize = assertedKeys.size();
for (K key : keys) {
K eventKey = null;
switch (event.getType()) {
case CLIENT_CACHE_ENTRY_CREATED:
eventKey = ((ClientCacheEntryCreatedEvent<K>) event).getKey();
break;
case CLIENT_CACHE_ENTRY_MODIFIED:
eventKey = ((ClientCacheEntryModifiedEvent<K>) event).getKey();
break;
case CLIENT_CACHE_ENTRY_REMOVED:
eventKey = ((ClientCacheEntryRemovedEvent<K>) event).getKey();
break;
case CLIENT_CACHE_ENTRY_EXPIRED:
eventKey = ((ClientCacheEntryExpiredEvent<K>) event).getKey();
break;
}
checkUnorderedKeyEvent(assertedKeys, key, eventKey);
}
int finalSize = assertedKeys.size();
assertEquals(initialSize + 1, finalSize);
}
}
private boolean checkUnorderedKeyEvent(List<K> assertedKeys, K key, K eventKey) {
if (key.equals(eventKey)) {
assertFalse(assertedKeys.contains(key));
assertedKeys.add(key);
return true;
}
return false;
}
public void expectFailoverEvent() {
pollEvent(ClientEvent.Type.CLIENT_CACHE_FAILOVER);
}
@ClientListener(filterFactoryName = "static-filter-factory")
public static class StaticFilteredEventLogListener<K> extends EventLogListener<K> {
public StaticFilteredEventLogListener(RemoteCache<K, ?> r) { super(r); }
}
@ClientListener(filterFactoryName = "raw-static-filter-factory", useRawData = true)
public static class RawStaticFilteredEventLogListener<K> extends EventLogListener<K> {
public RawStaticFilteredEventLogListener(RemoteCache<K, ?> r) { super(r); }
}
@ClientListener(filterFactoryName = "static-filter-factory", includeCurrentState = true)
public static class StaticFilteredEventLogWithStateListener<K> extends EventLogListener<K> {
public StaticFilteredEventLogWithStateListener(RemoteCache<K, ?> r) { super(r); }
}
@ClientListener(filterFactoryName = "dynamic-filter-factory")
public static class DynamicFilteredEventLogListener<K> extends EventLogListener<K> {
public DynamicFilteredEventLogListener(RemoteCache<K, ?> r) { super(r); }
}
@ClientListener(filterFactoryName = "dynamic-filter-factory", includeCurrentState = true)
public static class DynamicFilteredEventLogWithStateListener<K> extends EventLogListener<K> {
public DynamicFilteredEventLogWithStateListener(RemoteCache<K, ?> r) { super(r); }
}
@NamedFactory(name = "static-filter-factory")
public static class StaticCacheEventFilterFactory<K> implements CacheEventFilterFactory {
private final K staticKey;
public StaticCacheEventFilterFactory(K staticKey) {
this.staticKey = staticKey;
}
@Override
public CacheEventFilter<K, String> getFilter(Object[] params) {
return new StaticCacheEventFilter<>(staticKey);
}
static class StaticCacheEventFilter<K> implements CacheEventFilter<K, String>, Serializable {
final K staticKey;
StaticCacheEventFilter(K staticKey) {
this.staticKey = staticKey;
}
@ProtoFactory
StaticCacheEventFilter(WrappedMessage staticKey) {
this.staticKey = (K) staticKey.getValue();
}
@ProtoField(1)
public WrappedMessage getStaticKey() {
return new WrappedMessage(staticKey);
}
@Override
public boolean accept(K key, String previousValue, Metadata previousMetadata, String value,
Metadata metadata, EventType eventType) {
return staticKey.equals(key);
}
}
}
@NamedFactory(name = "dynamic-filter-factory")
public static class DynamicCacheEventFilterFactory implements CacheEventFilterFactory {
@Override
public CacheEventFilter<Integer, String> getFilter(Object[] params) {
return new DynamicCacheEventFilter(params);
}
static class DynamicCacheEventFilter implements CacheEventFilter<Integer, String>, Serializable {
private final Object[] params;
public DynamicCacheEventFilter(Object[] params) {
this.params = params;
}
@ProtoFactory
DynamicCacheEventFilter(ArrayList<WrappedMessage> wrappedParams) {
this.params = wrappedParams == null ? null : wrappedParams.stream().map(WrappedMessage::getValue).toArray();
}
@ProtoField(number = 1, collectionImplementation = ArrayList.class)
List<WrappedMessage> getWrappedParams() {
return Arrays.stream(params).map(WrappedMessage::new).collect(Collectors.toList());
}
@Override
public boolean accept(Integer key, String previousValue, Metadata previousMetadata, String value,
Metadata metadata, EventType eventType) {
return params[0].equals(key); // dynamic
}
}
}
@NamedFactory(name = "raw-static-filter-factory")
public static class RawStaticCacheEventFilterFactory implements CacheEventFilterFactory {
@Override
public CacheEventFilter<byte[], byte[]> getFilter(Object[] params) {
try {
// Static key is 2 marshalled
byte[] staticKey = ProtobufUtil.toWrappedByteArray(ProtobufUtil.newSerializationContext(), 2);
return new RawStaticCacheEventFilter(staticKey);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@ProtoName("RawStaticCacheEventFilter")
static class RawStaticCacheEventFilter implements CacheEventFilter<byte[], byte[]>, Serializable {
@ProtoField(1)
final byte[] staticKey;
@ProtoFactory
RawStaticCacheEventFilter(byte[] staticKey) {
this.staticKey = staticKey;
}
@Override
public boolean accept(byte[] key, byte[] previousValue, Metadata previousMetadata, byte[] value,
Metadata metadata, EventType eventType) {
return Arrays.equals(key, staticKey);
}
}
}
}
| 13,837
| 39.110145
| 120
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/EventSocketTimeoutTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withClientListener;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import java.net.SocketTimeoutException;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.SocketTimeoutErrorTest.TimeoutInducingInterceptor;
import org.infinispan.client.hotrod.exceptions.TransportException;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.interceptors.impl.EntryWrappingInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.event.EventSocketTimeoutTest")
public class EventSocketTimeoutTest extends SingleHotRodServerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.customInterceptors().addInterceptor().interceptor(
new TimeoutInducingInterceptor()).after(EntryWrappingInterceptor.class);
return TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration(builder));
}
@Override
protected HotRodServer createHotRodServer() {
HotRodServerConfigurationBuilder builder = new HotRodServerConfigurationBuilder();
return HotRodClientTestingUtil.startHotRodServer(cacheManager, builder);
}
@Override
protected RemoteCacheManager getRemoteCacheManager() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer().host(hotrodServer.getHost()).port(hotrodServer.getPort());
builder.socketTimeout(1000);
builder.maxRetries(0);
return new RemoteCacheManager(builder.build());
}
public void testSocketTimeoutWithEvent() {
final EventLogListener<String> l = new EventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
remote.put("uno", 1);
l.expectOnlyCreatedEvent("uno");
Exceptions.expectException(TransportException.class, SocketTimeoutException.class, () -> remote.put("FailFailFail", 99));
l.expectNoEvents();
remote.put("dos", 2);
l.expectOnlyCreatedEvent("dos");
});
}
}
| 2,824
| 43.84127
| 130
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/RemoteContinuousQueryTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
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.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.Search;
import org.infinispan.client.hotrod.exceptions.HotRodClientException;
import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB;
import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.time.TimeService;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.query.api.continuous.ContinuousQuery;
import org.infinispan.query.api.continuous.ContinuousQueryListener;
import org.infinispan.query.dsl.Query;
import org.infinispan.query.dsl.QueryFactory;
import org.infinispan.query.dsl.embedded.testdomain.User;
import org.infinispan.query.remote.impl.filter.IckleContinuousQueryProtobufCacheEventFilterConverterFactory;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.ControlledTimeService;
import org.infinispan.util.KeyValuePair;
import org.testng.annotations.Test;
/**
* Test remote continuous query.
*
* @author anistor@redhat.com
* @since 8.0
*/
@Test(groups = "functional", testName = "client.hotrod.event.RemoteContinuousQueryTest")
public class RemoteContinuousQueryTest extends MultiHotRodServersTest {
private static final int NUM_NODES = 5;
private RemoteCache<String, User> remoteCache;
private final ControlledTimeService timeService = new ControlledTimeService();
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfgBuilder = getConfigurationBuilder();
createHotRodServers(NUM_NODES, cfgBuilder);
waitForClusterToForm();
// Register the filter/converter factory. This should normally be discovered by the server via class path instead
// of being added manually here, but this is ok in a test.
IckleContinuousQueryProtobufCacheEventFilterConverterFactory factory = new IckleContinuousQueryProtobufCacheEventFilterConverterFactory();
for (int i = 0; i < NUM_NODES; i++) {
server(i).addCacheEventFilterConverterFactory(IckleContinuousQueryProtobufCacheEventFilterConverterFactory.FACTORY_NAME, factory);
TestingUtil.replaceComponent(server(i).getCacheManager(), TimeService.class, timeService, true);
}
remoteCache = client(0).getCache();
}
@Override
protected SerializationContextInitializer contextInitializer() {
return TestDomainSCI.INSTANCE;
}
protected ConfigurationBuilder getConfigurationBuilder() {
ConfigurationBuilder cfgBuilder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
cfgBuilder.indexing().enable()
.storage(LOCAL_HEAP)
.addIndexedEntity("sample_bank_account.User");
cfgBuilder.expiration().disableReaper();
return cfgBuilder;
}
/**
* Using grouping and aggregation with continuous query is not allowed.
*/
@Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN028509:.*")
public void testDisallowGroupingAndAggregation() {
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<User> query = qf.create("SELECT MAX(age) FROM sample_bank_account.User WHERE age >= 20");
ContinuousQuery<String, User> continuousQuery = Search.getContinuousQuery(remoteCache);
ContinuousQueryListener<String, Object[]> listener = new ContinuousQueryListener<String, Object[]>() {
};
continuousQuery.addContinuousQueryListener(query, listener);
}
public void testContinuousQuery() {
User user1 = new UserPB();
user1.setId(1);
user1.setName("John");
user1.setSurname("Doe");
user1.setGender(User.Gender.MALE);
user1.setAge(22);
user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2)));
user1.setNotes("Lorem ipsum dolor sit amet");
User user2 = new UserPB();
user2.setId(2);
user2.setName("Spider");
user2.setSurname("Man");
user2.setGender(User.Gender.MALE);
user2.setAge(32);
user2.setAccountIds(Collections.singleton(3));
User user3 = new UserPB();
user3.setId(3);
user3.setName("Spider");
user3.setSurname("Woman");
user3.setGender(User.Gender.FEMALE);
user3.setAge(40);
remoteCache.clear();
remoteCache.put("user" + user1.getId(), user1);
remoteCache.put("user" + user2.getId(), user2);
remoteCache.put("user" + user3.getId(), user3);
assertEquals(3, remoteCache.size());
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<User> query = qf.<User>create("FROM sample_bank_account.User WHERE age <= :ageParam")
.setParameter("ageParam", 32);
final BlockingQueue<KeyValuePair<String, User>> joined = new LinkedBlockingQueue<>();
final BlockingQueue<KeyValuePair<String, User>> updated = new LinkedBlockingQueue<>();
final BlockingQueue<String> left = new LinkedBlockingQueue<>();
ContinuousQueryListener<String, User> listener = new ContinuousQueryListener<String, User>() {
@Override
public void resultJoining(String key, User value) {
joined.add(new KeyValuePair<>(key, value));
}
@Override
public void resultUpdated(String key, User value) {
updated.add(new KeyValuePair<>(key, value));
}
@Override
public void resultLeaving(String key) {
left.add(key);
}
};
ContinuousQuery<String, User> continuousQuery = Search.getContinuousQuery(remoteCache);
continuousQuery.addContinuousQueryListener(query, listener);
expectElementsInQueue(joined, 2, (kv) -> kv.getValue().getAge(), 32, 22);
expectElementsInQueue(updated, 0);
expectElementsInQueue(left, 0);
user3.setAge(30);
remoteCache.put("user" + user3.getId(), user3);
expectElementsInQueue(joined, 1, (kv) -> kv.getValue().getAge(), 30);
expectElementsInQueue(updated, 0);
expectElementsInQueue(left, 0);
user1.setAge(23);
remoteCache.put("user" + user1.getId(), user1);
expectElementsInQueue(joined, 0);
expectElementsInQueue(updated, 1, (kv) -> kv.getValue().getAge(), 23);
expectElementsInQueue(left, 0);
user1.setAge(40);
user2.setAge(40);
user3.setAge(40);
remoteCache.put("user" + user1.getId(), user1);
remoteCache.put("user" + user2.getId(), user2);
remoteCache.put("user" + user3.getId(), user3);
expectElementsInQueue(joined, 0);
expectElementsInQueue(updated, 0);
expectElementsInQueue(left, 3);
remoteCache.clear();
user1.setAge(21);
user2.setAge(22);
remoteCache.put("expiredUser1", user1, 5, TimeUnit.MILLISECONDS);
remoteCache.put("expiredUser2", user2, 5, TimeUnit.MILLISECONDS);
expectElementsInQueue(joined, 2);
expectElementsInQueue(left, 0);
timeService.advance(6);
assertNull(remoteCache.get("expiredUser1"));
assertNull(remoteCache.get("expiredUser2"));
expectElementsInQueue(joined, 0);
expectElementsInQueue(left, 2);
continuousQuery.removeContinuousQueryListener(listener);
user2.setAge(22);
remoteCache.put("user" + user2.getId(), user2);
expectElementsInQueue(joined, 0);
expectElementsInQueue(left, 0);
}
public void testContinuousQueryWithProjections() {
User user1 = new UserPB();
user1.setId(1);
user1.setName("John");
user1.setSurname("Doe");
user1.setGender(User.Gender.MALE);
user1.setAge(22);
user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2)));
user1.setNotes("Lorem ipsum dolor sit amet");
User user2 = new UserPB();
user2.setId(2);
user2.setName("Spider");
user2.setSurname("Man");
user2.setGender(User.Gender.MALE);
user2.setAge(32);
user2.setAccountIds(Collections.singleton(3));
User user3 = new UserPB();
user3.setId(3);
user3.setName("Spider");
user3.setSurname("Woman");
user3.setGender(User.Gender.FEMALE);
user3.setAge(40);
remoteCache.clear();
remoteCache.put("user" + user1.getId(), user1);
remoteCache.put("user" + user2.getId(), user2);
remoteCache.put("user" + user3.getId(), user3);
assertEquals(3, remoteCache.size());
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<Object[]> query = qf.<Object[]>create("SELECT age FROM sample_bank_account.User WHERE age <= :ageParam")
.setParameter("ageParam", 32);
final BlockingQueue<KeyValuePair<String, Object[]>> joined = new LinkedBlockingQueue<>();
final BlockingQueue<KeyValuePair<String, Object[]>> updated = new LinkedBlockingQueue<>();
final BlockingQueue<String> left = new LinkedBlockingQueue<>();
ContinuousQueryListener<String, Object[]> listener = new ContinuousQueryListener<String, Object[]>() {
@Override
public void resultJoining(String key, Object[] value) {
joined.add(new KeyValuePair<>(key, value));
}
@Override
public void resultUpdated(String key, Object[] value) {
updated.add(new KeyValuePair<>(key, value));
}
@Override
public void resultLeaving(String key) {
left.add(key);
}
};
ContinuousQuery<String, User> continuousQuery = Search.getContinuousQuery(remoteCache);
continuousQuery.addContinuousQueryListener(query, listener);
expectElementsInQueue(joined, 2, (kv) -> kv.getValue()[0], 32, 22);
expectElementsInQueue(updated, 0);
expectElementsInQueue(left, 0);
user3.setAge(30);
remoteCache.put("user" + user3.getId(), user3);
expectElementsInQueue(joined, 1, (kv) -> kv.getValue()[0], 30);
expectElementsInQueue(updated, 0);
expectElementsInQueue(left, 0);
user1.setAge(23);
remoteCache.put("user" + user1.getId(), user1);
expectElementsInQueue(joined, 0);
expectElementsInQueue(updated, 1, (kv) -> kv.getValue()[0], 23);
expectElementsInQueue(left, 0);
user1.setAge(40);
user2.setAge(40);
user3.setAge(40);
remoteCache.put("user" + user1.getId(), user1);
remoteCache.put("user" + user2.getId(), user2);
remoteCache.put("user" + user3.getId(), user3);
expectElementsInQueue(joined, 0);
expectElementsInQueue(updated, 0);
expectElementsInQueue(left, 3);
remoteCache.clear();
user1.setAge(21);
user2.setAge(22);
remoteCache.put("expiredUser1", user1, 5, TimeUnit.MILLISECONDS);
remoteCache.put("expiredUser2", user2, 5, TimeUnit.MILLISECONDS);
expectElementsInQueue(joined, 2);
expectElementsInQueue(left, 0);
timeService.advance(6);
assertNull(remoteCache.get("expiredUser1"));
assertNull(remoteCache.get("expiredUser2"));
expectElementsInQueue(joined, 0);
expectElementsInQueue(left, 2);
continuousQuery.removeContinuousQueryListener(listener);
user2.setAge(22);
remoteCache.put("user" + user2.getId(), user2);
expectElementsInQueue(joined, 0);
expectElementsInQueue(left, 0);
}
public void testContinuousQueryChangingParameter() {
User user1 = new UserPB();
user1.setId(1);
user1.setName("John");
user1.setSurname("Doe");
user1.setGender(User.Gender.MALE);
user1.setAge(22);
user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2)));
user1.setNotes("Lorem ipsum dolor sit amet");
User user2 = new UserPB();
user2.setId(2);
user2.setName("Spider");
user2.setSurname("Man");
user2.setGender(User.Gender.MALE);
user2.setAge(32);
user2.setAccountIds(Collections.singleton(3));
User user3 = new UserPB();
user3.setId(3);
user3.setName("Spider");
user3.setSurname("Woman");
user3.setGender(User.Gender.FEMALE);
user3.setAge(40);
remoteCache.clear();
remoteCache.put("user" + user1.getId(), user1);
remoteCache.put("user" + user2.getId(), user2);
remoteCache.put("user" + user3.getId(), user3);
assertEquals(3, remoteCache.size());
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<Object[]> query = qf.<Object[]>create("SELECT age FROM sample_bank_account.User WHERE age <= :ageParam")
.setParameter("ageParam", 32);
final BlockingQueue<KeyValuePair<String, Object[]>> joined = new LinkedBlockingQueue<>();
final BlockingQueue<KeyValuePair<String, Object[]>> updated = new LinkedBlockingQueue<>();
final BlockingQueue<String> left = new LinkedBlockingQueue<>();
ContinuousQueryListener<String, Object[]> listener = new ContinuousQueryListener<String, Object[]>() {
@Override
public void resultJoining(String key, Object[] value) {
joined.add(new KeyValuePair<>(key, value));
}
@Override
public void resultUpdated(String key, Object[] value) {
updated.add(new KeyValuePair<>(key, value));
}
@Override
public void resultLeaving(String key) {
left.add(key);
}
};
ContinuousQuery<String, User> continuousQuery = Search.getContinuousQuery(remoteCache);
continuousQuery.addContinuousQueryListener(query, listener);
expectElementsInQueue(joined, 2, (kv) -> kv.getValue()[0], 32, 22);
expectElementsInQueue(updated, 0);
expectElementsInQueue(left, 0);
continuousQuery.removeContinuousQueryListener(listener);
query.setParameter("ageParam", 40);
listener = new ContinuousQueryListener<String, Object[]>() {
@Override
public void resultJoining(String key, Object[] value) {
joined.add(new KeyValuePair<>(key, value));
}
@Override
public void resultUpdated(String key, Object[] value) {
updated.add(new KeyValuePair<>(key, value));
}
@Override
public void resultLeaving(String key) {
left.add(key);
}
};
continuousQuery.addContinuousQueryListener(query, listener);
expectElementsInQueue(joined, 3);
expectElementsInQueue(updated, 0);
expectElementsInQueue(left, 0);
continuousQuery.removeContinuousQueryListener(listener);
}
private <T> void expectElementsInQueue(BlockingQueue<T> queue, int numElements) {
expectElementsInQueue(queue, numElements, null);
}
private <T, R> void expectElementsInQueue(BlockingQueue<T> queue, int numElements, Function<T, R> valueTransformer, Object... expectedValue) {
List<Object> expectedValues;
if (expectedValue.length != 0) {
if (expectedValue.length != numElements) {
throw new IllegalArgumentException("The number of expected values must either match the number of expected elements or no expected values should be specified.");
}
expectedValues = new ArrayList<>(expectedValue.length);
Collections.addAll(expectedValues, expectedValue);
} else {
expectedValues = null;
}
for (int i = 0; i < numElements; i++) {
final T o;
try {
o = queue.poll(5, TimeUnit.SECONDS);
assertNotNull("Queue was empty after reading " + i + " elements!", o);
} catch (InterruptedException e) {
throw new AssertionError("Interrupted while waiting for condition", e);
}
if (expectedValues != null) {
Object v = valueTransformer != null ? valueTransformer.apply(o) : o;
boolean found = expectedValues.remove(v);
assertTrue("Expectation failed on element number " + i + ", unexpected value: " + v, found);
}
}
try {
// no more elements expected here
Object o = queue.poll(100, TimeUnit.MILLISECONDS);
assertNull("No more elements expected in queue!", o);
} catch (InterruptedException e) {
throw new AssertionError("Interrupted while waiting for condition", e);
}
}
}
| 17,114
| 35.648822
| 173
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/RemoteListenerWithDslFilterTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.Search;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.exceptions.HotRodClientException;
import org.infinispan.client.hotrod.filter.Filters;
import org.infinispan.client.hotrod.marshall.MarshallerUtil;
import org.infinispan.client.hotrod.query.testdomain.protobuf.AddressPB;
import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB;
import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.protostream.ProtobufUtil;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.query.dsl.Query;
import org.infinispan.query.dsl.QueryFactory;
import org.infinispan.query.dsl.embedded.testdomain.Address;
import org.infinispan.query.dsl.embedded.testdomain.User;
import org.infinispan.query.remote.client.FilterResult;
import org.infinispan.query.remote.impl.filter.IckleCacheEventFilterConverterFactory;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
/**
* @author anistor@redhat.com
* @since 7.2
*/
@Test(groups = "functional", testName = "client.hotrod.event.RemoteListenerWithDslFilterTest")
public class RemoteListenerWithDslFilterTest extends MultiHotRodServersTest {
private static final int NUM_NODES = 5;
private RemoteCache<Object, Object> remoteCache;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfgBuilder = getConfigurationBuilder();
createHotRodServers(NUM_NODES, cfgBuilder);
waitForClusterToForm();
// Register the filter/converter factory. This should normally be discovered by the server via class path instead
// of being added manually here, but this is ok in a test.
IckleCacheEventFilterConverterFactory factory = new IckleCacheEventFilterConverterFactory();
for (int i = 0; i < NUM_NODES; i++) {
server(i).addCacheEventFilterConverterFactory(IckleCacheEventFilterConverterFactory.FACTORY_NAME, factory);
}
remoteCache = client(0).getCache();
}
@Override
protected SerializationContextInitializer contextInitializer() {
return TestDomainSCI.INSTANCE;
}
protected ConfigurationBuilder getConfigurationBuilder() {
ConfigurationBuilder cfgBuilder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
cfgBuilder.indexing().enable()
.storage(LOCAL_HEAP)
.addIndexedEntity("sample_bank_account.User");
return cfgBuilder;
}
public void testEventFilter() {
User user1 = new UserPB();
user1.setId(1);
user1.setName("John");
user1.setSurname("Doe");
user1.setGender(User.Gender.MALE);
user1.setAge(22);
user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2)));
user1.setNotes("Lorem ipsum dolor sit amet");
Address address1 = new AddressPB();
address1.setStreet("Main Street");
address1.setPostCode("X1234");
user1.setAddresses(Collections.singletonList(address1));
User user2 = new UserPB();
user2.setId(2);
user2.setName("Spider");
user2.setSurname("Man");
user2.setGender(User.Gender.MALE);
user2.setAge(32);
user2.setAccountIds(Collections.singleton(3));
Address address2 = new AddressPB();
address2.setStreet("Old Street");
address2.setPostCode("Y12");
Address address3 = new AddressPB();
address3.setStreet("Bond Street");
address3.setPostCode("ZZ");
user2.setAddresses(Arrays.asList(address2, address3));
User user3 = new UserPB();
user3.setId(3);
user3.setName("Spider");
user3.setSurname("Woman");
user3.setGender(User.Gender.FEMALE);
user3.setAge(31);
remoteCache.clear();
remoteCache.put("user_" + user1.getId(), user1);
remoteCache.put("user_" + user2.getId(), user2);
remoteCache.put("user_" + user3.getId(), user3);
assertEquals(3, remoteCache.size());
SerializationContext serCtx = MarshallerUtil.getSerializationContext(client(0));
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<Object[]> query = qf.<Object[]>create("SELECT age FROM sample_bank_account.User WHERE age <= :ageParam")
.setParameter("ageParam", 32);
ClientEntryListener listener = new ClientEntryListener(serCtx);
ClientEvents.addClientQueryListener(remoteCache, listener, query);
expectElementsInQueue(listener.createEvents, 3);
user3.setAge(40);
remoteCache.put("user_" + user1.getId(), user1);
remoteCache.put("user_" + user2.getId(), user2);
remoteCache.put("user_" + user3.getId(), user3);
assertEquals(3, remoteCache.size());
expectElementsInQueue(listener.modifyEvents, 2);
remoteCache.removeClientListener(listener);
}
public void testEventFilterChangingParameter() {
User user1 = new UserPB();
user1.setId(1);
user1.setName("John");
user1.setSurname("Doe");
user1.setGender(User.Gender.MALE);
user1.setAge(22);
user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2)));
user1.setNotes("Lorem ipsum dolor sit amet");
Address address1 = new AddressPB();
address1.setStreet("Main Street");
address1.setPostCode("X1234");
user1.setAddresses(Collections.singletonList(address1));
User user2 = new UserPB();
user2.setId(2);
user2.setName("Spider");
user2.setSurname("Man");
user2.setGender(User.Gender.MALE);
user2.setAge(32);
user2.setAccountIds(Collections.singleton(3));
Address address2 = new AddressPB();
address2.setStreet("Old Street");
address2.setPostCode("Y12");
Address address3 = new AddressPB();
address3.setStreet("Bond Street");
address3.setPostCode("ZZ");
user2.setAddresses(Arrays.asList(address2, address3));
User user3 = new UserPB();
user3.setId(3);
user3.setName("Spider");
user3.setSurname("Woman");
user3.setGender(User.Gender.FEMALE);
user3.setAge(31);
remoteCache.clear();
remoteCache.put("user_" + user1.getId(), user1);
remoteCache.put("user_" + user2.getId(), user2);
remoteCache.put("user_" + user3.getId(), user3);
assertEquals(3, remoteCache.size());
SerializationContext serCtx = MarshallerUtil.getSerializationContext(client(0));
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<Object[]> query = qf.<Object[]>create("SELECT age FROM sample_bank_account.User WHERE age <= :ageParam")
.setParameter("ageParam", 32);
ClientEntryListener listener = new ClientEntryListener(serCtx);
ClientEvents.addClientQueryListener(remoteCache, listener, query);
expectElementsInQueue(listener.createEvents, 3);
remoteCache.removeClientListener(listener);
query.setParameter("ageParam", 31);
listener = new ClientEntryListener(serCtx);
ClientEvents.addClientQueryListener(remoteCache, listener, query);
expectElementsInQueue(listener.createEvents, 2);
remoteCache.removeClientListener(listener);
}
/**
* Using grouping and aggregation with event filters is not allowed.
*/
@Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN028509:.*")
public void testDisallowGroupingAndAggregation() {
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<Object[]> query = qf.create("SELECT MAX(age) FROM sample_bank_account.User WHERE age >= 20");
ClientEntryListener listener = new ClientEntryListener(MarshallerUtil.getSerializationContext(client(0)));
ClientEvents.addClientQueryListener(remoteCache, listener, query);
}
/**
* Using non-raw listeners should throw an exception.
*/
@Test(expectedExceptions = IncorrectClientListenerException.class, expectedExceptionsMessageRegExp = "ISPN004058:.*")
public void testRequireRawDataListener() {
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<User> query = qf.create("FROM sample_bank_account.User WHERE age >= 20");
@ClientListener(filterFactoryName = Filters.QUERY_DSL_FILTER_FACTORY_NAME,
converterFactoryName = Filters.QUERY_DSL_FILTER_FACTORY_NAME,
useRawData = false, includeCurrentState = true)
class DummyListener {
@ClientCacheEntryCreated
public void handleClientCacheEntryCreatedEvent(ClientCacheEntryCustomEvent event) {
}
}
ClientEvents.addClientQueryListener(remoteCache, new DummyListener(), query);
}
/**
* Using non-raw listeners should throw an exception.
*/
@Test(expectedExceptions = IncorrectClientListenerException.class, expectedExceptionsMessageRegExp = "ISPN004059:.*")
public void testRequireQueryDslFilterFactoryNameForListener() {
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<User> query = qf.create("FROM sample_bank_account.User WHERE age >= 20");
@ClientListener(filterFactoryName = "some-filter-factory-name",
converterFactoryName = "some-filter-factory-name",
useRawData = true, includeCurrentState = true)
class DummyListener {
@ClientCacheEntryCreated
public void handleClientCacheEntryCreatedEvent(ClientCacheEntryCustomEvent event) {
}
}
ClientEvents.addClientQueryListener(remoteCache, new DummyListener(), query);
}
private void expectElementsInQueue(BlockingQueue<?> queue, int numElements) {
for (int i = 0; i < numElements; i++) {
try {
Object e = queue.poll(5, TimeUnit.SECONDS);
assertNotNull("Queue was empty!", e);
} catch (InterruptedException e) {
throw new AssertionError("Interrupted while waiting for condition", e);
}
}
try {
// no more elements expected here
Object e = queue.poll(100, TimeUnit.MILLISECONDS);
assertNull("No more elements expected in queue!", e);
} catch (InterruptedException e) {
throw new AssertionError("Interrupted while waiting for condition", e);
}
}
@ClientListener(filterFactoryName = Filters.QUERY_DSL_FILTER_FACTORY_NAME,
converterFactoryName = Filters.QUERY_DSL_FILTER_FACTORY_NAME,
useRawData = true, includeCurrentState = true)
private static class ClientEntryListener {
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
public final BlockingQueue<FilterResult> createEvents = new LinkedBlockingQueue<>();
public final BlockingQueue<FilterResult> modifyEvents = new LinkedBlockingQueue<>();
private final SerializationContext serializationContext;
public ClientEntryListener(SerializationContext serializationContext) {
this.serializationContext = serializationContext;
}
@ClientCacheEntryCreated
public void handleClientCacheEntryCreatedEvent(ClientCacheEntryCustomEvent event) throws IOException {
FilterResult r = ProtobufUtil.fromWrappedByteArray(serializationContext, (byte[]) event.getEventData());
createEvents.add(r);
log.debugf("handleClientCacheEntryCreatedEvent instance=%s projection=%s sortProjection=%s\n",
r.getInstance(),
r.getProjection() == null ? null : Arrays.asList(r.getProjection()),
r.getSortProjection() == null ? null : Arrays.asList(r.getSortProjection()));
}
@ClientCacheEntryModified
public void handleClientCacheEntryModifiedEvent(ClientCacheEntryCustomEvent event) throws IOException {
FilterResult r = ProtobufUtil.fromWrappedByteArray(serializationContext, (byte[]) event.getEventData());
modifyEvents.add(r);
log.debugf("handleClientCacheEntryModifiedEvent instance=%s projection=%s sortProjection=%s\n",
r.getInstance(),
r.getProjection() == null ? null : Arrays.asList(r.getProjection()),
r.getSortProjection() == null ? null : Arrays.asList(r.getSortProjection()));
}
@ClientCacheEntryRemoved
public void handleClientCacheEntryRemovedEvent(ClientCacheEntryRemovedEvent event) {
log.debugf("handleClientCacheEntryRemovedEvent %s\n", event.getKey());
}
}
}
| 13,649
| 39.868263
| 125
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/EagerKeyValueConverterTest.java
|
package org.infinispan.client.hotrod.event;
import static org.testng.AssertJUnit.assertNotNull;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.DataFormat;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.data.Person;
import org.infinispan.util.KeyValuePair;
import org.testng.annotations.Test;
/**
* Test for listener with EagerKeyValueVersionConverter
*
* @since 10.0
*/
@Test(groups = {"functional"}, testName = "client.hotrod.event.EagerKeyValueConverterTest")
public class EagerKeyValueConverterTest extends SingleHotRodServerTest {
@Override
protected SerializationContextInitializer contextInitializer() {
return TestDataSCI.INSTANCE;
}
public void testWriteMap() throws InterruptedException {
BlockingQueue<KeyValuePair<String, Person>> eventsQueue = new LinkedBlockingQueue<>();
RemoteCache<String, Person> cache = remoteCacheManager.getCache();
cache.addClientListener(new EventListener(eventsQueue, cache.getDataFormat()));
Map<String, Person> data = new HashMap<>();
data.put("1", new Person("John"));
data.put("2", new Person("Mary"));
data.put("3", new Person("George"));
cache.putAll(data);
KeyValuePair<String, Person> event = eventsQueue.poll(5, TimeUnit.SECONDS);
assertNotNull(event);
}
@ClientListener(converterFactoryName = "___eager-key-value-version-converter", useRawData = true)
static class EventListener {
private final Queue<KeyValuePair<String, Person>> eventsQueue;
private final DataFormat dataFormat;
EventListener(Queue<KeyValuePair<String, Person>> eventsQueue, DataFormat dataFormat) {
this.eventsQueue = eventsQueue;
this.dataFormat = dataFormat;
}
@ClientCacheEntryCreated
@ClientCacheEntryModified
public void handleCreatedModifiedEvent(ClientCacheEntryCustomEvent<byte[]> event) {
eventsQueue.add(readEvent(event));
}
private KeyValuePair<String, Person> readEvent(ClientCacheEntryCustomEvent<byte[]> event) {
byte[] eventData = event.getEventData();
ByteBuffer rawData = ByteBuffer.wrap(eventData);
byte[] rawKey = readElement(rawData);
byte[] rawValue = readElement(rawData);
return new KeyValuePair<>(dataFormat.keyToObj(rawKey, null), dataFormat.valueToObj(rawValue, null));
}
private byte[] readElement(ByteBuffer buffer) {
int length = UnsignedNumeric.readUnsignedInt(buffer);
byte[] element = new byte[length];
buffer.get(element);
return element;
}
}
}
| 3,270
| 33.797872
| 109
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/ClientEventSCI.java
|
package org.infinispan.client.hotrod.event;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.query.dsl.embedded.DslSCI;
@AutoProtoSchemaBuilder(
dependsOn = DslSCI.class,
includeClasses = {
ClientEventsTest.CustomKey.class,
ClientListenerWithFilterAndProtobufTest.CustomEventFilter.class,
ClientListenerWithFilterAndRawProtobufTest.CustomEventFilter.class,
CustomEventLogListener.CustomEvent.class,
CustomEventLogListener.DynamicConverterFactory.DynamicConverter.class,
CustomEventLogListener.FilterConverterFactory.FilterConverter.class,
CustomEventLogListener.RawStaticConverterFactory.RawStaticConverter.class,
CustomEventLogListener.SimpleConverterFactory.SimpleConverter.class,
CustomEventLogListener.StaticConverterFactory.StaticConverter.class,
EventLogListener.DynamicCacheEventFilterFactory.DynamicCacheEventFilter.class,
EventLogListener.RawStaticCacheEventFilterFactory.RawStaticCacheEventFilter.class,
EventLogListener.StaticCacheEventFilterFactory.StaticCacheEventFilter.class,
},
schemaFileName = "test.client.event.proto",
schemaFilePath = "proto/generated",
schemaPackageName = "org.infinispan.test.client",
service = false
)
public interface ClientEventSCI extends SerializationContextInitializer {
ClientEventSCI INSTANCE = new ClientEventSCIImpl();
}
| 1,571
| 49.709677
| 94
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/RemoteCacheSupplier.java
|
package org.infinispan.client.hotrod.event;
import org.infinispan.client.hotrod.RemoteCache;
public interface RemoteCacheSupplier<K> {
<V> RemoteCache<K, V> get();
}
| 171
| 20.5
| 48
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/ContinuousQueryObjectStorageTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
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.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.Search;
import org.infinispan.client.hotrod.exceptions.HotRodClientException;
import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB;
import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.time.TimeService;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.query.api.continuous.ContinuousQuery;
import org.infinispan.query.api.continuous.ContinuousQueryListener;
import org.infinispan.query.dsl.Query;
import org.infinispan.query.dsl.QueryFactory;
import org.infinispan.query.dsl.embedded.testdomain.User;
import org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS;
import org.infinispan.query.remote.impl.filter.IckleContinuousQueryProtobufCacheEventFilterConverterFactory;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.ControlledTimeService;
import org.infinispan.util.KeyValuePair;
import org.testng.annotations.Test;
/**
* Test remote continuous query when storing objects.
*
* @author anistor@redhat.com
* @since 9.0
*/
@Test(groups = "functional", testName = "client.hotrod.event.ContinuousQueryObjectStorageTest")
public class ContinuousQueryObjectStorageTest extends MultiHotRodServersTest {
private static final int NUM_NODES = 5;
private RemoteCache<String, User> remoteCache;
private ControlledTimeService timeService = new ControlledTimeService();
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfgBuilder = getConfigurationBuilder();
createHotRodServers(NUM_NODES, cfgBuilder);
waitForClusterToForm();
// Register the filter/converter factory. This should normally be discovered by the server via class path instead
// of being added manually here, but this is ok in a test.
IckleContinuousQueryProtobufCacheEventFilterConverterFactory factory = new IckleContinuousQueryProtobufCacheEventFilterConverterFactory();
for (int i = 0; i < NUM_NODES; i++) {
server(i).addCacheEventFilterConverterFactory(IckleContinuousQueryProtobufCacheEventFilterConverterFactory.FACTORY_NAME, factory);
TestingUtil.replaceComponent(server(i).getCacheManager(), TimeService.class, timeService, true);
}
remoteCache = client(0).getCache();
}
@Override
protected List<SerializationContextInitializer> contextInitializers() {
return Arrays.asList(TestDomainSCI.INSTANCE, ClientEventSCI.INSTANCE);
}
protected ConfigurationBuilder getConfigurationBuilder() {
ConfigurationBuilder cfgBuilder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
cfgBuilder.encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE);
cfgBuilder.encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE);
cfgBuilder.indexing().enable()
.storage(LOCAL_HEAP)
.addIndexedEntities(UserHS.class);
cfgBuilder.expiration().disableReaper();
return cfgBuilder;
}
/**
* Using grouping and aggregation with continuous query is not allowed.
*/
@Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN028509:.*")
public void testDisallowGroupingAndAggregation() {
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<Object[]> query = qf.create("SELECT MAX(age) FROM sample_bank_account.User WHERE age >= 20");
ContinuousQuery<String, User> continuousQuery = Search.getContinuousQuery(remoteCache);
ContinuousQueryListener<String, Object[]> listener = new ContinuousQueryListener<String, Object[]>() {
};
continuousQuery.addContinuousQueryListener(query, listener);
}
public void testContinuousQuery() {
User user1 = new UserPB();
user1.setId(1);
user1.setName("John");
user1.setSurname("Doe");
user1.setGender(User.Gender.MALE);
user1.setAge(22);
user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2)));
user1.setNotes("Lorem ipsum dolor sit amet");
User user2 = new UserPB();
user2.setId(2);
user2.setName("Spider");
user2.setSurname("Man");
user2.setGender(User.Gender.MALE);
user2.setAge(32);
user2.setAccountIds(Collections.singleton(3));
User user3 = new UserPB();
user3.setId(3);
user3.setName("Spider");
user3.setSurname("Woman");
user3.setGender(User.Gender.FEMALE);
user3.setAge(40);
remoteCache.clear();
remoteCache.put("user" + user1.getId(), user1);
remoteCache.put("user" + user2.getId(), user2);
remoteCache.put("user" + user3.getId(), user3);
assertEquals(3, remoteCache.size());
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<User> query = qf.<User>create("FROM sample_bank_account.User WHERE age <= :ageParam")
.setParameter("ageParam", 32);
final BlockingQueue<KeyValuePair<String, User>> joined = new LinkedBlockingQueue<>();
final BlockingQueue<String> left = new LinkedBlockingQueue<>();
ContinuousQueryListener<String, User> listener = new ContinuousQueryListener<String, User>() {
@Override
public void resultJoining(String key, User value) {
joined.add(new KeyValuePair<>(key, value));
}
@Override
public void resultLeaving(String key) {
left.add(key);
}
};
ContinuousQuery<String, User> continuousQuery = Search.getContinuousQuery(remoteCache);
continuousQuery.addContinuousQueryListener(query, listener);
expectElementsInQueue(joined, 2, (kv) -> kv.getValue().getAge(), 32, 22);
expectElementsInQueue(left, 0);
expectNoMoreElementsInQueues(joined, left);
user3.setAge(30);
remoteCache.put("user" + user3.getId(), user3);
expectElementsInQueue(joined, 1, (kv) -> kv.getValue().getAge(), 30);
expectElementsInQueue(left, 0);
expectNoMoreElementsInQueues(joined, left);
user1.setAge(40);
user2.setAge(40);
user3.setAge(40);
remoteCache.put("user" + user1.getId(), user1);
remoteCache.put("user" + user2.getId(), user2);
remoteCache.put("user" + user3.getId(), user3);
expectElementsInQueue(joined, 0);
expectElementsInQueue(left, 3);
expectNoMoreElementsInQueues(joined, left);
remoteCache.clear();
user1.setAge(21);
user2.setAge(22);
remoteCache.put("expiredUser1", user1, 5, TimeUnit.MILLISECONDS);
remoteCache.put("expiredUser2", user2, 5, TimeUnit.MILLISECONDS);
expectElementsInQueue(joined, 2);
expectElementsInQueue(left, 0);
expectNoMoreElementsInQueues(joined, left);
timeService.advance(6);
assertNull(remoteCache.get("expiredUser1"));
assertNull(remoteCache.get("expiredUser2"));
expectElementsInQueue(joined, 0);
expectElementsInQueue(left, 2);
expectNoMoreElementsInQueues(joined, left);
continuousQuery.removeContinuousQueryListener(listener);
user2.setAge(22);
remoteCache.put("user" + user2.getId(), user2);
expectElementsInQueue(joined, 0);
expectElementsInQueue(left, 0);
expectNoMoreElementsInQueues(joined, left);
}
public void testContinuousQueryWithProjections() throws InterruptedException {
User user1 = new UserPB();
user1.setId(1);
user1.setName("John");
user1.setSurname("Doe");
user1.setGender(User.Gender.MALE);
user1.setAge(22);
user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2)));
user1.setNotes("Lorem ipsum dolor sit amet");
User user2 = new UserPB();
user2.setId(2);
user2.setName("Spider");
user2.setSurname("Man");
user2.setGender(User.Gender.MALE);
user2.setAge(32);
user2.setAccountIds(Collections.singleton(3));
User user3 = new UserPB();
user3.setId(3);
user3.setName("Spider");
user3.setSurname("Woman");
user3.setGender(User.Gender.FEMALE);
user3.setAge(40);
remoteCache.clear();
remoteCache.put("user" + user1.getId(), user1);
remoteCache.put("user" + user2.getId(), user2);
remoteCache.put("user" + user3.getId(), user3);
assertEquals(3, remoteCache.size());
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<Object[]> query = qf.<Object[]>create("SELECT age FROM sample_bank_account.User WHERE age <= :ageParam")
.setParameter("ageParam", 32);
final BlockingQueue<KeyValuePair<String, Object[]>> joined = new LinkedBlockingQueue<>();
final BlockingQueue<String> left = new LinkedBlockingQueue<>();
ContinuousQueryListener<String, Object[]> listener = new ContinuousQueryListener<String, Object[]>() {
@Override
public void resultJoining(String key, Object[] value) {
joined.add(new KeyValuePair<>(key, value));
}
@Override
public void resultLeaving(String key) {
left.add(key);
}
};
ContinuousQuery<String, User> continuousQuery = Search.getContinuousQuery(remoteCache);
continuousQuery.addContinuousQueryListener(query, listener);
expectElementsInQueue(joined, 2, (kv) -> kv.getValue()[0], 32, 22);
expectElementsInQueue(left, 0);
expectNoMoreElementsInQueues(joined, left);
user3.setAge(30);
remoteCache.put("user" + user3.getId(), user3);
expectElementsInQueue(joined, 1, (kv) -> kv.getValue()[0], 30);
expectElementsInQueue(left, 0);
expectNoMoreElementsInQueues(joined, left);
user1.setAge(40);
user2.setAge(40);
user3.setAge(40);
remoteCache.put("user" + user1.getId(), user1);
remoteCache.put("user" + user2.getId(), user2);
remoteCache.put("user" + user3.getId(), user3);
expectElementsInQueue(joined, 0);
expectElementsInQueue(left, 3);
remoteCache.clear();
user1.setAge(21);
user2.setAge(22);
remoteCache.put("expiredUser1", user1, 5, TimeUnit.MILLISECONDS);
remoteCache.put("expiredUser2", user2, 5, TimeUnit.MILLISECONDS);
expectElementsInQueue(joined, 2);
expectElementsInQueue(left, 0);
timeService.advance(6);
assertNull(remoteCache.get("expiredUser1"));
assertNull(remoteCache.get("expiredUser2"));
expectElementsInQueue(joined, 0);
expectElementsInQueue(left, 2);
continuousQuery.removeContinuousQueryListener(listener);
user2.setAge(22);
remoteCache.put("user" + user2.getId(), user2);
expectElementsInQueue(joined, 0);
expectElementsInQueue(left, 0);
}
public void testContinuousQueryChangingParameter() throws InterruptedException {
User user1 = new UserPB();
user1.setId(1);
user1.setName("John");
user1.setSurname("Doe");
user1.setGender(User.Gender.MALE);
user1.setAge(22);
user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2)));
user1.setNotes("Lorem ipsum dolor sit amet");
User user2 = new UserPB();
user2.setId(2);
user2.setName("Spider");
user2.setSurname("Man");
user2.setGender(User.Gender.MALE);
user2.setAge(32);
user2.setAccountIds(Collections.singleton(3));
User user3 = new UserPB();
user3.setId(3);
user3.setName("Spider");
user3.setSurname("Woman");
user3.setGender(User.Gender.FEMALE);
user3.setAge(40);
remoteCache.clear();
remoteCache.put("user" + user1.getId(), user1);
remoteCache.put("user" + user2.getId(), user2);
remoteCache.put("user" + user3.getId(), user3);
assertEquals(3, remoteCache.size());
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<Object[]> query = qf.<Object[]>create("SELECT age FROM sample_bank_account.User WHERE age <= :ageParam")
.setParameter("ageParam", 32);
final BlockingQueue<KeyValuePair<String, Object[]>> joined = new LinkedBlockingQueue<>();
final BlockingQueue<String> left = new LinkedBlockingQueue<>();
ContinuousQueryListener<String, Object[]> listener = new ContinuousQueryListener<String, Object[]>() {
@Override
public void resultJoining(String key, Object[] value) {
joined.add(new KeyValuePair<>(key, value));
}
@Override
public void resultLeaving(String key) {
left.add(key);
}
};
ContinuousQuery<String, User> cq = Search.getContinuousQuery(remoteCache);
cq.addContinuousQueryListener(query, listener);
expectElementsInQueue(joined, 2, (kv) -> kv.getValue()[0], 32, 22);
expectElementsInQueue(left, 0);
expectNoMoreElementsInQueues(joined, left);
joined.clear();
left.clear();
cq.removeContinuousQueryListener(listener);
query.setParameter("ageParam", 40);
listener = new ContinuousQueryListener<String, Object[]>() {
@Override
public void resultJoining(String key, Object[] value) {
joined.add(new KeyValuePair<>(key, value));
}
@Override
public void resultLeaving(String key) {
left.add(key);
}
};
cq.addContinuousQueryListener(query, listener);
expectElementsInQueue(joined, 3);
expectElementsInQueue(left, 0);
cq.removeContinuousQueryListener(listener);
}
private <T> void expectElementsInQueue(BlockingQueue<T> queue, int numElements) {
expectElementsInQueue(queue, numElements, null);
}
private <T, R> void expectElementsInQueue(BlockingQueue<T> queue, int numElements, Function<T, R> valueTransformer, Object... expectedValue) {
List<Object> expectedValues;
if (expectedValue.length != 0) {
if (expectedValue.length != numElements) {
throw new IllegalArgumentException("The number of expected values must either match the number of expected elements or no expected values should be specified.");
}
expectedValues = new ArrayList<>(expectedValue.length);
Collections.addAll(expectedValues, expectedValue);
} else {
expectedValues = null;
}
for (int i = 0; i < numElements; i++) {
final T o;
try {
o = queue.poll(5, TimeUnit.SECONDS);
assertNotNull("Queue was empty after reading " + i + " elements!", o);
} catch (InterruptedException e) {
throw new AssertionError("Interrupted while waiting for condition", e);
}
if (expectedValues != null) {
Object v = valueTransformer != null ? valueTransformer.apply(o) : o;
boolean found = expectedValues.remove(v);
assertTrue("Expectation failed on element number " + i + ", unexpected value: " + v, found);
}
}
}
private void expectNoMoreElementsInQueues(BlockingQueue<?>... queues) {
// A short delay gives unexpected events in transit a chance to appear in the queue
TestingUtil.sleepThread(100);
for (BlockingQueue<?> queue : queues) {
assertNull("No more elements expected in queue!", queue.poll());
}
}
}
| 16,313
| 36.077273
| 173
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/NonIndexedCacheRemoteListenerWithDslFilterTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
/**
* @author anistor@redhat.com
* @since 8.0
*/
@Test(groups = "functional", testName = "client.hotrod.event.NonIndexedCacheRemoteListenerWithDslFilterTest")
public class NonIndexedCacheRemoteListenerWithDslFilterTest extends RemoteListenerWithDslFilterTest {
@Override
protected ConfigurationBuilder getConfigurationBuilder() {
return hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
}
}
| 738
| 34.190476
| 109
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/ClientListenerWithFilterAndRawProtobufTest.java
|
package org.infinispan.client.hotrod.event;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB;
import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.marshall.ProtoStreamMarshaller;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.filter.NamedFactory;
import org.infinispan.metadata.Metadata;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilter;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterFactory;
import org.infinispan.notifications.cachelistener.filter.EventType;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
import org.infinispan.query.dsl.embedded.testdomain.User;
import org.testng.annotations.Test;
/**
* A simple remote listener test with filter and protobuf marshalling. This test uses raw key/value in events.
*
* @author anistor@redhat.com
* @since 7.2
*/
@Test(groups = "functional", testName = "client.hotrod.event.ClientListenerWithFilterAndRawProtobufTest")
public class ClientListenerWithFilterAndRawProtobufTest extends MultiHotRodServersTest {
private final int NUM_NODES = 2;
private RemoteCache<Object, Object> remoteCache;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfgBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
createHotRodServers(NUM_NODES, cfgBuilder);
waitForClusterToForm();
for (int i = 0; i < NUM_NODES; i++) {
server(i).addCacheEventFilterFactory("custom-filter-factory", new CustomCacheEventFilterFactory());
}
remoteCache = client(0).getCache();
}
@Override
protected List<SerializationContextInitializer> contextInitializers() {
return Arrays.asList(ClientEventSCI.INSTANCE, TestDomainSCI.INSTANCE);
}
public void testEventFilter() throws Exception {
Object[] filterFactoryParams = new Object[]{"string_key_1", "user_1"};
ClientEntryListener listener = new ClientEntryListener();
remoteCache.addClientListener(listener, filterFactoryParams, null);
User user1 = new UserPB();
user1.setId(1);
user1.setName("John");
user1.setSurname("Doe");
user1.setGender(User.Gender.MALE);
user1.setAge(22);
remoteCache.put("string_key_1", "string value 1");
remoteCache.put("string_key_2", "string value 2");
remoteCache.put("user_1", user1);
assertEquals(3, remoteCache.keySet().size());
ClientCacheEntryCreatedEvent e = listener.createEvents.poll(5, TimeUnit.SECONDS);
assertEquals("string_key_1", e.getKey());
e = listener.createEvents.poll(5, TimeUnit.SECONDS);
assertEquals("user_1", e.getKey());
e = listener.createEvents.poll(5, TimeUnit.SECONDS);
assertNull("No more elements expected in queue!", e);
}
@ClientListener(filterFactoryName = "custom-filter-factory", useRawData = true)
public static class ClientEntryListener {
public final BlockingQueue<ClientCacheEntryCreatedEvent> createEvents = new LinkedBlockingQueue<>();
@ClientCacheEntryCreated
@SuppressWarnings("unused")
public void handleClientCacheEntryCreatedEvent(ClientCacheEntryCreatedEvent event) {
createEvents.add(event);
}
}
@NamedFactory(name = "custom-filter-factory")
public static class CustomCacheEventFilterFactory implements CacheEventFilterFactory {
private final ProtoStreamMarshaller marshaller = new ProtoStreamMarshaller();
@Override
public CacheEventFilter<byte[], byte[]> getFilter(Object[] params) {
String firstParam;
String secondParam;
try {
firstParam = (String) marshaller.objectFromByteBuffer((byte[]) params[0]);
secondParam = (String) marshaller.objectFromByteBuffer((byte[]) params[1]);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
return new CustomEventFilter(firstParam, secondParam);
}
}
@ProtoName("RawProtobufCustomEventFilter")
public static class CustomEventFilter implements CacheEventFilter<byte[], byte[]> {
private transient ProtoStreamMarshaller marshaller;
@ProtoField(1)
final String firstParam;
@ProtoField(2)
final String secondParam;
@ProtoFactory
CustomEventFilter(String firstParam, String secondParam) {
this.firstParam = firstParam;
this.secondParam = secondParam;
}
private ProtoStreamMarshaller getMarshaller() {
if (marshaller == null) {
marshaller = new ProtoStreamMarshaller();
}
return marshaller;
}
@Override
public boolean accept(byte[] key, byte[] oldValue, Metadata oldMetadata, byte[] newValue, Metadata newMetadata, EventType eventType) {
try {
String stringKey = (String) getMarshaller().objectFromByteBuffer(key);
// this filter accepts only the two keys it received as params
return firstParam.equals(stringKey) || secondParam.equals(stringKey);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
}
| 6,226
| 36.512048
| 140
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/EventWithStorageTypeTest.java
|
package org.infinispan.client.hotrod.event;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.data.Person;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
/**
* Test for receiving events in when the Server uses different storage types.
*/
@Test(groups = {"functional"}, testName = "client.hotrod.event.EventWithStorageTypeTest")
public class EventWithStorageTypeTest extends SingleHotRodServerTest {
private StorageType storageType;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.memory().storageType(storageType);
return TestCacheManagerFactory.createCacheManager(contextInitializer(), builder);
}
@Factory
public Object[] factory() {
return new Object[]{
new EventWithStorageTypeTest().storageType(StorageType.OBJECT),
new EventWithStorageTypeTest().storageType(StorageType.BINARY),
new EventWithStorageTypeTest().storageType(StorageType.OFF_HEAP),
};
}
private Object storageType(StorageType storageType) {
this.storageType = storageType;
return this;
}
@Override
protected SerializationContextInitializer contextInitializer() {
return TestDataSCI.INSTANCE;
}
@Override
protected String parameters() {
return "storageType-" + storageType;
}
@Test
public void testReceiveKeyValues() throws InterruptedException {
RemoteCache<String, Person> cache = remoteCacheManager.getCache();
EventListener listener = new EventListener();
cache.addClientListener(listener);
cache.put("1", new Person("John"));
Object key = listener.getEventKey();
assertNotNull(key);
assertEquals("1", key);
}
@ClientListener
@SuppressWarnings("unused")
static class EventListener {
private final BlockingQueue<String> eventsQueue = new LinkedBlockingQueue<>();
Object getEventKey() throws InterruptedException {
return eventsQueue.poll(5, TimeUnit.SECONDS);
}
@ClientCacheEntryCreated
public void handleCreatedEvent(ClientCacheEntryCreatedEvent<String> event) {
eventsQueue.add(event.getKey());
}
@ClientCacheEntryModified
public void handleModifiedEvent(ClientCacheEntryModifiedEvent<String> event) {
eventsQueue.add(event.getKey());
}
}
}
| 3,308
| 32.424242
| 89
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/FailoverEventLogListener.java
|
package org.infinispan.client.hotrod.event;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.annotation.ClientCacheFailover;
public class FailoverEventLogListener<K> extends EventLogListener<K> {
public BlockingQueue<ClientCacheFailoverEvent> failoverEvents = new ArrayBlockingQueue<>(128);
public FailoverEventLogListener(RemoteCache<K, ?> remote) {
super(remote);
}
@Override @SuppressWarnings("unchecked")
public <E extends ClientEvent> BlockingQueue<E> queue(ClientEvent.Type type) {
switch (type) {
case CLIENT_CACHE_ENTRY_CREATED: return (BlockingQueue<E>) createdEvents;
case CLIENT_CACHE_ENTRY_MODIFIED: return (BlockingQueue<E>) modifiedEvents;
case CLIENT_CACHE_ENTRY_REMOVED: return (BlockingQueue<E>) removedEvents;
case CLIENT_CACHE_FAILOVER: return (BlockingQueue<E>) failoverEvents;
default: throw new IllegalArgumentException("Unknown event type: " + type);
}
}
@ClientCacheFailover
@SuppressWarnings("unused")
public void handleFailover(ClientCacheFailoverEvent e) {
failoverEvents.add(e);
}
}
| 1,244
| 35.617647
| 97
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/ClientEventsTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withClientListener;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Set;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.VersionedValue;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.testng.annotations.Test;
/**
* @author Galder Zamarreño
*/
@Test(groups = {"functional", "smoke"}, testName = "client.hotrod.event.ClientEventsTest")
public class ClientEventsTest extends SingleHotRodServerTest {
@Override
protected SerializationContextInitializer contextInitializer() {
return ClientEventSCI.INSTANCE;
}
public void testCreatedEvent() {
final EventLogListener<Integer> l = new EventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
remote.put(1, "one");
l.expectOnlyCreatedEvent(1);
remote.put(2, "two");
l.expectOnlyCreatedEvent(2);
});
}
public void testModifiedEvent() {
final EventLogListener<Integer> l = new EventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
remote.put(1, "one");
l.expectOnlyCreatedEvent(1);
remote.put(1, "newone");
l.expectOnlyModifiedEvent(1);
});
}
public void testRemovedEvent() {
final EventLogListener<Integer> l = new EventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
remote.remove(1);
l.expectNoEvents();
remote.put(1, "one");
l.expectOnlyCreatedEvent(1);
remote.remove(1);
l.expectOnlyRemovedEvent(1);
});
}
public void testReplaceEvents() {
final EventLogListener<Integer> l = new EventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
remote.replace(1, "one");
l.expectNoEvents();
remote.put(1, "one");
l.expectOnlyCreatedEvent(1);
remote.replace(1, "newone");
l.expectOnlyModifiedEvent(1);
});
}
public void testPutIfAbsentEvents() {
final EventLogListener<Integer> l = new EventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
remote.putIfAbsent(1, "one");
l.expectOnlyCreatedEvent(1);
remote.putIfAbsent(1, "newone");
l.expectNoEvents();
});
}
public void testReplaceIfUnmodifiedEvents() {
final EventLogListener<Integer> l = new EventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
remote.replaceWithVersion(1, "one", 0);
l.expectNoEvents();
remote.putIfAbsent(1, "one");
l.expectOnlyCreatedEvent(1);
remote.replaceWithVersion(1, "one", 0);
l.expectNoEvents();
VersionedValue<?> versioned = remote.getWithMetadata(1);
remote.replaceWithVersion(1, "one", versioned.getVersion());
l.expectOnlyModifiedEvent(1);
});
}
public void testRemoveIfUnmodifiedEvents() {
final EventLogListener<Integer> l = new EventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
remote.removeWithVersion(1, 0);
l.expectNoEvents();
remote.putIfAbsent(1, "one");
l.expectOnlyCreatedEvent(1);
remote.removeWithVersion(1, 0);
l.expectNoEvents();
VersionedValue<?> versioned = remote.getWithMetadata(1);
remote.removeWithVersion(1, versioned.getVersion());
l.expectOnlyRemovedEvent(1);
});
}
public void testClearEvents() {
final EventLogListener<Integer> l = new EventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
remote.put(1, "one");
l.expectOnlyCreatedEvent(1);
remote.put(2, "two");
l.expectOnlyCreatedEvent(2);
remote.put(3, "three");
l.expectOnlyCreatedEvent(3);
remote.clear();
l.expectUnorderedEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED, 1, 2, 3);
});
}
public void testNoEventsBeforeAddingListener() {
RemoteCache<Integer, String> rcache = remoteCacheManager.getCache();
final EventLogListener<Integer> l = new EventLogListener<>(rcache);
rcache.put(1, "one");
l.expectNoEvents();
rcache.put(1, "newone");
l.expectNoEvents();
rcache.remove(1);
l.expectNoEvents();
createUpdateRemove(l);
}
private void createUpdateRemove(EventLogListener<Integer> l) {
withClientListener(l, remote -> {
remote.put(1, "one");
l.expectOnlyCreatedEvent(1);
remote.put(1, "newone");
l.expectOnlyModifiedEvent(1);
remote.remove(1);
l.expectOnlyRemovedEvent(1);
});
}
public void testNoEventsAfterRemovingListener() {
final RemoteCache<Integer, String> rcache = remoteCacheManager.getCache();
final EventLogListener<Integer> l = new EventLogListener<>(rcache);
createUpdateRemove(l);
rcache.put(1, "one");
l.expectNoEvents();
rcache.put(1, "newone");
l.expectNoEvents();
rcache.remove(1);
l.expectNoEvents();
}
public void testSetListeners() {
final RemoteCache<Integer, String> rcache = remoteCacheManager.getCache();
final EventLogListener l1 = new EventLogListener<>(rcache);
withClientListener(l1, remote1 -> {
Set<?> listeners1 = remote1.getListeners();
assertEquals(1, listeners1.size());
assertEquals(l1, listeners1.iterator().next());
final EventLogListener l2 = new EventLogListener<>(rcache);
withClientListener(l2, remote2 -> {
Set<?> listeners2 = remote2.getListeners();
assertEquals(2, listeners2.size());
assertTrue(listeners2.contains(l1));
assertTrue(listeners2.contains(l2));
});
});
Set<Object> listeners = rcache.getListeners();
assertEquals(0, listeners.size());
}
public void testCustomTypeEvents() {
final EventLogListener<CustomKey> l = new EventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
CustomKey key = new CustomKey(1);
remote.put(key, "one");
l.expectOnlyCreatedEvent(key);
remote.replace(key, "newone");
l.expectOnlyModifiedEvent(key);
remote.remove(key);
l.expectOnlyRemovedEvent(key);
});
}
public void testEventReplayAfterAddingListener() {
RemoteCache<Integer, String> cache = remoteCacheManager.getCache();
final WithStateEventLogListener<Integer> l = new WithStateEventLogListener<>(cache);
cache.put(1, "one");
cache.put(2, "two");
l.expectNoEvents();
withClientListener(l, remote ->
l.expectUnorderedEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED, 1, 2));
}
public void testNoEventReplayAfterAddingListener() {
RemoteCache<Integer, String> cache = remoteCacheManager.getCache();
final EventLogListener<Integer> l = new EventLogListener<>(cache);
cache.put(1, "one");
cache.put(2, "two");
l.expectNoEvents();
withClientListener(l, remote -> l.expectNoEvents());
}
@ClientListener(includeCurrentState = true)
public static class WithStateEventLogListener<K> extends EventLogListener<K> {
public WithStateEventLogListener(RemoteCache<K, ?> remote) {
super(remote);
}
}
static final class CustomKey {
@ProtoField(number = 1, defaultValue = "0")
final int id;
@ProtoFactory
CustomKey(int id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomKey customKey = (CustomKey) o;
return id == customKey.id;
}
@Override
public int hashCode() {
return id;
}
}
}
| 8,714
| 33.44664
| 98
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/ClientListenerWithDslFilterObjectStorageTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.Search;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.exceptions.HotRodClientException;
import org.infinispan.client.hotrod.filter.Filters;
import org.infinispan.client.hotrod.marshall.MarshallerUtil;
import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB;
import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.protostream.ProtobufUtil;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.query.dsl.Query;
import org.infinispan.query.dsl.QueryFactory;
import org.infinispan.query.dsl.embedded.testdomain.User;
import org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS;
import org.infinispan.query.remote.client.FilterResult;
import org.infinispan.query.remote.impl.filter.IckleCacheEventFilterConverterFactory;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
/**
* @author anistor@redhat.com
* @since 9.0
*/
@Test(groups = "functional", testName = "client.hotrod.event.ClientListenerWithDslFilterObjectStorageTest")
public class ClientListenerWithDslFilterObjectStorageTest extends MultiHotRodServersTest {
private static final int NUM_NODES = 5;
private RemoteCache<Object, Object> remoteCache;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfgBuilder = getConfigurationBuilder();
createHotRodServers(NUM_NODES, cfgBuilder);
waitForClusterToForm();
// Register the filter/converter factory. This should normally be discovered by the server via class path instead
// of being added manually here, but this is ok in a test.
IckleCacheEventFilterConverterFactory factory = new IckleCacheEventFilterConverterFactory();
for (int i = 0; i < NUM_NODES; i++) {
server(i).addCacheEventFilterConverterFactory(IckleCacheEventFilterConverterFactory.FACTORY_NAME, factory);
}
remoteCache = client(0).getCache();
}
@Override
protected List<SerializationContextInitializer> contextInitializers() {
return Arrays.asList(TestDomainSCI.INSTANCE, ClientEventSCI.INSTANCE);
}
protected ConfigurationBuilder getConfigurationBuilder() {
ConfigurationBuilder cfgBuilder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
cfgBuilder.encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE);
cfgBuilder.encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE);
cfgBuilder.indexing().enable()
.storage(LOCAL_HEAP)
.addIndexedEntities(UserHS.class);
return cfgBuilder;
}
public void testEventFilter() {
User user1 = new UserPB();
user1.setId(1);
user1.setName("John");
user1.setSurname("Doe");
user1.setGender(User.Gender.MALE);
user1.setAge(22);
user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2)));
user1.setNotes("Lorem ipsum dolor sit amet");
User user2 = new UserPB();
user2.setId(2);
user2.setName("Spider");
user2.setSurname("Man");
user2.setGender(User.Gender.MALE);
user2.setAge(32);
user2.setAccountIds(Collections.singleton(3));
User user3 = new UserPB();
user3.setId(3);
user3.setName("Spider");
user3.setSurname("Woman");
user3.setGender(User.Gender.FEMALE);
user3.setAge(31);
remoteCache.clear();
remoteCache.put("user_" + user1.getId(), user1);
remoteCache.put("user_" + user2.getId(), user2);
remoteCache.put("user_" + user3.getId(), user3);
assertEquals(3, remoteCache.size());
SerializationContext serCtx = MarshallerUtil.getSerializationContext(client(0));
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<Object[]> query = qf.<Object[]>create("SELECT age FROM sample_bank_account.User WHERE age <= :ageParam")
.setParameter("ageParam", 32);
ClientEntryListener listener = new ClientEntryListener(serCtx);
ClientEvents.addClientQueryListener(remoteCache, listener, query);
expectElementsInQueue(listener.createEvents, 3);
user3.setAge(40);
remoteCache.put("user_" + user1.getId(), user1);
remoteCache.put("user_" + user2.getId(), user2);
remoteCache.put("user_" + user3.getId(), user3);
assertEquals(3, remoteCache.size());
expectElementsInQueue(listener.modifyEvents, 2);
remoteCache.removeClientListener(listener);
}
public void testEventFilterChangingParameter() {
User user1 = new UserPB();
user1.setId(1);
user1.setName("John");
user1.setSurname("Doe");
user1.setGender(User.Gender.MALE);
user1.setAge(22);
user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2)));
user1.setNotes("Lorem ipsum dolor sit amet");
User user2 = new UserPB();
user2.setId(2);
user2.setName("Spider");
user2.setSurname("Man");
user2.setGender(User.Gender.MALE);
user2.setAge(32);
user2.setAccountIds(Collections.singleton(3));
User user3 = new UserPB();
user3.setId(3);
user3.setName("Spider");
user3.setSurname("Woman");
user3.setGender(User.Gender.FEMALE);
user3.setAge(31);
remoteCache.clear();
remoteCache.put("user_" + user1.getId(), user1);
remoteCache.put("user_" + user2.getId(), user2);
remoteCache.put("user_" + user3.getId(), user3);
assertEquals(3, remoteCache.size());
SerializationContext serCtx = MarshallerUtil.getSerializationContext(client(0));
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<Object[]> query = qf.<Object[]>create("SELECT age FROM sample_bank_account.User WHERE age <= :ageParam")
.setParameter("ageParam", 32);
ClientEntryListener listener = new ClientEntryListener(serCtx);
ClientEvents.addClientQueryListener(remoteCache, listener, query);
expectElementsInQueue(listener.createEvents, 3);
remoteCache.removeClientListener(listener);
query.setParameter("ageParam", 31);
listener = new ClientEntryListener(serCtx);
ClientEvents.addClientQueryListener(remoteCache, listener, query);
expectElementsInQueue(listener.createEvents, 2);
remoteCache.removeClientListener(listener);
}
/**
* Using grouping and aggregation with event filters is not allowed.
*/
@Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN028509:.*")
public void testDisallowGroupingAndAggregation() {
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<Object[]> query = qf.create("SELECT MAX(age) FROM sample_bank_account.User WHERE age >= 20");
ClientEntryListener listener = new ClientEntryListener(MarshallerUtil.getSerializationContext(client(0)));
ClientEvents.addClientQueryListener(remoteCache, listener, query);
}
/**
* Using non-raw listeners should throw an exception.
*/
@Test(expectedExceptions = IncorrectClientListenerException.class, expectedExceptionsMessageRegExp = "ISPN004058:.*")
public void testRequireRawDataListener() {
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<User> query = qf.create("FROM sample_bank_account.User WHERE age >= 20");
@ClientListener(filterFactoryName = Filters.QUERY_DSL_FILTER_FACTORY_NAME,
converterFactoryName = Filters.QUERY_DSL_FILTER_FACTORY_NAME,
useRawData = false, includeCurrentState = true)
class DummyListener {
@ClientCacheEntryCreated
public void handleClientCacheEntryCreatedEvent(ClientCacheEntryCustomEvent event) {
}
}
ClientEvents.addClientQueryListener(remoteCache, new DummyListener(), query);
}
/**
* Using non-raw listeners should throw an exception.
*/
@Test(expectedExceptions = IncorrectClientListenerException.class, expectedExceptionsMessageRegExp = "ISPN004059:.*")
public void testRequireQueryDslFilterFactoryNameForListener() {
QueryFactory qf = Search.getQueryFactory(remoteCache);
Query<User> query = qf.create("FROM sample_bank_account.User WHERE age >= 20");
@ClientListener(filterFactoryName = "some-filter-factory-name",
converterFactoryName = "some-filter-factory-name",
useRawData = true, includeCurrentState = true)
class DummyListener {
@ClientCacheEntryCreated
public void handleClientCacheEntryCreatedEvent(ClientCacheEntryCustomEvent event) {
}
}
ClientEvents.addClientQueryListener(remoteCache, new DummyListener(), query);
}
private void expectElementsInQueue(BlockingQueue<?> queue, int numElements) {
for (int i = 0; i < numElements; i++) {
try {
Object e = queue.poll(5, TimeUnit.SECONDS);
assertNotNull("Queue was empty!", e);
} catch (InterruptedException e) {
throw new AssertionError("Interrupted while waiting for condition", e);
}
}
try {
// no more elements expected here
Object e = queue.poll(5, TimeUnit.SECONDS);
assertNull("No more elements expected in queue!", e);
} catch (InterruptedException e) {
throw new AssertionError("Interrupted while waiting for condition", e);
}
}
@ClientListener(filterFactoryName = Filters.QUERY_DSL_FILTER_FACTORY_NAME,
converterFactoryName = Filters.QUERY_DSL_FILTER_FACTORY_NAME,
useRawData = true, includeCurrentState = true)
private static class ClientEntryListener {
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
public final BlockingQueue<FilterResult> createEvents = new LinkedBlockingQueue<>();
public final BlockingQueue<FilterResult> modifyEvents = new LinkedBlockingQueue<>();
private final SerializationContext serializationContext;
public ClientEntryListener(SerializationContext serializationContext) {
this.serializationContext = serializationContext;
}
@ClientCacheEntryCreated
public void handleClientCacheEntryCreatedEvent(ClientCacheEntryCustomEvent event) throws IOException {
byte[] eventData = (byte[]) event.getEventData();
FilterResult r = ProtobufUtil.fromWrappedByteArray(serializationContext, eventData);
createEvents.add(r);
log.debugf("handleClientCacheEntryCreatedEvent instance=%s projection=%s sortProjection=%s\n",
r.getInstance(),
r.getProjection() == null ? null : Arrays.asList(r.getProjection()),
r.getSortProjection() == null ? null : Arrays.asList(r.getSortProjection()));
}
@ClientCacheEntryModified
public void handleClientCacheEntryModifiedEvent(ClientCacheEntryCustomEvent event) throws IOException {
byte[] eventData = (byte[]) event.getEventData();
FilterResult r = ProtobufUtil.fromWrappedByteArray(serializationContext, eventData);
modifyEvents.add(r);
log.debugf("handleClientCacheEntryModifiedEvent instance=%s projection=%s sortProjection=%s\n",
r.getInstance(),
r.getProjection() == null ? null : Arrays.asList(r.getProjection()),
r.getSortProjection() == null ? null : Arrays.asList(r.getSortProjection()));
}
@ClientCacheEntryRemoved
public void handleClientCacheEntryRemovedEvent(ClientCacheEntryRemovedEvent event) {
log.debugf("handleClientCacheEntryRemovedEvent %s\n", event.getKey());
}
}
}
| 13,016
| 40.587859
| 125
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/ClientListenerWithFilterAndProtobufTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB;
import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.filter.NamedFactory;
import org.infinispan.metadata.Metadata;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilter;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterFactory;
import org.infinispan.notifications.cachelistener.filter.EventType;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.query.dsl.embedded.testdomain.User;
import org.testng.annotations.Test;
/**
* A simple remote listener test with filter and protobuf marshalling. This test uses unmarshalled key/value in events.
*
* @author anistor@redhat.com
* @since 7.2
*/
@Test(groups = "functional", testName = "client.hotrod.event.ClientListenerWithFilterAndProtobufTest")
public class ClientListenerWithFilterAndProtobufTest extends MultiHotRodServersTest {
private final int NUM_NODES = 2;
private RemoteCache<Object, Object> remoteCache;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder defaultClusteredCacheConfig = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
defaultClusteredCacheConfig.encoding().key().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE);
defaultClusteredCacheConfig.encoding().value().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE);
ConfigurationBuilder cfgBuilder = hotRodCacheConfiguration(defaultClusteredCacheConfig);
createHotRodServers(NUM_NODES, cfgBuilder);
waitForClusterToForm();
for (int i = 0; i < NUM_NODES; i++) {
server(i).addCacheEventFilterFactory("custom-filter-factory", new CustomCacheEventFilterFactory());
}
remoteCache = client(0).getCache();
}
@Override
protected List<SerializationContextInitializer> contextInitializers() {
return Arrays.asList(TestDomainSCI.INSTANCE, ClientEventSCI.INSTANCE);
}
public void testEventFilter() throws Exception {
Object[] filterFactoryParams = new Object[]{"string_key_1", "user_1"};
ClientEntryListener listener = new ClientEntryListener();
remoteCache.addClientListener(listener, filterFactoryParams, null);
User user1 = new UserPB();
user1.setId(1);
user1.setName("John");
user1.setSurname("Doe");
user1.setGender(User.Gender.MALE);
user1.setAge(22);
remoteCache.put("string_key_1", "string value 1");
remoteCache.put("string_key_2", "string value 2");
remoteCache.put("user_1", user1);
assertEquals(3, remoteCache.keySet().size());
ClientCacheEntryCreatedEvent e = listener.createEvents.poll(5, TimeUnit.SECONDS);
assertEquals("string_key_1", e.getKey());
e = listener.createEvents.poll(5, TimeUnit.SECONDS);
assertEquals("user_1", e.getKey());
e = listener.createEvents.poll(5, TimeUnit.SECONDS);
assertNull("No more elements expected in queue!", e);
}
@ClientListener(filterFactoryName = "custom-filter-factory")
public static class ClientEntryListener {
public final BlockingQueue<ClientCacheEntryCreatedEvent> createEvents = new LinkedBlockingQueue<>();
@ClientCacheEntryCreated
@SuppressWarnings("unused")
public void handleClientCacheEntryCreatedEvent(ClientCacheEntryCreatedEvent event) {
createEvents.add(event);
}
}
@NamedFactory(name = "custom-filter-factory")
public static class CustomCacheEventFilterFactory implements CacheEventFilterFactory {
@Override
public CacheEventFilter<String, Object> getFilter(Object[] params) {
String firstParam = (String) params[0];
String secondParam = (String) params[1];
return new CustomEventFilter(firstParam, secondParam);
}
}
public static class CustomEventFilter implements CacheEventFilter<String, Object> {
@ProtoField(1)
final String firstParam;
@ProtoField(2)
final String secondParam;
@ProtoFactory
CustomEventFilter(String firstParam, String secondParam) {
this.firstParam = firstParam;
this.secondParam = secondParam;
}
@Override
public boolean accept(String key, Object oldValue, Metadata oldMetadata, Object newValue, Metadata newMetadata, EventType eventType) {
// this filter accepts only the two keys it received as params
return firstParam.equals(key) || secondParam.equals(key);
}
}
}
| 5,527
| 38.205674
| 140
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/NonIndexedRemoteContinuousQueryTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
/**
* @author anistor@redhat.com
* @since 8.0
*/
@Test(groups = "functional", testName = "client.hotrod.event.NonIndexedRemoteContinuousQueryTest")
public class NonIndexedRemoteContinuousQueryTest extends RemoteContinuousQueryTest {
@Override
protected ConfigurationBuilder getConfigurationBuilder() {
ConfigurationBuilder cfgBuilder =
hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
cfgBuilder.expiration().disableReaper();
return cfgBuilder;
}
}
| 822
| 31.92
| 98
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/ClientCustomFilterEventsTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withClientListener;
import org.infinispan.client.hotrod.event.CustomEventLogListener.CustomEvent;
import org.infinispan.client.hotrod.event.CustomEventLogListener.FilterConverterFactory;
import org.infinispan.client.hotrod.event.CustomEventLogListener.FilterCustomEventLogListener;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverterFactory;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilter;
import org.infinispan.notifications.cachelistener.filter.CacheEventFilterFactory;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.event.ClientCustomFilterEventsTest")
public class ClientCustomFilterEventsTest extends SingleHotRodServerTest {
@Override
protected HotRodServer createHotRodServer() {
HotRodServerConfigurationBuilder builder = new HotRodServerConfigurationBuilder();
HotRodServer server = HotRodClientTestingUtil.startHotRodServer(cacheManager, builder);
server.addCacheEventFilterConverterFactory("filter-converter-factory", new FilterConverterFactory());
return server;
}
@Override
protected SerializationContextInitializer contextInitializer() {
return ClientEventSCI.INSTANCE;
}
@Test(expectedExceptions = IllegalStateException.class)
public void testIncorrectFilterFactory() {
hotrodServer.addCacheEventFilterFactory("xxx", new IncorrectFilterConverterFactory());
}
@Test(expectedExceptions = IllegalStateException.class)
public void testIncorrectConverterFactory() {
hotrodServer.addCacheEventConverterFactory("xxx", new IncorrectFilterConverterFactory());
}
public void testFilterCustomEvents() {
final FilterCustomEventLogListener<Integer> l =
new FilterCustomEventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, new Object[]{1}, null, remote -> {
remote.put(1, "one");
l.expectCreatedEvent(new CustomEvent(1, null, 1));
remote.put(1, "newone");
l.expectModifiedEvent(new CustomEvent(1, null, 2));
remote.put(2, "two");
l.expectCreatedEvent(new CustomEvent(2, "two", 3));
remote.put(2, "dos");
l.expectModifiedEvent(new CustomEvent(2, "dos", 4));
remote.remove(1);
l.expectRemovedEvent(new CustomEvent(1, null, 5));
remote.remove(2);
l.expectRemovedEvent(new CustomEvent(2, null, 6));
});
}
public static class IncorrectFilterConverterFactory implements CacheEventFilterFactory, CacheEventConverterFactory {
@Override
public <K, V> CacheEventFilter<K, V> getFilter(Object[] params) {
return null;
}
@Override
public <K, V, C> CacheEventConverter<K, V, C> getConverter(Object[] params) {
return null;
}
}
}
| 3,351
| 43.105263
| 119
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/RemoteCacheImplTest.java
|
package org.infinispan.client.hotrod.impl;
import static org.testng.AssertJUnit.assertEquals;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.impl.protocol.CodecUtils;
import org.testng.annotations.Test;
@Test (testName = "client.hotrod.RemoteCacheImplTest", groups = "unit" )
public class RemoteCacheImplTest {
@Test
public void testSubsecondConversion() {
assertEquals(0, CodecUtils.toSeconds(0, TimeUnit.MILLISECONDS));
assertEquals(1, CodecUtils.toSeconds(1, TimeUnit.MILLISECONDS));
assertEquals(1, CodecUtils.toSeconds(999, TimeUnit.MILLISECONDS));
assertEquals(1, CodecUtils.toSeconds(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testFractionOfSecondConversion() {
assertEquals(2, CodecUtils.toSeconds(1001, TimeUnit.MILLISECONDS));
assertEquals(2, CodecUtils.toSeconds(1999, TimeUnit.MILLISECONDS));
assertEquals(2, CodecUtils.toSeconds(2000, TimeUnit.MILLISECONDS));
assertEquals(3, CodecUtils.toSeconds(2001, TimeUnit.MILLISECONDS));
}
}
| 1,051
| 36.571429
| 73
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/ClientStatisticsTest.java
|
package org.infinispan.client.hotrod.impl;
import static org.testng.Assert.assertTrue;
import org.infinispan.commons.time.ControlledTimeService;
import org.testng.annotations.Test;
/**
* @since 10.0
* @author Diego Lovison
*/
@Test(groups = "functional", testName = "client.hotrod.impl.ClientStatisticsTest")
public class ClientStatisticsTest {
public void testAverageRemoteStoreTime() {
ControlledTimeService timeService = new ControlledTimeService();
ClientStatistics clientStatistics = new ClientStatistics(true, timeService);
// given: a put operation
long now = timeService.time();
// when: network is slow
timeService.advance(1200);
clientStatistics.dataStore(now, 1);
// then:
assertTrue(clientStatistics.getAverageRemoteStoreTime() > 0);
}
public void testAverageRemoteReadTime() {
ControlledTimeService timeService = new ControlledTimeService();
ClientStatistics clientStatistics = new ClientStatistics(true, timeService);
// given: a get operation
long now = timeService.time();
// when: network is slow
timeService.advance(1200);
clientStatistics.dataRead(true, now, 1);
// then:
assertTrue(clientStatistics.getAverageRemoteReadTime() > 0);
}
public void testAverageRemovesTime() {
ControlledTimeService timeService = new ControlledTimeService();
ClientStatistics clientStatistics = new ClientStatistics(true, timeService);
// given: a remove operation
long now = timeService.time();
// when: network is slow
timeService.advance(1200);
clientStatistics.dataRemove(now, 1);
// then:
assertTrue(clientStatistics.getAverageRemoteRemovesTime() > 0);
}
}
| 1,753
| 31.481481
| 82
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/iteration/ProtobufRemoteIteratorTest.java
|
package org.infinispan.client.hotrod.impl.iteration;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.Assert.assertEquals;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.Search;
import org.infinispan.client.hotrod.query.testdomain.protobuf.AccountPB;
import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.LocalizedCacheTopology;
import org.infinispan.filter.AbstractKeyValueFilterConverter;
import org.infinispan.filter.KeyValueFilterConverter;
import org.infinispan.filter.KeyValueFilterConverterFactory;
import org.infinispan.metadata.Metadata;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.query.dsl.Query;
import org.infinispan.query.dsl.QueryFactory;
import org.infinispan.query.dsl.embedded.testdomain.Account;
import org.testng.annotations.Test;
/**
* @author gustavonalle
* @since 8.0
*/
@Test(groups = "functional", testName = "client.hotrod.iteration.ProtobufRemoteIteratorTest")
public class ProtobufRemoteIteratorTest extends MultiHotRodServersTest implements AbstractRemoteIteratorTest {
private static final int NUM_NODES = 2;
private static final int CACHE_SIZE = 10;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfgBuilder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
cfgBuilder.encoding().key().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE);
cfgBuilder.encoding().value().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE);
createHotRodServers(NUM_NODES, cfgBuilder);
waitForClusterToForm();
}
@Override
protected SerializationContextInitializer contextInitializer() {
return TestDomainSCI.INSTANCE;
}
public void testSimpleIteration() {
RemoteCache<Integer, AccountPB> cache = clients.get(0).getCache();
populateCache(CACHE_SIZE, this::newAccountPB, cache);
List<AccountPB> results = new ArrayList<>();
cache.retrieveEntries(null, null, CACHE_SIZE).forEachRemaining(e -> results.add((AccountPB) e.getValue()));
assertEquals(CACHE_SIZE, results.size());
}
static final class ToStringFilterConverterFactory implements KeyValueFilterConverterFactory<Integer, AccountPB, String>, Serializable {
@Override
public KeyValueFilterConverter<Integer, AccountPB, String> getFilterConverter() {
return new ToStringFilterConverter();
}
}
static final class ToStringFilterConverter extends AbstractKeyValueFilterConverter<Integer, AccountPB, String> implements Serializable {
@Override
public String filterAndConvert(Integer key, AccountPB value, Metadata metadata) {
return value.toString();
}
}
public void testFilteredIteration() {
servers.forEach(s -> s.addKeyValueFilterConverterFactory("filterName", new ToStringFilterConverterFactory()));
RemoteCache<Integer, AccountPB> cache = clients.get(0).getCache();
populateCache(CACHE_SIZE, this::newAccountPB, cache);
Set<Integer> segments = rangeAsSet(1, 30);
Set<Entry<Object, Object>> results = new HashSet<>();
cache.retrieveEntries("filterName", segments, CACHE_SIZE).forEachRemaining(results::add);
Set<Object> values = extractValues(results);
assertForAll(values, s -> s instanceof String);
Marshaller marshaller = clients.iterator().next().getMarshaller();
LocalizedCacheTopology cacheTopology = advancedCache(0).getDistributionManager().getCacheTopology();
assertKeysInSegment(results, segments, marshaller, cacheTopology::getSegment);
}
public void testFilteredIterationWithQuery() {
RemoteCache<Integer, AccountPB> remoteCache = clients.get(0).getCache();
populateCache(CACHE_SIZE, this::newAccountPB, remoteCache);
QueryFactory queryFactory = Search.getQueryFactory(remoteCache);
int lowerId = 5;
int higherId = 8;
Query<Account> simpleQuery = queryFactory.<Account>create("FROM sample_bank_account.Account WHERE id BETWEEN :lowerId AND :higherId")
.setParameter("lowerId", lowerId)
.setParameter("higherId", higherId);
Set<Entry<Object, Object>> entries = extractEntries(remoteCache.retrieveEntriesByQuery(simpleQuery, null, 10));
Set<Integer> keys = extractKeys(entries);
assertEquals(4, keys.size());
assertForAll(keys, key -> key >= lowerId && key <= higherId);
assertForAll(entries, e -> e.getValue() instanceof AccountPB);
Query<Object[]> projectionsQuery = queryFactory.<Object[]>create("SELECT id, description FROM sample_bank_account.Account WHERE id BETWEEN :lowerId AND :higherId")
.setParameter("lowerId", lowerId)
.setParameter("higherId", higherId);
Set<Entry<Integer, Object[]>> entriesWithProjection = extractEntries(remoteCache.retrieveEntriesByQuery(projectionsQuery, null, 10));
assertEquals(4, entriesWithProjection.size());
assertForAll(entriesWithProjection, entry -> {
Integer id = entry.getKey();
Object[] projection = entry.getValue();
return projection[0].equals(id) && projection[1].equals("description for " + id);
});
}
}
| 5,921
| 43.863636
| 169
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/iteration/MultiServerReplRemoteIteratorTest.java
|
package org.infinispan.client.hotrod.impl.iteration;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
/**
* @author gustavonalle
* @since 8.0
*/
@Test(groups = "functional", testName = "client.hotrod.iteration.MultiServerReplRemoteIteratorTest")
public class MultiServerReplRemoteIteratorTest extends BaseMultiServerRemoteIteratorTest {
private static final int NUM_SERVERS = 3;
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(NUM_SERVERS, getCacheConfiguration());
}
private ConfigurationBuilder getCacheConfiguration() {
ConfigurationBuilder builder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false));
builder.clustering().hash().numSegments(60);
return builder;
}
}
| 989
| 34.357143
| 122
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/iteration/SegmentFilteredFailOverTest.java
|
package org.infinispan.client.hotrod.impl.iteration;
import static org.testng.Assert.assertEquals;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.commons.util.CloseableIterator;
import org.infinispan.query.dsl.embedded.testdomain.hsearch.AccountHS;
import org.testng.annotations.Test;
/**
* @author gustavonalle
* @since 8.2
*/
@Test(groups = "functional", testName = "client.hotrod.iteration.SegmentFilteredFailOverTest")
public class SegmentFilteredFailOverTest extends DistFailOverRemoteIteratorTest {
static final int ENTRIES = 1_000;
@Override
public void testFailOver() throws InterruptedException {
RemoteCache<Integer, AccountHS> remoteCache = clients.get(0).getCache();
populateCache(ENTRIES, this::newAccount, remoteCache);
Cache<Object, Object> cache = caches().get(0);
int totalSegments = cache.getCacheConfiguration().clustering().hash().numSegments();
Set<Integer> segments = IntStream.rangeClosed(0, totalSegments / 2).boxed().collect(Collectors.toSet());
long expectedCount = cache.keySet().stream().filterKeySegments(segments).count();
int actualCount = 0;
try (CloseableIterator<Entry<Object, Object>> iterator = remoteCache.retrieveEntries(null, segments, 10)) {
for (int i = 0; i < ENTRIES / 5; i++) {
iterator.next();
actualCount++;
}
killAnIterationServer();
while (iterator.hasNext()) {
iterator.next();
actualCount++;
}
}
assertEquals(actualCount, expectedCount);
}
}
| 1,747
| 30.781818
| 113
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/iteration/SegmentKeyTrackerTest.java
|
package org.infinispan.client.hotrod.impl.iteration;
import static org.infinispan.client.hotrod.impl.protocol.HotRodConstants.NO_ERROR_STATUS;
import static org.testng.AssertJUnit.assertTrue;
import java.net.SocketAddress;
import java.util.Set;
import org.infinispan.client.hotrod.DataFormat;
import org.infinispan.client.hotrod.impl.consistenthash.SegmentConsistentHash;
import org.infinispan.commons.configuration.ClassAllowList;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.marshall.IdentityMarshaller;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.commons.util.IntSet;
import org.infinispan.commons.util.IntSets;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.SegmentKeyTrackerTest")
public class SegmentKeyTrackerTest {
public void testNoDuplication() {
SocketAddress[][] segmentOwners = new SocketAddress[0][0];
SegmentConsistentHash ch = new SegmentConsistentHash();
ch.init(segmentOwners, 2);
DataFormat df = DataFormat.builder()
.keyType(MediaType.APPLICATION_OBJECT)
.keyMarshaller(IdentityMarshaller.INSTANCE)
.build();
KeyTracker tracker = new SegmentKeyTracker(df, ch, Set.of(0, 1));
// Belongs to segment 0
byte[] key = new byte[] { 0b0, 0b1 };
IntSet completed = IntSets.from(Set.of(0));
assertTrue(tracker.track(key, NO_ERROR_STATUS, new ClassAllowList()));
tracker.segmentsFinished(completed);
Exceptions.expectException(IllegalStateException.class, () ->
tracker.track(key, NO_ERROR_STATUS, new ClassAllowList()));
// Belongs to another segment.
byte[] anotherKey = new byte[] { 0b1, 0b0, 0b1 };
assertTrue(tracker.track(anotherKey, NO_ERROR_STATUS, new ClassAllowList()));
}
}
| 1,851
| 38.404255
| 89
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/iteration/BaseMultiServerRemoteIteratorTest.java
|
package org.infinispan.client.hotrod.impl.iteration;
import static org.testng.Assert.assertTrue;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.infinispan.client.hotrod.CacheTopologyInfo;
import org.infinispan.client.hotrod.MetadataValue;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.Configuration;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.util.CloseableIterator;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.distribution.ch.KeyPartitioner;
import org.infinispan.filter.AbstractKeyValueFilterConverter;
import org.infinispan.filter.KeyValueFilterConverter;
import org.infinispan.filter.KeyValueFilterConverterFactory;
import org.infinispan.filter.ParamKeyValueFilterConverterFactory;
import org.infinispan.metadata.Metadata;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoName;
import org.infinispan.query.dsl.embedded.DslSCI;
import org.infinispan.query.dsl.embedded.testdomain.hsearch.AccountHS;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @author gustavonalle
* @since 8.0
*/
@Test(groups = "functional")
public abstract class BaseMultiServerRemoteIteratorTest extends MultiHotRodServersTest implements AbstractRemoteIteratorTest {
public static final int CACHE_SIZE = 20;
@BeforeMethod
public void clear() {
clients.forEach(c -> c.getCache().clear());
}
@Override
protected void modifyGlobalConfiguration(GlobalConfigurationBuilder builder) {
builder.serialization().addContextInitializer(SCI.INSTANCE);
}
@Override
protected RemoteCacheManager createClient(int i) {
Configuration cfg = createHotRodClientConfigurationBuilder(server(i)).addContextInitializer(DslSCI.INSTANCE).build();
return new InternalRemoteCacheManager(cfg);
}
@Test
public void testBatchSizes() {
int maximumBatchSize = 120;
RemoteCache<Integer, AccountHS> cache = clients.get(0).getCache();
populateCache(CACHE_SIZE, this::newAccount, cache);
Set<Integer> expectedKeys = rangeAsSet(0, CACHE_SIZE);
for (int batch = 1; batch < maximumBatchSize; batch += 10) {
Set<Entry<Object, Object>> results = new HashSet<>(CACHE_SIZE);
CloseableIterator<Entry<Object, Object>> iterator = cache.retrieveEntries(null, null, batch);
iterator.forEachRemaining(results::add);
iterator.close();
assertEquals(CACHE_SIZE, results.size());
assertEquals(expectedKeys, extractKeys(results));
}
}
@Test
public void testEmptyCache() {
try (CloseableIterator<Entry<Object, Object>> iterator = client(0).getCache().retrieveEntries(null, null, 100)) {
assertFalse(iterator.hasNext());
assertFalse(iterator.hasNext());
}
}
@Test
public void testFilterBySegmentAndCustomFilter() {
String toHexConverterName = "toHexConverter";
servers.forEach(s -> s.addKeyValueFilterConverterFactory(toHexConverterName, new ToHexConverterFactory()));
RemoteCache<Integer, Integer> numbersCache = clients.get(0).getCache();
populateCache(CACHE_SIZE, i -> i, numbersCache);
Set<Integer> segments = setOf(15, 20, 25);
Set<Entry<Object, Object>> entries = new HashSet<>();
try (CloseableIterator<Entry<Object, Object>> iterator = numbersCache.retrieveEntries(toHexConverterName, segments, 10)) {
while (iterator.hasNext()) {
entries.add(iterator.next());
}
}
Set<String> values = extractValues(entries);
getKeysFromSegments(segments).forEach(i -> assertTrue(values.contains(Integer.toHexString(i))));
}
@Test
public void testFilterByCustomParamFilter() {
String factoryName = "substringConverter";
servers.forEach(s -> s.addKeyValueFilterConverterFactory(factoryName, new SubstringFilterFactory()));
int filterParam = 12;
RemoteCache<String, String> stringCache = clients.get(0).getCache();
IntStream.rangeClosed(0, CACHE_SIZE - 1).forEach(idx -> stringCache.put(String.valueOf(idx), Util.threadLocalRandomUUID().toString()));
Set<Entry<Object, Object>> entries = extractEntries(stringCache.retrieveEntries(factoryName, new Object[]{filterParam}, null, 10));
Set<String> values = extractValues(entries);
assertForAll(values, s -> s.length() == filterParam);
// Omitting param, filter should use default value
entries = extractEntries(stringCache.retrieveEntries(factoryName, 10));
values = extractValues(entries);
assertForAll(values, s -> s.length() == SubstringFilterFactory.DEFAULT_LENGTH);
}
@Test
public void testFilterBySegment() {
RemoteCache<Integer, AccountHS> cache = clients.get(0).getCache();
populateCache(CACHE_SIZE, this::newAccount, cache);
CacheTopologyInfo cacheTopologyInfo = cache.getCacheTopologyInfo();
// Request all segments from one node
Set<Integer> filterBySegments = cacheTopologyInfo.getSegmentsPerServer().values().iterator().next();
Set<Entry<Object, Object>> entries = new HashSet<>();
try (CloseableIterator<Entry<Object, Object>> iterator = cache.retrieveEntries(null, filterBySegments, 10)) {
while (iterator.hasNext()) {
entries.add(iterator.next());
}
}
Marshaller marshaller = clients.get(0).getMarshaller();
KeyPartitioner keyPartitioner = TestingUtil.extractComponent(cache(0), KeyPartitioner.class);
assertKeysInSegment(entries, filterBySegments, marshaller, keyPartitioner::getSegment);
}
@Test
public void testRetrieveMetadata() {
RemoteCache<Integer, AccountHS> cache = clients.get(0).getCache();
cache.put(1, newAccount(1), 1, TimeUnit.DAYS);
cache.put(2, newAccount(2), 2, TimeUnit.MINUTES, 30, TimeUnit.SECONDS);
cache.put(3, newAccount(3));
try (CloseableIterator<Entry<Object, MetadataValue<Object>>> iterator = cache.retrieveEntriesWithMetadata(null, 10)) {
Entry<Object, MetadataValue<Object>> entry = iterator.next();
if ((int) entry.getKey() == 1) {
assertEquals(24 * 3600, entry.getValue().getLifespan());
assertEquals(-1, entry.getValue().getMaxIdle());
}
if ((int) entry.getKey() == 2) {
assertEquals(2 * 60, entry.getValue().getLifespan());
assertEquals(30, entry.getValue().getMaxIdle());
}
if ((int) entry.getKey() == 3) {
assertEquals(-1, entry.getValue().getLifespan());
assertEquals(-1, entry.getValue().getMaxIdle());
}
}
}
static final class ToHexConverterFactory implements KeyValueFilterConverterFactory<Integer, Integer, String>, Serializable {
@Override
public KeyValueFilterConverter<Integer, Integer, String> getFilterConverter() {
return new HexFilterConverter();
}
@ProtoName("HexFilterConverter")
static class HexFilterConverter extends AbstractKeyValueFilterConverter<Integer, Integer, String> {
@Override
public String filterAndConvert(Integer key, Integer value, Metadata metadata) {
return Integer.toHexString(value);
}
}
}
static final class SubstringFilterFactory implements ParamKeyValueFilterConverterFactory<String, String, String> {
static final int DEFAULT_LENGTH = 20;
@Override
public KeyValueFilterConverter<String, String, String> getFilterConverter(Object[] params) {
return new SubstringFilterConverter(params);
}
static class SubstringFilterConverter extends AbstractKeyValueFilterConverter<String, String, String> {
@ProtoField(number = 1, defaultValue = "0")
final int length;
@ProtoFactory
SubstringFilterConverter(int length) {
this.length = length;
}
SubstringFilterConverter(Object[] params) {
this.length = (int) (params == null || params.length == 0 ? DEFAULT_LENGTH : params[0]);
}
@Override
public String filterAndConvert(String key, String value, Metadata metadata) {
return value.substring(0, length);
}
}
}
private Set<Integer> getKeysFromSegments(Set<Integer> segments) {
RemoteCacheManager remoteCacheManager = clients.get(0);
RemoteCache<Integer, ?> cache = remoteCacheManager.getCache();
Marshaller marshaller = clients.get(0).getMarshaller();
KeyPartitioner keyPartitioner = TestingUtil.extractComponent(cache(0), KeyPartitioner.class);
Set<Integer> keys = cache.keySet();
return keys.stream()
.filter(b -> segments.contains(keyPartitioner.getSegment(toByteBuffer(b, marshaller))))
.collect(Collectors.toSet());
}
@AutoProtoSchemaBuilder(
dependsOn = DslSCI.class,
includeClasses = {
ToHexConverterFactory.HexFilterConverter.class,
SubstringFilterFactory.SubstringFilterConverter.class
},
schemaFileName = "test.client.BaseMultiServerRemoteIterator.proto",
schemaFilePath = "proto/generated",
schemaPackageName = "org.infinispan.test.client.BaseMultiServerRemoteIterator",
service = false
)
interface SCI extends SerializationContextInitializer {
SCI INSTANCE = new SCIImpl();
}
}
| 10,263
| 39.730159
| 141
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/iteration/SingleServerObjectStorageRemoteIteratorTest.java
|
package org.infinispan.client.hotrod.impl.iteration;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.query.dsl.embedded.DslSCI;
import org.infinispan.server.hotrod.test.HotRodTestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* Remote iterator test with server storing java objects instead of binary content.
*
* @author vjuranek
* @since 8.2
*/
@Test(groups = "functional", testName = "client.hotrod.iteration.SingleServerObjectStorageRemoteIteratorTest")
public class SingleServerObjectStorageRemoteIteratorTest extends SingleServerRemoteIteratorTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder cb = HotRodTestingUtil.hotRodCacheConfiguration();
cb.encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE);
cb.encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE);
return TestCacheManagerFactory.createServerModeCacheManager(DslSCI.INSTANCE, cb);
}
}
| 1,175
| 38.2
| 110
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.