diff --git a/infinispan-remote/cache-admin-api/README.adoc b/infinispan-remote/cache-admin-api/README.adoc deleted file mode 100644 index e125bf9d..00000000 --- a/infinispan-remote/cache-admin-api/README.adoc +++ /dev/null @@ -1,15 +0,0 @@ -= Remote Cache Administration - -**Authors:** Wolf Fink + -**Technologies:** Infinispan, Hot Rod, Java + -**Summary:** Use Hot Rod Java clients to remotely create and administer caches -on Infinispan servers. - -. Add credentials to `InfinispanRemoteAdminCache.java`. -. Build and run the Hot Rod Java client as follows: - ----- -$ mvn clean package - -$ mvn exec:exec ----- diff --git a/infinispan-remote/cache-admin-api/pom.xml b/infinispan-remote/cache-admin-api/pom.xml index 07a01839..9a935112 100644 --- a/infinispan-remote/cache-admin-api/pom.xml +++ b/infinispan-remote/cache-admin-api/pom.xml @@ -46,5 +46,10 @@ org.infinispan infinispan-client-hotrod + + org.junit.jupiter + junit-jupiter + test + diff --git a/infinispan-remote/cache-admin-api/src/main/java/org/infinispan/tutorial/simple/remote/admin/InfinispanRemoteAdminCache.java b/infinispan-remote/cache-admin-api/src/main/java/org/infinispan/tutorial/simple/remote/admin/InfinispanRemoteAdminCache.java index 4440e9bb..e794d140 100644 --- a/infinispan-remote/cache-admin-api/src/main/java/org/infinispan/tutorial/simple/remote/admin/InfinispanRemoteAdminCache.java +++ b/infinispan-remote/cache-admin-api/src/main/java/org/infinispan/tutorial/simple/remote/admin/InfinispanRemoteAdminCache.java @@ -12,7 +12,7 @@ /** * The InfinispanRemoteAdminCache class shows how to remotely create caches * with Hot Rod Java clients using different approaches. - * By default caches are permanent and survive cluster restarts. + * By default, caches are permanent and survive cluster restarts. * To create volatile, temporary caches use "withFlags(AdminFlag.VOLATILE)". * Data in temporary caches is lost on full cluster restart. * @@ -22,21 +22,29 @@ * @author Wolf Dieter Fink */ public class InfinispanRemoteAdminCache { - private final RemoteCacheManager manager = TutorialsConnectorHelper.connect(); + public static final String SIMPLE_CACHE = "SimpleCache"; + public static final String CACHE_WITH_XMLCONFIGURATION = "CacheWithXMLConfiguration"; + public static final String CACHE_WITH_TEMPLATE = "CacheWithTemplate"; + static RemoteCacheManager cacheManager = TutorialsConnectorHelper.connect(); public static void main(String[] args) throws Exception { - InfinispanRemoteAdminCache client = new InfinispanRemoteAdminCache(); + connectToInfinispan(); - client.createSimpleCache(); - client.cacheWithTemplate(); - client.createCacheWithXMLConfiguration(); + createSimpleCache(); + cacheWithTemplate(); + createCacheWithXMLConfiguration(); - // Stop the Hot Rod client and release all resources. - client.stop(); + disconnect(); } - private void stop() { - TutorialsConnectorHelper.stop(manager); + static void connectToInfinispan() { + // Connect to the server + cacheManager = TutorialsConnectorHelper.connect(); + } + + static void disconnect() { + // Stop the cache manager and release all resources + TutorialsConnectorHelper.stop(cacheManager); } /** @@ -44,10 +52,9 @@ private void stop() { * StringConfiguration() method to pass the cache definition as * valid infinispan.xml. */ - private void createCacheWithXMLConfiguration() throws IOException { - String cacheName = "CacheWithXMLConfiguration"; - String xml = Files.readString(Paths.get(this.getClass().getClassLoader().getResource("CacheWithXMLConfiguration.xml").getPath())); - manager.administration().getOrCreateCache(cacheName, new StringConfiguration(xml)); + static void createCacheWithXMLConfiguration() throws IOException { + String xml = Files.readString(Paths.get(InfinispanRemoteAdminCache.class.getClassLoader().getResource("CacheWithXMLConfiguration.xml").getPath())); + cacheManager.administration().getOrCreateCache(CACHE_WITH_XMLCONFIGURATION, new StringConfiguration(xml)); System.out.println("Cache with configuration exists or is created."); } @@ -55,26 +62,26 @@ private void createCacheWithXMLConfiguration() throws IOException { * Creates a cache named CacheWithTemplate from the org.infinispan.DIST_SYNC * template. */ - private void cacheWithTemplate() throws IOException { - Path path = Paths.get(this.getClass().getClassLoader().getResource("cacheTemplate.xml").getPath()); + static void cacheWithTemplate() throws IOException { + Path path = Paths.get(InfinispanRemoteAdminCache.class.getClassLoader().getResource("cacheTemplate.xml").getPath()); String xmlTemplate = Files.readString(path); try { - manager.administration().createTemplate("template", new StringConfiguration(xmlTemplate)); + cacheManager.administration().createTemplate("template", new StringConfiguration(xmlTemplate)); } catch (Exception ce) { // If the System.out.println(ce.getMessage()); } - manager.administration().getOrCreateCache("CacheWithTemplate", "template"); + cacheManager.administration().getOrCreateCache(CACHE_WITH_TEMPLATE, "template"); System.out.println("Cache created from default template."); } /** * Creates a simple, local cache with no configuration. */ - private void createSimpleCache() { + static void createSimpleCache() { try { - manager.administration().createCache("SimpleCache", (String)null); + cacheManager.administration().createCache(SIMPLE_CACHE, (String)null); System.out.println("SimpleCache created."); } catch (Exception e) { System.out.println("Expected to fail for multiple invocations as the cache exists message: " + e.getMessage()); diff --git a/infinispan-remote/cache-admin-api/src/test/java/org/infinispan/tutorial/simple/remote/admin/InfinispanRemoteAdminCacheTest.java b/infinispan-remote/cache-admin-api/src/test/java/org/infinispan/tutorial/simple/remote/admin/InfinispanRemoteAdminCacheTest.java new file mode 100644 index 00000000..9e8f365e --- /dev/null +++ b/infinispan-remote/cache-admin-api/src/test/java/org/infinispan/tutorial/simple/remote/admin/InfinispanRemoteAdminCacheTest.java @@ -0,0 +1,48 @@ +package org.infinispan.tutorial.simple.remote.admin; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static org.infinispan.tutorial.simple.remote.admin.InfinispanRemoteAdminCache.CACHE_WITH_TEMPLATE; +import static org.infinispan.tutorial.simple.remote.admin.InfinispanRemoteAdminCache.CACHE_WITH_XMLCONFIGURATION; +import static org.infinispan.tutorial.simple.remote.admin.InfinispanRemoteAdminCache.SIMPLE_CACHE; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class InfinispanRemoteAdminCacheTest { + + @BeforeAll + public static void start() { + InfinispanRemoteAdminCache.connectToInfinispan(); + } + + @AfterAll + public static void stop() { + InfinispanRemoteAdminCache.disconnect(); + } + + @Test + public void testCacheManager() { + assertNotNull(InfinispanRemoteAdminCache.cacheManager); + } + + @Test + public void testCreateSimpleCache() { + InfinispanRemoteAdminCache.createSimpleCache(); + assertNotNull(InfinispanRemoteAdminCache.cacheManager.getCache(SIMPLE_CACHE)); + } + + @Test + public void testCreateWithTemplate() throws IOException { + InfinispanRemoteAdminCache.cacheWithTemplate(); + assertNotNull(InfinispanRemoteAdminCache.cacheManager.getCache(CACHE_WITH_TEMPLATE)); + } + + @Test + public void createCacheWithXMLConfiguration() throws IOException { + InfinispanRemoteAdminCache.createCacheWithXMLConfiguration(); + assertNotNull(InfinispanRemoteAdminCache.cacheManager.getCache(CACHE_WITH_XMLCONFIGURATION)); + } +} \ No newline at end of file diff --git a/infinispan-remote/cache/pom.xml b/infinispan-remote/cache/pom.xml index 2d8547c7..0d339402 100644 --- a/infinispan-remote/cache/pom.xml +++ b/infinispan-remote/cache/pom.xml @@ -46,5 +46,10 @@ org.infinispan infinispan-client-hotrod + + org.junit.jupiter + junit-jupiter + test + diff --git a/infinispan-remote/cache/src/main/java/org/infinispan/tutorial/simple/remote/InfinispanRemoteCache.java b/infinispan-remote/cache/src/main/java/org/infinispan/tutorial/simple/remote/InfinispanRemoteCache.java index f85bada3..3a7df2a1 100644 --- a/infinispan-remote/cache/src/main/java/org/infinispan/tutorial/simple/remote/InfinispanRemoteCache.java +++ b/infinispan-remote/cache/src/main/java/org/infinispan/tutorial/simple/remote/InfinispanRemoteCache.java @@ -14,15 +14,30 @@ */ public class InfinispanRemoteCache { + static RemoteCacheManager cacheManager; + static RemoteCache cache; + public static void main(String[] args) { - // Connect to the server - RemoteCacheManager cacheManager = TutorialsConnectorHelper.connect(); - // Obtain the remote cache - RemoteCache cache = cacheManager.getCache(TUTORIAL_CACHE_NAME); - /// Store a value + connectToInfinispan(); + manipulateCache(); + disconnect(); + } + + static void manipulateCache() { + // Store a value cache.put("key", "value"); // Retrieve the value and print it out System.out.printf("key = %s\n", cache.get("key")); + } + + static void connectToInfinispan() { + // Connect to the server + cacheManager = TutorialsConnectorHelper.connect(); + // Obtain the remote cache + cache = cacheManager.getCache(TUTORIAL_CACHE_NAME); + } + + static void disconnect() { // Stop the cache manager and release all resources TutorialsConnectorHelper.stop(cacheManager); } diff --git a/infinispan-remote/cache/src/test/java/org/infinispan/tutorial/simple/remote/InfinispanRemoteCacheTest.java b/infinispan-remote/cache/src/test/java/org/infinispan/tutorial/simple/remote/InfinispanRemoteCacheTest.java new file mode 100644 index 00000000..5325f15d --- /dev/null +++ b/infinispan-remote/cache/src/test/java/org/infinispan/tutorial/simple/remote/InfinispanRemoteCacheTest.java @@ -0,0 +1,31 @@ +package org.infinispan.tutorial.simple.remote; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class InfinispanRemoteCacheTest { + + @BeforeAll + public static void start() { + InfinispanRemoteCache.connectToInfinispan(); + } + + @AfterAll + public static void stop() { + InfinispanRemoteCache.disconnect(); + } + + @Test + public void testRemoteCache() { + assertNotNull(InfinispanRemoteCache.cache); + + InfinispanRemoteCache.manipulateCache(); + + assertEquals("value", InfinispanRemoteCache.cache.get("key")); + } + +} diff --git a/infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/TutorialsConnectorHelper.java b/infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/TutorialsConnectorHelper.java index 031e0f4d..5770a5c9 100644 --- a/infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/TutorialsConnectorHelper.java +++ b/infinispan-remote/connect-to-infinispan-server/src/main/java/org/infinispan/tutorial/simple/connect/TutorialsConnectorHelper.java @@ -1,5 +1,6 @@ package org.infinispan.tutorial.simple.connect; +import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ClientIntelligence; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; @@ -67,13 +68,11 @@ public static final RemoteCacheManager connect() { public static InfinispanContainer INFINISPAN_CONTAINER; public static final RemoteCacheManager connect(ConfigurationBuilder builder) { - RemoteCacheManager cacheManager = null; try { - builder.addServer().host(HOST).port(SINGLE_PORT); cacheManager = new RemoteCacheManager(builder.build()); - // Clear the cache in case it already exists from a previous running tutorial - cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); + //ping + System.out.println("Get cache names: " + cacheManager.getCacheNames()); } catch (Exception ex) { System.out.println("Unable to connect to a running server in localhost:11222. Try test containers"); if (cacheManager != null) { @@ -85,26 +84,39 @@ public static final RemoteCacheManager connect(ConfigurationBuilder builder) { if (cacheManager == null) { try { startInfinispanContainer(); - builder.addServer().host(HOST).port(INFINISPAN_CONTAINER.getFirstMappedPort()); + builder.addServer().host(HOST).port(INFINISPAN_CONTAINER.getMappedPort(SINGLE_PORT)); cacheManager = new RemoteCacheManager(builder.build()); - // Clear the cache in case it already exists from a previous running tutorial - cacheManager.getCache(TUTORIAL_CACHE_NAME).clear(); + //ping + System.out.println("Get cache names: " + cacheManager.getCacheNames()); } catch (Exception ex) { System.out.println("Infinispan Server start with Testcontainers failed. Exit"); System.exit(0); } } + if (cacheManager != null) { + // Clear the cache in case it already exists from a previous running tutorial + RemoteCache testCache = cacheManager.getCache(TUTORIAL_CACHE_NAME); + if (testCache != null) { + testCache.clear(); + } else { + System.out.println("Test cache does not exist"); + } + } // Return the connected cache manager return cacheManager; } public static InfinispanContainer startInfinispanContainer() { + return startInfinispanContainer(1000); + } + + public static InfinispanContainer startInfinispanContainer(long millis) { try { INFINISPAN_CONTAINER = new InfinispanContainer(); INFINISPAN_CONTAINER.withUser(USER); INFINISPAN_CONTAINER.withPassword(PASSWORD); INFINISPAN_CONTAINER.start(); - Thread.sleep(3000); + Thread.sleep(millis); } catch (Exception ex) { System.out.println("Unable to start Infinispan container"); return null; @@ -127,8 +139,10 @@ public static void stopInfinispanContainer() { } public static void stop(RemoteCacheManager cacheManager) { - cacheManager.stop(); - stopInfinispanContainer(); + if (cacheManager != null){ + cacheManager.stop(); + stopInfinispanContainer(); + } } } diff --git a/infinispan-remote/continuous-query/pom.xml b/infinispan-remote/continuous-query/pom.xml index 59b7e951..b21ea6a7 100644 --- a/infinispan-remote/continuous-query/pom.xml +++ b/infinispan-remote/continuous-query/pom.xml @@ -60,6 +60,11 @@ protostream-processor ${version.protostream} + + org.junit.jupiter + junit-jupiter + test + diff --git a/infinispan-remote/continuous-query/src/main/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteContinuousQuery.java b/infinispan-remote/continuous-query/src/main/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteContinuousQuery.java index 9e44ee5a..62252359 100644 --- a/infinispan-remote/continuous-query/src/main/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteContinuousQuery.java +++ b/infinispan-remote/continuous-query/src/main/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteContinuousQuery.java @@ -8,7 +8,6 @@ import org.infinispan.commons.api.query.Query; import org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper; -import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -57,17 +56,29 @@ public class InfinispanRemoteContinuousQuery { "followme", "infinispan"); - private static final String CACHE_NAME = "instaposts"; + static RemoteCacheManager client; + static InstaSchemaImpl schema; + static ContinuousQuery continuousQuery; + static ContinuousQueryListener listener; + static List queryPosts = new ArrayList<>(); + static Random random = new Random(); public static void main(String[] args) throws Exception { - // Connect to the server - ConfigurationBuilder builder = TutorialsConnectorHelper.connectionConfig(); - InstaSchemaImpl schema = new InstaSchemaImpl(); - builder.addContextInitializer(schema); - RemoteCacheManager client = TutorialsConnectorHelper.connect(builder); - // Create and add the Protobuf schema for InstaPost class. Note InstaPost is an annotated POJO - register(schema, client); + connectToInfinispan(); + createPostsAndQuery(1000, true); + cleanup(); + disconnect(); + } + + private static void cleanup() { + // Remove the listener. Listeners should be removed when they are no longer needed to avoid memory leaks + continuousQuery.removeContinuousQueryListener(listener); + // Remove the cache + client.administration().removeCache(TutorialsConnectorHelper.TUTORIAL_CACHE_NAME); + } + + public static void createPostsAndQuery(int size, boolean random) throws Exception { RemoteCache cache = client.getCache(TutorialsConnectorHelper.TUTORIAL_CACHE_NAME); // Create a query with lastName parameter @@ -80,24 +91,23 @@ public static void main(String[] args) throws Exception { ContinuousQuery continuousQuery = cache.continuousQuery(); // Create the continuous query listener. - List queryPosts = new ArrayList<>(); - ContinuousQueryListener listener = - new ContinuousQueryListener() { - // This method will be executed every time new items that correspond with the query arrive - @Override - public void resultJoining(String key, InstaPost post) { - System.out.println(String.format("@%s has posted again! Hashtag: #%s", post.user(), post.hashtag())); - queryPosts.add(post); - } - }; + listener = + new ContinuousQueryListener<>() { + // This method will be executed every time new items that correspond with the query arrive + @Override + public void resultJoining(String key, InstaPost post) { + System.out.println(String.format("@%s has posted again! Hashtag: #%s", post.user(), post.hashtag())); + queryPosts.add(post); + } + }; // And the listener corresponding the query to the continuous query continuousQuery.addContinuousQueryListener(query, listener); // Add 1000 random posts - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < size; i++) { // Add a post - addRandomPost(cache); + addPost(cache, random); // Await a little to see results Thread.sleep(10); @@ -105,27 +115,36 @@ public void resultJoining(String key, InstaPost post) { System.out.println("Total posts " + cache.size()); System.out.println("Total posts by @belen_esteban " + queryPosts.size()); - - // Remove the listener. Listeners should be removed when they are no longer needed to avoid memory leaks - continuousQuery.removeContinuousQueryListener(listener); - - // Remove the cache - client.administration().removeCache(CACHE_NAME); - - // Stop the client and release all resources - TutorialsConnectorHelper.stop(client); } - private static void addRandomPost(RemoteCache cache) { + private static void addPost(RemoteCache cache, boolean isRandom) { String id = UUID.randomUUID().toString(); - Random random = new Random(); - // Create the random post - InstaPost post = new InstaPost(id, USERS.get(random.nextInt(USERS.size())), HASHTAGS.get(random.nextInt(HASHTAGS.size()))); + InstaPost post; + if (isRandom) { + // Create the random post + post = new InstaPost(id, USERS.get(random.nextInt(USERS.size())), HASHTAGS.get(random.nextInt(HASHTAGS.size()))); + } else { + post = new InstaPost(id, "belen_esteban", "infinispan"); + } // Put a post in the cache cache.put(id, post); } - private static void register(InstaSchemaImpl schema, RemoteCacheManager cacheManager) throws IOException { + public static void connectToInfinispan() { + ConfigurationBuilder builder = TutorialsConnectorHelper.connectionConfig(); + schema = new InstaSchemaImpl(); + builder.addContextInitializer(schema); + client = TutorialsConnectorHelper.connect(builder); + // Create and add the Protobuf schema for InstaPost class. Note InstaPost is an annotated POJO + register(schema, client); + } + + public static void disconnect() { + // Stop the client and release all resources + TutorialsConnectorHelper.stop(client); + } + + private static void register(InstaSchemaImpl schema, RemoteCacheManager cacheManager) { // Retrieve metadata cache RemoteCache metadataCache = cacheManager.getCache(PROTOBUF_METADATA_CACHE_NAME); diff --git a/infinispan-remote/continuous-query/src/test/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteContinuousQueryTest.java b/infinispan-remote/continuous-query/src/test/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteContinuousQueryTest.java new file mode 100644 index 00000000..841e4751 --- /dev/null +++ b/infinispan-remote/continuous-query/src/test/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteContinuousQueryTest.java @@ -0,0 +1,33 @@ +package org.infinispan.tutorial.simple.remote.query; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper.TUTORIAL_CACHE_NAME; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class InfinispanRemoteContinuousQueryTest { + + @BeforeAll + public static void start() throws Exception { + InfinispanRemoteContinuousQuery.connectToInfinispan(); + } + + @AfterAll + public static void stop() { + InfinispanRemoteContinuousQuery.disconnect(); + } + + @Test + public void testContinuousQuery() throws Exception { + assertNotNull(InfinispanRemoteContinuousQuery.client); + + InfinispanRemoteContinuousQuery.createPostsAndQuery(1, false); + + assertEquals(1, InfinispanRemoteContinuousQuery.queryPosts.size()); + assertEquals(1, InfinispanRemoteContinuousQuery.client.getCache(TUTORIAL_CACHE_NAME).size()); + } + +} \ No newline at end of file diff --git a/infinispan-remote/counter/pom.xml b/infinispan-remote/counter/pom.xml index 252a3f2f..443b9e3c 100644 --- a/infinispan-remote/counter/pom.xml +++ b/infinispan-remote/counter/pom.xml @@ -46,5 +46,10 @@ org.infinispan infinispan-client-hotrod + + org.junit.jupiter + junit-jupiter + test + diff --git a/infinispan-remote/counter/src/main/java/org/infinispan/tutorial/simple/remote/counter/InfinispanRemoteCounter.java b/infinispan-remote/counter/src/main/java/org/infinispan/tutorial/simple/remote/counter/InfinispanRemoteCounter.java index 86d59706..fa8661f1 100644 --- a/infinispan-remote/counter/src/main/java/org/infinispan/tutorial/simple/remote/counter/InfinispanRemoteCounter.java +++ b/infinispan-remote/counter/src/main/java/org/infinispan/tutorial/simple/remote/counter/InfinispanRemoteCounter.java @@ -21,32 +21,38 @@ */ public class InfinispanRemoteCounter { - public static void main(String[] args) throws Exception { - // Connect to the server - RemoteCacheManager cacheManager = TutorialsConnectorHelper.connect(); + static RemoteCacheManager cacheManager; + static CounterManager counterManager; + static StrongCounter counter1; + static StrongCounter counter2; + static WeakCounter counter3; - // Retrieve the CounterManager from the CacheManager. Each CacheManager has it own CounterManager - CounterManager counterManager = RemoteCounterManagerFactory.asCounterManager(cacheManager); + public static void main(String[] args) throws Exception { + connectToInfinispan(); + manipulateCounters(); + disconnect(); + } + public static void manipulateCounters() throws Exception { // Create 3 counters. // The first counter is bounded to 10 (upper-bound). counterManager.defineCounter("counter-1", CounterConfiguration.builder(CounterType.BOUNDED_STRONG) - .upperBound(10) - .initialValue(1) - .build()); + .upperBound(10) + .initialValue(1) + .build()); // The second counter is unbounded counterManager.defineCounter("counter-2", CounterConfiguration.builder(CounterType.UNBOUNDED_STRONG) - .initialValue(2) - .build()); + .initialValue(2) + .build()); // And finally, the third counter is a weak counter. counterManager.defineCounter("counter-3", CounterConfiguration.builder(CounterType.WEAK) - .initialValue(3) - .build()); + .initialValue(3) + .build()); // StrongCounter provides the higher consistency. Its value is known during the increment/decrement and it may be bounded. // Bounded counters are aimed for uses cases where a limit is needed. - StrongCounter counter1 = counterManager.getStrongCounter("counter-1"); + counter1 = counterManager.getStrongCounter("counter-1"); // All methods returns a CompletableFuture. So you can do other work while the counter value is being computed. counter1.getValue().thenAccept(value -> System.out.println("Counter-1 initial value is " + value)).get(); @@ -68,12 +74,12 @@ public static void main(String[] args) throws Exception { }).get(); // Similar to counter-1, counter-2 is a strong counter but it is unbounded. It will never throw the CounterOutOfBoundsException - StrongCounter counter2 = counterManager.getStrongCounter("counter-2"); + counter2 = counterManager.getStrongCounter("counter-2"); // All counters allow a listener to be registered. // The handle can be used to remove the listener counter2.addListener(event -> System.out - .println("Counter-2 event: oldValue=" + event.getOldValue() + " newValue=" + event.getNewValue())); + .println("Counter-2 event: oldValue=" + event.getOldValue() + " newValue=" + event.getNewValue())); // Adding MAX_VALUE won't throws an exception. But the all the increments won't have any effect since we can store //any value larger the MAX_VALUE @@ -81,7 +87,7 @@ public static void main(String[] args) throws Exception { // Conditional operations are allowed in strong counters counter2.compareAndSet(Long.MAX_VALUE, 0) - .thenAccept(aBoolean -> System.out.println("Counter-2 CAS result is " + aBoolean)).get(); + .thenAccept(aBoolean -> System.out.println("Counter-2 CAS result is " + aBoolean)).get(); counter2.getValue().thenAccept(value -> System.out.println("Counter-2 value is " + value)).get(); // Reset the counter to its initial value (2) @@ -89,7 +95,7 @@ public static void main(String[] args) throws Exception { counter2.getValue().thenAccept(value -> System.out.println("Counter-2 initial value is " + value)).get(); // Retrieve counter-3 - WeakCounter counter3 = counterManager.getWeakCounter("counter-3"); + counter3 = counterManager.getWeakCounter("counter-3"); // Weak counter doesn't have its value available during updates. This makes the increment faster than the StrongCounter // Its value is computed lazily and stored locally. // Its main use case is for uses-case where faster increments are needed. @@ -97,9 +103,22 @@ public static void main(String[] args) throws Exception { // Check the counter value. System.out.println("Counter-3 value is " + counter3.getValue()); + } + public static void connectToInfinispan() { + // Connect to the server + cacheManager = TutorialsConnectorHelper.connect(); + + // Retrieve the CounterManager from the CacheManager. Each CacheManager has it own CounterManager + counterManager = RemoteCounterManagerFactory.asCounterManager(cacheManager); + } + + public static void disconnect() { + // Cleanup counters + counterManager.remove(counter1.getName()); + counterManager.remove(counter2.getName()); + counterManager.remove(counter3.getName()); // Stop the cache manager and release all resources TutorialsConnectorHelper.stop(cacheManager); } - } diff --git a/infinispan-remote/counter/src/test/java/org/infinispan/tutorial/simple/remote/counter/InfinispanRemoteCounterTest.java b/infinispan-remote/counter/src/test/java/org/infinispan/tutorial/simple/remote/counter/InfinispanRemoteCounterTest.java new file mode 100644 index 00000000..7e8b70ed --- /dev/null +++ b/infinispan-remote/counter/src/test/java/org/infinispan/tutorial/simple/remote/counter/InfinispanRemoteCounterTest.java @@ -0,0 +1,35 @@ +package org.infinispan.tutorial.simple.remote.counter; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class InfinispanRemoteCounterTest { + + @BeforeAll + public static void start() { + InfinispanRemoteCounter.connectToInfinispan(); + } + + @AfterAll + public static void stop() { + InfinispanRemoteCounter.disconnect(); + } + + @Test + public void testRemoteCounters() throws Exception { + assertNotNull(InfinispanRemoteCounter.cacheManager); + assertNotNull(InfinispanRemoteCounter.counterManager); + + InfinispanRemoteCounter.manipulateCounters(); + + assertNotNull(InfinispanRemoteCounter.counter1); + assertNotNull(InfinispanRemoteCounter.counter2); + assertNotNull(InfinispanRemoteCounter.counter3); + assertEquals(9, InfinispanRemoteCounter.counter1.sync().getValue()); + assertEquals(2, InfinispanRemoteCounter.counter2.sync().getValue()); + assertEquals(8, InfinispanRemoteCounter.counter3.sync().getValue()); + } +} diff --git a/infinispan-remote/cross-site-replication/pom.xml b/infinispan-remote/cross-site-replication/pom.xml index ac8aaab7..2c74c0ce 100644 --- a/infinispan-remote/cross-site-replication/pom.xml +++ b/infinispan-remote/cross-site-replication/pom.xml @@ -47,6 +47,11 @@ org.infinispan infinispan-client-hotrod + + org.junit.jupiter + junit-jupiter + test + diff --git a/infinispan-remote/cross-site-replication/src/main/java/org/infinispan/tutorial/simple/remote/xsite/InfinispanRemoteSwitchCluster.java b/infinispan-remote/cross-site-replication/src/main/java/org/infinispan/tutorial/simple/remote/xsite/InfinispanRemoteSwitchCluster.java index 3756c46d..25ec58b0 100644 --- a/infinispan-remote/cross-site-replication/src/main/java/org/infinispan/tutorial/simple/remote/xsite/InfinispanRemoteSwitchCluster.java +++ b/infinispan-remote/cross-site-replication/src/main/java/org/infinispan/tutorial/simple/remote/xsite/InfinispanRemoteSwitchCluster.java @@ -3,8 +3,11 @@ import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; +import org.infinispan.commons.configuration.StringConfiguration; import org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper; +import java.util.ArrayList; +import java.util.List; import java.util.stream.Collectors; /** @@ -15,32 +18,55 @@ * with Cross Site Replication enabled and the ./create-data.sh script in the docker-compose directory */ public class InfinispanRemoteSwitchCluster { + public static final String XSITE_CACHE = "xsiteCache"; + static RemoteCache cache; + static RemoteCacheManager client; + static StringBuilder log = new StringBuilder(); public static void main(String[] args) { + connectToInfinispan(); + manipulateCacheAndSwitchCluster(); + disconnect(false); + } + + static void manipulateCacheAndSwitchCluster() { + cache.put("hello", "world"); + printCluster("LON", cache); + System.out.println("hello " + cache.get("hello") + " from LON"); + client.switchToCluster("NYC"); + printCluster("NYC", cache); + System.out.println("hello " + cache.get("hello") + " from NYC"); + cache.put("hello-nyc", "world"); + System.out.println("hello-nyc " + cache.get("hello-nyc") + " from NYC"); + client.switchToDefaultCluster(); + printCluster("LON", cache); + } + + private static void printCluster(String clusterName, RemoteCache cache) { + String logMessage = clusterName + " members: " + cache.getCacheTopologyInfo().getSegmentsPerServer().keySet().stream().map(Object::toString).collect( + Collectors.joining(",")); + log.append(logMessage); + System.out.println(logMessage); + } + + public static void connectToInfinispan() { ConfigurationBuilder builder = TutorialsConnectorHelper.connectionConfig(); builder.addCluster("NYC").addClusterNodes("localhost:31223"); + client = TutorialsConnectorHelper.connect(builder); + cache = client.administration() + // this cache should exist if you start with docker-compose and run the create-data.sh script + .getOrCreateCache(XSITE_CACHE, new StringConfiguration("")); - try (RemoteCacheManager client = TutorialsConnectorHelper.connect(builder)) { - RemoteCache cache = client.getCache("xsiteCache"); - cache.put("hello", "world"); - printCluster("LON", cache); - System.out.println("hello " + cache.get("hello") + " from LON"); - client.switchToCluster("NYC"); - printCluster("NYC", cache); - System.out.println("hello " + cache.get("hello") + " from NYC"); - cache.put("hello-nyc", "world"); - System.out.println("hello-nyc " + cache.get("hello-nyc") + " from NYC"); - client.switchToDefaultCluster(); - printCluster("LON", cache); - // Connecting to NYC http://localhost:31222/console/cache/xsiteCache - // hello (copied from LON) and hello-nyc both exist in NYC - // hello exists in LON, but hello-nyc is absent because replication is active-passive from LON to NYC - TutorialsConnectorHelper.stop(client); - } } - private static void printCluster(String clusterName, RemoteCache cache) { - System.out.println(clusterName + " members: " + cache.getCacheTopologyInfo().getSegmentsPerServer().keySet().stream().map(Object::toString).collect( - Collectors.joining(","))); + public static void disconnect(boolean removeCache) { + if (removeCache) { + client.administration().removeCache(XSITE_CACHE); + } + + // Connecting to NYC http://localhost:31222/console/cache/xsiteCache + // hello (copied from LON) and hello-nyc both exist in NYC + // hello exists in LON, but hello-nyc is absent because replication is active-passive from LON to NYC + TutorialsConnectorHelper.stop(client); } } diff --git a/infinispan-remote/cross-site-replication/src/test/java/org/infinispan/tutorial/simple/remote/xsite/InfinispanRemoteSwitchClusterTest.java b/infinispan-remote/cross-site-replication/src/test/java/org/infinispan/tutorial/simple/remote/xsite/InfinispanRemoteSwitchClusterTest.java new file mode 100644 index 00000000..054486fc --- /dev/null +++ b/infinispan-remote/cross-site-replication/src/test/java/org/infinispan/tutorial/simple/remote/xsite/InfinispanRemoteSwitchClusterTest.java @@ -0,0 +1,35 @@ +package org.infinispan.tutorial.simple.remote.xsite; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class InfinispanRemoteSwitchClusterTest { + + @BeforeAll + public static void start() { + InfinispanRemoteSwitchCluster.connectToInfinispan(); + } + + @AfterAll + public static void stop() { + InfinispanRemoteSwitchCluster.disconnect(true); + } + + @Test + public void testXSite() { + assertNotNull(InfinispanRemoteSwitchCluster.XSITE_CACHE); + + InfinispanRemoteSwitchCluster.manipulateCacheAndSwitchCluster(); + + assertNotNull(InfinispanRemoteSwitchCluster.log); + String log = InfinispanRemoteSwitchCluster.log.toString(); + assertTrue(log.contains("LON members")); + assertTrue(log.contains("11222")); + assertTrue(log.contains("NYC members")); + assertTrue(log.contains("31223")); + } +} diff --git a/infinispan-remote/encoding/pom.xml b/infinispan-remote/encoding/pom.xml index 43be621f..918ff03f 100644 --- a/infinispan-remote/encoding/pom.xml +++ b/infinispan-remote/encoding/pom.xml @@ -46,5 +46,10 @@ org.infinispan infinispan-client-hotrod + + org.junit.jupiter + junit-jupiter + test + diff --git a/infinispan-remote/encoding/src/main/java/org/infinispan/tutorial/simple/encoding/InfinispanEncodingCaches.java b/infinispan-remote/encoding/src/main/java/org/infinispan/tutorial/simple/encoding/InfinispanEncodingCaches.java index 1e16b91a..6c51a54e 100644 --- a/infinispan-remote/encoding/src/main/java/org/infinispan/tutorial/simple/encoding/InfinispanEncodingCaches.java +++ b/infinispan-remote/encoding/src/main/java/org/infinispan/tutorial/simple/encoding/InfinispanEncodingCaches.java @@ -12,32 +12,18 @@ public class InfinispanEncodingCaches { - public static void main(String[] args) throws Exception { - ConfigurationBuilder builder = TutorialsConnectorHelper.connectionConfig(); - - URI textCacheURI = InfinispanEncodingCaches.class.getClassLoader().getResource("textCache.xml").toURI(); - URI jsonCacheURI = InfinispanEncodingCaches.class.getClassLoader().getResource("jsonCache.xml").toURI(); - URI xmlCacheURI = InfinispanEncodingCaches.class.getClassLoader().getResource("xmlCache.xml").toURI(); + static RemoteCacheManager cacheManager; + static RemoteCache textCache; + static RemoteCache jsonCache; + static RemoteCache xmlCache; - builder.remoteCache("textCache").configurationURI(textCacheURI); - builder.remoteCache("jsonCache").configurationURI(jsonCacheURI); - builder.remoteCache("xmlCache").configurationURI(xmlCacheURI); - - RemoteCacheManager cacheManager = TutorialsConnectorHelper.connect(builder); - RemoteCache textCache = cacheManager.getCache("textCache"); - RemoteCache jsonCache = cacheManager.getCache("jsonCache") - .withDataFormat(DataFormat.builder() - .keyMarshaller(new UTF8StringMarshaller()) - .valueMarshaller(new UTF8StringMarshaller()) - .keyType(MediaType.APPLICATION_JSON) - .valueType(MediaType.APPLICATION_JSON).build()); - RemoteCache xmlCache = cacheManager.getCache("xmlCache") - .withDataFormat(DataFormat.builder() - .keyMarshaller(new UTF8StringMarshaller()) - .valueMarshaller(new UTF8StringMarshaller()) - .keyType(MediaType.APPLICATION_XML) - .valueType(MediaType.APPLICATION_XML).build()); + public static void main(String[] args) throws Exception { + connectToInfinispan(); + manipulateCachesAndPrint(); + disconnect(false); + } + static void manipulateCachesAndPrint() { System.out.println("== Cache with text encoding and string marshaller."); textCache.put("text", "诶, 你好."); System.out.println("Get key from text cache: " + textCache.get("text")); @@ -49,8 +35,41 @@ public static void main(String[] args) throws Exception { System.out.println("== Cache with xml encoding and string marshaller."); xmlCache.put("xml", "infinispan"); System.out.println("Get key from xml cache: " + xmlCache.get("xml")); + } + + public static void connectToInfinispan() throws Exception { + ConfigurationBuilder builder = TutorialsConnectorHelper.connectionConfig(); + + URI textCacheURI = InfinispanEncodingCaches.class.getClassLoader().getResource("textCache.xml").toURI(); + URI jsonCacheURI = InfinispanEncodingCaches.class.getClassLoader().getResource("jsonCache.xml").toURI(); + URI xmlCacheURI = InfinispanEncodingCaches.class.getClassLoader().getResource("xmlCache.xml").toURI(); + + builder.remoteCache("textCache").configurationURI(textCacheURI); + builder.remoteCache("jsonCache").configurationURI(jsonCacheURI); + builder.remoteCache("xmlCache").configurationURI(xmlCacheURI); - cacheManager.stop(); + cacheManager = TutorialsConnectorHelper.connect(builder); + textCache = cacheManager.getCache("textCache"); + jsonCache = cacheManager.getCache("jsonCache") + .withDataFormat(DataFormat.builder() + .keyMarshaller(new UTF8StringMarshaller()) + .valueMarshaller(new UTF8StringMarshaller()) + .keyType(MediaType.APPLICATION_JSON) + .valueType(MediaType.APPLICATION_JSON).build()); + xmlCache = cacheManager.getCache("xmlCache") + .withDataFormat(DataFormat.builder() + .keyMarshaller(new UTF8StringMarshaller()) + .valueMarshaller(new UTF8StringMarshaller()) + .keyType(MediaType.APPLICATION_XML) + .valueType(MediaType.APPLICATION_XML).build()); } + public static void disconnect(boolean removeCaches) { + if (removeCaches) { + cacheManager.administration().removeCache(textCache.getName()); + cacheManager.administration().removeCache(jsonCache.getName()); + cacheManager.administration().removeCache(xmlCache.getName()); + } + TutorialsConnectorHelper.stop(cacheManager); + } } diff --git a/infinispan-remote/encoding/src/test/java/org/infinispan/tutorial/simple/encoding/InfinispanEncodingCachesTest.java b/infinispan-remote/encoding/src/test/java/org/infinispan/tutorial/simple/encoding/InfinispanEncodingCachesTest.java new file mode 100644 index 00000000..100c48cd --- /dev/null +++ b/infinispan-remote/encoding/src/test/java/org/infinispan/tutorial/simple/encoding/InfinispanEncodingCachesTest.java @@ -0,0 +1,36 @@ +package org.infinispan.tutorial.simple.encoding; + + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class InfinispanEncodingCachesTest { + + @BeforeAll + public static void start() throws Exception { + InfinispanEncodingCaches.connectToInfinispan(); + } + + @AfterAll + public static void stop() { + InfinispanEncodingCaches.disconnect(true); + } + + @Test + public void testEncoding() { + assertNotNull(InfinispanEncodingCaches.cacheManager); + assertNotNull(InfinispanEncodingCaches.xmlCache); + assertNotNull(InfinispanEncodingCaches.textCache); + assertNotNull(InfinispanEncodingCaches.jsonCache); + + InfinispanEncodingCaches.manipulateCachesAndPrint(); + + assertEquals("infinispan", InfinispanEncodingCaches.xmlCache.get("xml")); + assertEquals("{\"name\": \"infinispan\"}", InfinispanEncodingCaches.jsonCache.get("\"json\"")); + assertEquals("诶, 你好.", InfinispanEncodingCaches.textCache.get("text")); + } +} diff --git a/infinispan-remote/listeners/pom.xml b/infinispan-remote/listeners/pom.xml index 0614bb6f..7ae63bfb 100644 --- a/infinispan-remote/listeners/pom.xml +++ b/infinispan-remote/listeners/pom.xml @@ -46,5 +46,10 @@ org.infinispan infinispan-client-hotrod + + org.junit.jupiter + junit-jupiter + test + diff --git a/infinispan-remote/listeners/src/main/java/org/infinispan/tutorial/simple/remote/listen/InfinispanRemoteListen.java b/infinispan-remote/listeners/src/main/java/org/infinispan/tutorial/simple/remote/listen/InfinispanRemoteListen.java index 6bdc5162..7a0abfcc 100644 --- a/infinispan-remote/listeners/src/main/java/org/infinispan/tutorial/simple/remote/listen/InfinispanRemoteListen.java +++ b/infinispan-remote/listeners/src/main/java/org/infinispan/tutorial/simple/remote/listen/InfinispanRemoteListen.java @@ -9,6 +9,8 @@ import org.infinispan.client.hotrod.event.ClientCacheEntryModifiedEvent; import org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper; +import static org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper.TUTORIAL_CACHE_NAME; + /** * * Infinispan Server includes a default property realm that requires @@ -17,39 +19,71 @@ */ public class InfinispanRemoteListen { + static RemoteCacheManager cacheManager; + static RemoteCache cache; + static MyListener listener; + public static void main(String[] args) throws InterruptedException { - // Connect to the server - RemoteCacheManager cacheManager = TutorialsConnectorHelper.connect(); + connectToInfinispan(); - // Get the test cache - RemoteCache cache = cacheManager.getCache(TutorialsConnectorHelper.TUTORIAL_CACHE_NAME); + registerListener(); - // Register a listener - MyListener listener = new MyListener(); - cache.addClientListener(listener); + manipulateCache(); + + // Remote events are asynchronous, so wait a bit + Thread.sleep(1000); + disconnect(false); + } + + static void manipulateCache() { // Store some values cache.put("key1", "value1"); cache.put("key2", "value2"); cache.put("key1", "newValue"); - // Remote events are asynchronous, so wait a bit - Thread.sleep(1000); + } + + static void registerListener() { + // Register a listener + listener = new MyListener(); + cache.addClientListener(listener); + } + + public static void connectToInfinispan() { + // Connect to the server + cacheManager = TutorialsConnectorHelper.connect(); + + // Get the test cache + cache = cacheManager.getCache(TUTORIAL_CACHE_NAME); + } + + public static void disconnect(boolean removeCache) { // Remove listener cache.removeClientListener(listener); + + if (removeCache) { + cacheManager.administration().removeCache(TUTORIAL_CACHE_NAME); + } + // Stop the cache manager and release all resources TutorialsConnectorHelper.stop(cacheManager); } @ClientListener public static class MyListener { + StringBuilder logTrack = new StringBuilder(); @ClientCacheEntryCreated public void entryCreated(ClientCacheEntryCreatedEvent event) { - System.out.printf("Created %s%n", event.getKey()); + String logMessage = String.format("Created %s%n", event.getKey()); + logTrack.append(logMessage); + System.out.printf(logMessage); } @ClientCacheEntryModified public void entryModified(ClientCacheEntryModifiedEvent event) { - System.out.printf("About to modify %s%n", event.getKey()); + String logMessage = String.format("About to modify %s%n", event.getKey()); + logTrack.append(logMessage); + System.out.printf(logMessage); } } diff --git a/infinispan-remote/listeners/src/test/java/org/infinispan/tutorial/simple/remote/listen/InfinispanRemoteListenTest.java b/infinispan-remote/listeners/src/test/java/org/infinispan/tutorial/simple/remote/listen/InfinispanRemoteListenTest.java new file mode 100644 index 00000000..21932c9d --- /dev/null +++ b/infinispan-remote/listeners/src/test/java/org/infinispan/tutorial/simple/remote/listen/InfinispanRemoteListenTest.java @@ -0,0 +1,42 @@ +package org.infinispan.tutorial.simple.remote.listen; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class InfinispanRemoteListenTest { + + @BeforeAll + public static void start() { + InfinispanRemoteListen.connectToInfinispan(); + } + + @AfterAll + public static void stop() { + InfinispanRemoteListen.disconnect(true); + } + + @Test + public void testRemoteListen() throws Exception { + assertNotNull(InfinispanRemoteListen.cacheManager); + assertNotNull(InfinispanRemoteListen.cache); + + InfinispanRemoteListen.registerListener(); + + assertNotNull(InfinispanRemoteListen.listener); + + InfinispanRemoteListen.manipulateCache(); + + Thread.sleep(1000); + + String logTrack = InfinispanRemoteListen.listener.logTrack.toString(); + assertEquals(2, InfinispanRemoteListen.cache.size()); + assertTrue(logTrack.contains("Created")); + assertTrue(logTrack.contains("About to modify")); + } +} diff --git a/infinispan-remote/multimap/pom.xml b/infinispan-remote/multimap/pom.xml index 212cd55b..32e4ac6a 100644 --- a/infinispan-remote/multimap/pom.xml +++ b/infinispan-remote/multimap/pom.xml @@ -46,5 +46,10 @@ org.infinispan infinispan-client-hotrod + + org.junit.jupiter + junit-jupiter + test + diff --git a/infinispan-remote/multimap/src/main/java/org/infinispan/tutorial/simple/remote/multimap/InfinispanRemoteMultimap.java b/infinispan-remote/multimap/src/main/java/org/infinispan/tutorial/simple/remote/multimap/InfinispanRemoteMultimap.java index 0b5c003a..5ca6fa8a 100644 --- a/infinispan-remote/multimap/src/main/java/org/infinispan/tutorial/simple/remote/multimap/InfinispanRemoteMultimap.java +++ b/infinispan-remote/multimap/src/main/java/org/infinispan/tutorial/simple/remote/multimap/InfinispanRemoteMultimap.java @@ -6,6 +6,10 @@ import org.infinispan.client.hotrod.multimap.RemoteMultimapCacheManagerFactory; import org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper; +import java.util.concurrent.TimeUnit; + +import static org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper.TUTORIAL_CACHE_NAME; + /** * The Remote Multimap simple tutorial. *

@@ -18,29 +22,46 @@ */ public class InfinispanRemoteMultimap { + static RemoteCacheManager cacheManager; + static MultimapCacheManager multimapCacheManager; + static RemoteMultimapCache multimap; + public static void main(String[] args) throws Exception { + connectToInfinispan(); + manipulateMultimap(); + disconnect(false); + } + + static void manipulateMultimap() throws Exception { + multimap.put(2016, "Rosita"); + multimap.put(2016, "Guillermo"); + multimap.put(2016, "Patricia"); + multimap.put(2016, "Silvia"); + multimap.put(2017, "Matilda"); + multimap.put(2017, "Hector"); + multimap.put(2018, "Richard").get(10, TimeUnit.SECONDS); + + multimap.get(2016).whenComplete((v, ex) -> { + System.out.println(v); + }).join(); + } + + public static void connectToInfinispan() { // Connect to the server and create a cache - RemoteCacheManager cacheManager = TutorialsConnectorHelper.connect(); + cacheManager = TutorialsConnectorHelper.connect(); // Retrieve the MultimapCacheManager from the CacheManager. - MultimapCacheManager multimapCacheManager = RemoteMultimapCacheManagerFactory.from(cacheManager); + multimapCacheManager = RemoteMultimapCacheManagerFactory.from(cacheManager); // Retrieve the multimap cache. - RemoteMultimapCache people = multimapCacheManager.get(TutorialsConnectorHelper.TUTORIAL_CACHE_NAME); - people.put(2016, "Alberto"); - people.put(2016, "Oihana"); - people.put(2016, "Roman"); - people.put(2016, "Ane"); - people.put(2017, "Paula"); - people.put(2017, "Aimar"); - people.put(2018, "Elaia"); - - people.get(2016).whenComplete((v, ex) -> { - System.out.println(v); - }).join(); + multimap = multimapCacheManager.get(TUTORIAL_CACHE_NAME); + } + public static void disconnect(boolean removeCache) { + if (removeCache) { + cacheManager.administration().removeCache(TUTORIAL_CACHE_NAME); + } // Stop the cache manager and release all resources TutorialsConnectorHelper.stop(cacheManager); } - } diff --git a/infinispan-remote/multimap/src/test/java/org/infinispan/tutorial/simple/remote/multimap/InfinispanRemoteMultimapTest.java b/infinispan-remote/multimap/src/test/java/org/infinispan/tutorial/simple/remote/multimap/InfinispanRemoteMultimapTest.java new file mode 100644 index 00000000..f8d7a129 --- /dev/null +++ b/infinispan-remote/multimap/src/test/java/org/infinispan/tutorial/simple/remote/multimap/InfinispanRemoteMultimapTest.java @@ -0,0 +1,36 @@ +package org.infinispan.tutorial.simple.remote.multimap; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.Collection; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class InfinispanRemoteMultimapTest { + + @BeforeAll + public static void start() { + InfinispanRemoteMultimap.connectToInfinispan(); + } + + @AfterAll + public static void stop() { + InfinispanRemoteMultimap.disconnect(true); + } + + @Test + public void testRemoteMultimap() throws Exception { + assertNotNull(InfinispanRemoteMultimap.cacheManager); + assertNotNull(InfinispanRemoteMultimap.multimapCacheManager); + assertNotNull(InfinispanRemoteMultimap.multimap); + + InfinispanRemoteMultimap.manipulateMultimap(); + Collection people = InfinispanRemoteMultimap.multimap.get(2018).get(10, TimeUnit.SECONDS); + assertEquals(1, people.size()); + assertEquals("Richard", people.toArray()[0]); + } +} diff --git a/infinispan-remote/near-cache/pom.xml b/infinispan-remote/near-cache/pom.xml index 6febd0d8..b71bd214 100644 --- a/infinispan-remote/near-cache/pom.xml +++ b/infinispan-remote/near-cache/pom.xml @@ -46,5 +46,10 @@ org.infinispan infinispan-client-hotrod + + org.junit.jupiter + junit-jupiter + test + diff --git a/infinispan-remote/near-cache/src/main/java/org/infinispan/tutorial/simple/nearcache/InfinispanNearCache.java b/infinispan-remote/near-cache/src/main/java/org/infinispan/tutorial/simple/nearcache/InfinispanNearCache.java index bbec2e24..d8e3e9b5 100644 --- a/infinispan-remote/near-cache/src/main/java/org/infinispan/tutorial/simple/nearcache/InfinispanNearCache.java +++ b/infinispan-remote/near-cache/src/main/java/org/infinispan/tutorial/simple/nearcache/InfinispanNearCache.java @@ -1,33 +1,27 @@ package org.infinispan.tutorial.simple.nearcache; -import java.time.Duration; -import java.time.Instant; -import java.util.Random; - 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.tutorial.simple.connect.TutorialsConnectorHelper; +import java.time.Duration; +import java.time.Instant; +import java.util.Random; + +import static org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper.TUTORIAL_CACHE_NAME; + public class InfinispanNearCache { public static final String CACHE_WITH_NEAR_CACHING = "testCacheNearCaching"; - public static void main(String[] args) { - ConfigurationBuilder builder = TutorialsConnectorHelper.connectionConfig(); - // Add an additional cache with near caching configuration - builder.remoteCache(CACHE_WITH_NEAR_CACHING) - .configuration(TutorialsConnectorHelper.TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", CACHE_WITH_NEAR_CACHING)) - .nearCacheMode(NearCacheMode.INVALIDATED) - .nearCacheMaxEntries(20) - .nearCacheUseBloomFilter(true); - - // Connect to the server with the near cache configuration for the test cache - RemoteCacheManager cacheManager = TutorialsConnectorHelper.connect(builder); + static RemoteCacheManager cacheManager; + static RemoteCache testCache; + static RemoteCache withNearCaching; - RemoteCache testCache = cacheManager.getCache(TutorialsConnectorHelper.TUTORIAL_CACHE_NAME); - RemoteCache withNearCaching = cacheManager.getCache(CACHE_WITH_NEAR_CACHING); + public static void main(String[] args) { + connectToInfinispan(); for (int i = 1; i<= 20; i++) { testCache.put(i, String.valueOf(i)); @@ -38,11 +32,10 @@ public static void main(String[] args) { readCache(testCache); readCache(withNearCaching); - // Stop the cache manager and release all resources - cacheManager.stop(); + disconnect(false); } - private static void readCache(RemoteCache cache) { + static void readCache(RemoteCache cache) { Instant start = Instant.now(); Random random = new Random(); random.ints(10_000, 1, 20).forEach(num -> cache.get(num)); @@ -51,4 +44,27 @@ private static void readCache(RemoteCache cache) { System.out.println(String.format("Time to complete with cache %s is %d milliseconds", cache.getName(), timeElapsed)); } + public static void connectToInfinispan() { + ConfigurationBuilder builder = TutorialsConnectorHelper.connectionConfig(); + // Add an additional cache with near caching configuration + builder.remoteCache(CACHE_WITH_NEAR_CACHING) + .configuration(TutorialsConnectorHelper.TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", CACHE_WITH_NEAR_CACHING)) + .nearCacheMode(NearCacheMode.INVALIDATED) + .nearCacheMaxEntries(20) + .nearCacheUseBloomFilter(true); + + // Connect to the server with the near cache configuration for the test cache + cacheManager = TutorialsConnectorHelper.connect(builder); + testCache = cacheManager.getCache(TUTORIAL_CACHE_NAME); + withNearCaching = cacheManager.getCache(CACHE_WITH_NEAR_CACHING); + } + + public static void disconnect(boolean removeCache) { + if (removeCache) { + cacheManager.administration().removeCache(TUTORIAL_CACHE_NAME); + cacheManager.administration().removeCache(CACHE_WITH_NEAR_CACHING); + } + // Stop the cache manager and release all resources + cacheManager.stop(); + } } diff --git a/infinispan-remote/near-cache/src/test/java/org/infinispan/tutorial/simple/nearcache/InfinispanNearCacheTest.java b/infinispan-remote/near-cache/src/test/java/org/infinispan/tutorial/simple/nearcache/InfinispanNearCacheTest.java new file mode 100644 index 00000000..a3b347e2 --- /dev/null +++ b/infinispan-remote/near-cache/src/test/java/org/infinispan/tutorial/simple/nearcache/InfinispanNearCacheTest.java @@ -0,0 +1,27 @@ +package org.infinispan.tutorial.simple.nearcache; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class InfinispanNearCacheTest { + + @BeforeAll + public static void start() { + InfinispanNearCache.connectToInfinispan(); + } + + @AfterAll + public static void stop() { + InfinispanNearCache.disconnect(true); + } + + @Test + public void testNearCache() { + assertNotNull(InfinispanNearCache.testCache); + assertNotNull(InfinispanNearCache.withNearCaching); + } + +} \ No newline at end of file diff --git a/infinispan-remote/per-cache-configuration/pom.xml b/infinispan-remote/per-cache-configuration/pom.xml index ef929098..b8a92663 100644 --- a/infinispan-remote/per-cache-configuration/pom.xml +++ b/infinispan-remote/per-cache-configuration/pom.xml @@ -44,5 +44,10 @@ org.infinispan infinispan-client-hotrod + + org.junit.jupiter + junit-jupiter + test + diff --git a/infinispan-remote/per-cache-configuration/src/main/java/org/infinispan/tutorial/simple/remote/percache/InfinispanRemotePerCache.java b/infinispan-remote/per-cache-configuration/src/main/java/org/infinispan/tutorial/simple/remote/percache/InfinispanRemotePerCache.java index b99f5663..059978c3 100644 --- a/infinispan-remote/per-cache-configuration/src/main/java/org/infinispan/tutorial/simple/remote/percache/InfinispanRemotePerCache.java +++ b/infinispan-remote/per-cache-configuration/src/main/java/org/infinispan/tutorial/simple/remote/percache/InfinispanRemotePerCache.java @@ -21,41 +21,67 @@ public class InfinispanRemotePerCache { + public static final String MY_CACHE = "my-cache"; + public static final String ANOTHER_CACHE = "another-cache"; + public static final String URI_CACHE = "uri-cache"; + static RemoteCacheManager cacheManager; + static RemoteCache cache; + static RemoteCache anotherCache; + static RemoteCache uriCache; + public static void main(String[] args) throws Exception { + connectToInfinispan(); + manipulateCaches(); + + disconnect(false); + } + + static void manipulateCaches() { + // Obtain a remote cache that does not exist. + // Rather than return null, create the cache from a template. + cache = cacheManager.getCache(MY_CACHE); + /// Store a value + cache.put("hello", "world"); + // Retrieve the value and print it out + System.out.printf("key = %s\n", cache.get("hello")); + + anotherCache = cacheManager.getCache(ANOTHER_CACHE); + /// Store a value + anotherCache.put("hello-another", "world-another"); + // Retrieve the value and print it out + System.out.printf("key = %s\n", anotherCache.get("hello-another")); + + uriCache = cacheManager.getCache(URI_CACHE); + /// Store a value + uriCache.put("hello-uri", "world-uri"); + // Retrieve the value and print it out + System.out.printf("key = %s\n", uriCache.get("hello-uri")); + } + + public static void connectToInfinispan() throws Exception { // Create a configuration for a locally-running server ConfigurationBuilder builder = TutorialsConnectorHelper.connectionConfig(); //Add per-cache configuration that uses an org.infinispan cache template. - builder.remoteCache("my-cache") - .templateName(DefaultTemplate.DIST_SYNC); + builder.remoteCache(MY_CACHE) + .templateName(DefaultTemplate.DIST_SYNC); //Add per-cache configuration with a cache definition in XML format. - builder.remoteCache("another-cache") - .configuration(""); - - builder.remoteCache("uri-cache").configurationURI( - InfinispanRemotePerCache.class.getClassLoader().getResource("cacheConfig.xml").toURI()); - - // Connect to the server - try (RemoteCacheManager cacheManager = TutorialsConnectorHelper.connect(builder)) { - // Obtain a remote cache that does not exist. - // Rather than return null, create the cache from a template. - RemoteCache cache = cacheManager.getCache("my-cache"); - /// Store a value - cache.put("hello", "world"); - // Retrieve the value and print it out - System.out.printf("key = %s\n", cache.get("hello")); - - RemoteCache anotherCache = cacheManager.getCache("another-cache"); - /// Store a value - anotherCache.put("hello-another", "world-another"); - // Retrieve the value and print it out - System.out.printf("key = %s\n", anotherCache.get("hello-another")); - - RemoteCache uriCache = cacheManager.getCache("uri-cache"); - /// Store a value - uriCache.put("hello-uri", "world-uri"); - // Retrieve the value and print it out - System.out.printf("key = %s\n", uriCache.get("hello-uri")); + builder.remoteCache(ANOTHER_CACHE) + .configuration(""); + + builder.remoteCache(URI_CACHE).configurationURI( + InfinispanRemotePerCache.class.getClassLoader().getResource("cacheConfig.xml").toURI()); + + cacheManager = TutorialsConnectorHelper.connect(builder); + } + + public static void disconnect(boolean removeCaches) { + if (removeCaches) { + cacheManager.administration().removeCache(MY_CACHE); + cacheManager.administration().removeCache(ANOTHER_CACHE); + cacheManager.administration().removeCache(URI_CACHE); } + + TutorialsConnectorHelper.stop(cacheManager); } } diff --git a/infinispan-remote/per-cache-configuration/src/test/java/org/infinispan/tutorial/simple/remote/percache/InfinispanRemotePerCacheTest.java b/infinispan-remote/per-cache-configuration/src/test/java/org/infinispan/tutorial/simple/remote/percache/InfinispanRemotePerCacheTest.java new file mode 100644 index 00000000..0fdaa88a --- /dev/null +++ b/infinispan-remote/per-cache-configuration/src/test/java/org/infinispan/tutorial/simple/remote/percache/InfinispanRemotePerCacheTest.java @@ -0,0 +1,35 @@ +package org.infinispan.tutorial.simple.remote.percache; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + + +public class InfinispanRemotePerCacheTest { + + @BeforeAll + public static void start() throws Exception { + InfinispanRemotePerCache.connectToInfinispan(); + } + + @AfterAll + public static void stop() { + InfinispanRemotePerCache.disconnect(true); + } + + @Test + public void testRemotePerCacheConfiguration() { + assertNotNull(InfinispanRemotePerCache.cacheManager); + assertNull(InfinispanRemotePerCache.cache); + assertNull(InfinispanRemotePerCache.anotherCache); + assertNull(InfinispanRemotePerCache.uriCache); + + InfinispanRemotePerCache.manipulateCaches(); + assertNotNull(InfinispanRemotePerCache.cache); + assertNotNull(InfinispanRemotePerCache.anotherCache); + assertNotNull(InfinispanRemotePerCache.uriCache); + } +} \ No newline at end of file diff --git a/infinispan-remote/query/pom.xml b/infinispan-remote/query/pom.xml index c1ff2688..f1e03aa6 100644 --- a/infinispan-remote/query/pom.xml +++ b/infinispan-remote/query/pom.xml @@ -65,5 +65,10 @@ protostream-processor ${version.protostream} + + org.junit.jupiter + junit-jupiter + test + diff --git a/infinispan-remote/query/src/main/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteQuery.java b/infinispan-remote/query/src/main/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteQuery.java index b26ba206..326b4692 100644 --- a/infinispan-remote/query/src/main/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteQuery.java +++ b/infinispan-remote/query/src/main/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteQuery.java @@ -5,9 +5,6 @@ import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.api.query.Query; import org.infinispan.protostream.GeneratedSchema; -import org.infinispan.query.Search; -import org.infinispan.query.dsl.impl.BaseQueryFactory; -import org.infinispan.server.resp.commands.connection.SELECT; import org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper; import java.net.URI; @@ -28,9 +25,83 @@ public class InfinispanRemoteQuery { public static final String INDEXED_PEOPLE_CACHE = "indexedPeopleCache"; + static RemoteCacheManager client; + static RemoteCache peopleCache; public static void main(String[] args) throws Exception { + connectToInfinispan(); + addDataToCache(); + queryAll(); + queryWithWhereStatementOnValues(); + queryByKey(); + queryWithProjection(); + deleteByQuery(); + + disconnect(false); + } + + static List queryAll() { + // Query all + Query query = peopleCache.query("FROM tutorial.Person"); + List queryResult = query.execute().list(); + // Print the results + System.out.println("SIZE " + queryResult.size()); + System.out.println(queryResult); + return queryResult; + } + + static List deleteByQuery() { + Query query = peopleCache.query("DELETE FROM tutorial.Person p where p.key.pseudo = 'dmalfoy'"); + System.out.println("== DELETE count:" + query.execute().count().value()); + // Query all + query = peopleCache.query("FROM tutorial.Person"); + List queryResult = query.execute().list(); + // Print the results + System.out.println("SIZE " + queryResult.size()); + System.out.println(queryResult); + return queryResult; + } + + static List queryWithProjection() { + // Create a query with projection + System.out.println("== Query with key and values projection"); + Query queryProjection = peopleCache.query("SELECT p.key.pseudo, p.firstName, p.lastName FROM tutorial.Person p where p.bornIn = 'London'"); + // Execute the queryProjection + List queryResultProjection = queryProjection.execute().list() + .stream() + .map(r -> new PersonDTO(r[0] + "", r[1] + " " + r[2])) + .toList(); + // Print the results queryResultProjection + System.out.println(queryResultProjection); + return queryResultProjection; + } + + static List queryByKey() { + // Create a query by key + System.out.println("== Query by key values"); + Query query = peopleCache.query("FROM tutorial.Person p where p.key.pseudo = 'dmalfoy'"); + // Execute the query + List queryResult = query.execute().list(); + // Print the results queryResult + System.out.println(queryResult); + return queryResult; + } + + static List queryWithWhereStatementOnValues() { + // Create a query with lastName parameter + System.out.println("== Query on values"); + Query query = peopleCache.query("FROM tutorial.Person p where p.lastName = :lastName"); + // Set the parameter value + query.setParameter("lastName", "Granger"); + // Execute the query + List queryResult = query.execute().list(); + // Print the results + System.out.println(queryResult); + return queryResult; + } + + static void connectToInfinispan() throws Exception { ConfigurationBuilder builder = TutorialsConnectorHelper.connectionConfig(); // Add the Protobuf serialization context in the client @@ -41,14 +112,16 @@ public static void main(String[] args) throws Exception { builder.remoteCache(INDEXED_PEOPLE_CACHE).configurationURI(indexedCacheURI); // Connect to the server - RemoteCacheManager client = TutorialsConnectorHelper.connect(builder); + client = TutorialsConnectorHelper.connect(builder); // Create and add the Protobuf schema in the server addPersonSchema(client); // Get the people cache, create it if needed with the default configuration - RemoteCache peopleCache = client.getCache(INDEXED_PEOPLE_CACHE); + peopleCache = client.getCache(INDEXED_PEOPLE_CACHE); + } + static void addDataToCache() { // Create the persons dataset to be stored in the cache Map people = new HashMap<>(); people.put(new PersonKey("1", "hgranger"), @@ -62,52 +135,13 @@ public static void main(String[] args) throws Exception { // Put all the values in the cache peopleCache.putAll(people); - // Query all - Query query = peopleCache.query("FROM tutorial.Person"); - List queryResult = query.execute().list(); - // Print the results - System.out.println("SIZE " + queryResult.size()); - System.out.println(queryResult); - - // Create a query with lastName parameter - System.out.println("== Query on values"); - query = peopleCache.query("FROM tutorial.Person p where p.lastName = :lastName"); - // Set the parameter value - query.setParameter("lastName", "Granger"); - // Execute the query - queryResult = query.execute().list(); - // Print the results - System.out.println(queryResult); - - // Create a query by key - System.out.println("== Query by key values"); - query = peopleCache.query("FROM tutorial.Person p where p.key.pseudo = 'dmalfoy'"); - // Execute the query - queryResult = query.execute().list(); - // Print the results queryResult - System.out.println(queryResult); - - // Create a query with projection - System.out.println("== Query with key and values projection"); - Query queryProjection = peopleCache.query("SELECT p.key.pseudo, p.firstName, p.lastName FROM tutorial.Person p where p.bornIn = 'London'"); - // Execute the queryProjection - List queryResultProjection = queryProjection.execute().list() - .stream() - .map(r -> new PersonDTO(r[0] + "", r[1] + " " + r[2])) - .toList(); - // Print the results queryResultProjection - System.out.println(queryResultProjection); + } - query = peopleCache.query("DELETE FROM tutorial.Person p where p.key.pseudo = 'dmalfoy'"); - System.out.println("== DELETE count:" + query.execute().count().value()); - // Query all - query = peopleCache.query("FROM tutorial.Person"); - queryResult = query.execute().list(); - // Print the results - System.out.println("SIZE " + queryResult.size()); - System.out.println(queryResult); + public static void disconnect(boolean removeCaches) { + if (removeCaches) { + client.administration().removeCache(INDEXED_PEOPLE_CACHE); + } - // Stop the client and release all resources TutorialsConnectorHelper.stop(client); } diff --git a/infinispan-remote/query/src/test/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteQueryTest.java b/infinispan-remote/query/src/test/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteQueryTest.java new file mode 100644 index 00000000..97f0ef9b --- /dev/null +++ b/infinispan-remote/query/src/test/java/org/infinispan/tutorial/simple/remote/query/InfinispanRemoteQueryTest.java @@ -0,0 +1,61 @@ +package org.infinispan.tutorial.simple.remote.query; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class InfinispanRemoteQueryTest { + + @BeforeAll + public static void start() throws Exception { + InfinispanRemoteQuery.connectToInfinispan(); + } + + @AfterAll + public static void stop() { + InfinispanRemoteQuery.disconnect(true); + } + + @Test + public void testRemoteQuery() { + assertNotNull(InfinispanRemoteQuery.client); + assertNotNull(InfinispanRemoteQuery.peopleCache); + + List people = InfinispanRemoteQuery.queryAll(); + assertEquals(0, people.size()); + + InfinispanRemoteQuery.addDataToCache(); + + people = InfinispanRemoteQuery.queryAll(); + assertEquals(4, people.size()); + + List peopleFiltered = InfinispanRemoteQuery.queryWithWhereStatementOnValues(); + assertEquals(1, peopleFiltered.size()); + assertEquals("Granger", peopleFiltered.get(0).lastName()); + + List peopleFilteredByKey = InfinispanRemoteQuery.queryByKey(); + assertEquals(1, peopleFilteredByKey.size()); + assertEquals("Malfoy", peopleFilteredByKey.get(0).lastName()); + + List personDTOS = InfinispanRemoteQuery.queryWithProjection(); + assertEquals(3, personDTOS.size()); + Set collected = personDTOS.stream().map(InfinispanRemoteQuery.PersonDTO::pseudo).collect(Collectors.toSet()); + assertEquals(3, collected.size()); + assertTrue(collected.contains("dmalfoy")); + + // Shut up Malfoy !! + InfinispanRemoteQuery.deleteByQuery(); + + // Malfoy has been removed + peopleFilteredByKey = InfinispanRemoteQuery.queryByKey(); + assertEquals(0, peopleFilteredByKey.size()); + } +} \ No newline at end of file diff --git a/infinispan-remote/reactive-api/pom.xml b/infinispan-remote/reactive-api/pom.xml index 836812b9..9fa0a806 100644 --- a/infinispan-remote/reactive-api/pom.xml +++ b/infinispan-remote/reactive-api/pom.xml @@ -46,5 +46,10 @@ org.infinispan infinispan-hotrod + + org.junit.jupiter + junit-jupiter + test + diff --git a/infinispan-remote/reactive-api/src/main/java/org/infinispan/tutorial/simple/reactive/InfinispanReactiveApi.java b/infinispan-remote/reactive-api/src/main/java/org/infinispan/tutorial/simple/reactive/InfinispanReactiveApi.java index 02fac4d3..a5067f09 100644 --- a/infinispan-remote/reactive-api/src/main/java/org/infinispan/tutorial/simple/reactive/InfinispanReactiveApi.java +++ b/infinispan-remote/reactive-api/src/main/java/org/infinispan/tutorial/simple/reactive/InfinispanReactiveApi.java @@ -2,9 +2,12 @@ import org.infinispan.api.Infinispan; import org.infinispan.api.mutiny.MutinyCache; +import org.infinispan.api.sync.SyncCache; import org.infinispan.commons.util.OS; import org.infinispan.hotrod.configuration.ClientIntelligence; import org.infinispan.hotrod.configuration.HotRodConfigurationBuilder; +import org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper; +import org.jetbrains.annotations.NotNull; import java.time.Duration; import java.time.LocalDateTime; @@ -12,6 +15,7 @@ import java.util.concurrent.ScheduledExecutorService; import static org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper.HOST; +import static org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper.INFINISPAN_CONTAINER; import static org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper.PASSWORD; import static org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper.SINGLE_PORT; import static org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper.TUTORIAL_CACHE_CONFIG; @@ -20,39 +24,96 @@ public class InfinispanReactiveApi { + static Infinispan infinispan; + static MutinyCache cache; + public static void main(String[] args) { + connect(); + initCache(); + manipulateCacheReactive(); + disconnect(false); + } + + static void initCache() { + cache = infinispan.mutiny() + .caches().get(TUTORIAL_CACHE_NAME) + .await().atMost(Duration.ofMillis(100)); + } + + static void manipulateCacheReactive() { + ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); + + cache.set("hello", "reactive") + .chain(ignore -> cache.get("hello")) + .onItem().invoke(v -> System.out.printf("%s -- %s\n", LocalDateTime.now(), v)) + .map(v -> v + " is nice!!") + .onItem().delayIt().onExecutor(executor).by(Duration.ofSeconds(1)) + .invoke(v -> System.out.printf("%s -- %s\n", LocalDateTime.now(), v)) + .await().atMost(Duration.ofSeconds(2)); + + executor.shutdown(); + } + + public static final void connect() { // New API Connection + HotRodConfigurationBuilder builder = createHotRodConfigurationBuilder(); + infinispan = null; + try { + infinispan = Infinispan.create(builder.build()); + clearCache(); + } catch (Exception ex) { + System.out.println("Unable to connect to a running server in localhost:11222. Try test containers"); + infinispan = null; + } + + if (infinispan == null) { + try { + TutorialsConnectorHelper.startInfinispanContainer(); + builder = createHotRodConfigurationBuilder(); + builder.addServer().host(HOST).port(INFINISPAN_CONTAINER.getMappedPort(SINGLE_PORT)); + infinispan = Infinispan.create(builder.build()); + clearCache(); + } catch (Exception ex) { + System.out.println("Infinispan Server start with Testcontainers failed. Exit"); + System.exit(0); + } + } + } + + @NotNull + private static HotRodConfigurationBuilder createHotRodConfigurationBuilder() { HotRodConfigurationBuilder builder = new HotRodConfigurationBuilder(); if (OS.getCurrentOs().equals(OS.MAC_OS) || OS.getCurrentOs().equals(OS.WINDOWS)) { // This is for DEV MODE LOCAL !! Don't add this in production, you will hit performance issues builder.clientIntelligence(ClientIntelligence.BASIC); } - builder - .addServer().host(HOST).port(SINGLE_PORT) - .security().authentication() - .username(USER) - .password(PASSWORD); + builder.security().authentication() + .username(USER) + .password(PASSWORD); + builder.remoteCache(TUTORIAL_CACHE_NAME) - .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); + .configuration(TUTORIAL_CACHE_CONFIG.replace("CACHE_NAME", TUTORIAL_CACHE_NAME)); + return builder; + } - Infinispan infinispan = Infinispan.create(builder.build()); - MutinyCache cache = infinispan.mutiny() - .caches().get(TUTORIAL_CACHE_NAME) - .await().atMost(Duration.ofMillis(100)); + private static void clearCache() { + if (infinispan != null) { + // Clear the cache in case it already exists from a previous running tutorial + SyncCache cache = infinispan.sync().caches().get(TUTORIAL_CACHE_NAME); + if (cache != null) { + cache.clear(); + } + } + } - ScheduledExecutorService executor = Executors.newScheduledThreadPool(4, t -> { - Thread wrap = new Thread(t); - wrap.setDaemon(true); - return wrap; - }); - cache.set("hello", "reactive") - .chain(ignore -> cache.get("hello")) - .onItem().invoke(v -> System.out.printf("%s -- %s\n", LocalDateTime.now(), v)) - .map(v -> v + " is nice!!") - .onItem().delayIt().onExecutor(executor).by(Duration.ofSeconds(1)) - .invoke(v -> System.out.printf("%s -- %s\n", LocalDateTime.now(), v)) - .await().atMost(Duration.ofSeconds(2)); + public static void disconnect(boolean removeCache) { + if (infinispan != null) { + if (removeCache) { + infinispan.sync().caches().remove(TUTORIAL_CACHE_NAME); + } + infinispan.close(); + } } } diff --git a/infinispan-remote/reactive-api/src/test/java/org/infinispan/tutorial/simple/reactive/InfinispanReactiveApiTest.java b/infinispan-remote/reactive-api/src/test/java/org/infinispan/tutorial/simple/reactive/InfinispanReactiveApiTest.java new file mode 100644 index 00000000..4a4a726e --- /dev/null +++ b/infinispan-remote/reactive-api/src/test/java/org/infinispan/tutorial/simple/reactive/InfinispanReactiveApiTest.java @@ -0,0 +1,36 @@ +package org.infinispan.tutorial.simple.reactive; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper.TUTORIAL_CACHE_NAME; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@Disabled +public class InfinispanReactiveApiTest { + + @BeforeAll + public static void start() { + InfinispanReactiveApi.connect(); + } + + @AfterAll + public static void stop() { + InfinispanReactiveApi.disconnect(true); + } + + @Test + public void testReactive() { + assertNotNull(InfinispanReactiveApi.infinispan); + InfinispanReactiveApi.initCache(); + assertNotNull(InfinispanReactiveApi.cache); + InfinispanReactiveApi.manipulateCacheReactive(); + assertEquals("reactive", InfinispanReactiveApi + .infinispan.sync().caches() + .get(TUTORIAL_CACHE_NAME).get("hello")); + } + +} diff --git a/infinispan-remote/redis-client/pom.xml b/infinispan-remote/redis-client/pom.xml index 3e7a1841..6d5a4bb0 100644 --- a/infinispan-remote/redis-client/pom.xml +++ b/infinispan-remote/redis-client/pom.xml @@ -9,7 +9,9 @@ infinispan-simple-tutorials Infinispan Simple Tutorials: Redis Client - + + 5.1.3 + @@ -45,7 +47,12 @@ redis.clients jedis - 5.1.3 + ${jedis.version} + + + org.junit.jupiter + junit-jupiter + test diff --git a/infinispan-remote/redis-client/src/main/java/org/infinispan/tutorial/simple/redis/RedisClientCache.java b/infinispan-remote/redis-client/src/main/java/org/infinispan/tutorial/simple/redis/RedisClientCache.java index d6930d0b..7f46f8bb 100644 --- a/infinispan-remote/redis-client/src/main/java/org/infinispan/tutorial/simple/redis/RedisClientCache.java +++ b/infinispan-remote/redis-client/src/main/java/org/infinispan/tutorial/simple/redis/RedisClientCache.java @@ -1,22 +1,65 @@ package org.infinispan.tutorial.simple.redis; import org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper; +import org.jetbrains.annotations.NotNull; import redis.clients.jedis.JedisPooled; public class RedisClientCache { + static JedisPooled jedis = null; + public static void main(String[] args) { - String redisUri = String.format("redis://%s:%s@%s:%s", - TutorialsConnectorHelper.USER, - TutorialsConnectorHelper.PASSWORD, - TutorialsConnectorHelper.HOST, - TutorialsConnectorHelper.SINGLE_PORT); + connect(); + manipulateWithRESP(); + disconnect(); + } - JedisPooled jedis = new JedisPooled(redisUri); + static void manipulateWithRESP() { String key = "Hello"; jedis.set(key, "world"); String value = jedis.get(key); System.out.println(String.format("Read from Infinispan using a Redis Client (Resp Protocol): %s %s", key, value)); } + static void disconnect() { + TutorialsConnectorHelper.stopInfinispanContainer(); + } + + static void connect() { + try { + jedis = createJedis(TutorialsConnectorHelper.SINGLE_PORT); + jedis.ping(); + } catch (Exception ex) { + // Unable to connect + System.out.println("Unable to connect, try to run a container with test containers"); + jedis = null; + } + + if (jedis == null) { + TutorialsConnectorHelper.startInfinispanContainer(); + if (TutorialsConnectorHelper.isContainerStarted()) { + jedis = createJedis(TutorialsConnectorHelper.INFINISPAN_CONTAINER.getFirstMappedPort()); + } else { + System.out.println("Unable to run Infinispan container"); + System.exit(0); + } + } + + try { + jedis.ping(); + } catch (Exception ex) { + System.out.println("Unable to ping with RESP"); + System.exit(0); + } + } + + private static JedisPooled createJedis(int port) { + String redisUri = String.format("redis://%s:%s@%s:%s", + TutorialsConnectorHelper.USER, + TutorialsConnectorHelper.PASSWORD, + TutorialsConnectorHelper.HOST, + port); + return new JedisPooled(redisUri); + } + } diff --git a/infinispan-remote/redis-client/src/test/java/org/infinispan/tutorial/simple/redis/RedisClientCacheTest.java b/infinispan-remote/redis-client/src/test/java/org/infinispan/tutorial/simple/redis/RedisClientCacheTest.java new file mode 100644 index 00000000..7799b3a2 --- /dev/null +++ b/infinispan-remote/redis-client/src/test/java/org/infinispan/tutorial/simple/redis/RedisClientCacheTest.java @@ -0,0 +1,30 @@ +package org.infinispan.tutorial.simple.redis; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.infinispan.tutorial.simple.redis.RedisClientCache.jedis; +import static org.infinispan.tutorial.simple.redis.RedisClientCache.manipulateWithRESP; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class RedisClientCacheTest { + + @BeforeAll + public static void start() throws Exception { + RedisClientCache.connect(); + } + + @AfterAll + public static void stop() { + RedisClientCache.disconnect(); + } + + @Test + public void testRESPWithInfinispan() { + assertNotNull(jedis); + manipulateWithRESP(); + assertEquals("world", jedis.get("Hello")); + } +} diff --git a/infinispan-remote/security/secured-cache/pom.xml b/infinispan-remote/security/secured-cache/pom.xml index afed578e..7b25cc3e 100644 --- a/infinispan-remote/security/secured-cache/pom.xml +++ b/infinispan-remote/security/secured-cache/pom.xml @@ -46,5 +46,10 @@ org.infinispan infinispan-client-hotrod + + org.junit.jupiter + junit-jupiter + test + diff --git a/infinispan-remote/security/secured-cache/src/main/java/org/infinispan/tutorial/simple/remote/InfinispanAuthorizationCache.java b/infinispan-remote/security/secured-cache/src/main/java/org/infinispan/tutorial/simple/remote/InfinispanAuthorizationCache.java index 6448f236..a3416d7f 100644 --- a/infinispan-remote/security/secured-cache/src/main/java/org/infinispan/tutorial/simple/remote/InfinispanAuthorizationCache.java +++ b/infinispan-remote/security/secured-cache/src/main/java/org/infinispan/tutorial/simple/remote/InfinispanAuthorizationCache.java @@ -8,6 +8,8 @@ import java.net.URI; +import static org.infinispan.tutorial.simple.connect.TutorialsConnectorHelper.TUTORIAL_CACHE_NAME; + /** * Run the Infinispan Server using the Docker Image * Or make sure you create a user that is called 'admin'. @@ -15,17 +17,19 @@ */ public class InfinispanAuthorizationCache { - public static void main(String[] args) throws Exception { - ConfigurationBuilder configurationBuilder = TutorialsConnectorHelper.connectionConfig(); - URI securedCacheConfig = InfinispanAuthorizationCache.class.getClassLoader().getResource("securedCache.xml").toURI(); - configurationBuilder.remoteCache("securedCache").configurationURI(securedCacheConfig); + public static final String SECURED_CACHE = "securedCache"; + static RemoteCacheManager cacheManager; + static RemoteCache cache; + static RemoteCache securedCache; + static String message = ""; - // Connect to Infinispan with an additional cache that is secured with authorization for - // deployer role only. We are connecting with 'admin' user that has 'admin' role. - RemoteCacheManager cacheManager = TutorialsConnectorHelper.connect(configurationBuilder); - RemoteCache cache = cacheManager.getCache(TutorialsConnectorHelper.TUTORIAL_CACHE_NAME); - RemoteCache securedCache = cacheManager.getCache("securedCache"); + public static void main(String[] args) throws Exception { + connectToInfinispan(); + manipulateCache(); + disconnect(false); + } + static void manipulateCache() { // Store a value in a non secured cache cache.put("key", "value"); @@ -33,11 +37,29 @@ public static void main(String[] args) throws Exception { // Store a value in a cache where your role is has not access granted securedCache.put("key", "value"); } catch (HotRodClientException ex) { + message = ex.getMessage().toLowerCase(); System.out.println(ex.getMessage()); } + } + public static void connectToInfinispan() throws Exception { + ConfigurationBuilder configurationBuilder = TutorialsConnectorHelper.connectionConfig(); + URI securedCacheConfig = InfinispanAuthorizationCache.class.getClassLoader().getResource("securedCache.xml").toURI(); + configurationBuilder.remoteCache(SECURED_CACHE).configurationURI(securedCacheConfig); + + // Connect to Infinispan with an additional cache that is secured with authorization for + // deployer role only. We are connecting with 'admin' user that has 'admin' role. + cacheManager = TutorialsConnectorHelper.connect(configurationBuilder); + cache = cacheManager.getCache(TUTORIAL_CACHE_NAME); + securedCache = cacheManager.getCache(SECURED_CACHE); + } + + public static void disconnect(boolean removeCaches) { + if (removeCaches && cacheManager != null) { + cacheManager.administration().removeCache(TUTORIAL_CACHE_NAME); + cacheManager.administration().removeCache(SECURED_CACHE); + } // Stop the cache manager and release all resources TutorialsConnectorHelper.stop(cacheManager); } - } diff --git a/infinispan-remote/security/secured-cache/src/test/java/org/infinispan/tutorial/simple/remote/InfinispanAuthorizationCacheTest.java b/infinispan-remote/security/secured-cache/src/test/java/org/infinispan/tutorial/simple/remote/InfinispanAuthorizationCacheTest.java new file mode 100644 index 00000000..adcbb98d --- /dev/null +++ b/infinispan-remote/security/secured-cache/src/test/java/org/infinispan/tutorial/simple/remote/InfinispanAuthorizationCacheTest.java @@ -0,0 +1,34 @@ +package org.infinispan.tutorial.simple.remote; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class InfinispanAuthorizationCacheTest { + + @BeforeAll + public static void start() throws Exception { + InfinispanAuthorizationCache.connectToInfinispan(); + } + + @AfterAll + public static void stop() { + InfinispanAuthorizationCache.disconnect(true); + } + + @Test + public void testInfinispanAuthorizationCache() { + assertNotNull(InfinispanAuthorizationCache.cacheManager); + assertNotNull(InfinispanAuthorizationCache.cache); + assertNotNull(InfinispanAuthorizationCache.securedCache); + + InfinispanAuthorizationCache.manipulateCache(); + + assertTrue(InfinispanAuthorizationCache.message.contains("unauthorized")); + } + +} \ No newline at end of file diff --git a/infinispan-remote/transactions/pom.xml b/infinispan-remote/transactions/pom.xml index 49b9edbb..b31cad03 100644 --- a/infinispan-remote/transactions/pom.xml +++ b/infinispan-remote/transactions/pom.xml @@ -46,5 +46,10 @@ org.infinispan infinispan-client-hotrod + + org.junit.jupiter + junit-jupiter + test + diff --git a/infinispan-remote/transactions/src/main/java/org/infinispan/tutorial/simple/remote/transaction/InfinispanRemoteTx.java b/infinispan-remote/transactions/src/main/java/org/infinispan/tutorial/simple/remote/transaction/InfinispanRemoteTx.java index 177a6d7c..1e6270c9 100644 --- a/infinispan-remote/transactions/src/main/java/org/infinispan/tutorial/simple/remote/transaction/InfinispanRemoteTx.java +++ b/infinispan-remote/transactions/src/main/java/org/infinispan/tutorial/simple/remote/transaction/InfinispanRemoteTx.java @@ -22,25 +22,18 @@ */ public class InfinispanRemoteTx { - private static final String CACHE_NAME = "simple-tx-cache"; + static final String CACHE_NAME = "simple-tx-cache"; - public static void main(String[] args) throws Exception { - // Create a configuration for a locally-running server - ConfigurationBuilder builder = TutorialsConnectorHelper.connectionConfig(); - // Add a transactional cache on startup - URI cacheConfig = InfinispanRemoteTx.class.getClassLoader().getResource("simple-tx-cache.xml").toURI(); - builder.remoteCache(CACHE_NAME) - // The cache that will be created is transactional - .configurationURI(cacheConfig) - // Use the simple TransactionManager in hot rod client - .transactionManagerLookup(RemoteTransactionManagerLookup.getInstance()) - // The cache will be enlisted as Synchronization - .transactionMode(TransactionMode.NON_XA); + static RemoteCacheManager cacheManager; + static RemoteCache cache; - // Connect to the server - RemoteCacheManager cacheManager = TutorialsConnectorHelper.connect(builder); - RemoteCache cache = cacheManager.getCache(CACHE_NAME); + public static void main(String[] args) throws Exception { + connectToInfinispan(); + manipulateWithTx(); + disconnect(false); + } + static void manipulateWithTx() throws Exception { // Obtain the transaction manager TransactionManager transactionManager = cache.getTransactionManager(); // Perform some operations within a transaction and commit it @@ -57,8 +50,31 @@ public static void main(String[] args) throws Exception { transactionManager.rollback(); // Display the current cache contents System.out.printf("key1 = %s\nkey2 = %s\n", cache.get("key1"), cache.get("key2")); + } + + public static void connectToInfinispan() throws Exception { + // Create a configuration for a locally-running server + ConfigurationBuilder builder = TutorialsConnectorHelper.connectionConfig(); + // Add a transactional cache on startup + URI cacheConfig = InfinispanRemoteTx.class.getClassLoader().getResource("simple-tx-cache.xml").toURI(); + builder.remoteCache(CACHE_NAME) + // The cache that will be created is transactional + .configurationURI(cacheConfig) + // Use the simple TransactionManager in hot rod client + .transactionManagerLookup(RemoteTransactionManagerLookup.getInstance()) + // The cache will be enlisted as Synchronization + .transactionMode(TransactionMode.NON_XA); + + // Connect to the server + cacheManager = TutorialsConnectorHelper.connect(builder); + cache = cacheManager.getCache(CACHE_NAME); + } + + public static void disconnect(boolean removeCaches) { + if (removeCaches) { + cacheManager.administration().removeCache(CACHE_NAME); + } // Stop the cache manager and release all resources TutorialsConnectorHelper.stop(cacheManager); } - } diff --git a/infinispan-remote/transactions/src/test/java/org/infinispan/tutorial/simple/remote/transaction/InfinispanRemoteTxTest.java b/infinispan-remote/transactions/src/test/java/org/infinispan/tutorial/simple/remote/transaction/InfinispanRemoteTxTest.java new file mode 100644 index 00000000..8f7f4260 --- /dev/null +++ b/infinispan-remote/transactions/src/test/java/org/infinispan/tutorial/simple/remote/transaction/InfinispanRemoteTxTest.java @@ -0,0 +1,38 @@ +package org.infinispan.tutorial.simple.remote.transaction; + + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.infinispan.tutorial.simple.remote.transaction.InfinispanRemoteTx.cache; +import static org.infinispan.tutorial.simple.remote.transaction.InfinispanRemoteTx.cacheManager; +import static org.infinispan.tutorial.simple.remote.transaction.InfinispanRemoteTx.connectToInfinispan; +import static org.infinispan.tutorial.simple.remote.transaction.InfinispanRemoteTx.disconnect; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class InfinispanRemoteTxTest { + + @BeforeAll + public static void start() throws Exception { + connectToInfinispan(); + } + + @AfterAll + public static void stop() { + disconnect(true); + } + + @Test + public void testTransactions() throws Exception { + assertNotNull(cacheManager); + assertNotNull(cache); + + InfinispanRemoteTx.manipulateWithTx(); + + assertEquals("value1", cache.get("key1")); + assertEquals("value2", cache.get("key2")); + } + +}