repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/DistributedMassIndexingTest.java
package org.infinispan.query.distributed; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.testng.Assert.assertEquals; import org.infinispan.Cache; import org.infinispan.configuration.cache.ClusteringConfiguration; import org.infinispan.context.Flag; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.core.stats.IndexInfo; import org.infinispan.query.core.stats.IndexStatisticsSnapshot; import org.infinispan.query.dsl.Query; import org.infinispan.query.helper.StaticTestingErrorHandler; import org.infinispan.query.queries.faceting.Car; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * @author Sanne Grinovero &lt;sanne@hibernate.org&gt; (C) 2012 Red Hat Inc. */ @Test(groups = "functional", testName = "query.distributed.DistributedMassIndexingTest") public class DistributedMassIndexingTest extends MultipleCacheManagersTest { protected static final int NUM_NODES = 3; { cleanup = CleanupPhase.AFTER_METHOD; } protected String getConfigurationFile() { return "dynamic-indexing-distribution.xml"; } @Override protected void createCacheManagers() throws Throwable { for (int i = 0; i < NUM_NODES; i++) { EmbeddedCacheManager cacheManager = TestCacheManagerFactory.fromXml(getConfigurationFile()); registerCacheManager(cacheManager); cacheManager.getCache(); } waitForClusterToForm(); } @AfterMethod(alwaysRun = true) @Override protected void clearContent() throws Throwable { super.clearContent(); } public void testReindexing() throws Exception { cache(0).put(key("F1NUM"), new Car("megane", "white", 300)); verifyFindsCar(1, "megane"); cache(1).put(key("F2NUM"), new Car("megane", "blue", 300)); verifyFindsCar(2, "megane"); //add an entry without indexing it: cache(1).getAdvancedCache().withFlags(Flag.SKIP_INDEXING).put(key("F3NUM"), new Car("megane", "blue", 300)); verifyFindsCar(2, "megane"); //re-sync datacontainer with indexes: rebuildIndexes(); verifyFindsCar(3, "megane"); //verify we cleanup old stale index values by deleting an entry without deleting the corresponding index value cache(2).getAdvancedCache().withFlags(Flag.SKIP_INDEXING).remove(key("F2NUM")); assertIndexedEntities(3, Car.class, cache(2)); //re-sync rebuildIndexes(); assertIndexedEntities(2, Car.class, cache(2)); verifyFindsCar(2, "megane"); } public void testPartiallyReindex() throws Exception { cache(0).getAdvancedCache().withFlags(Flag.SKIP_INDEXING).put(key("F1NUM"), new Car("megane", "white", 300)); Search.getIndexer(cache(0)).run(key("F1NUM")).toCompletableFuture().join(); verifyFindsCar(1, "megane"); cache(0).remove(key("F1NUM")); verifyFindsCar(0, "megane"); } protected Object key(String keyId) { //Used to verify remoting is fine with non serializable keys return new NonSerializableKeyType(keyId); } protected void rebuildIndexes() throws Exception { Cache<?, ?> cache = cache(0); CompletionStages.join(Search.getIndexer(cache).run()); } protected void verifyFindsCar(int expectedCount, String carMake) { for (Cache<String, Car> cache : this.<String, Car>caches()) { StaticTestingErrorHandler.assertAllGood(cache); verifyFindsCar(cache, expectedCount, carMake); } } protected void verifyFindsCar(Cache<?, Car> cache, int expectedCount, String carMake) { String q = String.format("FROM %s where make:'%s'", Car.class.getName(), carMake); Query<Car> cacheQuery = Search.getQueryFactory(cache).create(q); assertEquals(cacheQuery.list().size(), expectedCount); } private void assertIndexedEntities(int expected, Class<?> entityClass, Cache<?, Car> cache) { IndexStatisticsSnapshot indexStatistics = await(Search.getClusteredSearchStatistics(cache)).getIndexStatistics(); IndexInfo indexInfo = indexStatistics.indexInfos().get(entityClass.getName()); int count = (int) indexInfo.count(); // each entry is indexed in all owners for redundancy final ClusteringConfiguration clusteringConfiguration = cache.getCacheConfiguration().clustering(); long indexedCount; if (clusteringConfiguration.cacheMode().isReplicated()) { indexedCount = count / caches().size(); } else { indexedCount = count / clusteringConfiguration.hash().numOwners(); } assertEquals(indexedCount, expected); } }
4,822
39.191667
119
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/MassIndexingAllOffHeapTest.java
package org.infinispan.query.distributed; import org.testng.annotations.Test; /** * Tests for Mass Indexing with both index caches and data cache stored off-heap. * * @since 9.2 */ @Test(groups = "functional", testName = "query.distributed.MassIndexingAllOffHeapTest") public class MassIndexingAllOffHeapTest extends DistributedMassIndexingTest { @Override protected String getConfigurationFile() { return "mass-index-offheap-all.xml"; } }
463
23.421053
87
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/MassIndexingTest.java
package org.infinispan.query.distributed; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.testng.Assert.assertFalse; import java.util.concurrent.CompletionStage; import java.util.concurrent.CountDownLatch; import java.util.function.Function; import java.util.stream.IntStream; import org.infinispan.Cache; import org.infinispan.commons.util.Util; import org.infinispan.context.Flag; import org.infinispan.functional.FunctionalTestUtils; import org.infinispan.query.Indexer; import org.infinispan.query.Search; import org.infinispan.query.api.NotIndexedType; import org.infinispan.query.impl.massindex.IndexUpdater; import org.infinispan.query.impl.massindex.MassIndexerAlreadyStartedException; import org.infinispan.query.queries.faceting.Car; import org.infinispan.test.TestingUtil; import org.mockito.Mockito; import org.testng.annotations.Test; /** * Running mass indexer on big bunch of data. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.distributed.MassIndexingTest") public class MassIndexingTest extends DistributedMassIndexingTest { public void testReindexing() { for (int i = 0; i < 10; i++) { cache(i % 2).getAdvancedCache().withFlags(Flag.SKIP_INDEXING).put(key("F" + i + "NUM"), new Car((i % 2 == 0 ? "megane" : "bmw"), "blue", 300 + i)); } //Adding also non-indexed values cache(0).getAdvancedCache().put(key("FNonIndexed1NUM"), new NotIndexedType("test1")); cache(0).getAdvancedCache().put(key("FNonIndexed2NUM"), new NotIndexedType("test2")); verifyFindsCar(0, "megane"); verifyFindsCar(0, "test1"); verifyFindsCar(0, "test2"); cache(0).getAdvancedCache().withFlags(Flag.SKIP_INDEXING).put(key("FNonIndexed3NUM"), new NotIndexedType("test3")); verifyFindsCar(0, "test3"); //re-sync datacontainer with indexes: rebuildIndexes(); verifyFindsCar(5, "megane"); verifyFindsCar(0, "test1"); verifyFindsCar(0, "test2"); } @Test public void testOverlappingMassIndexers() { Cache<Integer, Car> cache = cache(0); IntStream.range(0, 10).forEach(i -> cache.put(i, new Car("whatever", "whatever", 0))); Indexer massIndexer = Search.getIndexer(cache); CountDownLatch latch = new CountDownLatch(1); instrumentIndexer(massIndexer, latch); CompletionStage<Void> first = massIndexer.run(); CompletionStage<Void> second = massIndexer.run(); latch.countDown(); assertTrue(isSuccess(second) && isError(first) || isSuccess(first) && isError(second)); assertFalse(massIndexer.isRunning()); CompletionStage<Void> third = massIndexer.run(); assertTrue(isSuccess(third)); } private void instrumentIndexer(Indexer original, CountDownLatch latch) { TestingUtil.replaceField(original, "indexUpdater", (Function<IndexUpdater, IndexUpdater>) indexUpdater -> { IndexUpdater mock = Mockito.spy(indexUpdater); Mockito.doAnswer(invocation -> { latch.await(); return invocation.callRealMethod(); }).when(mock).flush(any()); return mock; }); } public boolean isSuccess(CompletionStage<Void> future) { try { FunctionalTestUtils.await(future); return true; } catch (Throwable e) { return false; } } private boolean isError(CompletionStage<Void> future) { try { FunctionalTestUtils.await(future); return false; } catch (Throwable e) { return Util.getRootCause(e).getClass().equals(MassIndexerAlreadyStartedException.class); } } @Override protected void rebuildIndexes() { Cache<?, ?> cache = cache(0); join(Search.getIndexer(cache).run()); } }
3,908
31.848739
121
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/LocalMassIndexingTest.java
package org.infinispan.query.distributed; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.Map; import java.util.function.BiConsumer; import java.util.stream.IntStream; import org.infinispan.Cache; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Indexer; import org.infinispan.query.Search; import org.infinispan.query.core.stats.IndexInfo; import org.infinispan.query.core.stats.SearchStatistics; import org.infinispan.query.queries.faceting.Car; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Tests for selectively reindexing members of the clusters by using local mode * * @since 13.0 */ @Test(groups = "functional", testName = "query.distributed.LocalFlagMassIndexingTest") public class LocalMassIndexingTest extends MultipleCacheManagersTest { protected static final int NUM_NODES = 3; private static final int ENTRIES = 50; protected String getConfigurationFile() { return "dynamic-indexing-distribution.xml"; } @Override protected void createCacheManagers() throws Throwable { for (int i = 0; i < NUM_NODES; i++) { EmbeddedCacheManager cacheManager = TestCacheManagerFactory.fromXml(getConfigurationFile()); registerCacheManager(cacheManager); cacheManager.getCache(); } waitForClusterToForm(); Cache<Integer, Car> cache = cache(0); IntStream.range(0, ENTRIES).forEach(i -> cache.put(i, new Car("brand", "color", 100))); } public void testReindexing() throws Exception { final Indexer indexer0 = Search.getIndexer(cache(0)); final Indexer indexer1 = Search.getIndexer(cache(1)); final Indexer indexer2 = Search.getIndexer(cache(2)); join(indexer0.run()); assertAllIndexed(); clearIndexes(); // Local indexing should not touch the indexes of other caches join(indexer0.runLocal()); assertOnlyIndexed(0); clearIndexes(); join(indexer1.runLocal()); assertOnlyIndexed(1); clearIndexes(); join(indexer2.runLocal()); assertOnlyIndexed(2); } void clearIndexes() { join(Search.getIndexer(cache(0)).remove()); } private void assertIndexState(BiConsumer<IndexInfo, Integer> cacheIndexInfo) { IntStream.range(0, NUM_NODES).forEach(i -> { Cache<?, ?> cache = cache(i); SearchStatistics searchStatistics = Search.getSearchStatistics(cache); Map<String, IndexInfo> indexInfo = join(searchStatistics.getIndexStatistics().computeIndexInfos()); cacheIndexInfo.accept(indexInfo.get(Car.class.getName()), i); }); } private void assertAllIndexed() { assertIndexState((indexInfo, i) -> assertTrue(indexInfo.count() > 0)); } private void assertOnlyIndexed(int id) { assertIndexState((indexInfo, i) -> { long count = indexInfo.count(); if (i == id) { assertTrue(count > 0); } else { assertEquals(count, 0); } }); } }
3,224
30.31068
108
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/PerfTest.java
package org.infinispan.query.distributed; import static org.testng.AssertJUnit.assertEquals; import java.util.concurrent.TimeUnit; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.commons.util.Util; import org.infinispan.context.Flag; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.queries.faceting.Car; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Stress test running on an indexed Cache which is storing the index in a distributed Lucene Directory * * This test takes approximately 30 seconds: better increment the number of iterations. * It takes approximately half a second to insert 2000 entries in the indexed cache * when running DIST in 4 nodes, and it's much faster when run in single node. * * TestNG enables assertions: these have an impact on Lucene so better run it as a main! * * @author Adrian Nistor (C) 2013 Red Hat Inc. * @author Sanne Grinovero (C) 2013 Red Hat Inc. */ @Test(groups = "profiling", testName = "query.distributed.PerfTest", singleThreaded = true) public class PerfTest extends MultipleCacheManagersTest { private static final int NUM_NODES = 4; private static final int LOG_ON_EACH = 2000; private static final int NUMBER_OF_ITERATIONS = 50; @Override protected void createCacheManagers() throws Throwable { for (int i = 0; i < NUM_NODES; i++) { EmbeddedCacheManager cacheManager = TestCacheManagerFactory.fromXml("indexing-perf.xml"); registerCacheManager(cacheManager); } waitForClusterToForm(new String[]{ getDefaultCacheName(), "LuceneIndexesMetadata", "LuceneIndexesData", "LuceneIndexesLocking", }); } public void testIndexing() throws Exception { int carId = 0; int cacheId = 0; final long start = System.nanoTime(); for (int outherLoop = 0; outherLoop < NUMBER_OF_ITERATIONS; outherLoop++) { final Cache<String, Car> cache = getWriteOnlyCache(cacheId++ % NUM_NODES); System.out.print("Using " + cacheId + ": " + cache + "\t"); final long blockStart = System.nanoTime(); cache.startBatch(); for (int innerLoop = 0; innerLoop < LOG_ON_EACH; innerLoop++) { carId++; cache.put("car" + carId, new Car("megane", "blue", 300 + carId)); carId++; cache.put("car" + carId, new Car("bmw", "blue", 300 + carId)); } cache.endBatch(true); System.out.println("Inserted " + LOG_ON_EACH + " cars in " + Util.prettyPrintTime(System.nanoTime() - blockStart, TimeUnit.NANOSECONDS)); } System.out.println("Test took " + Util.prettyPrintTime(System.nanoTime() - start, TimeUnit.NANOSECONDS)); verifyFindsCar(carId / 2, "megane"); } private Cache<String, Car> getWriteOnlyCache(int cacheId) { Cache<String, Car> cache = cache(cacheId); AdvancedCache<String, Car> advancedCache = cache.getAdvancedCache(); AdvancedCache<String, Car> withFlags = advancedCache.withFlags(Flag.IGNORE_RETURN_VALUES, Flag.SKIP_INDEX_CLEANUP); return withFlags; } private void verifyFindsCar(int expectedCount, String carMake) { for (int i = 0; i < NUM_NODES; i++) { verifyFindsCar(cache(i), expectedCount, carMake); } } private void verifyFindsCar(Cache cache, int expectedCount, String carMake) { String q = String.format("FROM %s WHERE make:'%s'", Car.class.getName(), carMake); Query cacheQuery = Search.getQueryFactory(cache).create(q); assertEquals(expectedCount, cacheQuery.execute().count().value()); } /** * Recommended tuning options: * -Xms4g -Xmx4g -XX:+UseParallelGC -Djava.net.preferIPv4Stack=true -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Dcom.arjuna.ats.arjuna.coordinator.CoordinatorEnvironmentBean.asyncPrepare=true -XX:+UseLargePages -Djava.awt.headless=true -Dlog4j.configurationFile=log4j2.xml * * Diagnostic options: * -Xms6g -Xmx6g -XX:+UseParallelGC -Djava.net.preferIPv4Stack=true -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Dcom.arjuna.ats.arjuna.coordinator.CoordinatorEnvironmentBean.asyncPrepare=true -XX:+UseLargePages -Djava.awt.headless=true -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintTenuringDistribution -XX:-PrintTLAB -XX:+PrintHeapAtGCExtended -XX:+PrintAdaptiveSizePolicy -XX:+PrintGCApplicationStoppedTime -XX:-PrintGCApplicationConcurrentTime -Xloggc:/tmp/lucene.gclog -XX:+ParallelRefProcEnabled -XX:+UnlockCommercialFeatures -XX:+FlightRecorder -XX:StartFlightRecording=delay=10s,duration=24h,filename=/tmp/flight_record_lucene.jfr,settings=/opt/flightrecorder/profile_2ms -Dlog4j.configurationFile=log4j2.xml */ public static void main(String[] args) throws Throwable { PerfTest test = new PerfTest(); test.createBeforeClass(); try { test.testIndexing(); } finally { test.destroy(); } } }
5,309
46.410714
808
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/MassIndexerAsyncBackendTest.java
package org.infinispan.query.distributed; import org.infinispan.Cache; import org.infinispan.commons.test.ThreadLeakChecker; import org.infinispan.context.Flag; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.test.Transaction; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.CompletionStages; import org.jboss.byteman.contrib.bmunit.BMNGListener; import org.jboss.byteman.contrib.bmunit.BMRule; import org.testng.annotations.AfterClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * Tests for running MassIndexer on async indexing backend * * @author gustavonalle * @since 7.2 */ @Test(groups = "functional", testName = "query.distributed.MassIndexerAsyncBackendTest") @Listeners(BMNGListener.class) public class MassIndexerAsyncBackendTest extends MultipleCacheManagersTest { protected static final int NUM_NODES = 2; protected static final int NUM_ENTRIES = 10; @Override protected void createCacheManagers() throws Throwable { for (int i = 0; i < NUM_NODES; i++) { EmbeddedCacheManager cacheManager = TestCacheManagerFactory.fromXml("dist-indexing-async.xml"); registerCacheManager(cacheManager); } waitForClusterToForm("default", "LuceneIndexesMetadata", "LuceneIndexesData", "LuceneIndexesLocking"); } @AfterClass(alwaysRun = true) @Override protected void destroy() { // DistributedExecutorMassIndexer leaks executor, see ISPN-7606 ThreadLeakChecker.ignoreThreadsContaining("DefaultExecutorService-"); super.destroy(); } @Test @BMRule(name = "Delay the purge of the index", targetClass = "org.hibernate.search.backend.impl.lucene.works.PurgeAllWorkExecutor", targetMethod = "performWork", action = "delay(500)" ) public void testMassIndexOnAsync() throws Exception { final Cache<Object, Object> cache = caches().get(0); for (int i = 0; i < NUM_ENTRIES; i++) { cache.getAdvancedCache().withFlags(Flag.SKIP_INDEXING).put(String.valueOf(i), new Transaction(i, "12345")); } for (Cache c : caches()) { CompletionStages.join(Search.getIndexer(c).run()); assertAllIndexed(c); } } private void assertAllIndexed(final Cache cache) { eventually(() -> { int size = Search.getQueryFactory(cache).create("FROM " + Transaction.class.getName()).list().size(); return size == NUM_ENTRIES; }); } }
2,626
32.679487
116
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/ShardingMassIndexTest.java
package org.infinispan.query.distributed; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.Assert.assertEquals; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.Search; import org.infinispan.query.helper.TestQueryHelperFactory; import org.infinispan.query.queries.faceting.Car; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.Test; /** * Tests for MassIndexer on sharded indexes * * @author gustavonalle * @since 7.1 */ @Test(groups = "functional", testName = "query.distributed.ShardingMassIndexTest") public class ShardingMassIndexTest extends MultipleCacheManagersTest { protected static final int NUM_NODES = 3; @Override @SuppressWarnings("unchecked") protected void createCacheManagers() throws Throwable { // Car is split into 2 shards: one is going to Infinispan Directory with a shared index, the other is // going to Ram with a local index ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); cacheCfg .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Car.class); createClusteredCaches(NUM_NODES, QueryTestSCI.INSTANCE, cacheCfg); waitForClusterToForm(getDefaultCacheName()); } @Test(enabled = false, description = "Shards going to different index managers are not currently supported") public void testReindex() throws Exception { Cache<Integer, Object> cache = cache(0); cache.put(1, new Car("mazda", "red", 200)); cache.put(2, new Car("mazda", "blue", 200)); cache.put(3, new Car("audi", "blue", 170)); cache.put(4, new Car("audi", "black", 170)); checkIndex(4, Car.class); runMassIndexer(); checkIndex(4, Car.class); cache.clear(); runMassIndexer(); checkIndex(0, Car.class); } protected void checkIndex(int expectedNumber, Class<?> entity) { for (Cache<?, ?> c : caches()) { int size = TestQueryHelperFactory.queryAll(c, entity).size(); assertEquals(size, expectedNumber); } } protected void runMassIndexer() { join(Search.getIndexer(cache(0)).run()); } }
2,488
32.186667
111
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/OverlappingDistMassIndexTest.java
package org.infinispan.query.distributed; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.test.Block; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.query.test.Transaction; import org.testng.annotations.Test; /** * Tests for entities sharing the same index in DIST caches. * * @author gustavonalle * @since 7.1 */ @Test(groups = "functional", testName = "query.distributed.OverlappingDistMassIndexTest") public class OverlappingDistMassIndexTest extends OverlappingIndexMassIndexTest { @Override @SuppressWarnings("unchecked") protected void createCacheManagers() throws Throwable { ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); cacheCfg .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Transaction.class) .addIndexedEntity(Block.class); createClusteredCaches(NUM_NODES, QueryTestSCI.INSTANCE, cacheCfg); waitForClusterToForm(getDefaultCacheName()); caches = caches(); } }
1,238
30.769231
97
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/MassIndexingWithStoreTest.java
package org.infinispan.query.distributed; import org.infinispan.Cache; import org.infinispan.query.queries.faceting.Car; import org.testng.annotations.Test; /** * Test for MassIndexer with a store * * @author gustavonalle * @since 7.1 */ @Test(groups = "functional", testName = "query.distributed.MassIndexingWithStoreTest") public class MassIndexingWithStoreTest extends DistributedMassIndexingTest { @Override protected String getConfigurationFile() { return "mass-index-with-store.xml"; } @Override public void testReindexing() throws Exception { Cache<String, Car> cache0 = cache(0); for (int i = 0; i < 10; i++) { cache0.put("CAR#" + i, new Car("Volkswagen", "white", 200)); } rebuildIndexes(); verifyFindsCar(10, "Volkswagen"); } }
811
24.375
86
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/ClusteredQueryMassIndexingTest.java
package org.infinispan.query.distributed; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.Cache; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.queries.faceting.Car; import org.testng.annotations.Test; /** * Tests verifying that the Mass Indexing works for Clustered queries as well. */ @Test(groups = "functional", testName = "query.distributed.ClusteredQueryMassIndexingTest") public class ClusteredQueryMassIndexingTest extends DistributedMassIndexingTest { @Override protected String getConfigurationFile() { return "unshared-indexing-distribution.xml"; } protected void verifyFindsCar(Cache cache, int expectedCount, String carMake) { String q = String.format("FROM %s WHERE make:'%s'", Car.class.getName(), carMake); Query cacheQuery = Search.getQueryFactory(cache).create(q); assertEquals(expectedCount, cacheQuery.execute().list().size()); } }
981
31.733333
91
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/IndexManagerLocalTest.java
package org.infinispan.query.distributed; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import jakarta.transaction.TransactionManager; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.helper.StaticTestingErrorHandler; import org.infinispan.query.test.Person; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.Test; /** * Similar to MultiNodeDistributedTest, but using a local cache configuration both for * the indexed cache and for the storage of the index data. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.distributed.IndexManagerLocalTest") public class IndexManagerLocalTest extends SingleCacheManagerTest { protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder .clustering() .cacheMode(CacheMode.LOCAL) .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); if (transactionsEnabled()) { builder.transaction().transactionMode(TransactionMode.TRANSACTIONAL); } return TestCacheManagerFactory.createCacheManager(builder); } protected boolean transactionsEnabled() { return false; } public void testIndexingWork() throws Exception { assertIndexSize(0); store("k1", new Person("K. Firt", "Is not a character from the matrix", 1)); assertIndexSize(1); store("k2", new Person("K. Seycond", "Is a pilot", 1)); assertIndexSize(2); } protected void store(String key, Person person) throws Exception { TransactionManager transactionManager = cache.getAdvancedCache().getTransactionManager(); if (transactionsEnabled()) transactionManager.begin(); cache.put(key, person); if (transactionsEnabled()) transactionManager.commit(); } protected void assertIndexSize(int expectedIndexSize) { Query<Person> query = Search.getQueryFactory(cache).create("FROM " + Person.class.getName()); assertEquals(expectedIndexSize, query.execute().list().size()); StaticTestingErrorHandler.assertAllGood(cache); } }
2,600
36.157143
99
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/MassIndexingOffHeapDataOnlyTest.java
package org.infinispan.query.distributed; import org.testng.annotations.Test; /** * Tests for Mass Indexing where all index caches are stored on-heap, but cache data is off-heap. * * @since 9.2 */ @Test(groups = "functional", testName = "query.distributed.MassIndexingOffHeapDataOnlyTest") public class MassIndexingOffHeapDataOnlyTest extends DistributedMassIndexingTest { @Override protected String getConfigurationFile() { return "mass-index-offheap-data-only.xml"; } }
495
25.105263
97
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/DistProgrammaticMassIndexTest.java
package org.infinispan.query.distributed; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.helper.StaticTestingErrorHandler; import org.infinispan.query.queries.faceting.Car; import org.infinispan.query.test.QueryTestSCI; import org.testng.annotations.Test; /** * Tests verifying that the Mass Indexing for programmatic cache configuration works as well. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.distributed.DistProgrammaticMassIndexTest") public class DistProgrammaticMassIndexTest extends DistributedMassIndexingTest { @Override protected void createCacheManagers() throws Throwable { createCluster(holder -> { String defaultName = getClass().getSimpleName(); holder.getGlobalConfigurationBuilder().defaultCacheName(defaultName).serialization().addContextInitializer(QueryTestSCI.INSTANCE); ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); cacheCfg.indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Car.class); cacheCfg.clustering().stateTransfer().fetchInMemoryState(true); holder.newConfigurationBuilder(defaultName).read(cacheCfg.build()); }, NUM_NODES); } protected void verifyFindsCar(Cache cache, int count, String carMake) { String q = String.format("FROM %s where make:'%s'", Car.class.getName(), carMake); Query cacheQuery = Search.getQueryFactory(cache).create(q); assertEquals(count, cacheQuery.execute().list().size()); StaticTestingErrorHandler.assertAllGood(cache); } }
1,962
38.26
139
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/NonSerializableKeyType.java
package org.infinispan.query.distributed; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import org.infinispan.commons.marshall.Externalizer; import org.infinispan.commons.marshall.SerializeWith; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.query.Transformable; import org.infinispan.query.Transformer; /** * @author Sanne Grinovero &lt;sanne@hibernate.org&gt; (C) 2012 Red Hat Inc. */ @SerializeWith(NonSerializableKeyType.CustomExternalizer.class) @Transformable(transformer = NonSerializableKeyType.CustomTransformer.class) public class NonSerializableKeyType { @ProtoField(number = 1) final String keyValue; @ProtoFactory NonSerializableKeyType(final String keyValue) { this.keyValue = keyValue; } @Override public int hashCode() { return keyValue.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NonSerializableKeyType other = (NonSerializableKeyType) obj; if (keyValue == null) { if (other.keyValue != null) return false; } else if (!keyValue.equals(other.keyValue)) return false; return true; } public static class CustomExternalizer implements Externalizer<NonSerializableKeyType> { @Override public void writeObject(ObjectOutput output, NonSerializableKeyType object) throws IOException { output.writeUTF(object.keyValue); } @Override public NonSerializableKeyType readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new NonSerializableKeyType(input.readUTF()); } } public static class CustomTransformer implements Transformer { @Override public Object fromString(String s) { return new NonSerializableKeyType(s); } @Override public String toString(Object customType) { return ((NonSerializableKeyType)customType).keyValue; } } }
2,200
27.960526
110
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/LocalCacheMassIndexerTest.java
package org.infinispan.query.distributed; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.junit.Assert.assertFalse; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Indexer; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.test.Person; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Tests for Mass Indexer in a local cache. * * @author gustavonalle * @since 7.1 */ @Test(groups = "functional", testName = "query.distributed.LocalCacheMassIndexerTest") public class LocalCacheMassIndexerTest extends SingleCacheManagerTest { private static final int NUM_ENTITIES = 50; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(false); cfg.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); return TestCacheManagerFactory.createCacheManager(cfg); } private long indexSize(Cache<?, ?> cache) { QueryFactory queryFactory = Search.getQueryFactory(cache); // queryFactory.refresh(Object.class); Query<?> query = queryFactory.create("FROM " + Person.class.getName()); return query.execute().count().value(); } private void fillData() { for (int i = 0; i < NUM_ENTITIES; i++) { cache.put(i, new Person("name" + i, "blurb" + i, i)); } } @BeforeMethod public void clean() { cache.clear(); } @Test public void testMassIndexer() { fillData(); Indexer massIndexer = Search.getIndexer(cache); assertEquals(NUM_ENTITIES, indexSize(cache)); join(massIndexer.run()); assertEquals(NUM_ENTITIES, indexSize(cache)); cache.clear(); join(massIndexer.run()); assertEquals(0, indexSize(cache)); fillData(); join(massIndexer.run()); assertFalse(massIndexer.isRunning()); assertEquals(NUM_ENTITIES, indexSize(cache)); // Force local join(massIndexer.runLocal()); assertFalse(massIndexer.isRunning()); assertEquals(NUM_ENTITIES, indexSize(cache)); } public void testPartiallyReindex() throws Exception { cache.getAdvancedCache().withFlags(Flag.SKIP_INDEXING).put(0, new Person("name" + 0, "blurb" + 0, 0)); verifyFindsPerson(0, "name" + 0); join(Search.getIndexer(cache).run(0)); verifyFindsPerson(1, "name" + 0); cache.remove(0); verifyFindsPerson(0, "name" + 0); } protected void verifyFindsPerson(int expectedCount, String name) throws Exception { QueryFactory queryFactory = Search.getQueryFactory(cache); String q = String.format("FROM %s where name:'%s'", Person.class.getName(), name); Query cacheQuery = queryFactory.create(q); assertEquals(expectedCount, cacheQuery.execute().count().value()); } }
3,381
31.519231
108
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/AsyncMassIndexTest.java
package org.infinispan.query.distributed; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.query.test.Transaction; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.Test; /** * Test for the non blocking MassIndexer * * @author gustavonalle * @since 7.1 */ @Test(groups = "functional", testName = "query.distributed.AsyncMassIndexTest") public class AsyncMassIndexTest extends MultipleCacheManagersTest { protected static final int NUM_NODES = 2; protected CleanupPhase cleanup = CleanupPhase.AFTER_METHOD; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); cacheCfg .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Transaction.class); createClusteredCaches(NUM_NODES, QueryTestSCI.INSTANCE, cacheCfg); waitForClusterToForm(getDefaultCacheName()); } private void populate(int elements) { Cache<Integer, Transaction> cache = cache(0); for (int i = 0; i < elements; i++) { cache.put(i, new Transaction(i + 200, "bytes")); } } @Test public void testListener() throws Exception { Cache<Integer, Transaction> cache = cache(0); int elements = 50; populate(elements); CompletableFuture<Void> future = Search.getIndexer(cache).run().toCompletableFuture(); final CountDownLatch endLatch = new CountDownLatch(1); future.whenComplete((v, t) -> endLatch.countDown()); endLatch.await(); checkIndex(elements); } protected void checkIndex(int expectedNumber) { Cache<Integer, Transaction> c = cache(0); Query<Transaction> q = Search.getQueryFactory(c).create("FROM " + Transaction.class.getName()); long resultSize = q.execute().count().value(); assertEquals(expectedNumber, resultSize); } }
2,412
31.608108
101
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/UnsharedDistRedundantMassIndexTest.java
package org.infinispan.query.distributed; import org.testng.annotations.Test; /** * Test for MassIndexer on DIST caches with Index.ALL with local filesystem indexes. * * @since 10.1 */ @Test(groups = "functional", testName = "query.distributed.UnsharedDistRedundantMassIndexTest") public class UnsharedDistRedundantMassIndexTest extends UnsharedDistMassIndexTest { @Override protected String getConfigurationFile() { return "non-shared-redundant-index.xml"; } }
484
25.944444
95
java
null
infinispan-main/query/src/test/java/org/infinispan/query/queries/NumericType.java
package org.infinispan.query.queries; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; /** * A new additional entity type for testing Infinispan Querying. * * @author Anna Manukyan */ @Indexed(index = "numeric") public class NumericType { private int num1; private int num2; private String name; public NumericType(int num1, int num2) { this.num1 = num1; this.num2 = num2; } @Basic(projectable = true) public int getNum1() { return num1; } @Basic(projectable = true) public int getNum2() { return num2; } @Basic(projectable = true) public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NumericType that = (NumericType) o; if (num1 != that.num1) return false; if (num2 != that.num2) return false; return true; } @Override public int hashCode() { int result = num1; result = 31 * result + num2; return result; } }
1,221
18.09375
64
java
null
infinispan-main/query/src/test/java/org/infinispan/query/queries/ranges/QueryRangesTest.java
package org.infinispan.query.queries.ranges; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.TimeZone; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.test.Person; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Tests verifying that query ranges work properly. * * @author Anna Manukyan */ @Test(groups = {"functional"}, testName = "query.queries.ranges.QueryRangesTest") public class QueryRangesTest extends SingleCacheManagerTest { protected final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); private Person person1; private Person person2; private Person person3; private Person person4; protected String key1 = "test1"; protected String key2 = "test2"; protected String key3 = "test3"; public QueryRangesTest() { cleanup = CleanupPhase.AFTER_METHOD; DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT")); } protected Query<Person> createQuery(String predicate) { QueryFactory searchManager = Search.getQueryFactory(cache); String query = String.format("FROM %s WHERE %s", Person.class.getName(), predicate); return searchManager.create(query); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); return TestCacheManagerFactory.createCacheManager(cfg); } public void testQueryingRangeBelowExcludingLimit() throws ParseException { loadTestingData(); Query<?> cacheQuery = createQuery("age:[* TO 29]"); List<?> found = cacheQuery.execute().list(); assertEquals(2, found.size()); assert found.contains(person1); assert found.contains(person3); assert !found.contains(person4) : "This should not contain object person4"; person4 = new Person(); person4.setName("Mighty Goat"); person4.setBlurb("Also eats grass"); person4.setAge(28); cache.put("mighty", person4); found = cacheQuery.execute().list(); assert found.size() == 3 : "Size of list should be 3"; assert found.contains(person1); assert found.contains(person3); assert found.contains(person4) : "This should now contain object person4"; } public void testQueryingRangeBelowWithLimit() throws ParseException { loadTestingData(); Query<?> cacheQuery = createQuery("age:[* to 30]"); List<?> found = cacheQuery.execute().list(); assertEquals(3, found.size()); assert found.contains(person1); assert found.contains(person2); assert found.contains(person3); assert !found.contains(person4) : "This should not contain object person4"; person4 = new Person(); person4.setName("Mighty Goat"); person4.setBlurb("Also eats grass"); person4.setAge(28); cache.put("mighty", person4); found = cacheQuery.execute().list(); assert found.size() == 4 : "Size of list should be 4"; assert found.contains(person1); assert found.contains(person2); assert found.contains(person3); assert found.contains(person4) : "This should now contain object person4"; } public void testQueryingRangeAboveExcludingLimit() throws ParseException { loadTestingData(); Query<?> cacheQuery = createQuery("age:[31 to *]"); List<?> found = cacheQuery.execute().list(); assertEquals(0, found.size()); cacheQuery = createQuery("age:[21 to *]"); found = cacheQuery.execute().list(); assertEquals(2, found.size()); assert found.contains(person2); assert found.contains(person3); assert !found.contains(person4) : "This should not contain object person4"; person4 = new Person(); person4.setName("Mighty Goat"); person4.setBlurb("Also eats grass"); person4.setAge(28); cache.put("mighty", person4); found = cacheQuery.execute().list(); assert found.size() == 3 : "Size of list should be 3"; assert found.contains(person2); assert found.contains(person3); assert found.contains(person4) : "This should now contain object person4"; } public void testQueryingRangeAboveWithLimit() throws ParseException { loadTestingData(); Query<?> cacheQuery = createQuery("age:[31 to *]"); List<?> found = cacheQuery.execute().list(); assertEquals(0, found.size()); cacheQuery = createQuery("age:[20 to *]"); found = cacheQuery.execute().list(); assertEquals(3, found.size()); assert found.contains(person1); assert found.contains(person2); assert found.contains(person3); assert !found.contains(person4) : "This should not contain object person4"; person4 = new Person(); person4.setName("Mighty Goat"); person4.setBlurb("Also eats grass"); person4.setAge(28); cache.put("mighty", person4); found = cacheQuery.execute().list(); assert found.size() == 4 : "Size of list should be 3"; assert found.contains(person1); assert found.contains(person2); assert found.contains(person3); assert found.contains(person4) : "This should now contain object person4"; } public void testQueryingRange() throws ParseException { loadTestingData(); Query<?> cacheQuery = createQuery("age:[21 TO 29]"); List<?> found = cacheQuery.execute().list(); assertEquals(1, found.size()); assert found.contains(person3); assert !found.contains(person4) : "This should not contain object person4"; person4 = new Person(); person4.setName("Mighty Goat"); person4.setBlurb("Mighty Goat also eats grass"); person4.setAge(28); cache.put("mighty", person4); found = cacheQuery.execute().list(); assert found.size() == 2 : "Size of list should be 3"; assert found.contains(person3); assert found.contains(person4) : "This should now contain object person4"; } public void testQueryingRangeWithLimits() throws ParseException { loadTestingData(); Query<?> cacheQuery = createQuery("age:[20 to 30]"); List<?> found = cacheQuery.execute().list(); assertEquals(3, found.size()); assert found.contains(person1); assert found.contains(person2); assert found.contains(person3); assert !found.contains(person4) : "This should not contain object person4"; person4 = new Person(); person4.setName("Mighty Goat"); person4.setBlurb("Mighty Goat also eats grass"); person4.setAge(28); cache.put("mighty", person4); found = cacheQuery.execute().list(); assert found.size() == 4 : "Size of list should be 3"; assert found.contains(person1); assert found.contains(person2); assert found.contains(person3); assert found.contains(person4) : "This should now contain object person4"; Person person5 = new Person(); person5.setName("ANother Goat"); person5.setBlurb("Some other goat should eat grass."); person5.setAge(31); cache.put("anotherGoat", person5); found = cacheQuery.execute().list(); assert found.size() == 4 : "Size of list should be 3"; assert found.contains(person1); assert found.contains(person2); assert found.contains(person3); assert found.contains(person4) : "This should now contain object person4"; } public void testQueryingRangeWithLimitsAndExclusions() throws ParseException { loadTestingData(); Query<?> cacheQuery = createQuery("age:[21 to 30]"); List<?> found = cacheQuery.execute().list(); assertEquals(2, found.size()); assert found.contains(person2); assert found.contains(person3); assert !found.contains(person4) : "This should not contain object person4"; person4 = new Person(); person4.setName("Mighty Goat"); person4.setBlurb("Mighty Goat also eats grass"); person4.setAge(28); cache.put("mighty", person4); found = cacheQuery.execute().list(); assertEquals(3, found.size()); assert found.contains(person2); assert found.contains(person3); assert found.contains(person4) : "This should now contain object person4"; Person person5 = new Person(); person5.setName("ANother Goat"); person5.setBlurb("Some other goat should eat grass."); person5.setAge(31); cache.put("anotherGoat", person5); found = cacheQuery.execute().list(); assertEquals(3, found.size()); assert found.contains(person2); assert found.contains(person3); assert found.contains(person4) : "This should now contain object person4"; cacheQuery = createQuery("age:[20 to 29]"); found = cacheQuery.execute().list(); assertEquals(3, found.size()); assert found.contains(person1); assert found.contains(person3); assert found.contains(person4); } public void testQueryingRangeForDatesWithLimitsAndExclusions() throws ParseException { loadTestingData(); Query<?> cacheQuery = createQuery("dateOfGraduation:['20020506' to '20120630']"); List<?> found = cacheQuery.execute().list(); assertEquals(2, found.size()); assert found.contains(person1); assert found.contains(person2); person4 = new Person("Mighty Goat", "Mighty Goat also eats grass", 28, makeDate("2007-06-15")); //date in ranges cache.put("mighty", person4); found = cacheQuery.execute().list(); assertEquals(3, found.size()); assert found.contains(person1); assert found.contains(person2); assert found.contains(person4) : "This should now contain object person4"; Person person5 = new Person("Another Goat", "Some other goat should eat grass.", 31, makeDate("2012-07-05")); //date out of ranges cache.put("anotherGoat", person5); found = cacheQuery.execute().list(); assertEquals(3, found.size()); assert found.contains(person1); assert found.contains(person2); assert found.contains(person4); cacheQuery = createQuery("dateOfGraduation:['20020505' to '20120609']"); found = cacheQuery.execute().list(); assertEquals(3, found.size()); assert found.contains(person2); assert found.contains(person3); assert found.contains(person4); } protected void loadTestingData() throws ParseException { person1 = new Person(); person1.setName("Navin Surtani"); person1.setBlurb("Likes playing WoW"); person1.setAge(20); person1.setDateOfGraduation(makeDate("2012-06-10")); person2 = new Person(); person2.setName("Big Goat"); person2.setBlurb("Eats grass"); person2.setAge(30); person2.setDateOfGraduation(makeDate("2002-07-05")); person3 = new Person(); person3.setName("Mini Goat"); person3.setBlurb("Eats cheese"); person3.setAge(25); person3.setDateOfGraduation(makeDate("2002-05-05")); cache.put(key1, person1); cache.put(key2, person2); cache.put(key3, person3); } protected Date makeDate(String dateStr) throws ParseException { return DATE_FORMAT.parse(dateStr); } }
11,902
31.790634
136
java
null
infinispan-main/query/src/test/java/org/infinispan/query/queries/faceting/Car.java
package org.infinispan.query.queries.faceting; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Text; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; /** * @author Hardy Ferentschik */ @Indexed(index = "car") public class Car { private String color; private String make; // the Search6's aggregation is the new HS5's faceting @Basic(aggregable = true) private int cubicCapacity; @ProtoFactory public Car(String make, String color, int cubicCapacity) { this.color = color; this.cubicCapacity = cubicCapacity; this.make = make; } @Text @ProtoField(number = 1) public String getMake() { return make; } @Basic(projectable = true) @ProtoField(number = 2) public String getColor() { return color; } @ProtoField(number = 3, defaultValue = "0") public int getCubicCapacity() { return cubicCapacity; } @Override public String toString() { return "Car{color='" + color + "', make='" + make + "', cubicCapacity=" + cubicCapacity + '}'; } }
1,227
22.615385
100
java
null
infinispan-main/query/src/test/java/org/infinispan/query/queries/phrases/EmbeddedQueryTest.java
package org.infinispan.query.queries.phrases; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.junit.Assert.assertEquals; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.impl.ComponentRegistryUtils; import org.infinispan.query.test.Author; import org.infinispan.query.test.Book; import org.infinispan.search.mapper.mapping.SearchMapping; import org.infinispan.search.mapper.mapping.metamodel.IndexMetamodel; import org.infinispan.search.mapper.mapping.metamodel.ObjectFieldMetamodel; import org.infinispan.search.mapper.mapping.metamodel.ValueFieldMetamodel; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.queries.phrases.EmbeddedQueryTest") public class EmbeddedQueryTest extends SingleCacheManagerTest { public EmbeddedQueryTest() { cleanup = CleanupPhase.AFTER_METHOD; } private <T> Query<T> createCacheQuery(Class<T> clazz, String alias, String predicate) { String queryStr = String.format("FROM %s %s WHERE %s", clazz.getName(), alias, predicate); return Search.getQueryFactory(cache).create(queryStr); } public void testSimpleQuery() { assertEquals(0, cache.size()); cache.put("author#1", new Author("author1", "surname1")); cache.put("author#2", new Author("author2", "surname2")); cache.put("author#3", new Author("author3", "surname3")); assertEquals(3, cache.size()); Query<Author> query = createCacheQuery(Author.class, "a", "a.name:'author1'"); List<Author> result = query.execute().list(); assertEquals(1, result.size()); assertEquals("surname1", result.get(0).getSurname()); } public void testEmbeddedQuery() { assertEquals(0, cache.size()); Author a1 = new Author("author1", "surname1"); Author a2 = new Author("author2", "surname2"); Author a3 = new Author("author3", "surname3"); Set<Author> aSet1 = new HashSet<>(); aSet1.add(a1); aSet1.add(a2); Set<Author> aSet2 = new HashSet<>(); aSet2.add(a1); aSet2.add(a3); Set<Author> aSet3 = new HashSet<>(); Book book1 = new Book("Book1", "Some very interesting book", aSet1); Book book2 = new Book("Book2", "Not so interesting book", aSet2); Book book3 = new Book("Book3", "Book of unknown author", aSet3); cache.put("book#1", book1); cache.put("book#2", book2); cache.put("book#3", book3); assertEquals(3, cache.size()); Query<Book> query = createCacheQuery(Book.class, "b", "b.authors.name:'author1'"); List<Book> result = query.execute().list(); assertEquals(2, result.size()); query = createCacheQuery(Book.class, "b", "b.description:'interesting'"); result = query.execute().list(); assertEquals(2, result.size()); } public void testEmbeddedMetamodel() { SearchMapping searchMapping = ComponentRegistryUtils.getSearchMapping(cache); Map<String, IndexMetamodel> metamodel = searchMapping.metamodel(); Json make = Json.make(metamodel); assertThat(make).isNotNull(); // try to parse as JSON // 2 root entities assertThat(metamodel).hasSize(2); IndexMetamodel indexMetamodel = metamodel.get(Book.class.getName()); assertThat(indexMetamodel.getIndexName()).isEqualTo(Book.class.getName()); assertThat(indexMetamodel.getValueFields()).hasSize(4); assertThat(indexMetamodel.getObjectFields()).hasSize(1); ObjectFieldMetamodel embedded = indexMetamodel.getObjectFields().get("authors"); assertThat(embedded.isMultiValued()).isTrue(); assertThat(embedded.isMultiValuedInRoot()).isTrue(); assertThat(embedded.isNested()).isTrue(); assertThat(embedded.getValueFields()).hasSize(2); ValueFieldMetamodel surname = embedded.getValueFields().get("surname"); assertThat(surname.isSearchable()).isTrue(); assertThat(surname.isProjectable()).isFalse(); ValueFieldMetamodel name = embedded.getValueFields().get("name"); assertThat(name.getType()).isEqualTo(String.class); assertThat(name.getAnalyzer()).hasValue("standard"); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg .indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Book.class) .addIndexedEntity(Author.class); return TestCacheManagerFactory.createCacheManager(cfg); } }
5,025
39.532258
96
java
null
infinispan-main/query/src/test/java/org/infinispan/query/queries/phrases/QueryPhrasesTest.java
package org.infinispan.query.queries.phrases; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.List; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.objectfilter.ParsingException; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.queries.NumericType; import org.infinispan.query.test.AnotherGrassEater; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Tests and verifies that the querying using keywords, phrases, etc works properly. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.queries.phrases.QueryPhrasesTest") public class QueryPhrasesTest extends SingleCacheManagerTest { private Person person1; private Person person2; private Person person3; private Person person4; private String key1 = "test1"; private String key2 = "test2"; private String key3 = "test3"; private NumericType type1; private NumericType type2; private NumericType type3; public QueryPhrasesTest() { cleanup = CleanupPhase.AFTER_METHOD; } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg .indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(NumericType.class) .addIndexedEntity(Person.class) .addIndexedEntity(AnotherGrassEater.class); return TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE, cfg); } private <T> Query<T> createCacheQuery(Class<T> clazz, String predicate) { String queryStr = String.format("FROM %s WHERE %s", clazz.getName(), predicate); return Search.getQueryFactory(cache).create(queryStr); } public void testBooleanQueriesMustNot() { loadTestingData(); Query<Person> cacheQuery = createCacheQuery(Person.class, "-name:'Goat'"); List<Person> found = cacheQuery.execute().list(); assertEquals(1, found.size()); assertTrue(found.contains(person1)); cacheQuery = createCacheQuery(Person.class, "name:'Goat'"); found = cacheQuery.execute().list(); assertEquals(2, found.size()); assertTrue(found.contains(person2)); assertTrue(found.contains(person3)); } public void testBooleanQueriesShould() { loadTestingData(); Query<Person> cacheQuery = createCacheQuery(Person.class, "name:'Goat' OR age <= 20"); List<Person> found = cacheQuery.execute().list(); assertEquals(3, found.size()); assertTrue(found.contains(person1)); assertTrue(found.contains(person2)); assertTrue(found.contains(person3)); cacheQuery = createCacheQuery(Person.class, "name:'Goat' OR age < 20"); found = cacheQuery.execute().list(); assertEquals(2, found.size()); assertTrue(found.contains(person2)); assertTrue(found.contains(person3)); } public void testBooleanQueriesShouldNot() { loadTestingData(); Query<Person> cacheQuery = createCacheQuery(Person.class, "name:'Goat'^0.5 OR age:[* to 20]^2"); List<Person> found = cacheQuery.execute().list(); assertEquals(3, found.size()); assertEquals(person1, found.get(0)); assertEquals(person2, found.get(1)); assertEquals(person3, found.get(2)); cacheQuery = createCacheQuery(Person.class, "name:'Goat'^9.5 OR age:[* to 20]^2"); found = cacheQuery.execute().list(); assertEquals(3, found.size()); assertEquals(person2, found.get(0)); assertEquals(person3, found.get(1)); assertEquals(person1, found.get(2)); } public void testFuzzyOnFieldsAndField() { loadTestingData(); Query<Person> cacheQuery = createCacheQuery(Person.class, "name:'Goat'~2"); List<Person> found = cacheQuery.execute().list(); assertEquals(2, found.size()); assertTrue(found.contains(person2)); assertTrue(found.contains(person3)); person4 = new Person(); person4.setName("Test"); person4.setBlurb("Test goat"); cache.put("testKey", person4); cacheQuery = createCacheQuery(Person.class, "name:'goat'~2 OR blurb:'goat'~2"); found = cacheQuery.execute().list(); assertEquals(3, found.size()); assertTrue(found.contains(person2)); assertTrue(found.contains(person3)); assertTrue(found.contains(person4)); } public void testFuzzyWithThresholdWithPrefixLength() { person1 = new Person("yyJohn", "Eat anything", 10); person2 = new Person("yyJonn", "Eat anything", 10); cache.put(key1, person1); cache.put(key2, person2); //Ignore "yy" at the beginning (prefix==2), the difference between the remaining parts of two terms //must be no more than edit distance -> return only 1 person Query<Person> cacheQuery = createCacheQuery(Person.class, "name:'yyJohny'~1"); List<Person> found = cacheQuery.execute().list(); assertEquals(1, found.size()); assertTrue(found.contains(person1)); //return all as edit distance excluding the prefix fit all documents cacheQuery = createCacheQuery(Person.class, "name:'yyJohn'~2"); List<Person> foundWithLowerThreshold = cacheQuery.execute().list(); assertEquals(2, foundWithLowerThreshold.size()); assertTrue(foundWithLowerThreshold.contains(person1)); assertTrue(foundWithLowerThreshold.contains(person2)); } public void testQueryingRangeWithAnd() { NumericType type1 = new NumericType(10, 20); NumericType type2 = new NumericType(20, 10); NumericType type3 = new NumericType(10, 10); cache.put(key1, type1); cache.put(key2, type2); cache.put(key3, type3); Query<NumericType> cacheQuery = createCacheQuery(NumericType.class, "num1:[* TO 19] OR num2:[* TO 19]"); List<NumericType> found = cacheQuery.execute().list(); assertEquals(3, found.size()); //<------ All entries should be here, because andField is executed as SHOULD; assertTrue(found.contains(type1)); assertTrue(found.contains(type2)); assertTrue(found.contains(type3)); NumericType type4 = new NumericType(11, 10); cache.put("newKey", type4); found = cacheQuery.execute().list(); assertEquals(4, found.size()); assertTrue(found.contains(type3)); assertTrue(found.contains(type2)); assertTrue(found.contains(type1)); assertTrue(found.contains(type4)); //@TODO write here another case with not-matching entries } @Test(expectedExceptions = ParsingException.class) public void testWildcardWithWrongName() { loadTestingData(); Query<Person> cacheQuery = createCacheQuery(Person.class, "wrongname:'*Goat*'"); List<Person> found = cacheQuery.execute().list(); assertEquals(2, found.size()); } public void testWildcard() { loadNumericTypes(); Query<NumericType> cacheQuery = createCacheQuery(NumericType.class, "name LIKE '%wildcard%'"); List<NumericType> found = cacheQuery.execute().list(); assertEquals(3, found.size()); assertTrue(found.contains(type1)); assertTrue(found.contains(type2)); assertTrue(found.contains(type3)); cacheQuery = createCacheQuery(NumericType.class, "name LIKE 'nothing%'"); found = cacheQuery.execute().list(); assertEquals(0, found.size()); NumericType type4 = new NumericType(35, 40); type4.setName("nothing special."); cache.put("otherKey", type4); found = cacheQuery.execute().list(); assertEquals(1, found.size()); assertTrue(found.contains(type4)); cacheQuery = createCacheQuery(NumericType.class, "name LIKE '%nothing%'"); found = cacheQuery.execute().list(); assertEquals(2, found.size()); assertTrue(found.contains(type2)); assertTrue(found.contains(type4)); } public void testKeyword() { loadTestingData(); Query<Person> cacheQuery = createCacheQuery(Person.class, "name:'Eats' OR blurb:'Eats'"); List<Person> found = cacheQuery.execute().list(); assertEquals(2, found.size()); person4 = new Person(); person4.setName("Some name with Eats"); person4.setBlurb("Description without keyword."); cache.put("someKey", person4); found = cacheQuery.execute().list(); assertEquals(3, found.size()); assertTrue(found.contains(person2)); assertTrue(found.contains(person3)); assertTrue(found.contains(person4)); } public void testPhraseSentence() { loadTestingData(); Query<Person> cacheQuery = createCacheQuery(Person.class, "blurb:'Eats grass'"); List<Person> found = cacheQuery.execute().list(); assertEquals(1, found.size()); assertTrue(found.contains(person2)); person4 = new Person(); person4.setName("Another goat"); person4.setBlurb("Eats grass and drinks water."); cache.put("anotherKey", person4); found = cacheQuery.execute().list(); assertEquals(2, found.size()); assertTrue(found.contains(person2)); assertTrue(found.contains(person4)); } public void testPhraseSentenceForNonAnalyzedEntries() { loadNumericTypes(); Query<NumericType> cacheQuery = createCacheQuery(NumericType.class, "name = 'Some string'"); List<NumericType> found = cacheQuery.execute().list(); assertEquals(0, found.size()); NumericType type4 = new NumericType(45, 50); type4.setName("Some string"); cache.put("otherKey", type4); found = cacheQuery.execute().list(); assertEquals(1, found.size()); assertTrue(found.contains(type4)); } public void testPhraseWithSlop() { loadTestingData(); Query<Person> cacheQuery = createCacheQuery(Person.class, "blurb:'Eats grass'~3"); List<Person> found = cacheQuery.execute().list(); assertEquals(1, found.size()); assertTrue(found.contains(person2)); person4 = new Person(); person4.setName("other goat"); person4.setBlurb("Eats green grass."); cache.put("otherKey", person4); found = cacheQuery.execute().list(); assertEquals(2, found.size()); assertTrue(found.contains(person2)); assertTrue(found.contains(person4)); person4.setBlurb("Eats green tasty grass."); cache.put("otherKey", person4); found = cacheQuery.execute().list(); assertEquals(2, found.size()); assertTrue(found.contains(person2)); assertTrue(found.contains(person4)); person4.setBlurb("Eats green, tasty, juicy grass."); cache.put("otherKey", person4); found = cacheQuery.execute().list(); assertEquals(2, found.size()); assertTrue(found.contains(person2)); assertTrue(found.contains(person4)); person4.setBlurb("Eats green, tasty, juicy, fresh grass."); cache.put("otherKey", person4); found = cacheQuery.execute().list(); assertEquals(1, found.size()); assertTrue(found.contains(person2)); } public void testPhraseWithSlopWithoutAnalyzer() { loadNumericTypes(); Query<NumericType> cacheQuery = createCacheQuery(NumericType.class, "name='Some string'"); List<NumericType> found = cacheQuery.execute().list(); assertEquals(0, found.size()); NumericType type = new NumericType(10, 60); type.setName("Some string"); cache.put("otherKey", type); found = cacheQuery.execute().list(); assertEquals(1, found.size()); assertTrue(found.contains(type)); NumericType type1 = new NumericType(20, 60); type1.setName("Some other string"); cache.put("otherKey1", type1); found = cacheQuery.execute().list(); assertEquals(1, found.size()); assertTrue(found.contains(type)); } public void testAllExcept() { loadTestingData(); Query<Person> cacheQuery = createCacheQuery(Person.class, "name:[* TO *]"); List<Person> found = cacheQuery.execute().list(); assertEquals(3, found.size()); assertTrue(found.contains(person2)); assertTrue(found.contains(person1)); assertTrue(found.contains(person3)); cacheQuery = createCacheQuery(Person.class, "-name:[* TO *]"); found = cacheQuery.execute().list(); assertEquals(0, found.size()); cacheQuery = createCacheQuery(Person.class, "-name:'Goat'"); found = cacheQuery.execute().list(); assertEquals(1, found.size()); assertTrue(found.contains(person1)); } public void testAllExceptWithoutAnalyzer() { loadNumericTypes(); Query<NumericType> cacheQuery = createCacheQuery(NumericType.class, "name LIKE '%string%'"); List<NumericType> found = cacheQuery.execute().list(); assertEquals(3, found.size()); assertTrue(found.contains(type1)); assertTrue(found.contains(type2)); assertTrue(found.contains(type3)); cacheQuery = createCacheQuery(NumericType.class, "not(name LIKE '%string%')"); found = cacheQuery.execute().list(); assertEquals(0, found.size()); } private void loadTestingData() { person1 = new Person(); person1.setName("Navin Surtani"); person1.setBlurb("Likes playing WoW"); person1.setAge(20); person2 = new Person(); person2.setName("Big Goat"); person2.setBlurb("Eats grass"); person2.setAge(30); person3 = new Person(); person3.setName("Mini Goat"); person3.setBlurb("Eats cheese"); person3.setAge(25); cache.put(key1, person1); cache.put(key2, person2); cache.put(key3, person3); } private void loadNumericTypes() { type1 = new NumericType(10, 20); type1.setName("Some string for testing wildcards."); type2 = new NumericType(15, 25); type2.setName("This string has nothing to do with wildcards."); type3 = new NumericType(20, 30); type3.setName("Some other string for testing wildcards."); cache.put(key1, type1); cache.put(key2, type2); cache.put(key3, type3); } }
14,536
31.667416
115
java
null
infinispan-main/query/src/test/java/org/infinispan/query/helper/TestableCluster.java
package org.infinispan.query.helper; import static org.testng.AssertJUnit.assertTrue; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; public class TestableCluster<K, V> { private final List<EmbeddedCacheManager> cacheManagers = new ArrayList<>(); private final List<Cache<K, V>> caches = new ArrayList<>(); private final String configurationResourceName; public TestableCluster(String configurationResourceName) { this.configurationResourceName = configurationResourceName; } public synchronized EmbeddedCacheManager startNewNode() { EmbeddedCacheManager cacheManager; try { cacheManager = TestCacheManagerFactory.fromXml(configurationResourceName); } catch (IOException e) { throw new RuntimeException(e); } cacheManagers.add(cacheManager); Cache<K, V> cache = cacheManager.getCache(); caches.add(cache); waitForStableTopology(cache, caches); return cacheManager; } public synchronized Cache<K, V> getCache(int nodeId) { return caches.get(nodeId); } public synchronized void killAll() { TestingUtil.killCacheManagers(cacheManagers); caches.clear(); cacheManagers.clear(); } public synchronized Iterable<Cache<K, V>> iterateAllCaches() { return new ArrayList<Cache<K, V>>(caches); } public synchronized void killNode(Cache<K, V> cache) { EmbeddedCacheManager cacheManager = cache.getCacheManager(); TestingUtil.killCacheManagers(cacheManager); assertTrue(caches.remove(cache)); assertTrue(cacheManagers.remove(cacheManager)); waitForStableTopology(cache, caches); } private static <K, V> void waitForStableTopology(Cache<K, V> cache, List<Cache<K, V>> caches) { if (cache.getCacheConfiguration().clustering().cacheMode() != CacheMode.LOCAL) { TestingUtil.waitForNoRebalance(caches); } } }
2,173
30.970588
98
java
null
infinispan-main/query/src/test/java/org/infinispan/query/helper/StaticTestingErrorHandler.java
package org.infinispan.query.helper; import static org.assertj.core.api.Assertions.assertThat; import org.infinispan.Cache; import org.infinispan.search.mapper.mapping.SearchMapping; public final class StaticTestingErrorHandler { public static void assertAllGood(Cache... caches) { for (Cache cache : caches) { assertAllGood(cache); } } public static void assertAllGood(Cache cache) { SearchMapping searchMapping = TestQueryHelperFactory.extractSearchMapping(cache); assertThat(searchMapping.genericIndexingFailures()).isZero(); assertThat(searchMapping.entityIndexingFailures()).isZero(); } }
651
27.347826
87
java
null
infinispan-main/query/src/test/java/org/infinispan/query/helper/IndexAccessor.java
package org.infinispan.query.helper; import static org.testng.AssertJUnit.fail; import java.io.IOException; import java.util.List; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.search.Sort; import org.apache.lucene.store.Directory; import org.hibernate.search.backend.lucene.index.LuceneIndexManager; import org.hibernate.search.backend.lucene.index.impl.LuceneIndexManagerImpl; import org.hibernate.search.backend.lucene.index.impl.Shard; import org.hibernate.search.backend.lucene.lowlevel.index.impl.IndexAccessorImpl; import org.hibernate.search.engine.backend.index.IndexManager; import org.hibernate.search.engine.common.spi.SearchIntegration; import org.hibernate.search.engine.environment.bean.BeanHolder; import org.hibernate.search.engine.reporting.FailureHandler; import org.hibernate.search.engine.reporting.impl.FailSafeFailureHandlerWrapper; import org.hibernate.search.engine.search.query.SearchQuery; import org.infinispan.Cache; import org.infinispan.commons.util.ReflectionUtil; import org.infinispan.search.mapper.mapping.SearchIndexedEntity; import org.infinispan.search.mapper.mapping.SearchMapping; /** * Provides some low level api index instances. * <p> * For tests only. * * @author Fabio Massimo Ercoli */ public class IndexAccessor { private final LuceneIndexManagerImpl indexManager; private final List<Shard> shardsForTests; private final IndexAccessorImpl indexAccessor; public static IndexAccessor of(Cache<?, ?> cache, Class<?> entityType) { return new IndexAccessor(cache, entityType); } public IndexAccessor(Cache<?, ?> cache, Class<?> entityType) { SearchMapping searchMapping = TestQueryHelperFactory.extractSearchMapping(cache); SearchIndexedEntity searchIndexedEntity = searchMapping.indexedEntity(entityType); if (searchIndexedEntity == null) { fail("Entity " + entityType + " is not indexed."); } indexManager = (LuceneIndexManagerImpl) searchIndexedEntity.indexManager().unwrap(LuceneIndexManager.class); shardsForTests = indexManager.getShardsForTests(); indexAccessor = shardsForTests.get(0).indexAccessorForTests(); } public IndexManager getIndexManager() { return indexManager; } public List<Shard> getShardsForTests() { return shardsForTests; } /** * Provides a Lucene index reader. * The instance is not supposed to be closed by the caller. * Hibernate Search will take care of it. * * @return a Lucene index reader */ public DirectoryReader getIndexReader() { try { return indexAccessor.getIndexReader(); } catch (IOException e) { throw new RuntimeException("Cannot get index reader"); } } public Directory getDirectory() { return indexAccessor.getDirectoryForTests(); } public static Sort extractSort(SearchQuery<?> searchQuery) { return (Sort) ReflectionUtil.getValue(searchQuery, "luceneSort"); } public static FailureHandler extractFailureHandler(Cache<?, ?> cache) { SearchIntegration searchIntegration = (SearchIntegration) ReflectionUtil.getValue(TestQueryHelperFactory.extractSearchMapping(cache), "integration"); BeanHolder<? extends FailureHandler> failureHandlerHolder = (BeanHolder<? extends FailureHandler>) ReflectionUtil.getValue(searchIntegration, "failureHandlerHolder"); FailureHandler failureHandler = failureHandlerHolder.get(); if (failureHandler instanceof FailSafeFailureHandlerWrapper) { return (FailureHandler) ReflectionUtil.getValue(failureHandler, "delegate"); } return failureHandler; } }
3,684
36.222222
114
java
null
infinispan-main/query/src/test/java/org/infinispan/query/helper/SearchMappingHelper.java
package org.infinispan.query.helper; import java.lang.invoke.MethodHandles; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import org.infinispan.query.concurrent.FailureCounter; import org.infinispan.search.mapper.mapping.SearchMapping; import org.infinispan.search.mapper.mapping.SearchMappingBuilder; import org.infinispan.search.mapper.mapping.impl.DefaultAnalysisConfigurer; import org.infinispan.search.mapper.model.impl.InfinispanBootstrapIntrospector; import org.infinispan.util.concurrent.BlockingManager; public class SearchMappingHelper { private static final String BACKEND_PREFIX = "hibernate.search.backend"; private SearchMappingHelper() { } public static SearchMapping createSearchMappingForTests(BlockingManager blockingManager, Class<?>... types) { Map<String, Object> properties = new LinkedHashMap<>(); properties.put(BACKEND_PREFIX + ".analysis.configurer", new DefaultAnalysisConfigurer()); properties.put("directory.type", "local-heap"); InfinispanBootstrapIntrospector introspector = SearchMappingBuilder.introspector(MethodHandles.lookup()); // do not pass any entity loader nor identifier bridges return SearchMapping.builder(introspector, null, Collections.emptyList(), blockingManager, new FailureCounter()) .setProperties(properties) .addEntityTypes(new HashSet<>(Arrays.asList(types))) .build(Optional.empty()); } }
1,576
39.435897
118
java
null
infinispan-main/query/src/test/java/org/infinispan/query/helper/TestQueryHelperFactory.java
package org.infinispan.query.helper; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertNotNull; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.factories.ComponentRegistry; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.test.CustomKey3; import org.infinispan.query.test.CustomKey3Transformer; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.search.mapper.mapping.SearchMapping; import org.infinispan.test.AbstractCacheTest; import org.infinispan.test.fwk.TestCacheManagerFactory; /** * Creates a test query helper * * @author Manik Surtani * @author Sanne Grinovero * @since 4.0 */ public class TestQueryHelperFactory { public static <E> Query<E> createCacheQuery(Class<?> entity, Cache<?, ?> cache, String fieldName, String searchString) { QueryFactory queryFactory = Search.getQueryFactory(cache); String q = String.format("FROM %s WHERE %s:'%s'", entity.getName(), fieldName, searchString); return queryFactory.create(q); } public static <T> List<T> queryAll(Cache<?, ?> cache, Class<T> entityType) { Query<T> query = Search.getQueryFactory(cache).create("FROM " + entityType.getName()); return query.execute().list(); } public static SearchMapping extractSearchMapping(Cache<?, ?> cache) { ComponentRegistry componentRegistry = cache.getAdvancedCache().getComponentRegistry(); SearchMapping searchMapping = componentRegistry.getComponent(SearchMapping.class); assertNotNull(searchMapping); return searchMapping; } public static List<EmbeddedCacheManager> createTopologyAwareCacheNodes(int numberOfNodes, CacheMode cacheMode, boolean transactional, boolean indexLocalOnly, boolean isRamDirectoryProvider, String defaultCacheName, Class<?>... indexedTypes) { return createTopologyAwareCacheNodes(numberOfNodes, cacheMode, transactional, indexLocalOnly, isRamDirectoryProvider, defaultCacheName, f -> { }, indexedTypes); } public static List<EmbeddedCacheManager> createTopologyAwareCacheNodes(int numberOfNodes, CacheMode cacheMode, boolean transactional, boolean indexLocalOnly, boolean isRamDirectoryProvider, String defaultCacheName, Consumer<ConfigurationBuilderHolder> holderConsumer, Class<?>... indexedTypes) { List<EmbeddedCacheManager> managers = new ArrayList<>(); ConfigurationBuilder builder = AbstractCacheTest.getDefaultClusteredCacheConfig(cacheMode, transactional); builder.indexing().enable().addKeyTransformer(CustomKey3.class, CustomKey3Transformer.class); builder.indexing().storage(LOCAL_HEAP); if (cacheMode.isClustered()) { builder.clustering().stateTransfer().fetchInMemoryState(true); } for (Class<?> indexedType : indexedTypes) { builder.indexing().addIndexedEntity(indexedType); } for (int i = 0; i < numberOfNodes; i++) { ConfigurationBuilderHolder holder = new ConfigurationBuilderHolder(); GlobalConfigurationBuilder globalConfigurationBuilder = holder.getGlobalConfigurationBuilder().clusteredDefault(); globalConfigurationBuilder.transport().machineId("a" + i).rackId("b" + i).siteId("test" + i).defaultCacheName(defaultCacheName); globalConfigurationBuilder.serialization().addContextInitializer(QueryTestSCI.INSTANCE); holderConsumer.accept(holder); holder.newConfigurationBuilder(defaultCacheName).read(builder.build()); EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(holder); managers.add(cm); } return managers; } }
4,396
43.867347
182
java
null
infinispan-main/query/src/test/java/org/infinispan/query/tx/TransactionIsolationTest.java
package org.infinispan.query.tx; import static org.infinispan.commons.test.Exceptions.assertException; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.fail; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; import jakarta.transaction.RollbackException; import jakarta.transaction.Transaction; import org.infinispan.Cache; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.commons.CacheException; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.query.Search; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.test.AnotherGrassEater; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestException; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.transaction.LockingMode; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.tx.TransactionIsolationTest") @CleanupAfterMethod public class TransactionIsolationTest extends MultipleCacheManagersTest { private static final Person RADIM = new Person("Radim", "So young!", 29); private static final Person TRISTAN = new Person("Tristan", "Too old.", 44); @Override public Object[] factory() { return new Object[]{ new TransactionIsolationTest().lockingMode(LockingMode.PESSIMISTIC), new TransactionIsolationTest().lockingMode(LockingMode.OPTIMISTIC), }; } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true); builder.transaction().lockingMode(lockingMode); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class) .addIndexedEntity(AnotherGrassEater.class); createClusteredCaches(2, QueryTestSCI.INSTANCE, builder); } public void testDuringTransactionPrimary() throws Exception { testDuringTransaction(getStringKeyForCache(cache(0))); } public void testDuringTransactionBackup() throws Exception { testDuringTransaction(getStringKeyForCache(cache(1))); } private void testDuringTransaction(String key) throws Exception { cache(0).put(key, RADIM); QueryFactory qf0 = Search.getQueryFactory(cache(0)); assertEquals(Collections.singletonList(RADIM), getYoungerThan(qf0, 30)); TestingUtil.withTx(tm(0), () -> { cache(0).put(key, TRISTAN); // here we could do the check but indexed query does not reflect changes in tx context Transaction suspended = tm(0).suspend(); assertEquals(Collections.singletonList(RADIM), getYoungerThan(qf0, 30)); tm(0).resume(suspended); return null; }); assertEquals(Collections.emptyList(), getYoungerThan(qf0, 30)); assertEquals(Collections.singletonList(TRISTAN), getYoungerThan(qf0, 100)); } public void testPrepareFailurePrimary() throws Exception { testPrepareFailure(getStringKeyForCache(cache(0))); } public void testPrepareFailureBackup() throws Exception { testPrepareFailure(getStringKeyForCache(cache(1))); } private void testPrepareFailure(String key) throws Exception { cache(0).put(key, RADIM); QueryFactory qf0 = Search.getQueryFactory(cache(0)); assertEquals(Collections.singletonList(RADIM), getYoungerThan(qf0, 30)); cache(0).getAdvancedCache().getAsyncInterceptorChain().addInterceptor(new FailPrepare(), 0); tm(0).begin(); cache(0).put(key, TRISTAN); try { tm(0).commit(); fail("Should rollback"); } catch (Throwable t) { if (t instanceof CacheException) { t = t.getCause(); } assertException(RollbackException.class, t); } // pessimistic mode commits in the prepare command Person expected = lockingMode == LockingMode.OPTIMISTIC ? RADIM : TRISTAN; assertEquals(expected, cache(0).get(key)); assertEquals(expected, cache(1).get(key)); // In pessimistic cache TRISTAN is in cache but it does not match the criteria // so the result should be empty List<Person> expectedResult = lockingMode == LockingMode.OPTIMISTIC ? Collections.singletonList(RADIM) : Collections.emptyList(); assertEquals(expectedResult, getYoungerThan(qf0, 30)); } @AfterMethod public void dropFailPrepare() { cache(0).getAdvancedCache().getAsyncInterceptorChain().removeInterceptor(FailPrepare.class); } private List<Object> getYoungerThan(QueryFactory queryFactory, int age) { String q = String.format("FROM %s where age:[* to %s]", Person.class.getName(), age); return queryFactory.create(q).execute().list(); } private String getStringKeyForCache(Cache cache) { LocalizedCacheTopology topology = cache.getAdvancedCache().getDistributionManager().getCacheTopology(); return IntStream.generate(ThreadLocalRandom.current()::nextInt).mapToObj(i -> "key" + i) .filter(key -> topology.getDistribution(key).isPrimary()).findAny().get(); } static class FailPrepare extends DDAsyncInterceptor { @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { return invokeNextThenApply(ctx, command, ((rCtx, rCommand, rv) -> { throw new TestException("Induced!"); })); } } }
6,057
37.833333
109
java
null
infinispan-main/query/src/test/java/org/infinispan/query/tx/NonLocalIndexingTest.java
package org.infinispan.query.tx; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.test.TestingUtil.withTx; import java.util.concurrent.Callable; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.test.AnotherGrassEater; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.Assert; import org.testng.annotations.Test; /** * Test to make sure indexLocalOnly=false behaves the same with or without * transactions enabled. * See also ISPN-2467 and subclasses. * * @author Sanne Grinovero &lt;sanne@hibernate.org&gt; (C) 2012 Red Hat Inc. */ @Test(groups = "functional", testName = "query.tx.NonLocalIndexingTest") public class NonLocalIndexingTest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, transactionsEnabled()); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class) .addIndexedEntity(AnotherGrassEater.class); createClusteredCaches(2, QueryTestSCI.INSTANCE, builder); } //Extension point to override configuration protected boolean transactionsEnabled() { return false; } public void testQueryAfterAddingNewNode() throws Exception { store("Astronaut", new Person("Astronaut", "is asking his timezone", 32), cache(0)); assertFind("timezone", 1); assertFind("asking", 1); assertFind("cat", 0); store("Webdeveloper", new Person("Webdeveloper", "is confused by the timezone concept", 32), cache(1)); assertFind("cat", 0); assertFind("timezone", 2); //We're using the name as a key so this is an update in practice of the Astronaut record: store("Astronaut", new Person("Astronaut", "thinks about his cat", 32), cache(1)); assertFind("cat", 1); assertFind("timezone", 1); store("Astronaut", new AnotherGrassEater("Astronaut", "is having a hard time to find grass"), cache(1)); //replacing same key with a new type: assertFind("cat", 0); assertFind("grass", 0); } private void assertFind(String keyword, int expectedCount) { assertFind(cache(0), keyword, expectedCount); assertFind(cache(1), keyword, expectedCount); } private static void assertFind(Cache cache, String keyword, int expectedCount) { String q = String.format("FROM %s WHERE blurb:'%s'", Person.class.getName(), keyword); Query<Object> cacheQuery = Search.getQueryFactory(cache).create(q); long resultSize = cacheQuery.execute().count().value(); Assert.assertEquals(resultSize, expectedCount); } private void store(final String key, final Object value, final Cache<Object, Object> cache) throws Exception { Callable<Void> callable = () -> { cache.put(key, value); return null; }; if (transactionsEnabled()) { withTx(cache.getAdvancedCache().getTransactionManager(), callable); } else { callable.call(); } } }
3,407
37.292135
113
java
null
infinispan-main/query/src/test/java/org/infinispan/query/tx/NonLocalTransactionalIndexingTest.java
package org.infinispan.query.tx; import org.testng.annotations.Test; /** * Test to make sure indexLocalOnly=false behaves the same with or without * transactions enabled. * See also ISPN-2467 and subclasses. * * @author Sanne Grinovero &lt;sanne@hibernate.org&gt; (C) 2012 Red Hat Inc. */ @Test(groups = "functional", testName = "query.tx.NonLocalTransactionalIndexingTest") public class NonLocalTransactionalIndexingTest extends NonLocalIndexingTest { @Override protected boolean transactionsEnabled() { return true; } }
547
25.095238
85
java
null
infinispan-main/query/src/test/java/org/infinispan/query/tx/TwoPhaseCommitIndexingTest.java
package org.infinispan.query.tx; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import java.util.concurrent.atomic.AtomicBoolean; import org.hibernate.search.util.common.SearchException; import org.infinispan.Cache; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.interceptors.impl.EntryWrappingInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.Assert; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.tx.TwoPhaseCommitIndexingTest") public class TwoPhaseCommitIndexingTest extends SingleCacheManagerTest { private final AtomicBoolean injectFailures = new AtomicBoolean(); private final BlowUpInterceptor nastyInterceptor = new BlowUpInterceptor(injectFailures); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg .customInterceptors() .addInterceptor() .after(EntryWrappingInterceptor.class) .interceptor(nastyInterceptor) .transaction() .transactionMode(TransactionMode.TRANSACTIONAL) .use1PcForAutoCommitTransactions(false) .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class) .locking().isolationLevel(IsolationLevel.READ_COMMITTED); return TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE, cfg); } public void testQueryAfterAddingNewNode() throws Exception { //We'll fail the first operation by having an exception thrown after prepare //but before the commit: store("Astronaut", new Person("Astronaut", "is asking his timezone", 32), true); //Nothing should be applied to the indexes: assertFind("timezone", 0); assertFind("asking", 0); assertFind("cat", 0); store("Astronaut", new Person("Astronaut", "is asking his timezone", 32), false); assertFind("timezone", 1); assertFind("asking", 1); assertFind("cat", 0); } private void assertFind(String keyword, int expectedCount) { assertFind(cache, keyword, expectedCount); } private static void assertFind(Cache cache, String keyword, int expectedCount) { QueryFactory queryFactory = Search.getQueryFactory(cache); String q = String.format("FROM %s WHERE blurb:'%s'", Person.class.getName(), keyword); Query<?> cacheQuery = queryFactory.create(q); int resultSize = cacheQuery.execute().count().value(); Assert.assertEquals(resultSize, expectedCount); } private void store(final String key, final Object value, boolean failTheOperation) { if (failTheOperation) { injectFailures.set(true); try { cache.put(key, value); Assert.fail("Should have failed the implicit transaction"); } catch (Exception e) { //Expected } finally { injectFailures.set(false); } } else { cache.put(key, value); } } static class BlowUpInterceptor extends DDAsyncInterceptor { private final AtomicBoolean injectFailures; public BlowUpInterceptor(AtomicBoolean injectFailures) { this.injectFailures = injectFailures; } @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { if (injectFailures.get()) { throw new SearchException("Test"); } else { return super.visitPrepareCommand(ctx, command); } } } }
4,271
36.473684
107
java
null
infinispan-main/query/src/test/java/org/infinispan/query/tx/TransactionalQueryTest.java
package org.infinispan.query.tx; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.query.helper.TestQueryHelperFactory.createCacheQuery; import static org.infinispan.test.TestingUtil.withTx; import java.util.concurrent.Callable; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Text; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.tx.TransactionalQueryTest") public class TransactionalQueryTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Session.class); return TestCacheManagerFactory.createCacheManager(new SCIImpl(), cfg); } @BeforeMethod public void initialize() throws Exception { // Initialize the cache withTx(tm(), (Callable<Void>) () -> { for (int i = 0; i < 100; i++) { cache.put(String.valueOf(i), new Session(String.valueOf(i))); } return null; }); } public void run() throws Exception { // Verify querying works createCacheQuery(Session.class, cache, "Id", "2"); // Remove something that exists withTx(tm(), (Callable<Void>) () -> { cache.remove("50"); return null; }); // Remove something that doesn't exist with a transaction // This also fails without using a transaction withTx(tm(), (Callable<Void>) () -> { cache.remove("200"); return null; }); } @Indexed(index = "SessionIndex") public static class Session { private String m_id; @ProtoFactory Session(String id) { m_id = id; } @Text(name = "Id") @ProtoField(number = 1) public String getId() { return m_id; } } @AutoProtoSchemaBuilder( includeClasses = Session.class, schemaFileName = "test.query.tx.TransactionalQueryTest.proto", schemaFilePath = "proto/generated", schemaPackageName = "org.infinispan.test.TransactionalQueryTest", service = false ) interface SCI extends SerializationContextInitializer { } }
2,927
31.175824
82
java
null
infinispan-main/query/src/test/java/org/infinispan/query/maxresult/CustomDefaultMaxResultTest.java
package org.infinispan.query.maxresult; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.Cache; import org.infinispan.commons.test.annotation.TestForIssue; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.query.model.Game; import org.infinispan.query.model.NonIndexedGame; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.maxresult.CustomDefaultMaxResultTest") @TestForIssue(jiraKey = "ISPN-14194") public class CustomDefaultMaxResultTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder indexed = new ConfigurationBuilder(); indexed .query() .defaultMaxResults(50) .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity("org.infinispan.query.model.Game"); ConfigurationBuilder notIndexed = new ConfigurationBuilder(); notIndexed .query() .defaultMaxResults(50); EmbeddedCacheManager manager = TestCacheManagerFactory.createCacheManager(); manager.defineConfiguration("indexed-games", indexed.build()); manager.defineConfiguration("not-indexed-games", notIndexed.build()); return manager; } @Test public void testNonIndexed() { Cache<Integer, NonIndexedGame> games = cacheManager.getCache("not-indexed-games"); // verify that the cache configuration is correctly acquired assertThat(games.getCacheConfiguration().query().defaultMaxResults()).isEqualTo(50); for (int i = 1; i <= 110; i++) { games.put(i, new NonIndexedGame("Game " + i, "This is the game " + i + "# of a series")); } QueryFactory factory = Search.getQueryFactory(games); Query<NonIndexedGame> query = factory.create("from org.infinispan.query.model.NonIndexedGame"); QueryResult<NonIndexedGame> result = query.execute(); assertThat(result.count().value()).isEqualTo(110); assertThat(result.list()).hasSize(50); // use custom default query = factory.create("from org.infinispan.query.model.NonIndexedGame"); query.maxResults(200); // raise it result = query.execute(); assertThat(result.count().value()).isEqualTo(110); assertThat(result.list()).hasSize(110); } @Test public void testIndexed() { Cache<Integer, Game> games = cacheManager.getCache("indexed-games"); // verify that the cache configuration is correctly acquired assertThat(games.getCacheConfiguration().query().defaultMaxResults()).isEqualTo(50); for (int i = 1; i <= 110; i++) { games.put(i, new Game("Game " + i, "This is the game " + i + "# of a series")); } QueryFactory factory = Search.getQueryFactory(games); Query<Game> query = factory.create("from org.infinispan.query.model.Game"); QueryResult<Game> result = query.execute(); assertThat(result.count().value()).isEqualTo(110); assertThat(result.list()).hasSize(50); // use custom default query = factory.create("from org.infinispan.query.model.Game"); query.maxResults(200); // raise it result = query.execute(); assertThat(result.count().value()).isEqualTo(110); assertThat(result.list()).hasSize(110); } }
3,790
37.683673
101
java
null
infinispan-main/query/src/test/java/org/infinispan/query/maxresult/EmbeddedDefaultMaxResultTest.java
package org.infinispan.query.maxresult; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.Cache; import org.infinispan.commons.test.annotation.TestForIssue; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.query.model.Game; import org.infinispan.query.model.NonIndexedGame; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.maxresult.EmbeddedDefaultMaxResultTest") @TestForIssue(jiraKey = "ISPN-14194") public class EmbeddedDefaultMaxResultTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder indexed = new ConfigurationBuilder(); indexed.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("org.infinispan.query.model.Game"); ConfigurationBuilder notIndexed = new ConfigurationBuilder(); EmbeddedCacheManager manager = TestCacheManagerFactory.createCacheManager(); manager.defineConfiguration("indexed-games", indexed.build()); manager.defineConfiguration("not-indexed-games", notIndexed.build()); return manager; } @Test public void testNonIndexed() { Cache<Integer, NonIndexedGame> games = cacheManager.getCache("not-indexed-games"); for (int i = 1; i <= 110; i++) { games.put(i, new NonIndexedGame("Game " + i, "This is the game " + i + "# of a series")); } QueryFactory factory = Search.getQueryFactory(games); Query<NonIndexedGame> query = factory.create("from org.infinispan.query.model.NonIndexedGame"); QueryResult<NonIndexedGame> result = query.execute(); assertThat(result.count().value()).isEqualTo(110); assertThat(result.list()).hasSize(100); // use the default query = factory.create("from org.infinispan.query.model.NonIndexedGame"); query.maxResults(200); // raise it result = query.execute(); assertThat(result.count().value()).isEqualTo(110); assertThat(result.list()).hasSize(110); } @Test public void testIndexed() { Cache<Integer, Game> games = cacheManager.getCache("indexed-games"); for (int i = 1; i <= 110; i++) { games.put(i, new Game("Game " + i, "This is the game " + i + "# of a series")); } QueryFactory factory = Search.getQueryFactory(games); Query<Game> query = factory.create("from org.infinispan.query.model.Game"); QueryResult<Game> result = query.execute(); assertThat(result.count().value()).isEqualTo(110); assertThat(result.list()).hasSize(100); // use the default query = factory.create("from org.infinispan.query.model.Game"); query.maxResults(200); // raise it result = query.execute(); assertThat(result.count().value()).isEqualTo(110); assertThat(result.list()).hasSize(110); } }
3,304
37.882353
101
java
null
infinispan-main/query/src/test/java/org/infinispan/query/maxresult/DistributedHitCountAccuracyTest.java
package org.infinispan.query.maxresult; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.Cache; import org.infinispan.commons.test.annotation.TestForIssue; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.query.model.Game; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.maxresult.DistributedHitCountAccuracyTest") @TestForIssue(jiraKey = "ISPN-15036") public class DistributedHitCountAccuracyTest extends MultipleCacheManagersTest { private static final String QUERY_TEXT = "from org.infinispan.query.model.Game where description : 'game'"; private Cache<Integer, Game> node1; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder config = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); config .clustering().hash().numOwners(2) .indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("org.infinispan.query.model.Game") .query().hitCountAccuracy(10); // lower the default accuracy; createClusteredCaches(2, config); node1 = cache(0); cache(1); } @Test public void smokeTest() { executeSmokeTest(node1); } static void executeSmokeTest(Cache<Integer, Game> cache) { for (int i = 1; i <= 5000; i++) { cache.put(i, new Game("Game " + i, "This is the game " + i + "# of a series")); } QueryFactory factory = Search.getQueryFactory(cache); Query<Game> query = factory.create(QUERY_TEXT); QueryResult<Game> result = query.execute(); assertThat(result.list()).hasSize(100); // the hit count accuracy does not allow to compute the hit count assertThat(result.hitCount()).isNotPresent(); // the hit count accuracy does not allow to compute **an exact** hit count assertThat(result.count().isExact()).isFalse(); query = factory.create(QUERY_TEXT); // raise the default accuracy query.hitCountAccuracy(5_000); result = query.execute(); assertThat(result.list()).hasSize(100); assertThat(result.hitCount()).hasValue(5_000); assertThat(result.count().isExact()).isTrue(); assertThat(result.count().value()).isEqualTo(5_000); // the distributed iterator is supposed to work normally query = factory.create(QUERY_TEXT); try (CloseableIterator<Game> iterator = query.iterator()) { assertThat(iterator).toIterable().hasSize(100); } query = factory.create(QUERY_TEXT); // raise the default accuracy query.hitCountAccuracy(5_000); try (CloseableIterator<Game> iterator = query.iterator()) { assertThat(iterator).toIterable().hasSize(100); } } }
3,214
36.823529
110
java
null
infinispan-main/query/src/test/java/org/infinispan/query/maxresult/LocalHitCountAccuracyTest.java
package org.infinispan.query.maxresult; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.commons.test.annotation.TestForIssue; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.maxresult.LocalHitCountAccuracyTest") @TestForIssue(jiraKey = "ISPN-14195") public class LocalHitCountAccuracyTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder indexed = new ConfigurationBuilder(); indexed.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("org.infinispan.query.model.Game"); indexed.query().hitCountAccuracy(10); // lower the default accuracy EmbeddedCacheManager manager = TestCacheManagerFactory.createCacheManager(); manager.defineConfiguration("indexed-games", indexed.build()); return manager; } @Test public void smokeTest() { DistributedHitCountAccuracyTest.executeSmokeTest(cacheManager.getCache("indexed-games")); } }
1,313
37.647059
95
java
null
infinispan-main/query/src/test/java/org/infinispan/query/partitionhandling/NonSharedIndexTest.java
package org.infinispan.query.partitionhandling; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.test.Person; import org.testng.annotations.Test; /** * @since 9.3 */ @Test(groups = "functional", testName = "query.partitionhandling.NonSharedIndexTest") public class NonSharedIndexTest extends SharedIndexTest { @Override protected ConfigurationBuilder cacheConfiguration() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); return configurationBuilder; } @Override protected void amendCacheManagerBeforeStart(EmbeddedCacheManager cm) { } }
906
29.233333
85
java
null
infinispan-main/query/src/test/java/org/infinispan/query/partitionhandling/NonIndexedQuery.java
package org.infinispan.query.partitionhandling; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.test.Person; import org.testng.annotations.Test; /** * @since 9.3 */ @Test(groups = "functional", testName = "query.partitionhandling.NonIndexedQuery") public class NonIndexedQuery extends SharedIndexTest { @Override protected ConfigurationBuilder cacheConfiguration() { return new ConfigurationBuilder(); } @Override protected String getQuery() { return "from " + Person.class.getName() + " p where p.nonIndexedField = 'Pe'"; } @Override protected void amendCacheManagerBeforeStart(EmbeddedCacheManager cm) { } }
752
25.892857
84
java
null
infinispan-main/query/src/test/java/org/infinispan/query/partitionhandling/HybridQueryTest.java
package org.infinispan.query.partitionhandling; import org.infinispan.query.test.Person; import org.testng.annotations.Test; /** * @since 9.3 */ @Test(groups = "functional", testName = "query.partitionhandling.HybridQueryTest") public class HybridQueryTest extends SharedIndexTest { @Override protected String getQuery() { return "from " + Person.class.getName() + " p where p.age >= 0 and p.nonIndexedField = 'Pe'"; } }
441
25
99
java
null
infinispan-main/query/src/test/java/org/infinispan/query/partitionhandling/NonSharedIndexWithLocalCachesTest.java
package org.infinispan.query.partitionhandling; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.test.Person; import org.testng.annotations.Test; /** * @since 9.3 */ @Test(groups = "functional", testName = "query.partitionhandling.NonSharedIndexWithLocalCachesTest") public class NonSharedIndexWithLocalCachesTest extends NonSharedIndexTest { @Override protected ConfigurationBuilder cacheConfiguration() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); return configurationBuilder; } }
795
29.615385
100
java
null
infinispan-main/query/src/test/java/org/infinispan/query/partitionhandling/SharedIndexTest.java
package org.infinispan.query.partitionhandling; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.stream.IntStream; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.partitionhandling.AvailabilityException; import org.infinispan.partitionhandling.BasePartitionHandlingTest; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.testng.annotations.Test; /** * @since 9.3 */ @Test(groups = "functional", testName = "query.partitionhandling.SharedIndexTest") public class SharedIndexTest extends BasePartitionHandlingTest { protected int totalEntries = 100; public SharedIndexTest() { numMembersInCluster = 3; cacheMode = CacheMode.DIST_SYNC; cleanup = CleanupPhase.AFTER_TEST; } @Override protected ConfigurationBuilder cacheConfiguration() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); return configurationBuilder; } @Override protected SerializationContextInitializer serializationContextInitializer() { return QueryTestSCI.INSTANCE; } @Test(expectedExceptions = AvailabilityException.class) public void shouldThrowExceptionInDegradedMode() { Cache<Integer, Person> cache = cache(0); IntStream.range(0, totalEntries).forEach(i -> cache.put(i, new Person("Person " + i, "", i))); executeQueries(); splitCluster(new int[]{0}, new int[]{1, 2}); partition(0).assertDegradedMode(); executeQueries(); } protected void assertAllNodesQueryResults(int results) { assertEquals(results, totalEntries); } protected void assertSingleNodeQueryResults(int results) { assertTrue(results > 0); } private void executeQueries() { String q = getQuery(); caches().forEach(c -> { Query allNodesQuery = Search.getQueryFactory(c).create(q); assertAllNodesQueryResults(allNodesQuery.getResultSize()); }); Query singleNodeQuery = Search.getQueryFactory(cache(0)).create(q); assertSingleNodeQueryResults(singleNodeQuery.list().size()); } protected String getQuery() { return "from " + Person.class.getName() + " p where p.name:'person*'"; } }
2,735
30.813953
100
java
null
infinispan-main/query/src/test/java/org/infinispan/query/impl/QueryCacheEmbeddedTest.java
package org.infinispan.query.impl; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import java.util.Set; import java.util.stream.Collectors; import org.assertj.core.util.Sets; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.query.Search; import org.infinispan.query.core.impl.QueryCache; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.embedded.impl.SearchQueryParsingResult; import org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.Test; /** * @author anistor@redhat.com * @since 7.0 */ @Test(groups = "functional", testName = "query.impl.QueryCacheEmbeddedTest") @CleanupAfterMethod public class QueryCacheEmbeddedTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg.transaction() .transactionMode(TransactionMode.TRANSACTIONAL) .indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(UserHS.class); return TestCacheManagerFactory.createCacheManager(cfg); } public void testQueryCache() { // populate our data cache UserHS user = new UserHS(); user.setId(1); user.setName("John"); cache.put("user_" + user.getId(), user); // obtain the query cache component QueryCache queryCache = ComponentRegistryUtils.getQueryCache(cache); // force creation of the lazy internal cache and ensure it is empty queryCache.get("someCacheName", "someQueryString", null, "typeDiscriminator", (queryString, acc) -> queryString); // ensure internal cache is empty queryCache.clear(); // obtain a reference to the internal query cache via reflection Cache<?, ?> internalCache = TestingUtil.extractField(QueryCache.class, queryCache, "lazyCache"); String queryString = "from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS u where u.name = 'John'"; // everything is ready to go // ensure the QueryCreator gets invoked int[] invoked = {0}; IckleParsingResult<?> created = queryCache.get(cache.getName(), queryString, null, IckleParsingResult.class, (qs, acc) -> { invoked[0]++; return null; }); assertEquals(1, invoked[0]); assertNull(created); // test that the query cache does not have it already assertEquals(0, internalCache.size()); // create and execute a query Query<?> query = Search.getQueryFactory(cache).create(queryString); query.execute().list(); // ensure the query cache has it now: one FilterParsingResult and one SearchQueryParsingResult assertEquals(2, internalCache.size()); Set<Class<?>> cacheValueClasses = internalCache.values().stream().map(Object::getClass).collect(Collectors.toSet()); Set<Class<?>> expectedCachedValueClasses = Sets.newLinkedHashSet(IckleParsingResult.class, SearchQueryParsingResult.class); assertEquals(expectedCachedValueClasses, cacheValueClasses); // ensure the QueryCreator does not get invoked now IckleParsingResult<?> cached = queryCache.get(cache.getName(), queryString, null, IckleParsingResult.class, (qs, acc) -> { throw new AssertionError("QueryCreator should not be invoked now"); }); assertNotNull(cached); } }
4,006
39.07
129
java
null
infinispan-main/query/src/test/java/org/infinispan/query/reindex/LocalIndexerRemoveTest.java
package org.infinispan.query.reindex; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.util.concurrent.CompletionStages.join; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.infinispan.Cache; import org.infinispan.commons.test.annotation.TestForIssue; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.IndexStorage; import org.infinispan.configuration.cache.IndexingMode; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Indexer; import org.infinispan.query.Search; import org.infinispan.query.core.stats.IndexInfo; import org.infinispan.query.core.stats.SearchStatistics; import org.infinispan.query.model.TypeA; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.reindex.LocalIndexerRemoveTest") @TestForIssue(jiraKey = "ISPN-14189") public class LocalIndexerRemoveTest extends SingleCacheManagerTest { private static final String CACHE_NAME = "types"; private static final int ENTRIES = 5_000; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder config = new ConfigurationBuilder(); config .indexing() .enable() .indexingMode(IndexingMode.MANUAL) .storage(IndexStorage.LOCAL_HEAP) .addIndexedEntity(TypeA.class); EmbeddedCacheManager result = TestCacheManagerFactory.createCacheManager(); result.defineConfiguration(CACHE_NAME, config.build()); return result; } @Test public void test() throws Exception { Cache<Integer, TypeA> typesCache = cacheManager.getCache(CACHE_NAME); Indexer indexer = Search.getIndexer(typesCache); SearchStatistics searchStatistics = Search.getSearchStatistics(typesCache); Map<Integer, TypeA> values = IntStream.range(0, ENTRIES).boxed() .collect(Collectors.toMap(Function.identity(), i -> new TypeA("value " + i))); typesCache.putAll(values); // the indexing mode is manual, thus the index is empty IndexInfo indexInfo = indexInfo(searchStatistics); assertThat(indexInfo.count()).isZero(); // the indexer fills the index join(indexer.runLocal()); indexInfo = indexInfo(searchStatistics); assertThat(indexInfo.count()).isEqualTo(ENTRIES); // removing the index data join(indexer.remove()); Thread.sleep(500); indexInfo = indexInfo(searchStatistics); assertThat(indexInfo.count()).isZero(); long firstCallSize = indexInfo.size(); indexInfo = indexInfo(searchStatistics); assertThat(indexInfo.count()).isZero(); long secondCallSize = indexInfo.size(); // it seems that the first call to the state after the purge is always wrong and the second call is always correct, // no matter how much time we wait after the purge assertThat(firstCallSize - secondCallSize).isLessThanOrEqualTo(1000); } private IndexInfo indexInfo(SearchStatistics searchStatistics) { Map<String, IndexInfo> indexInfos = join(searchStatistics.getIndexStatistics().computeIndexInfos()); String key = TypeA.class.getName(); assertThat(indexInfos).containsKey(key); IndexInfo indexInfo = indexInfos.get(key); return indexInfo; } }
3,559
36.473684
121
java
null
infinispan-main/query/src/test/java/org/infinispan/query/performance/TuningOptionsAppliedTest.java
package org.infinispan.query.performance; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.helper.IndexAccessor; import org.infinispan.query.test.Person; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.Assert; import org.testng.annotations.Test; /** * Verifies the options used for performance tuning are actually being applied to the Search engine * * @author Sanne Grinovero * @since 5.3 */ @Test(groups = "functional", testName = "query.performance.TuningOptionsAppliedTest") public class TuningOptionsAppliedTest extends AbstractInfinispanTest { public void verifyFSDirectoryOptions() throws IOException { EmbeddedCacheManager embeddedCacheManager = TestCacheManagerFactory.fromXml("nrt-performance-writer.xml"); try { IndexAccessor indexAccessor = IndexAccessor.of(embeddedCacheManager.getCache("Indexed"), Person.class); verifyShardingOptions(indexAccessor, 6); verifyUsesFSDirectory(indexAccessor); } finally { TestingUtil.killCacheManagers(embeddedCacheManager); } } private void verifyShardingOptions(IndexAccessor accessorForTests, int expectedShards) { assertThat(accessorForTests.getShardsForTests()).hasSize(expectedShards); } private void verifyUsesFSDirectory(IndexAccessor accessorForTests) { Directory directory = accessorForTests.getDirectory(); Assert.assertTrue(directory instanceof FSDirectory); } }
1,749
36.234043
112
java
null
infinispan-main/query/src/test/java/org/infinispan/query/performance/LoopingWriterTest.java
package org.infinispan.query.performance; import java.io.IOException; import java.text.NumberFormat; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.commons.util.Util; import org.infinispan.context.Flag; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.test.Person; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.Assert; import org.testng.annotations.Test; /** * Starts writing a lot of data in a loop. Used to measure ingestion rate. * * -server -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:+UseParNewGC -Xss500k -Xmx12G -Xms12G -Dlog4j.configurationFile=log4j2.xml * * @author Sanne Grinovero * @since 5.3 */ @Test(groups = "profiling", testName = "query.performance.LoopingWriterTest") public class LoopingWriterTest extends AbstractInfinispanTest { private static final int TOTAL_LOOPS = Integer.MAX_VALUE; private static final int TIMESAMPLE_PERIODICITY = 6000; private static final int QUERY_PERIODICITY = 15170; public void neverEndingWrite() throws IOException { EmbeddedCacheManager embeddedCacheManager = TestCacheManagerFactory.fromXml("nrt-performance-writer-infinispandirectory.xml"); try { Cache<Object, Object> cache = embeddedCacheManager.getCache("Indexed"); cache = cache.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES); writeStuff(cache); } finally { embeddedCacheManager.stop(); } } /** * We write a lot of elements.. and run a Query occasionally to check. */ private void writeStuff(final Cache<Object, Object> cache) { final long startTime = System.nanoTime(); for (int i = 1; i < TOTAL_LOOPS; i++) { final String key = "K" + i; final Person value = new Person(key, key, i); cache.put(key, value); if (i % QUERY_PERIODICITY == 0) { countElementsViaQuery(cache, i); } if (i % TIMESAMPLE_PERIODICITY == 0) { final long currentTimeStamp = System.nanoTime(); final long elapsed = currentTimeStamp - startTime; final double elementsWrittenPerSecond = ((double) TimeUnit.NANOSECONDS.convert(i, TimeUnit.SECONDS)) / elapsed; NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(2); nf.setGroupingUsed(true); System.out.println( "Transactions committed to index per second: " + nf.format(elementsWrittenPerSecond) + ". Total documents: " + i + " Total time: " + Util.prettyPrintTime(elapsed, TimeUnit.NANOSECONDS) ); } } } private void countElementsViaQuery(Cache<Object, Object> cache, int expectedElements) { QueryFactory queryFactory = Search.getQueryFactory(cache); long resultSize = queryFactory.create("FROM " + Person.class.getName()).execute().count().value(); Assert.assertEquals(resultSize, expectedElements); System.out.println("Query OK! found (as expected) " + resultSize + " elements"); } @Test(enabled = false) // Disable explicitly to avoid TestNG thinking this is a test!! public static void main(String[] args) throws IOException { LoopingWriterTest runner = new LoopingWriterTest(); runner.neverEndingWrite(); } }
3,535
39.643678
137
java
null
infinispan-main/query/src/test/java/org/infinispan/query/persistence/InconsistentIndexesAfterRestartTest.java
package org.infinispan.query.persistence; import static org.infinispan.configuration.cache.IndexStorage.FILESYSTEM; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.testng.Assert.assertEquals; import java.io.File; import java.nio.file.Paths; import java.util.List; import org.infinispan.Cache; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Text; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests persistent index state us in synch with the values stored in a CacheLoader after a CacheManager is restarted. * * @author Jan Slezak * @author Sanne Grinovero * @since 5.2 */ @Test(groups = "functional", testName = "query.persistence.InconsistentIndexesAfterRestartTest") public class InconsistentIndexesAfterRestartTest extends AbstractInfinispanTest { private static String TMP_DIR; @Test public void testPutSearchablePersistentWithoutBatchingWithoutTran() throws Exception { testPutTwice(false, false); } @Test public void testPutSearchablePersistentWithBatchingWithoutTran() throws Exception { testPutTwice(true, false); } @Test public void testPutSearchablePersistentWithBatchingInTran() throws Exception { testPutTwice(true, true); } private void testPutTwice(boolean batching, boolean inTran) throws Exception { testPutOperation(batching, inTran); testPutOperation(batching, inTran); } private void testPutOperation(boolean batching, final boolean inTran) { withCacheManager(new CacheManagerCallable(getCacheManager(batching)) { @Override public void call() throws Exception { Cache<Object, Object> c = cm.getCache(); if (inTran) c.getAdvancedCache().getTransactionManager().begin(); c.put("key1", new SEntity(1, "name1", "surname1")); if (inTran) c.getAdvancedCache().getTransactionManager().commit(); assertEquals(searchByName("name1", c).size(), 1, "should be 1, even repeating this"); } }); } private EmbeddedCacheManager getCacheManager(boolean batchingEnabled) { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault(); globalBuilder.globalState().enable().persistentLocation(TMP_DIR); globalBuilder.serialization().addContextInitializer(SCI.INSTANCE); ConfigurationBuilder builder = new ConfigurationBuilder(); builder .persistence() .addSingleFileStore() .fetchPersistentState(true) .indexing() .enable() .storage(FILESYSTEM).path(Paths.get(TMP_DIR, "idx").toString()) .addIndexedEntity(SEntity.class) .invocationBatching() .enable(batchingEnabled); return TestCacheManagerFactory.createCacheManager(globalBuilder, builder); } private List searchByName(String name, Cache c) { QueryFactory queryFactory = Search.getQueryFactory(c); Query<?> q = queryFactory.create(SEntity.searchByName(name)); int resultSize = q.execute().count().value(); List<?> l = q.list(); assert l.size() == resultSize; return q.list(); } @Indexed public static class SEntity { public static final String IDX_NAME = "name"; private final long id; private final String name; private final String surname; @ProtoFactory SEntity(long id, String name, String surname) { this.id = id; this.name = name; this.surname = surname; } @ProtoField(number = 1, defaultValue = "0") public long getId() { return id; } @Text @ProtoField(number = 2) public String getName() { return name; } @Basic(projectable = true) @ProtoField(number = 3) public String getSurname() { return surname; } @Override public String toString() { return "SEntity{" + "id=" + id + ", name='" + name + '\'' + ", surname='" + surname + '\'' + '}'; } public static String searchByName(String name) { return String.format("FROM %s WHERE %s:'%s'", SEntity.class.getName(), IDX_NAME, name.toLowerCase()); } } @BeforeClass protected void setUpTempDir() { TMP_DIR = CommonsTestingUtil.tmpDirectory(this.getClass()); new File(TMP_DIR).mkdirs(); } @AfterClass protected void clearTempDir() { Util.recursiveFileRemove(TMP_DIR); } @AutoProtoSchemaBuilder( includeClasses = SEntity.class, schemaFileName = "test.query.persistence.InconsistentIndexesAfterRestartTest.proto", schemaFilePath = "proto/generated", schemaPackageName = "org.infinispan.test.InconsistentIndexesAfterRestartTest", service = false ) interface SCI extends SerializationContextInitializer { SCI INSTANCE = new SCIImpl(); } }
5,988
32.458101
118
java
null
infinispan-main/query/src/test/java/org/infinispan/query/persistence/EntryActivatingTest.java
package org.infinispan.query.persistence; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.manager.CacheContainer; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.persistence.support.WaitNonBlockingStore; import org.infinispan.query.Search; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.indexedembedded.City; import org.infinispan.query.indexedembedded.Country; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.search.mapper.mapping.SearchMapping; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * @author Sanne Grinovero &lt;sanne@infinispan.org&gt; (C) 2011 Red Hat Inc. */ @Test(groups = "functional", testName = "query.persistence.EntryActivatingTest") public class EntryActivatingTest extends AbstractInfinispanTest { Cache<String, Country> cache; WaitNonBlockingStore store; CacheContainer cm; QueryFactory queryFactory; SearchMapping searchMapping; @BeforeClass public void setUp() { recreateCacheManager(); } @AfterClass public void tearDown() { TestingUtil.killCacheManagers(cm); } public void testPersistence() throws PersistenceException { verifyFullTextHasMatches(0); Country italy = new Country(); italy.countryName = "Italy"; City rome = new City(); rome.name = "Rome"; italy.cities.add(rome); cache.put("IT", italy); assert !store.contains("IT"); verifyFullTextHasMatches(1); cache.evict("IT"); assert store.contains("IT"); InternalCacheEntry internalCacheEntry = cache.getAdvancedCache().getDataContainer().get("IT"); assert internalCacheEntry == null; verifyFullTextHasMatches(1); Country country = cache.get("IT"); assert country != null; assert "Italy".equals(country.countryName); verifyFullTextHasMatches(1); cache.stop(); assert searchMapping.isClose(); TestingUtil.killCacheManagers(cm); // Now let's check the entry is not re-indexed during data preloading: recreateCacheManager(); // People should generally use a persistent index; we use RAMDirectory for // test cleanup, so for our configuration it needs now to contain zero // matches: on filesystem it would be exactly one as expected (two when ISPN-1179 was open) verifyFullTextHasMatches(0); } private void recreateCacheManager() { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg.persistence() .passivation(true) .addStore(DummyInMemoryStoreConfigurationBuilder.class) .preload(true) .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Country.class) ; cm = TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE, cfg); cache = cm.getCache(); store = TestingUtil.getFirstStore(cache); queryFactory = Search.getQueryFactory(cache); searchMapping = TestingUtil.extractComponent(cache, SearchMapping.class); } private void verifyFullTextHasMatches(int i) { String query = String.format("FROM %s WHERE countryName:'Italy'", Country.class.getName()); List<Object> list = queryFactory.create(query).list(); assertEquals(i, list.size()); } }
3,905
32.672414
100
java
null
infinispan-main/query/src/test/java/org/infinispan/query/persistence/SharedCacheLoaderQueryDistributedIndexTest.java
package org.infinispan.query.persistence; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author anistor@redhat.com * @since 5.2 */ @Test(groups = "functional", testName = "query.persistence.SharedCacheLoaderQueryDistributedIndexTest") public class SharedCacheLoaderQueryDistributedIndexTest extends SharedCacheLoaderQueryIndexTest { @Override protected void configureCache(ConfigurationBuilder builder) { super.configureCache(builder); builder.indexing().enable().storage(LOCAL_HEAP); } }
652
28.681818
103
java
null
infinispan-main/query/src/test/java/org/infinispan/query/persistence/SharedCacheLoaderQueryIndexTest.java
package org.infinispan.query.persistence; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.List; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.query.statetransfer.BaseReIndexingTest; import org.infinispan.query.test.Person; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; /** * Tests behaviour of indexing and querying when a cache is clustered and * and it's configured with a shared cache store. If preload is enabled, * it should be possible to index the preloaded contents. * * @author Galder Zamarreño * @since 5.2 */ @Test(groups = "functional", testName = "query.persistence.SharedCacheLoaderQueryIndexTest") public class SharedCacheLoaderQueryIndexTest extends BaseReIndexingTest { @Override protected void configureCache(ConfigurationBuilder builder) { // To force a shared cache store, make sure storeName property // for dummy store is the same for all nodes builder.clustering().stateTransfer().fetchInMemoryState(false) .persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class).shared(true).preload(true). storeName(getClass().getName()); } public void testPreloadIndexingAfterAddingNewNode() { loadCacheEntries(this.<String, Person>caches().get(0)); List<DummyInMemoryStore> cacheStores = TestingUtil.cachestores(caches()); for (DummyInMemoryStore dimcs: cacheStores) { assertTrue("Cache misconfigured, maybe cache store not pointing to same place, maybe passivation on...etc", dimcs.contains(persons[0].getName())); int clear = dimcs.stats().get("clear"); assertEquals("Cache store should not be cleared, purgeOnStartup is false", clear, 0); int write = dimcs.stats().get("write"); assertEquals("Cache store should have been written to 4 times, but was written to " + write + " times", write, 4); } // Before adding a node, verify that the query resolves properly executeSimpleQuery(this.<String, Person>caches().get(0)); addNodeCheckingContentsAndQuery(); } }
2,323
40.5
155
java
null
infinispan-main/query/src/test/java/org/infinispan/query/model/NonIndexedGame.java
package org.infinispan.query.model; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; public class NonIndexedGame { private String name; private String description; @ProtoFactory public NonIndexedGame(String name, String description) { this.name = name; this.description = description; } @ProtoField(1) public String getName() { return name; } @ProtoField(2) public String getDescription() { return description; } @Override public String toString() { return "Game{" + "name='" + name + '\'' + ", description='" + description + '\'' + '}'; } }
727
19.222222
59
java
null
infinispan-main/query/src/test/java/org/infinispan/query/model/TypeA.java
package org.infinispan.query.model; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; @Indexed(index = "index-A") public class TypeA { private String value; @ProtoFactory public TypeA(String value) { this.value = value; } @Basic @ProtoField(value = 1) public String getValue() { return value; } }
516
20.541667
59
java
null
infinispan-main/query/src/test/java/org/infinispan/query/model/TypeB.java
package org.infinispan.query.model; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; @Indexed(index = "index-B") public class TypeB { private String value; @ProtoFactory public TypeB(String value) { this.value = value; } @Basic @ProtoField(value = 1) public String getValue() { return value; } }
516
20.541667
59
java
null
infinispan-main/query/src/test/java/org/infinispan/query/model/TypeC.java
package org.infinispan.query.model; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; @Indexed(index = "index-C") public class TypeC { private String value; @ProtoFactory public TypeC(String value) { this.value = value; } @Basic @ProtoField(value = 1) public String getValue() { return value; } }
516
20.541667
59
java
null
infinispan-main/query/src/test/java/org/infinispan/query/model/Book.java
package org.infinispan.query.model; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Text; @Indexed public class Book { @Basic(sortable = true, name = "label") private String title; @Text(analyzer = "whitespace", name = "naming") private String description; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
676
20.15625
55
java
null
infinispan-main/query/src/test/java/org/infinispan/query/model/Game.java
package org.infinispan.query.model; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Keyword; import org.infinispan.api.annotations.indexing.Text; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; @Indexed(index = "play") public class Game { private String name; private String description; @ProtoFactory public Game(String name, String description) { this.name = name; this.description = description; } @Keyword(projectable = true) @ProtoField(1) public String getName() { return name; } @Text @ProtoField(2) public String getDescription() { return description; } @Override public String toString() { return "Game{" + "name='" + name + '\'' + ", description='" + description + '\'' + '}'; } @AutoProtoSchemaBuilder(includeClasses = {Game.class, NonIndexedGame.class}) public interface GameSchema extends GeneratedSchema { GameSchema INSTANCE = new GameSchemaImpl(); } }
1,252
24.571429
79
java
null
infinispan-main/query/src/test/java/org/infinispan/query/model/Color.java
package org.infinispan.query.model; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Keyword; import org.infinispan.api.annotations.indexing.Text; @Indexed public class Color { @Basic private final String name; @Basic(name = "desc1") @Keyword(name = "desc2") @Text(name = "desc3") private final String description; public Color(String name, String description) { this.name = name; this.description = description; } public String getName() { return name; } public String getDescription() { return description; } }
688
20.53125
55
java
null
infinispan-main/query/src/test/java/org/infinispan/query/model/Developer.java
package org.infinispan.query.model; import java.io.Serializable; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Keyword; import org.infinispan.api.annotations.indexing.Text; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; @Indexed public class Developer implements Serializable { private String nick; private String email; private String biography; private Integer contributions = 0; @ProtoFactory public Developer(String nick, String email, String biography, Integer contributions) { this.nick = nick; this.email = email; this.biography = biography; this.contributions = contributions; } @Keyword(projectable = true) @ProtoField(number = 1) public String getNick() { return nick; } public void setNick(String nick) { this.nick = nick; } @Keyword @ProtoField(number = 2) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Text @ProtoField(number = 3) public String getBiography() { return biography; } public void setBiography(String biography) { this.biography = biography; } @Basic(projectable = true) @ProtoField(number = 4, defaultValue = "0") public Integer getContributions() { return contributions; } public void setContributions(Integer contributions) { this.contributions = contributions; } @Override public String toString() { return "Developer{" + "nick='" + nick + '\'' + ", email='" + email + '\'' + ", biography='" + biography + '\'' + ", contributions=" + contributions + '}'; } @AutoProtoSchemaBuilder( includeClasses = Developer.class, schemaFileName = "developer.proto", schemaPackageName = "io.dev" ) public interface DeveloperSchema extends GeneratedSchema { DeveloperSchema INSTANCE = new DeveloperSchemaImpl(); } }
2,293
23.934783
89
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/ObjectStorageLocalCacheTest.java
package org.infinispan.query.blackbox; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT_TYPE; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.test.AnotherGrassEater; import org.infinispan.query.test.CustomKey3; import org.infinispan.query.test.CustomKey3Transformer; import org.infinispan.query.test.Person; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Verify queries when configuring storage as application/x-java-objects. * * @author Martin Gencur * @since 6.0 */ @Test(groups = "functional", testName = "query.blackbox.ObjectStorageLocalCacheTest") public class ObjectStorageLocalCacheTest extends LocalCacheTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg.encoding().key().mediaType(APPLICATION_OBJECT_TYPE) .encoding().value().mediaType(APPLICATION_OBJECT_TYPE) .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class) .addIndexedEntity(AnotherGrassEater.class) .addKeyTransformer(CustomKey3.class, CustomKey3Transformer.class); enhanceConfig(cfg); return TestCacheManagerFactory.createCacheManager(cfg); } }
1,522
38.051282
86
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/LocalCacheStorageTypeTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.test.AnotherGrassEater; import org.infinispan.query.test.CustomKey3; import org.infinispan.query.test.CustomKey3Transformer; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * @author vjuranek * @since 9.2 */ @Test(groups = {"functional", "smoke"}, testName = "query.blackbox.LocalCacheStorageTypeTest") public class LocalCacheStorageTypeTest extends LocalCacheTest { protected StorageType storageType; @Override protected String parameters() { return "[" + storageType + "]"; } @Factory public Object[] factory() { return new Object[]{ new LocalCacheStorageTypeTest().withStorageType(StorageType.OFF_HEAP), new LocalCacheStorageTypeTest().withStorageType(StorageType.BINARY), new LocalCacheStorageTypeTest().withStorageType(StorageType.OBJECT), }; } LocalCacheStorageTypeTest withStorageType(StorageType storageType) { this.storageType = storageType; return this; } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg.indexing() .enable() .storage(LOCAL_HEAP) .addKeyTransformer(CustomKey3.class, CustomKey3Transformer.class) .addIndexedEntity(Person.class) .addIndexedEntity(AnotherGrassEater.class); cfg.memory() .storageType(storageType); enhanceConfig(cfg); return TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE, cfg); } }
2,046
33.116667
94
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/IndexingWithPersistenceTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.query.helper.TestQueryHelperFactory.queryAll; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.function.Consumer; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.context.Flag; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.manager.PersistenceManager; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.query.test.AnotherGrassEater; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.blackbox.IndexingWithPersistenceTest") public class IndexingWithPersistenceTest extends SingleCacheManagerTest { private static final String KEY = "k"; private static final Person RADIM = new Person("Radim", "Tough guy!", 29); private static final Person DAN = new Person("Dan", "Not that tough.", 39); private static final AnotherGrassEater FLUFFY = new AnotherGrassEater("Fluffy", "Very cute."); private DummyInMemoryStore store; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class) .addIndexedEntity(AnotherGrassEater.class); builder.persistence().addStore(new DummyInMemoryStoreConfigurationBuilder(builder.persistence())); EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE, builder); cache = cacheManager.getCache(); PersistenceManager pm = TestingUtil.extractComponent(cache, PersistenceManager.class); store = pm.getStores(DummyInMemoryStore.class).iterator().next(); return cacheManager; } public void testPut() { test(c -> c.put(KEY, FLUFFY), this::assertFluffyIndexed, false); } public void testPutIgnoreReturnValue() { test(c -> c.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES).put(KEY, FLUFFY), this::assertFluffyIndexed, false); } public void testPutMap() { test(c -> c.putAll(Collections.singletonMap(KEY, FLUFFY)), this::assertFluffyIndexed, false); } public void testReplace() { test(c -> c.replace(KEY, FLUFFY), this::assertFluffyIndexed, false); } public void testRemove() { test(c -> c.remove(KEY), sm -> {}, true); } public void testCompute() { test(c -> c.compute(KEY, (k, old) -> FLUFFY), this::assertFluffyIndexed, false); } public void testComputeRemove() { test(c -> c.compute(KEY, (k, old) -> null), sm -> {}, true); } public void testMerge() { test(c -> c.merge(KEY, FLUFFY, (o, n) -> n), this::assertFluffyIndexed, false); } public void testMergeRemove() { test(c -> c.merge(KEY, FLUFFY, (o, n) -> null), sm -> {}, true); } private void test(Consumer<Cache<Object, Object>> op, Consumer<Cache<?, ?>> check, boolean remove) { // insert entity and make it evicted (move to the store) cache.put(KEY, RADIM); // to prevent the case when index becomes empty (and we mistake it for correctly removed item) we add another person cache.put("k2", DAN); // it should be indexed List<Person> found = queryAll(cache, Person.class); assertEquals(Arrays.asList(RADIM, DAN), sortByAge(found)); // evict cache.evict(KEY); // check the entry is in the store MarshallableEntry<?, ?> inStore = store.loadEntry(KEY); assertNotNull(inStore); assertTrue("In store: " + inStore, inStore.getValue() instanceof Person); // ...and not in the container assertNull(cache.getAdvancedCache().getDataContainer().peek(KEY)); // do the modification op.accept(cache); // now the person should be gone assertEquals(Collections.singletonList(DAN), queryAll(cache, Person.class)); // and the indexes for other type should be updated check.accept(cache); InternalCacheEntry<?, ?> ice = cache.getAdvancedCache().getDataContainer().peek(KEY); inStore = store.loadEntry(KEY); if (remove) { assertNull(ice); assertNull(inStore); } else { assertNotNull(ice); assertTrue("In DC: " + ice, ice.getValue() instanceof AnotherGrassEater); assertNotNull(inStore); assertTrue("In store: " + inStore, inStore.getValue() instanceof AnotherGrassEater); } } private List<Person> sortByAge(List<Person> people) { new ArrayList<>(people).sort(Comparator.comparingInt(Person::getAge)); return people; } private void assertFluffyIndexed(Cache<?, ?> cache) { assertEquals(Collections.singletonList(FLUFFY), queryAll(cache, AnotherGrassEater.class)); } }
5,679
38.172414
126
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/ClusteredPessimisticLockingCacheTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.test.CustomKey3; import org.infinispan.query.test.CustomKey3Transformer; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.transaction.LockingMode; import org.testng.annotations.Test; /** * Tests which test the querying on Clustered cache with Pessimistic Lock for transaction. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.blackbox.ClusteredPessimisticLockingCacheTest") public class ClusteredPessimisticLockingCacheTest extends ClusteredCacheTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, transactionsEnabled()); cacheCfg.transaction().lockingMode(LockingMode.PESSIMISTIC); cacheCfg.indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class) .addKeyTransformer(CustomKey3.class, CustomKey3Transformer.class); enhanceConfig(cacheCfg); createClusteredCaches(2, QueryTestSCI.INSTANCE, cacheCfg); cache1 = cache(0); cache2 = cache(1); } protected boolean transactionsEnabled() { return true; } }
1,487
35.292683
113
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/ClusteredQueryMultipleCachesTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.Search; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.fwk.TransportFlags; import org.testng.annotations.Test; /** * Tests for testing clustered queries functionality on multiple cache instances * (In these tests we have two caches in each CacheManager) * * @author Israel Lacerra &lt;israeldl@gmail.com&gt; * @since 5.2 */ @Test(groups = "functional", testName = "query.blackbox.ClusteredQueryMultipleCachesTest") public class ClusteredQueryMultipleCachesTest extends ClusteredQueryTest { Cache<String, Person> cacheBMachine1, cacheBMachine2; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(getCacheMode(), false); cacheCfg.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); createClusteredCaches(2, QueryTestSCI.INSTANCE, cacheCfg, new TransportFlags(), "cacheA", "cacheB"); cacheAMachine1 = manager(0).getCache("cacheA"); cacheAMachine2 = manager(1).getCache("cacheA"); cacheBMachine1 = manager(0).getCache("cacheB"); cacheBMachine2 = manager(1).getCache("cacheB"); queryFactory1 = Search.getQueryFactory(cacheAMachine1); queryFactory2 = Search.getQueryFactory(cacheAMachine2); populateCache(); } @Override protected void prepareTestData() { super.prepareTestData(); Person person5 = new Person(); person5.setName("People In Another Cache"); person5.setBlurb("Also eats grass"); person5.setAge(5); cacheBMachine2.put("anotherNewOne", person5); } }
1,913
34.444444
106
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/ClusteredCacheWithAsyncDirTest.java
package org.infinispan.query.blackbox; import java.net.URL; import org.infinispan.commons.util.FileLookupFactory; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StoreConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.jdbc.common.configuration.AbstractJdbcStoreConfigurationBuilder; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Testing the ISPN Directory configuration with Async. JDBC CacheStore. The tests are performed for Clustered cache. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.blackbox.ClusteredCacheWithAsyncDirTest") public class ClusteredCacheWithAsyncDirTest extends ClusteredCacheTest { @Override protected void createCacheManagers() throws Exception { cacheManagers.add(createCacheManager(1)); cacheManagers.add(createCacheManager(2)); waitForClusterToForm(); cache1 = cacheManagers.get(0).getCache("JDBCBased_LocalIndex"); cache2 = cacheManagers.get(1).getCache("JDBCBased_LocalIndex"); } private EmbeddedCacheManager createCacheManager(int nodeIndex) throws Exception { URL is = FileLookupFactory.newInstance().lookupFileLocation("async-jdbc-store-config.xml", Thread.currentThread().getContextClassLoader()); ParserRegistry parserRegistry = new ParserRegistry(Thread.currentThread().getContextClassLoader()); ConfigurationBuilderHolder holder = parserRegistry.parse(is); holder.getGlobalConfigurationBuilder().serialization().addContextInitializer(QueryTestSCI.INSTANCE); for (ConfigurationBuilder builder : holder.getNamedConfigurationBuilders().values()) { for (StoreConfigurationBuilder storeBuilder : builder.persistence().stores()) { if (storeBuilder instanceof AbstractJdbcStoreConfigurationBuilder) { AbstractJdbcStoreConfigurationBuilder jdbcStoreBuilder = (AbstractJdbcStoreConfigurationBuilder) storeBuilder; jdbcStoreBuilder.simpleConnection() .driverClass("org.h2.Driver") .connectionUrl("jdbc:h2:mem:infinispan_string_based_" + nodeIndex + ";DB_CLOSE_DELAY=-1") .username("sa"); } } } return TestCacheManagerFactory.createClusteredCacheManager(holder); } protected boolean transactionsEnabled() { return true; } }
2,684
43.75
125
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/KeyTypeTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import java.util.List; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.test.CustomKey; import org.infinispan.query.test.Person; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.Test; /** * Class that will put in different kinds of keys into the cache and run a query on it to see if * different primitives will work as keys. * * @author Navin Surtani */ @Test(groups = "functional", testName = "query.blackbox.KeyTypeTest") public class KeyTypeTest extends SingleCacheManagerTest { private Person person1; public KeyTypeTest() { cleanup = CleanupPhase.AFTER_METHOD; } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg .transaction() .transactionMode(TransactionMode.TRANSACTIONAL) .indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); cacheManager = TestCacheManagerFactory.createCacheManager(cfg); person1 = new Person(); person1.setName("Navin"); person1.setBlurb("Owns a macbook"); person1.setAge(20); return cacheManager; } public void testPrimitiveAndStringKeys() { String key1 = "key1"; int key2 = 2; byte key3 = 3; float key4 = 4; long key5 = 5; short key6 = 6; boolean key7 = true; double key8 = 8; char key9 = '9'; cache.put(key1, person1); cache.put(key2, person1); cache.put(key3, person1); cache.put(key4, person1); cache.put(key5, person1); cache.put(key6, person1); cache.put(key7, person1); cache.put(key8, person1); cache.put(key9, person1); // Going to search the 'blurb' field for 'owns' Query cacheQuery = Search.getQueryFactory(cache).create(getQuery()); assertEquals(9, cacheQuery.execute().count().value()); List<Person> found = cacheQuery.list(); for (int i = 0; i < 9; i++) { assertEquals(person1, found.get(i)); } } private String getQuery() { return String.format("FROM %s WHERE blurb:'owns'", Person.class.getName()); } public void testCustomKeys() { CustomKey key1 = new CustomKey(1, 2, 3); CustomKey key2 = new CustomKey(900, 800, 700); CustomKey key3 = new CustomKey(1024, 2048, 4096); cache.put(key1, person1); cache.put(key2, person1); cache.put(key3, person1); Query cacheQuery = Search.getQueryFactory(cache).create(getQuery()); assertEquals(3, cacheQuery.execute().count().value()); } }
3,096
29.97
96
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/SearchFactoryShutdownTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.CacheContainer; import org.infinispan.query.test.Person; import org.infinispan.search.mapper.mapping.SearchMapping; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.Test; /** * Ensures the search factory is properly shut down. * * @author Manik Surtani * @since 4.2 */ @Test(testName = "query.blackbox.SearchFactoryShutdownTest", groups = "functional") public class SearchFactoryShutdownTest extends AbstractInfinispanTest { public void testCorrectShutdown() { CacheContainer cc = null; try { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg .transaction() .transactionMode(TransactionMode.TRANSACTIONAL) .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); cc = TestCacheManagerFactory.createCacheManager(cfg); Cache<?, ?> cache = cc.getCache(); SearchMapping searchMapping = TestingUtil.extractComponent(cache, SearchMapping.class); assertFalse(searchMapping.isClose()); cc.stop(); assertTrue(searchMapping.isClose()); } finally { // proper cleanup for exceptional execution TestingUtil.killCacheManagers(cc); } } }
1,782
32.018519
96
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/IndexingDuringStateTransferTest.java
package org.infinispan.query.blackbox; import static java.util.concurrent.TimeUnit.SECONDS; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.query.helper.TestQueryHelperFactory.queryAll; import static org.infinispan.test.TestingUtil.orTimeout; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNull; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; import org.infinispan.Cache; import org.infinispan.commands.ReplicableCommand; import org.infinispan.commands.statetransfer.StateResponseCommand; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.query.helper.StaticTestingErrorHandler; import org.infinispan.query.test.AnotherGrassEater; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.rpc.RpcOptions; import org.infinispan.remoting.transport.Address; import org.infinispan.remoting.transport.ResponseCollector; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.topology.CacheTopology; import org.infinispan.util.AbstractDelegatingRpcManager; import org.infinispan.util.ControlledConsistentHashFactory; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.blackbox.IndexingDuringStateTransferTest") public class IndexingDuringStateTransferTest extends MultipleCacheManagersTest { private static final String KEY = "k"; private static final Person RADIM = new Person("Radim", "Tough guy!", 29); private static final Person DAN = new Person("Dan", "Not that tough.", 39); private static final AnotherGrassEater FLUFFY = new AnotherGrassEater("Fluffy", "Very cute."); private ConfigurationBuilder builder; private final ControlledConsistentHashFactory.Default chf = new ControlledConsistentHashFactory.Default(0, 1); @Override protected void createCacheManagers() throws Throwable { builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); builder.indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class) .addIndexedEntity(AnotherGrassEater.class); builder.clustering().hash().numSegments(1).numOwners(2).consistentHashFactory(chf); createClusteredCaches(2, QueryTestSCI.INSTANCE, builder); } @BeforeMethod public void cleanData() { caches().forEach(Cache::clear); } public void testPut() { test(c -> c.put(KEY, FLUFFY), this::assertFluffyIndexed); } public void testPutIgnoreReturnValue() { test(c -> c.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES).put(KEY, FLUFFY), this::assertFluffyIndexed); } public void testPutMap() { test(c -> c.putAll(Collections.singletonMap(KEY, FLUFFY)), this::assertFluffyIndexed); } public void testReplace() { test(c -> c.replace(KEY, FLUFFY), this::assertFluffyIndexed); } public void testRemove() { test(c -> c.remove(KEY), sm -> { }); } public void testCompute() { test(c -> c.compute(KEY, (k, old) -> FLUFFY), this::assertFluffyIndexed); } // The test fails as compute command on backup owner retrieves remote value from primary owner, but this may // already have the value applied. This command then does not commit (as it thinks that there is no change) // and therefore CommitManager does not know that it must not let the entry be state-transferred in. @Test(enabled = false, description = "ISPN-7590") public void testComputeRemove() { test(c -> c.compute(KEY, (k, old) -> null), sm -> { }); } public void testMerge() { test(c -> c.merge(KEY, FLUFFY, (o, n) -> n), this::assertFluffyIndexed); } // Same as above, though this started failing only after functional commands were triangelized @Test(enabled = false, description = "ISPN-7590") public void testMergeRemove() { test(c -> c.merge(KEY, FLUFFY, (o, n) -> null), sm -> { }); } /** * The test checks that when we replace a Person entity with entity of another type (Animal) * or completely remove it the old index is still correctly updated. */ private void test(Consumer<Cache<Object, Object>> op, Consumer<Cache<Object, Object>> check) { Cache<Object, Object> cache0 = cache(0); Cache<Object, Object> cache1 = cache(1); assertEquals(0, queryAll(cache0, Person.class).size()); // add a new key cache0.put(KEY, RADIM); // to prevent the case when index becomes empty (and we mistake it for correctly removed item) we add another person cache0.put("k2", DAN); StaticTestingErrorHandler.assertAllGood(cache0, cache1); List<Person> found = queryAll(cache0, Person.class); assertEquals(Arrays.asList(RADIM, DAN), sortByAge(found)); // add new node, cache(0) will lose ownership of the segment chf.setOwnerIndexes(1, 2); addClusterEnabledCacheManager(QueryTestSCI.INSTANCE, builder).getCache(); // wait until the node discards old entries eventuallyEquals(null, () -> cache0.getAdvancedCache().getDataContainer().peek(KEY)); // block state response commands AtomicReference<Throwable> exception = new AtomicReference<>(); CompletableFuture<Void> allowStateResponse = new CompletableFuture<>(); caches().forEach( c -> TestingUtil.wrapComponent(c, RpcManager.class, original -> new AbstractDelegatingRpcManager(original) { @Override protected <T> CompletionStage<T> performRequest(Collection<Address> targets, ReplicableCommand command, ResponseCollector<T> collector, Function<ResponseCollector<T>, CompletionStage<T>> invoker, RpcOptions rpcOptions) { if (command instanceof StateResponseCommand) { CompletableFuture<Void> stageWithTimeout = orTimeout(allowStateResponse, 10, SECONDS, testExecutor()); return CompletionStages.handleAndCompose(stageWithTimeout, (ignored, t) -> { if (t != null) { exception.set(t); } return super.performRequest(targets, command, collector, invoker, rpcOptions); }); } return super.performRequest(targets, command, collector, invoker, rpcOptions); } })); // stop the other cache, cache(0) should get the entry back chf.setOwnerIndexes(0, 1); Future<?> stoppingCacheFuture = fork(() -> killMember(2)); // wait until it starts rebalancing TestingUtil.waitForTopologyPhase(Collections.emptyList(), CacheTopology.Phase.READ_OLD_WRITE_ALL, cache(0)); // check that cache(0) does not have the data yet assertNull(cache0.getAdvancedCache().getDataContainer().peek(KEY)); // overwrite the entry with another type op.accept(cache0); // unblock state transfer allowStateResponse.complete(null); // wait for the new node to be added try { stoppingCacheFuture.get(10, SECONDS); } catch (Exception e) { throw new RuntimeException(e); } assertNull(exception.get()); // check results StaticTestingErrorHandler.assertAllGood(cache0, cache(1)); // The person should have been removed assertEquals(Collections.singletonList(DAN), queryAll(cache0, Person.class)); Object value = cache(0).get(KEY); assertFalse("Current value: " + value, value instanceof Person); // Check that the operation is reflected in index check.accept(cache0); } private List<Person> sortByAge(List<Person> people) { people.sort(Comparator.comparingInt(Person::getAge)); return people; } private void assertFluffyIndexed(Cache<Object,Object> cache) { assertEquals(Collections.singletonList(FLUFFY), queryAll(cache, AnotherGrassEater.class)); } }
8,909
40.635514
122
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/ClusteredCacheTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.distribution.Ownership.BACKUP; import static org.infinispan.distribution.Ownership.NON_OWNER; import static org.infinispan.distribution.Ownership.PRIMARY; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.Future; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import jakarta.transaction.TransactionManager; import org.infinispan.Cache; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.Ownership; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.query.Search; import org.infinispan.query.backend.QueryInterceptor; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.query.helper.StaticTestingErrorHandler; import org.infinispan.query.test.CustomKey3; import org.infinispan.query.test.CustomKey3Transformer; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * @author Navin Surtani * @author Sanne Grinovero */ @Test(groups = {"functional"}, testName = "query.blackbox.ClusteredCacheTest") public class ClusteredCacheTest extends MultipleCacheManagersTest { protected Cache<Object, Person> cache1; protected Cache<Object, Person> cache2; private Person person1; private Person person2; private Person person3; private Person person4; private Query<Person> cacheQuery; private final String key1 = "Navin"; private final String key2 = "BigGoat"; private final String key3 = "MiniGoat"; public ClusteredCacheTest() { cleanup = CleanupPhase.AFTER_METHOD; } public Object[] factory() { return new Object[]{ new ClusteredCacheTest().storageType(StorageType.OFF_HEAP), new ClusteredCacheTest().storageType(StorageType.BINARY), new ClusteredCacheTest().storageType(StorageType.OBJECT), }; } @AfterMethod(alwaysRun = true) @Override protected void clearContent() throws Throwable { // Update the indexes as well -- see ISPN-9890 cache(0).clear(); super.clearContent(); } protected void enhanceConfig(ConfigurationBuilder cacheCfg) { // meant to be overridden } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, transactionsEnabled()); cacheCfg.indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class) .addKeyTransformer(CustomKey3.class, CustomKey3Transformer.class); cacheCfg.memory() .storageType(storageType); enhanceConfig(cacheCfg); createClusteredCaches(2, QueryTestSCI.INSTANCE, cacheCfg); cache1 = cache(0); cache2 = cache(1); } private void prepareTestedObjects() { person1 = new Person(); person1.setName("Navin Surtani"); person1.setBlurb("Likes playing WoW"); person1.setAge(30); person2 = new Person(); person2.setName("BigGoat"); person2.setBlurb("Eats grass"); person2.setAge(22); person3 = new Person(); person3.setName("MiniGoat"); person3.setBlurb("Eats cheese"); person3.setAge(15); } protected Query<Person> createQuery(Cache<?, ?> cache, String predicate) { QueryFactory queryFactory = Search.getQueryFactory(cache); String query = String.format("FROM %s WHERE %s", Person.class.getName(), predicate); return queryFactory.create(query); } protected Query<Person> createSelectAllQuery(Cache<?, ?> cache) { QueryFactory queryFactory = Search.getQueryFactory(cache); return queryFactory.create("FROM " + Person.class.getName()); } protected void prepareTestData() throws Exception { prepareTestedObjects(); TransactionManager transactionManager = cache1.getAdvancedCache().getTransactionManager(); // Put the 3 created objects in the cache1. if (transactionsEnabled()) transactionManager.begin(); cache1.put(key1, person1); cache1.put(key2, person2); cache1.put(key3, person3); if (transactionsEnabled()) transactionManager.commit(); StaticTestingErrorHandler.assertAllGood(cache1, cache2); } protected boolean transactionsEnabled() { return false; } public void testSimple() throws Exception { prepareTestData(); cacheQuery = createQuery(cache1, "blurb:'playing'"); List<Person> found = cacheQuery.execute().list(); assertEquals(1, found.size()); if (found.get(0) == null) { log.warn("found.get(0) is null"); Person p1 = cache2.get(key1); if (p1 == null) { log.warn("Person p1 is null in sc2 and cannot actually see the data of person1 in sc1"); } else { log.trace("p1 name is " + p1.getName()); } } assertEquals(person1, found.get(0)); StaticTestingErrorHandler.assertAllGood(cache1, cache2); } private void assertQueryInterceptorPresent(Cache<?, ?> c) { QueryInterceptor i = TestingUtil.findInterceptor(c, QueryInterceptor.class); assert i != null : "Expected to find a QueryInterceptor, only found " + c.getAdvancedCache().getAsyncInterceptorChain().getInterceptors(); } public void testModified() throws Exception { prepareTestData(); assertQueryInterceptorPresent(cache2); cacheQuery = createQuery(cache2, "blurb:'playing'"); List<Person> found = cacheQuery.execute().list(); assert found.size() == 1 : "Expected list of size 1, was of size " + found.size(); assert found.get(0).equals(person1); person1.setBlurb("Likes pizza"); cache1.put("Navin", person1); cacheQuery = createQuery(cache2, "blurb:'pizza'"); found = cacheQuery.execute().list(); assert found.size() == 1; assert found.get(0).equals(person1); StaticTestingErrorHandler.assertAllGood(cache1, cache2); } public void testAdded() throws Exception { prepareTestData(); cacheQuery = createQuery(cache2, "blurb:'eats'"); List<Person> found = cacheQuery.execute().list(); assertEquals(2, found.size()); assertTrue(found.contains(person2)); assertTrue(found.contains(person3)); assertFalse("This should not contain object person4", found.contains(person4)); person4 = new Person(); person4.setName("Mighty Goat"); person4.setBlurb("Also eats grass"); cache1.put("mighty", person4); cacheQuery = createQuery(cache2, "blurb:'eats'"); found = cacheQuery.execute().list(); assertEquals(3, found.size()); assertTrue(found.contains(person2)); assertTrue(found.contains(person3)); assertTrue("This should now contain object person4", found.contains(person4)); StaticTestingErrorHandler.assertAllGood(cache1, cache2); } public void testRemoved() throws Exception { prepareTestData(); cacheQuery = createQuery(cache2, "blurb:'eats'"); List<Person> found = cacheQuery.execute().list(); assert found.size() == 2; assert found.contains(person2); assert found.contains(person3) : "This should still contain object person3"; cache1.remove(key3); cacheQuery = createQuery(cache2, "blurb:'eats'"); found = cacheQuery.execute().list(); assert found.size() == 1; assert found.contains(person2); assert !found.contains(person3) : "This should not contain object person3 anymore"; assert countIndex(cache1) == 2 : "Two documents should remain in the index"; StaticTestingErrorHandler.assertAllGood(cache1, cache2); } protected int countIndex(Cache<?, ?> cache) { Query<?> query = Search.getQueryFactory(cache).create("FROM " + Person.class.getName()); return query.execute().count().value(); } private Optional<Cache<Object, Person>> findCache(Ownership ownership, Object key) { List<Cache<Object, Person>> caches = caches(); ClusteringDependentLogic cdl = cache1.getAdvancedCache().getComponentRegistry().getComponent(ClusteringDependentLogic.class); DistributionInfo distribution = cdl.getCacheTopology().getDistribution(key); Predicate<Cache<?, ?>> predicate = null; switch (ownership) { case PRIMARY: predicate = c -> c.getAdvancedCache().getRpcManager().getAddress().equals(distribution.primary()); break; case BACKUP: predicate = c -> distribution.writeBackups().contains(c.getAdvancedCache().getRpcManager().getAddress()); break; case NON_OWNER: predicate = c -> !distribution.writeOwners().contains(c.getAdvancedCache().getRpcManager().getAddress()); } return caches.stream().filter(predicate).findFirst(); } public void testConditionalRemoveFromPrimary() throws Exception { testConditionalRemoveFrom(PRIMARY); } public void testConditionalRemoveFromBackup() throws Exception { testConditionalRemoveFrom(BACKUP); } public void testConditionalRemoveFromNonOwner() throws Exception { testConditionalRemoveFrom(NON_OWNER); } public void testConditionalReplaceFromPrimary() throws Exception { testConditionalReplaceFrom(PRIMARY); } public void testConditionalReplaceFromBackup() throws Exception { testConditionalReplaceFrom(BACKUP); } public void testConditionalReplaceFromNonOwner() throws Exception { testConditionalReplaceFrom(NON_OWNER); } private void testConditionalReplaceFrom(Ownership memberType) throws Exception { prepareTestData(); Cache<Object, Person> cache = findCache(memberType, key1).orElse(cache2); assertEquals(createQuery(cache2, "blurb:'wow'").execute().list().size(), 1); boolean replaced = cache.replace(key1, person1, person2); assertTrue(replaced); assertEquals(createQuery(cache1, "blurb:'wow'").execute().list().size(), 0); assertEquals(createQuery(cache, "blurb:'wow'").execute().count().value(), 0); } private void testConditionalRemoveFrom(Ownership owneship) throws Exception { prepareTestData(); Cache<Object, Person> cache = findCache(owneship, key1).orElse(cache2); cache.remove(key1, person1); assertEquals(createSelectAllQuery(cache2).execute().list().size(), 2); assertEquals(countIndex(cache), 2); cache.remove(key1, person1); assertEquals(createSelectAllQuery(cache2).execute().list().size(), 2); assertEquals(countIndex(cache), 2); cache = findCache(owneship, key3).orElse(cache2); cache.remove(key3); assertEquals(createSelectAllQuery(cache2).execute().list().size(), 1); assertEquals(countIndex(cache), 1); StaticTestingErrorHandler.assertAllGood(cache1, cache2); } public void testGetResultSize() throws Exception { prepareTestData(); cacheQuery = createQuery(cache2, "blurb:'playing'"); List<Person> found = cacheQuery.execute().list(); assertEquals(1, found.size()); StaticTestingErrorHandler.assertAllGood(cache1, cache2); } public void testPutMap() throws Exception { prepareTestData(); assertEquals(3, createSelectAllQuery(cache2).execute().list().size()); Map<String, Person> allWrites = new HashMap<>(); allWrites.put(key1, person1); allWrites.put(key2, person2); allWrites.put(key3, person3); cache2.putAll(allWrites); List<Person> found = createSelectAllQuery(cache2).execute().list(); assertEquals(3, found.size()); cache2.putAll(allWrites); found = createSelectAllQuery(cache2).execute().list(); assertEquals(3, found.size()); StaticTestingErrorHandler.assertAllGood(cache1, cache2); } public void testPutMapAsync() throws Exception { prepareTestData(); assert createSelectAllQuery(cache2).execute().list().size() == 3; person4 = new Person(); person4.setName("New Goat"); person4.setBlurb("Also eats grass"); Map<String, Person> allWrites = new HashMap<>(); allWrites.put(key1, person1); allWrites.put(key2, person2); allWrites.put(key3, person3); allWrites.put("newGoat", person4); Future<Void> futureTask = cache2.putAllAsync(allWrites); futureTask.get(); assert futureTask.isDone(); List<Person> found = createSelectAllQuery(cache2).execute().list(); assertEquals(4, found.size()); assert found.contains(person4); futureTask = cache1.putAllAsync(allWrites); futureTask.get(); assert futureTask.isDone(); found = createSelectAllQuery(cache2).execute().list(); assertEquals(4, found.size()); assert found.contains(person4); StaticTestingErrorHandler.assertAllGood(cache1, cache2); } public void testPutForExternalRead() throws Exception { prepareTestData(); assertEquals(3, createSelectAllQuery(cache2).execute().list().size()); person4 = new Person(); person4.setName("New Goat"); person4.setBlurb("Also eats grass"); cache2.putForExternalRead("newGoat", person4); eventually(() -> cache2.get("newGoat") != null); Query<Person> query = createSelectAllQuery(cache2); eventually(() -> { List<Person> found = query.execute().list(); return found.size() == 4 && found.contains(person4); }); Person person5 = new Person(); person5.setName("Abnormal Goat"); person5.setBlurb("Plays with grass."); cache2.putForExternalRead("newGoat", person5); eventually(() -> { QueryResult<Person> result = query.execute(); List<Person> found = result.list(); return found.size() == 4 && result.count().value() == 4 && found.contains(person4) && !found.contains(person5); }); StaticTestingErrorHandler.assertAllGood(cache1, cache2); } public void testPutIfAbsent() throws Exception { prepareTestData(); assert createSelectAllQuery(cache2).execute().list().size() == 3; person4 = new Person(); person4.setName("New Goat"); person4.setBlurb("Also eats grass"); cache2.putIfAbsent("newGoat", person4); List<Person> found = createSelectAllQuery(cache2).execute().list(); assertEquals(4, found.size()); assert found.contains(person4); Person person5 = new Person(); person5.setName("Abnormal Goat"); person5.setBlurb("Plays with grass."); cache2.putIfAbsent("newGoat", person5); found = createSelectAllQuery(cache2).execute().list(); assertEquals(4, found.size()); assertFalse(found.contains(person5)); assertTrue(found.contains(person4)); StaticTestingErrorHandler.assertAllGood(cache1, cache2); } public void testPutIfAbsentAsync() throws Exception { prepareTestData(); assertEquals(3, createSelectAllQuery(cache2).execute().list().size()); person4 = new Person(); person4.setName("New Goat"); person4.setBlurb("Also eats grass"); Future<Person> futureTask = cache2.putIfAbsentAsync("newGoat", person4); futureTask.get(); assertTrue(futureTask.isDone()); List<Person> found = createSelectAllQuery(cache2).execute().list(); assertEquals(4, found.size()); assertTrue(found.contains(person4)); Person person5 = new Person(); person5.setName("Abnormal Goat"); person5.setBlurb("Plays with grass."); futureTask = cache2.putIfAbsentAsync("newGoat", person5); futureTask.get(); assertTrue(futureTask.isDone()); found = createSelectAllQuery(cache2).execute().list(); assertEquals(4, found.size()); assertFalse(found.contains(person5)); assertTrue(found.contains(person4)); StaticTestingErrorHandler.assertAllGood(cache1, cache2); } public void testPutAsync() throws Exception { prepareTestData(); assertEquals(3, createSelectAllQuery(cache2).execute().list().size()); person4 = new Person(); person4.setName("New Goat"); person4.setBlurb("Also eats grass"); Future<Person> f = cache2.putAsync("newGoat", person4); f.get(); assertTrue(f.isDone()); List<Person> found = createSelectAllQuery(cache2).execute().list(); assertEquals(4, found.size()); assertTrue(found.contains(person4)); Person person5 = new Person(); person5.setName("Abnormal Goat"); person5.setBlurb("Plays with grass."); f = cache2.putAsync("newGoat", person5); f.get(); assertTrue(f.isDone()); found = createSelectAllQuery(cache2).execute().list(); assertEquals(4, found.size()); assertFalse(found.contains(person4)); assertTrue(found.contains(person5)); StaticTestingErrorHandler.assertAllGood(cache1, cache2); } public void testClear() throws Exception { prepareTestData(); String predicate = "blurb:'eats' OR blurb:'playing'"; Query<Person> cacheQuery1 = createQuery(cache1, predicate); Query<Person> cacheQuery2 = createQuery(cache2, predicate); assertEquals(3, cacheQuery1.execute().count().value()); assertEquals(3, cacheQuery2.execute().count().value()); cache2.clear(); assertEquals(0, cacheQuery1.execute().list().size()); assertEquals(0, cacheQuery2.execute().list().size()); StaticTestingErrorHandler.assertAllGood(cache1, cache2); } public void testSearchKeyTransformer() throws Exception { prepareTestedObjects(); TransactionManager transactionManager = cache1.getAdvancedCache().getTransactionManager(); CustomKey3 customKey1 = new CustomKey3(key1); CustomKey3 customKey2 = new CustomKey3(key2); CustomKey3 customKey3 = new CustomKey3(key3); // Put the 3 created objects in the cache1. if (transactionsEnabled()) transactionManager.begin(); cache1.put(customKey1, person1); cache1.put(customKey2, person2); cache1.put(customKey3, person3); if (transactionsEnabled()) transactionManager.commit(); Query<Person> cacheQuery = createQuery(cache1, "blurb:'Eats'"); int counter = 0; // TODO HSEARCH-3323 Restore support for scrolling try (CloseableIterator<Person> found = cacheQuery.iterator()) { while (found.hasNext()) { found.next(); counter++; } } assertEquals(2, counter); StaticTestingErrorHandler.assertAllGood(cache1, cache2); } public void testCompute() throws Exception { prepareTestData(); TransactionManager transactionManager = cache2.getAdvancedCache().getTransactionManager(); assertEquals(3, createSelectAllQuery(cache2).execute().list().size()); String key = "newGoat"; person4 = new Person(key, "eats something", 42); // compute a new key BiFunction<Object, Person, Person> remappingFunction = (BiFunction<Object, Person, Person> & Serializable) (k, v) -> new Person(k.toString(), "eats something", 42); if (transactionsEnabled()) transactionManager.begin(); cache2.compute(key, remappingFunction); if (transactionsEnabled()) transactionManager.commit(); StaticTestingErrorHandler.assertAllGood(cache1, cache2); List<Person> found = createSelectAllQuery(cache2).execute().list(); assertEquals(4, found.size()); assertTrue(found.contains(person4)); // compute and replace existing key BiFunction<Object, Person, Person> remappingExisting = (BiFunction<Object, Person, Person> & Serializable) (k, v) -> new Person(k.toString(), "eats other things", 42); if (transactionsEnabled()) transactionManager.begin(); cache2.compute(key, remappingExisting); if (transactionsEnabled()) transactionManager.commit(); StaticTestingErrorHandler.assertAllGood(cache1, cache2); found = createSelectAllQuery(cache2).execute().list(); assertEquals(4, found.size()); assertFalse(found.contains(person4)); assertTrue(found.contains(new Person(key, "eats other things", 42))); // remove if compute result is null BiFunction<Object, Person, Person> remappingToNull = (BiFunction<Object, Person, Person> & Serializable) (k, v) -> null; if (transactionsEnabled()) transactionManager.begin(); cache2.compute(key, remappingToNull); if (transactionsEnabled()) transactionManager.commit(); StaticTestingErrorHandler.assertAllGood(cache1, cache2); found = createSelectAllQuery(cache2).execute().list(); assertEquals(3, found.size()); assertFalse(found.contains(person4)); assertFalse(found.contains(new Person(key, "eats other things", 42))); } public void testComputeIfPresent() throws Exception { prepareTestData(); TransactionManager transactionManager = cache2.getAdvancedCache().getTransactionManager(); assertEquals(3, createSelectAllQuery(cache2).execute().list().size()); // compute and replace existing key BiFunction<Object, Person, Person> remappingExisting = (BiFunction<Object, Person, Person> & Serializable) (k, v) -> new Person("replaced", "personOneChanged", 42); if (transactionsEnabled()) transactionManager.begin(); cache2.computeIfPresent(key1, remappingExisting); if (transactionsEnabled()) transactionManager.commit(); StaticTestingErrorHandler.assertAllGood(cache1, cache2); List<Person> found = createSelectAllQuery(cache2).execute().list(); assertEquals(3, found.size()); assertFalse(found.contains(person1)); assertTrue(found.contains(new Person("replaced", "personOneChanged", 42))); String newKey = "newGoat"; person4 = new Person(newKey, "eats something", 42); // do nothing for non existing keys BiFunction<Object, Person, Person> remappingFunction = (BiFunction<Object, Person, Person> & Serializable) (k, v) -> new Person(k.toString(), "eats something", 42); if (transactionsEnabled()) transactionManager.begin(); cache2.computeIfPresent(newKey, remappingFunction); if (transactionsEnabled()) transactionManager.commit(); StaticTestingErrorHandler.assertAllGood(cache1, cache2); found = createSelectAllQuery(cache2).execute().list(); assertEquals(3, found.size()); assertFalse(found.contains(person4)); // remove if compute result is null BiFunction<Object, Person, Person> remappingToNull = (BiFunction<Object, Person, Person> & Serializable) (k, v) -> null; if (transactionsEnabled()) transactionManager.begin(); cache2.computeIfPresent(key2, remappingToNull); if (transactionsEnabled()) transactionManager.commit(); StaticTestingErrorHandler.assertAllGood(cache1, cache2); found = createSelectAllQuery(cache2).execute().list(); assertFalse(found.contains(person2)); } public void testComputeIfAbsent() throws Exception { prepareTestData(); TransactionManager transactionManager = cache2.getAdvancedCache().getTransactionManager(); assertEquals(3, createSelectAllQuery(cache2).execute().list().size()); String key = "newGoat"; person4 = new Person(key, "eats something", 42); // compute a new key Function<Object, Person> mappingFunction = (Function<Object, Person> & Serializable) k -> new Person(k.toString(), "eats something", 42); if (transactionsEnabled()) transactionManager.begin(); cache2.computeIfAbsent(key, mappingFunction); if (transactionsEnabled()) transactionManager.commit(); StaticTestingErrorHandler.assertAllGood(cache1, cache2); List<Person> found = createSelectAllQuery(cache2).execute().list(); assertEquals(4, found.size()); assertTrue(found.contains(person4)); // do nothing for existing keys if (transactionsEnabled()) transactionManager.begin(); cache2.computeIfAbsent(key1, mappingFunction); if (transactionsEnabled()) transactionManager.commit(); StaticTestingErrorHandler.assertAllGood(cache1, cache2); found = createSelectAllQuery(cache2).execute().list(); assertEquals(4, found.size()); assertFalse(found.contains(new Person(key1, "eats something", 42))); assertTrue(found.contains(person1)); // do nothing if null Function<Object, Person> mappingToNull = (Function<Object, Person> & Serializable) k -> null; if (transactionsEnabled()) transactionManager.begin(); cache2.computeIfAbsent("anotherKey", mappingToNull); if (transactionsEnabled()) transactionManager.commit(); StaticTestingErrorHandler.assertAllGood(cache1, cache2); found = createSelectAllQuery(cache2).execute().list(); assertEquals(4, found.size()); assertFalse(found.contains(null)); } public void testMerge() throws Exception { prepareTestData(); TransactionManager transactionManager = cache2.getAdvancedCache().getTransactionManager(); assertEquals(3, createSelectAllQuery(cache2).execute().list().size()); String key = "newGoat"; person4 = new Person(key, "eats something", 42); // merge a new key if (transactionsEnabled()) transactionManager.begin(); cache2.merge(key, person4, (k1, v3) -> new Person(key, "eats something", 42)); if (transactionsEnabled()) transactionManager.commit(); StaticTestingErrorHandler.assertAllGood(cache1, cache2); List<Person> found = createSelectAllQuery(cache2).execute().list(); assertEquals(4, found.size()); assertTrue(found.contains(person4)); // merge and replace existing key if (transactionsEnabled()) transactionManager.begin(); cache2.merge(key, new Person(key, "hola", 42), (v1, v2) -> new Person(v1.getName() + "_" + v2.getName(), v1.getBlurb() + "_" + v2.getBlurb(), v1.getAge() + v2.getAge())); if (transactionsEnabled()) transactionManager.commit(); StaticTestingErrorHandler.assertAllGood(cache1, cache2); found = createSelectAllQuery(cache2).execute().list(); assertEquals(4, found.size()); assertFalse(found.contains(person4)); assertTrue(found.contains(new Person("newGoat_newGoat", "eats something_hola", 84))); // remove if merge result is null if (transactionsEnabled()) transactionManager.begin(); cache2.merge(key, person4, (k, v) -> null); if (transactionsEnabled()) transactionManager.commit(); StaticTestingErrorHandler.assertAllGood(cache1, cache2); found = createSelectAllQuery(cache2).execute().list(); assertEquals(3, found.size()); assertFalse(found.contains(person4)); assertFalse(found.contains(new Person("newGoat_newGoat", "eats something_hola", 84))); } }
27,821
36.495957
143
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/ClusteredCachePerfIspnTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.query.test.CustomKey3; import org.infinispan.query.test.CustomKey3Transformer; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Testing the functionality of NRT index manager for clustered caches. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.blackbox.ClusteredCachePerfIspnTest") public class ClusteredCachePerfIspnTest extends ClusteredCacheTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, transactionsEnabled()); cacheCfg.indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class) .addKeyTransformer(CustomKey3.class, CustomKey3Transformer.class) .writer().ramBufferSize(54).commitInterval(10000).queueCount(6).queueSize(4096).threadPoolSize(6) .merge().factor(30).maxSize(1024); enhanceConfig(cacheCfg); for (int i = 0; i < 2; i++) { ConfigurationBuilderHolder holder = new ConfigurationBuilderHolder(); holder.getGlobalConfigurationBuilder() .clusteredDefault() .defaultCacheName(TestCacheManagerFactory.DEFAULT_CACHE_NAME) .serialization().addContextInitializer(QueryTestSCI.INSTANCE); holder.getNamedConfigurationBuilders().put(TestCacheManagerFactory.DEFAULT_CACHE_NAME, cacheCfg); addClusterEnabledCacheManager(holder); } cache1 = manager(0).getCache(); cache2 = manager(1).getCache(); } }
2,030
38.057692
113
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/TopologyAwareClusteredCacheTest.java
package org.infinispan.query.blackbox; import java.util.List; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.helper.TestQueryHelperFactory; import org.infinispan.query.test.Person; import org.testng.annotations.Test; /** * Testing the query functionality on clustered caches started on TopologyAware nodes. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.blackbox.TopologyAwareClusteredCacheTest") public class TopologyAwareClusteredCacheTest extends ClusteredCacheTest { @Override protected void createCacheManagers() throws Throwable { List<EmbeddedCacheManager> managers = TestQueryHelperFactory.createTopologyAwareCacheNodes( 2, getCacheMode(), transactionEnabled(), isIndexLocalOnly(), isRamDirectory(), "default", Person.class); registerCacheManager(managers); cache1 = cache(0); cache2 = cache(1); waitForClusterToForm(); } public CacheMode getCacheMode() { return CacheMode.REPL_SYNC; } public boolean isIndexLocalOnly() { return false; } public boolean isRamDirectory() { return true; } public boolean transactionEnabled() { return false; } }
1,283
25.75
119
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/LocalCacheTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.infinispan.Cache; import org.infinispan.cache.impl.CacheImpl; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.query.helper.StaticTestingErrorHandler; import org.infinispan.query.test.AnotherGrassEater; import org.infinispan.query.test.CustomKey3; import org.infinispan.query.test.CustomKey3Transformer; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = {"functional", "smoke"}, testName = "query.blackbox.LocalCacheTest") public class LocalCacheTest extends SingleCacheManagerTest { protected Person person1; protected Person person2; protected Person person3; protected Person person4; protected AnotherGrassEater anotherGrassEater; protected String key1 = "Navin"; protected String key2 = "BigGoat"; protected String key3 = "MiniGoat"; protected String anotherGrassEaterKey = "anotherGrassEaterKey"; public LocalCacheTest() { cleanup = CleanupPhase.AFTER_METHOD; } private <T> Query<T> createQuery(String predicate, Class<T> entity) { QueryFactory queryFactory = Search.getQueryFactory(cache); return queryFactory.create(String.format("FROM %s WHERE %s", entity.getName(), predicate)); } public void testSimple() { loadTestingData(); Query<Person> cacheQuery = createQuery("blurb:'playing'", Person.class); List<Person> found = cacheQuery.execute().list(); int elems = found.size(); assert elems == 1 : "Expected 1 but was " + elems; Person val = found.get(0); assert val.equals(person1) : "Expected " + person1 + " but was " + val; StaticTestingErrorHandler.assertAllGood(cache); } public void testSimpleLocal() { loadTestingData(); QueryFactory queryFactory = Search.getQueryFactory(cache); Query<Person> cacheQuery = queryFactory.create("FROM " + Person.class.getName()); List<Person> found = cacheQuery.local(true).execute().list(); assertEquals(3, found.size()); StaticTestingErrorHandler.assertAllGood(this.cache); } public void testEagerIterator() { loadTestingData(); Query<Person> cacheQuery = createQuery("blurb:'playing'", Person.class); try (CloseableIterator<Person> found = cacheQuery.iterator()) { assertTrue(found.hasNext()); found.next(); assertFalse(found.hasNext()); } StaticTestingErrorHandler.assertAllGood(cache); } public void testIteratorWithProjections() { loadTestingData(); QueryFactory queryFactory = Search.getQueryFactory(cache); String q = String.format("SELECT name, blurb from %s p where name:'navin'", Person.class.getName()); Query<Object[]> query = queryFactory.create(q); try (CloseableIterator<Object[]> found = query.iterator()) { assertTrue(found.hasNext()); Object[] next = found.next(); assertEquals("Navin Surtani", next[0]); assertEquals("Likes playing WoW", next[1]); assertFalse(found.hasNext()); } StaticTestingErrorHandler.assertAllGood(cache); } @Test(expectedExceptions = UnsupportedOperationException.class) public void testEagerIteratorRemove() { loadTestingData(); Query<?> cacheQuery = createQuery("blurb:'playing'", Person.class); try (CloseableIterator<?> found = cacheQuery.iterator()) { assertTrue(found.hasNext()); found.remove(); } } @Test(expectedExceptions = NoSuchElementException.class) public void testEagerIteratorExCase() { loadTestingData(); Query<?> cacheQuery = createQuery("blurb:'playing'", Person.class); try (CloseableIterator<?> found = cacheQuery.iterator()) { assertTrue(found.hasNext()); found.next(); assertFalse(found.hasNext()); found.next(); } } public void testMultipleResults() { loadTestingData(); Query<Person> cacheQuery = createQuery("name:'goat'", Person.class); QueryResult<Person> result = cacheQuery.execute(); List<Person> found = result.list(); assert found.size() == 2; assertEquals(2, getNumberOfHits(result)); assertTrue(found.contains(person2)); assertTrue(found.contains(person3)); StaticTestingErrorHandler.assertAllGood(cache); } public void testModified() { loadTestingData(); Query<Person> cacheQuery = createQuery("blurb:'playing'", Person.class); List<Person> found = cacheQuery.execute().list(); assert found.size() == 1; assert found.get(0).equals(person1); person1.setBlurb("Likes pizza"); cache.put(key1, person1); cacheQuery = createQuery("blurb:'pizza'", Person.class); found = cacheQuery.execute().list(); assert found.size() == 1; assert found.get(0).equals(person1); StaticTestingErrorHandler.assertAllGood(cache); } public void testAdded() { loadTestingData(); Query<Person> cacheQuery = createQuery("name:'Goat'", Person.class); QueryResult<Person> result = cacheQuery.execute(); List<Person> found = result.list(); assertEquals(2, found.size()); assertEquals(2, getNumberOfHits(result)); assertTrue(found.contains(person2)); assertTrue(found.contains(person3)); assertFalse(found.contains(person4)); person4 = new Person(); person4.setName("Mighty Goat"); person4.setBlurb("Also eats grass"); cache.put("mighty", person4); cacheQuery = createQuery("name:'Goat'", Person.class); found = cacheQuery.execute().list(); assert found.size() == 3 : "Size of list should be 3"; assert found.contains(person2); assert found.contains(person3); assert found.contains(person4) : "This should now contain object person4"; StaticTestingErrorHandler.assertAllGood(cache); } public void testRemoved() { loadTestingData(); Query<Person> cacheQuery = createQuery("name:'Goat'", Person.class); QueryResult<Person> result = cacheQuery.execute(); List<Person> found = result.list(); assertEquals(2, found.size()); assertEquals(2, getNumberOfHits(result)); assertTrue(found.contains(person2)); assertTrue(found.contains(person3)); cache.remove(key3); cacheQuery = createQuery("name:'Goat'", Person.class); found = cacheQuery.execute().list(); assertEquals(1, found.size()); assertTrue(found.contains(person2)); assertFalse(found.contains(person3)); StaticTestingErrorHandler.assertAllGood(cache); } public void testUpdated() { loadTestingData(); Query<Person> cacheQuery = createQuery("name:'Goat'", Person.class); QueryResult<Person> result = cacheQuery.execute(); List<Person> found = result.list(); assertEquals(2, found.size()); assertEquals(2, getNumberOfHits(result)); assertTrue(found.contains(person2)); cache.put(key2, person1); cacheQuery = createQuery("name:'Goat'", Person.class); result = cacheQuery.execute(); found = result.list(); assertEquals(1, found.size()); assertEquals(1, getNumberOfHits(result)); assertFalse(found.contains(person2)); assertFalse(found.contains(person1)); StaticTestingErrorHandler.assertAllGood(cache); } public void testSetSort() { loadTestingData(); String queryString = String.format("FROM %s p WHERE p.name:'Goat' ORDER BY p.age", Person.class.getName()); Query<Person> cacheQuery = Search.<Person>getQueryFactory(cache).create(queryString); QueryResult<Person> result = cacheQuery.execute(); List<Person> found = result.list(); assertEquals(2, found.size()); found = cacheQuery.execute().list(); assertEquals(2, found.size()); assertEquals(person3, found.get(0)); // person3 is 25 and named Goat assertEquals(person2, found.get(1)); // person2 is 30 and named Goat StaticTestingErrorHandler.assertAllGood(cache); //Now change the stored values: person2.setAge(10); cache.put(key2, person2); found = cacheQuery.execute().list(); assertEquals(2, found.size()); found = cacheQuery.execute().list(); assertEquals(2, found.size()); assertEquals(person2, found.get(0)); // person2 is 10 and named Goat assertEquals(person3, found.get(1)); // person3 is 25 and named Goat StaticTestingErrorHandler.assertAllGood(cache); } public void testSetFilter() { loadTestingData(); Query<?> cacheQuery = createQuery("name:'goat'", Person.class); List<?> found = cacheQuery.execute().list(); assertEquals(2, found.size()); cacheQuery = createQuery("name:'goat' AND blurb:'cheese'", Person.class); found = cacheQuery.execute().list(); assertEquals(1, found.size()); StaticTestingErrorHandler.assertAllGood(cache); } public void testLazyIterator() { loadTestingData(); Query<?> cacheQuery = createQuery("blurb:'playing'", Person.class); try (CloseableIterator<?> found = cacheQuery.iterator()) { assertTrue(found.hasNext()); found.next(); assertFalse(found.hasNext()); } StaticTestingErrorHandler.assertAllGood(cache); } public void testIteratorWithDefaultOptions() { loadTestingData(); Query<?> cacheQuery = createQuery("blurb:'playing'", Person.class); try (CloseableIterator<?> found = cacheQuery.iterator()) { assertTrue(found.hasNext()); found.next(); assertFalse(found.hasNext()); } StaticTestingErrorHandler.assertAllGood(cache); } @Test(expectedExceptions = UnsupportedOperationException.class) public void testIteratorRemove() { loadTestingData(); Query<?> cacheQuery = createQuery("blurb:'Eats'", Person.class); try (CloseableIterator<?> iterator = cacheQuery.iterator()) { if (iterator.hasNext()) { iterator.next(); iterator.remove(); } } StaticTestingErrorHandler.assertAllGood(cache); } public void testLazyIteratorWithOffset() { loadTestingData(); Query<?> cacheQuery = createQuery("blurb:'Eats'", Person.class).startOffset(1); try (CloseableIterator<?> iterator = cacheQuery.iterator()) { assertEquals(1, countElements(iterator)); } StaticTestingErrorHandler.assertAllGood(cache); } @Test(expectedExceptions = IllegalArgumentException.class) public void testSearchManagerWithNullCache() { Search.getQueryFactory(null); } @Test(expectedExceptions = NoSuchElementException.class) public void testLazyIteratorWithNoElementsFound() { loadTestingData(); Query<?> cacheQuery = createQuery("blurb:'fish'", Person.class).startOffset(1); try (CloseableIterator<?> found = cacheQuery.iterator()) { found.next(); } } public void testSearchKeyTransformer() { loadTestingDataWithCustomKey(); Query<Person> cacheQuery = createQuery("blurb:'Eats'", Person.class); try (CloseableIterator<Person> iterator = cacheQuery.iterator()) { assertEquals(2, countElements(iterator)); } StaticTestingErrorHandler.assertAllGood(cache); } @Test(expectedExceptions = IllegalArgumentException.class) public void testSearchWithWrongCache() { Cache<?, ?> cache = mock(CacheImpl.class); when(cache.getAdvancedCache()).thenReturn(null); Search.getQueryFactory(cache); } //Another test just for covering Search.java instantiation, although it is unnecessary. As well as covering the //valueOf() method of FetchMode, again just for adding coverage. public void testSearchManagerWithInstantiation() { loadTestingData(); Query<?> cacheQuery = createQuery("blurb:'playing'", Person.class); try (CloseableIterator<?> found = cacheQuery.iterator()) { assertTrue(found.hasNext()); found.next(); assertFalse(found.hasNext()); } } public void testGetResultSize() { loadTestingData(); Query<?> cacheQuery = createQuery("blurb:'playing'", Person.class); assertEquals(1, getNumberOfHits(cacheQuery.execute())); StaticTestingErrorHandler.assertAllGood(cache); } public void testMaxResults() { loadTestingData(); Query<Person> cacheQuery = createQuery("blurb:'eats'", Person.class).maxResults(1); QueryResult<Person> result = cacheQuery.execute(); assertEquals(2, getNumberOfHits(result)); // NOTE: getResultSize() ignores pagination (maxResults, firstResult) assertEquals(1, result.list().size()); try (CloseableIterator<?> eagerIterator = cacheQuery.iterator()) { assertEquals(1, countElements(eagerIterator)); } StaticTestingErrorHandler.assertAllGood(cache); } private int countElements(Iterator<?> iterator) { int count = 0; while (iterator.hasNext()) { iterator.next(); count++; } return count; } public void testClear() { loadTestingData(); String predicate = "name:'navin' OR name:'goat'"; Query<Person> cacheQuery = createQuery(predicate, Person.class); // We know that we've got all 3 hits. assertEquals(3, getNumberOfHits(cacheQuery.execute())); cache.clear(); cacheQuery = createQuery(predicate, Person.class); assertEquals(0, getNumberOfHits(cacheQuery.execute())); StaticTestingErrorHandler.assertAllGood(cache); } public void testTypeFiltering() { loadTestingData(); Query<?> cacheQuery = createQuery("blurb:'grass'", Person.class); List<?> found = cacheQuery.execute().list(); assertEquals(1, found.size()); assertTrue(found.contains(person2)); cacheQuery = createQuery("blurb:'grass'", AnotherGrassEater.class); found = cacheQuery.execute().list(); assertEquals(1, found.size()); assertEquals(found.get(0), anotherGrassEater); StaticTestingErrorHandler.assertAllGood(cache); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg .indexing() .enable() .storage(LOCAL_HEAP) .addKeyTransformer(CustomKey3.class, CustomKey3Transformer.class) .addIndexedEntity(Person.class) .addIndexedEntity(AnotherGrassEater.class); enhanceConfig(cfg); return TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE, cfg); } @Override protected void teardown() { if (cache != null) { // a proper cache.clear() should ensure indexes and stores are cleared too if present // this is better and more complete than the cleanup performed by the superclass cache.clear(); } super.teardown(); } protected void loadTestingData() { prepareTestingData(); cache.put(key1, person1); // person2 is verified as number of matches in multiple tests, // so verify duplicate insertion doesn't affect result counts: cache.put(key2, person2); cache.put(key2, person2); cache.put(key2, person2); cache.put(key3, person3); cache.put(anotherGrassEaterKey, anotherGrassEater); StaticTestingErrorHandler.assertAllGood(cache); } protected void loadTestingDataWithCustomKey() { prepareTestingData(); CustomKey3 customeKey1 = new CustomKey3(key1); CustomKey3 customeKey2 = new CustomKey3(key2); CustomKey3 customeKey3 = new CustomKey3(key3); cache.put(customeKey1, person1); // person2 is verified as number of matches in multiple tests, // so verify duplicate insertion doesn't affect result counts: cache.put(customeKey2, person2); cache.put(customeKey2, person2); cache.put(customeKey2, person2); cache.put(customeKey3, person3); cache.put(anotherGrassEaterKey, anotherGrassEater); StaticTestingErrorHandler.assertAllGood(cache); } private void prepareTestingData() { person1 = new Person(); person1.setName("Navin Surtani"); person1.setAge(20); person1.setBlurb("Likes playing WoW"); person1.setNonIndexedField("test1"); person2 = new Person(); person2.setName("Big Goat"); person2.setAge(30); person2.setBlurb("Eats grass"); person2.setNonIndexedField("test2"); person3 = new Person(); person3.setName("Mini Goat"); person3.setAge(25); person3.setBlurb("Eats cheese"); person3.setNonIndexedField("test3"); anotherGrassEater = new AnotherGrassEater("Another grass-eater", "Eats grass"); StaticTestingErrorHandler.assertAllGood(cache); } protected void enhanceConfig(ConfigurationBuilder c) { // no op, meant to be overridden } private long getNumberOfHits(QueryResult<?> queryResult) { return queryResult.count().value(); } }
17,997
32.084559
119
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/LocalCacheAsyncCacheStoreTest.java
package org.infinispan.query.blackbox; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.testng.AssertJUnit.assertTrue; import java.io.File; import org.infinispan.commons.util.Util; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Testing the ISPN Directory configuration with Async. FileCacheStore. The tests are performed on Local cache. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.blackbox.LocalCacheAsyncCacheStoreTest") public class LocalCacheAsyncCacheStoreTest extends LocalCacheTest { private final String indexDirectory = tmpDirectory("asyncStore"); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { cacheManager = TestCacheManagerFactory.fromXml("async-file-store-config.xml"); cache = cacheManager.getCache("queryCache_lucenestore_async_filestore"); return cacheManager; } @Override protected void setup() throws Exception { Util.recursiveFileRemove(indexDirectory); boolean created = new File(indexDirectory).mkdirs(); assertTrue(created); super.setup(); } @Override protected void teardown() { try { super.teardown(); } finally { Util.recursiveFileRemove(indexDirectory); } } }
1,418
29.191489
111
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/ObjectStorageClusteredCacheTest.java
package org.infinispan.query.blackbox; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT_TYPE; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.test.CustomKey3; import org.infinispan.query.test.CustomKey3Transformer; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.testng.annotations.Test; /** * Verify queries with configured media type as objects. * * @author Martin Gencur * @since 6.0 */ @Test(groups = "functional", testName = "query.blackbox.ObjectStorageClusteredCacheTest") public class ObjectStorageClusteredCacheTest extends ClusteredCacheTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, transactionsEnabled()); cacheCfg .encoding().key().mediaType(APPLICATION_OBJECT_TYPE) .encoding().value().mediaType(APPLICATION_OBJECT_TYPE) .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class) .addKeyTransformer(CustomKey3.class, CustomKey3Transformer.class); enhanceConfig(cacheCfg); createClusteredCaches(2, QueryTestSCI.INSTANCE, cacheCfg); cache1 = cache(0); cache2 = cache(1); } }
1,506
35.756098
113
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/TopologyAwareClusteredQueryTest.java
package org.infinispan.query.blackbox; import static org.infinispan.query.helper.TestQueryHelperFactory.createTopologyAwareCacheNodes; import java.util.List; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.test.Person; import org.testng.annotations.Test; /** * Tests for testing clustered queries functionality on topology aware nodes. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.blackbox.TopologyAwareClusteredQueryTest") public class TopologyAwareClusteredQueryTest extends ClusteredQueryTest { @Override protected void createCacheManagers() throws Throwable { List<EmbeddedCacheManager> managers = createTopologyAwareCacheNodes(2, getCacheMode(), transactionEnabled(), isIndexLocalOnly(), isRamDirectory(), "default", Person.class); registerCacheManager(managers); cacheAMachine1 = cache(0); cacheAMachine2 = cache(1); queryFactory1 = Search.getQueryFactory(cacheAMachine1); queryFactory2 = Search.getQueryFactory(cacheAMachine2); waitForClusterToForm(); populateCache(); } public CacheMode getCacheMode() { return CacheMode.REPL_SYNC; } public boolean isIndexLocalOnly() { return true; } public boolean isRamDirectory() { return true; } public boolean transactionEnabled() { return false; } }
1,618
29.54717
114
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/ClusteredQueryEmptyIndexTest.java
package org.infinispan.query.blackbox; import java.util.stream.IntStream; import org.infinispan.query.helper.StaticTestingErrorHandler; import org.infinispan.query.test.Person; import org.testng.annotations.Test; /** * Tests for clustered queries where some of the local indexes are empty * @since 9.1 */ @Test(groups = "functional", testName = "query.blackbox.ClusteredQueryEmptyIndexTest") public class ClusteredQueryEmptyIndexTest extends ClusteredQueryTest { protected void prepareTestData() { IntStream.range(0, NUM_ENTRIES).boxed() .map(i -> new Person("name" + i, "blurb" + i, i)).forEach(p -> cacheAMachine1.put(p.getName(), p)); StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } }
754
30.458333
111
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/LocalCachePerfProgrammaticConfTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertTrue; import java.io.File; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.test.AnotherGrassEater; import org.infinispan.query.test.CustomKey3; import org.infinispan.query.test.CustomKey3Transformer; import org.infinispan.query.test.Person; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Testing the tuned options with programmatic configuration. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.blackbox.LocalCachePerfProgrammaticConfTest") public class LocalCachePerfProgrammaticConfTest extends LocalCacheTest { private final String indexDirectory = CommonsTestingUtil.tmpDirectory(getClass()); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg .indexing() .enable() .storage(LOCAL_HEAP) .path(indexDirectory) .addIndexedEntity(Person.class) .addIndexedEntity(AnotherGrassEater.class) .addKeyTransformer(CustomKey3.class, CustomKey3Transformer.class) .writer().threadPoolSize(6).queueCount(6).queueSize(4096); enhanceConfig(cfg); return TestCacheManagerFactory.createCacheManager(cfg); } @Override protected void setup() throws Exception { Util.recursiveFileRemove(indexDirectory); boolean created = new File(indexDirectory).mkdirs(); assertTrue(created); super.setup(); } @Override protected void teardown() { try { super.teardown(); } finally { Util.recursiveFileRemove(indexDirectory); } } }
2,048
31.52381
92
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/TopologyAwareDistributedCacheTest.java
package org.infinispan.query.blackbox; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.Test; /** * Testing query functionality on RAM directory for DIST_SYNC cache mode with enabled Topology aware nodes. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.blackbox.TopologyAwareDistributedCacheTest") public class TopologyAwareDistributedCacheTest extends TopologyAwareClusteredCacheTest { @Override public CacheMode getCacheMode() { return CacheMode.DIST_SYNC; } }
547
27.842105
107
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/LocalIndexSyncStateTransferTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.functional.FunctionalTestUtils.await; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.stream.Collectors; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.Search; import org.infinispan.query.core.stats.IndexInfo; import org.infinispan.query.core.stats.IndexStatistics; import org.infinispan.query.test.AnotherGrassEater; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.Test; /** * Tests for correctness of local indexes syncing during state transfer */ @Test(groups = "functional", testName = "query.blackbox.LocalIndexStateTransferTest") public class LocalIndexSyncStateTransferTest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { createClusteredCaches(2, QueryTestSCI.INSTANCE, getBuilder()); } protected ConfigurationBuilder getBuilder() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class) .addIndexedEntity(AnotherGrassEater.class); return builder; } private void assertIndexesSynced() { List<Cache<Integer, Object>> caches = caches(); caches.forEach(this::assertIndexesSynced); } private Map<String, Long> getIndexCountPerEntity(Cache<Integer, Object> cache) { IndexStatistics indexStatistics = Search.getSearchStatistics(cache).getIndexStatistics(); Map<String, IndexInfo> stringIndexInfoMap = await(indexStatistics.computeIndexInfos().toCompletableFuture()); return stringIndexInfoMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().count())); } private void assertIndexesSynced(Cache<Integer, Object> c) { String address = c.getAdvancedCache().getRpcManager().getAddress().toString(); Map<Class<?>, AtomicInteger> countPerEntity = getEntityCountPerClass(c); Map<String, Long> indexInfo = getIndexCountPerEntity(c); countPerEntity.forEach((entity, count) -> { long indexed = indexInfo.get(entity.getName()); Supplier<String> messageSupplier = () -> String.format("On node %s index contains %d entries for entity %s," + " but data container has %d", address, indexed, entity.getName(), count.get()); eventually(messageSupplier, () -> indexed == count.get()); }); } protected Map<Class<?>, AtomicInteger> getEntityCountPerClass(Cache<Integer, Object> c) { Map<Class<?>, AtomicInteger> countPerEntity = new HashMap<>(); c.getAdvancedCache().getDataContainer().forEach(e -> { Class<?> entity = e.getValue().getClass(); countPerEntity.computeIfAbsent(entity, aClass -> new AtomicInteger(0)).incrementAndGet(); }); return countPerEntity; } public void testIndexSyncedDuringST() { // Populate caches Cache<Integer, Person> cache = cache(0); for (int i = 0; i < 10; i++) { cache.put(i, new Person("person" + i, "blurb" + i, i + 10)); } assertIndexesSynced(); // Add a new Node addClusterEnabledCacheManager(QueryTestSCI.INSTANCE, getBuilder()).getCache(); assertIndexesSynced(); // Remove a node killMember(2); assertIndexesSynced(); } }
3,802
39.457447
124
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/LocalCacheFSDirectoryTest.java
package org.infinispan.query.blackbox; import static org.testng.AssertJUnit.assertTrue; import java.io.File; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.IndexStorage; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.test.AnotherGrassEater; import org.infinispan.query.test.CustomKey3; import org.infinispan.query.test.CustomKey3Transformer; import org.infinispan.query.test.Person; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Run the basic set of operations with filesystem-based index storage. * The default FSDirectory implementation for non Windows systems should be NIOFSDirectory. * SimpleFSDirectory implementation will be used on Windows. * * @author Martin Gencur */ @Test(groups = "functional", testName = "query.blackbox.LocalCacheFSDirectoryTest") public class LocalCacheFSDirectoryTest extends LocalCacheTest { private final String indexDirectory = CommonsTestingUtil.tmpDirectory(getClass()); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg.indexing().enable() .storage(IndexStorage.FILESYSTEM).path(indexDirectory) .addIndexedEntity(Person.class) .addIndexedEntity(AnotherGrassEater.class) .addKeyTransformer(CustomKey3.class, CustomKey3Transformer.class); return TestCacheManagerFactory.createCacheManager(cfg); } @Override protected void setup() throws Exception { Util.recursiveFileRemove(indexDirectory); boolean created = new File(indexDirectory).mkdirs(); assertTrue(created); super.setup(); } @Override protected void teardown() { try { super.teardown(); } finally { Util.recursiveFileRemove(indexDirectory); } } }
2,052
33.79661
91
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/IndexedCacheRestartTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.test.TestingUtil.extractInterceptorChain; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.InterceptorConfiguration; import org.infinispan.configuration.cache.InterceptorConfiguration.Position; import org.infinispan.interceptors.AsyncInterceptor; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.backend.QueryInterceptor; import org.infinispan.query.dsl.Query; import org.infinispan.query.indexedembedded.Book; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Tests whether indexed caches can restart without problems. * * @author Galder Zamarreño * @author Sanne Grinovero * @author Marko Luksa * @since 5.2 */ @Test(testName = "query.blackbox.IndexedCacheRestartTest", groups = "functional") public class IndexedCacheRestartTest extends AbstractInfinispanTest { private EmbeddedCacheManager cm; public void testLocalIndexedCacheRestart() throws Exception { indexedCacheRestart(false); } public void testLocalIndexedCacheRestartManager() throws Exception { indexedCacheRestart(true); } private void indexedCacheRestart(boolean stopManager) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Book.class); // Test that the query module doesn't break user-configured custom interceptors // Not needed since ISPN-10262, as the query module is no longer configuring any custom interceptors final NoOpInterceptor noOpInterceptor = new NoOpInterceptor(); builder.customInterceptors().addInterceptor().interceptor(noOpInterceptor).position(Position.FIRST); cm = TestCacheManagerFactory.createCacheManager(builder); Cache<String, Book> cache = cm.getCache(); assertNotNull(extractInterceptorChain(cache).findInterceptorExtending(QueryInterceptor.class)); assertTrue(cache.isEmpty()); addABook(cache); assertFindBook(cache); if (stopManager) { cm.stop(); cm = TestCacheManagerFactory.createCacheManager(builder); cache = cm.getCache(); } else { cache.stop(); assertCacheHasCustomInterceptor(cache, noOpInterceptor); cache.start(); } assertNotNull(extractInterceptorChain(cache).findInterceptorExtending(QueryInterceptor.class)); assertTrue(cache.isEmpty()); //stopped cache lost all data, and in memory index is lost: re-store both //(not needed with permanent indexes and caches using a cachestore) addABook(cache); assertFindBook(cache); assertCacheHasCustomInterceptor(cache, noOpInterceptor); } private void addABook(Cache<String, Book> cache) { cache.put("1", new Book("Infinispan Data Grid Platform", "Francesco Marchioni and Manik Surtani", "Packt Publishing")); } private void assertCacheHasCustomInterceptor(Cache<?, ?> cache, AsyncInterceptor interceptor) { for (InterceptorConfiguration interceptorConfig : cache.getCacheConfiguration().customInterceptors().interceptors()) { if (interceptor == interceptorConfig.asyncInterceptor()) { return; } } fail("Expected to find interceptor " + interceptor + " among custom interceptors of cache, but it was not there."); } private static void assertFindBook(Cache<?, ?> cache) { String q = String.format("FROM %s WHERE title:'infinispan'", Book.class.getName()); Query cacheQuery = Search.getQueryFactory(cache).create(q); List<Book> list = cacheQuery.list(); assertEquals(1, list.size()); } @AfterMethod(alwaysRun = true) public void stopManager() { cm.stop(); } static class NoOpInterceptor extends DDAsyncInterceptor { } }
4,494
36.14876
124
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/DistributedCacheClusteredQueryTest.java
package org.infinispan.query.blackbox; import static org.testng.AssertJUnit.assertEquals; import java.util.List; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.testng.annotations.Test; /** * Testing Clustered distributed queries on Distributed cache. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.blackbox.DistributedCacheClusteredQueryTest") public class DistributedCacheClusteredQueryTest extends ClusteredQueryTest { public CacheMode getCacheMode() { return CacheMode.DIST_SYNC; } @Override protected int numOwners() { return 1; } @Test public void testIndexedQueryLocalOnly() { QueryFactory queryFactoryA = Search.getQueryFactory(cache(0)); QueryFactory queryFactoryB = Search.getQueryFactory(cache(1)); final Query<Object> normalQueryA = queryFactoryA.create(queryString); final Query<Object> normalQueryB = queryFactoryB.create(queryString); assertEquals(10, normalQueryA.execute().count().value()); assertEquals(10, normalQueryB.execute().count().value()); List<?> results1 = normalQueryA.local(true).execute().list(); List<?> results2 = normalQueryB.local(true).execute().list(); assertEquals(10, results1.size() + results2.size()); } @Test public void testNonIndexedQueryLocalOnly() { String q = "FROM org.infinispan.query.test.Person p where p.nonIndexedField = 'na'"; QueryFactory queryFactoryA = Search.getQueryFactory(cache(0)); QueryFactory queryFactoryB = Search.getQueryFactory(cache(1)); List<?> results1 = queryFactoryA.create(q).local(true).execute().list(); List<?> results2 = queryFactoryB.create(q).local(true).execute().list(); assertEquals(NUM_ENTRIES, results1.size() + results2.size()); q = "SELECT COUNT(nonIndexedField) FROM org.infinispan.query.test.Person GROUP BY nonIndexedField"; results1 = queryFactoryA.create(q).local(true).execute().list(); results2 = queryFactoryB.create(q).local(true).execute().list(); final Object[] row1 = (Object[]) results1.get(0); final Object[] row2 = (Object[]) results2.get(0); assertEquals(NUM_ENTRIES, (long) row1[0] + (long) row2[0]); } }
2,370
32.871429
105
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/LocalCachePerformantConfTest.java
package org.infinispan.query.blackbox; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.testng.AssertJUnit.assertTrue; import java.io.File; import org.infinispan.commons.util.Util; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Tests the functionality of the queries in case when the NRT index manager is used in combination with FileStore. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.blackbox.LocalCachePerformantConfTest") public class LocalCachePerformantConfTest extends LocalCacheTest { /** * The file constant needs to match what's defined in the configuration file. */ private final String indexDirectory = tmpDirectory("LocalCachePerformantConfTest"); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { cacheManager = TestCacheManagerFactory.fromXml("testconfig-LocalCachePerformantConfTest.xml"); cache = cacheManager.getCache("Indexed"); return cacheManager; } @Override protected void setup() throws Exception { Util.recursiveFileRemove(indexDirectory); boolean created = new File(indexDirectory).mkdirs(); assertTrue(created); super.setup(); } @Override protected void teardown() { try { super.teardown(); } finally { Util.recursiveFileRemove(indexDirectory); } } }
1,518
29.38
115
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/LocalCachePerfIspnDirConfTest.java
package org.infinispan.query.blackbox; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Tests the functionality of the queries in case when the NRT index manager is used in combination with ISPN Directory. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.blackbox.LocalCachePerfIspnDirConfTest") public class LocalCachePerfIspnDirConfTest extends LocalCacheTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { cacheManager = TestCacheManagerFactory.fromXml("nrt-performance-writer-infinispandirectory.xml"); cache = cacheManager.getCache("Indexed"); return cacheManager; } }
772
34.136364
120
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/ClusteredDistCacheTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.test.CustomKey3; import org.infinispan.query.test.CustomKey3Transformer; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.testng.annotations.Test; /** * @since 9.1 */ @Test(groups = {"functional"}, testName = "query.blackbox.ClusteredDistCacheTest") public class ClusteredDistCacheTest extends ClusteredCacheTest { protected Cache<Object, Person> cache3; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); cacheCfg.indexing() .enable() .storage(LOCAL_HEAP) .addKeyTransformer(CustomKey3.class, CustomKey3Transformer.class) .addIndexedEntity(Person.class); enhanceConfig(cacheCfg); createClusteredCaches(3, QueryTestSCI.INSTANCE, cacheCfg); cache1 = cache(0); cache2 = cache(1); cache3 = cache(2); } }
1,256
31.230769
97
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/ClusteredQueryTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.AssertJUnit.assertEquals; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.StreamSupport; import org.apache.lucene.index.IndexReader; import org.infinispan.Cache; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.HashConfiguration; import org.infinispan.configuration.cache.StorageType; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.query.helper.IndexAccessor; import org.infinispan.query.helper.StaticTestingErrorHandler; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * ClusteredQueryTest. * @author Israel Lacerra &lt;israeldl@gmail.com&gt; * @since 5.1 */ @Test(groups = "functional", testName = "query.blackbox.ClusteredQueryTest") public class ClusteredQueryTest extends MultipleCacheManagersTest { static final int NUM_ENTRIES = 50; Cache<String, Person> cacheAMachine1, cacheAMachine2; private Query<Person> cacheQuery; protected String queryString = String.format("FROM %s where blurb:'blurb1?'", Person.class.getName()); private final String allPersonsQuery = "FROM " + Person.class.getName(); protected QueryFactory queryFactory1; protected QueryFactory queryFactory2; @Override public Object[] factory() { return new Object[]{ new ClusteredQueryTest().storageType(StorageType.OFF_HEAP), new ClusteredQueryTest().storageType(StorageType.BINARY), new ClusteredQueryTest().storageType(StorageType.OBJECT), }; } @AfterMethod @Override protected void clearContent() { // Leave it be } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(getCacheMode(), false); cacheCfg .clustering().hash().numOwners(numOwners()) .indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); if (storageType != null) { cacheCfg.memory() .storageType(storageType); } createClusteredCaches(2, QueryTestSCI.INSTANCE, cacheCfg); cacheAMachine1 = cache(0); cacheAMachine2 = cache(1); queryFactory1 = Search.getQueryFactory(cacheAMachine1); queryFactory2 = Search.getQueryFactory(cacheAMachine2); populateCache(); } protected CacheMode getCacheMode() { return CacheMode.REPL_SYNC; } protected int numOwners() { return HashConfiguration.NUM_OWNERS.getDefaultValue(); } protected void prepareTestData() { IntStream.range(0, NUM_ENTRIES).boxed() .map(i -> new Person("name" + i, "blurb" + i, i)) .forEach(p -> { Cache<String, Person> cache = p.getAge() % 2 == 0 ? cacheAMachine1 : cacheAMachine2; cache.put(p.getName(), p); }); StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } // TODO HSEARCH-3323 Restore support for scrolling @Test(enabled = false) public void testLazyOrdered() { Query<Person> cacheQuery = createSortedQuery(); for (int i = 0; i < 2; i++) { try (CloseableIterator<Person> iterator = cacheQuery.iterator()) { assertEquals(10, cacheQuery.execute().count().value()); int previousAge = 0; while (iterator.hasNext()) { Person person = iterator.next(); assertTrue(person.getAge() > previousAge); previousAge = person.getAge(); } } } StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } // TODO HSEARCH-3323 Restore support for scrolling @Test(enabled = false) public void testLazyNonOrdered() { try (CloseableIterator<Person> ignored = cacheQuery.iterator()) { assertEquals(10, cacheQuery.execute().count().value()); } StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } public void testLocalQuery() { final Query<Person> localQuery1 = queryFactory1.create(queryString); List<Person> results1 = localQuery1.execute().list(); final Query<Person> localQuery2 = queryFactory1.create(queryString); List<Person> results2 = localQuery2.execute().list(); assertEquals(10, results1.size()); assertEquals(10, results2.size()); StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } public void testEagerOrdered() { Query<Person> cacheQuery = createSortedQuery(); try (CloseableIterator<Person> iterator = cacheQuery.iterator()) { assertEquals(10, cacheQuery.execute().count().value()); int previousAge = 0; while (iterator.hasNext()) { Person person = iterator.next(); assertTrue(person.getAge() > previousAge); previousAge = person.getAge(); } } StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } @Test(expectedExceptions = NoSuchElementException.class) public void testIteratorNextOutOfBounds() { cacheQuery.maxResults(1); try (CloseableIterator<Person> iterator = cacheQuery.iterator()) { assertTrue(iterator.hasNext()); iterator.next(); assertFalse(iterator.hasNext()); iterator.next(); } StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } @Test(expectedExceptions = UnsupportedOperationException.class) public void testIteratorRemove() { cacheQuery.maxResults(1); try (CloseableIterator<Person> iterator = cacheQuery.iterator()) { assert iterator.hasNext(); iterator.remove(); } StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } public void testList() { Query<Person> cacheQuery = createSortedQuery(); QueryResult<Person> result = cacheQuery.execute(); List<Person> results = result.list(); assertEquals(10, result.count().value()); int previousAge = 0; for (Person person : results) { assertTrue(person.getAge() > previousAge); previousAge = person.getAge(); } StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } public void testGetResultSizeList() { assertEquals(10, cacheQuery.execute().list().size()); } public void testPagination() { Query<Person> cacheQuery = createSortedQuery(); cacheQuery.startOffset(2); cacheQuery.maxResults(1); QueryResult<Person> results = cacheQuery.execute(); List<Person> list = results.list(); assertEquals(1, list.size()); assertEquals(10, results.count().value()); Person result = list.get(0); assertEquals(12, result.getAge()); StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } @Test public void testPagination2() { int[] pageSizes = new int[]{1, 5, 7, NUM_ENTRIES + 10}; for (int pageSize : pageSizes) { testPaginationWithoutSort(pageSize); testPaginationWithSort(pageSize, "age"); } } private void testPaginationWithoutSort(int pageSize) { testPaginationInternal(pageSize, null); } private void testPaginationWithSort(int pageSize, String sortField) { testPaginationInternal(pageSize, sortField); } private void testPaginationInternal(int pageSize, String sortField) { Query<Person> paginationQuery = buildPaginationQuery(0, pageSize, sortField); int idx = 0; Set<String> keys = new HashSet<>(); while (idx < NUM_ENTRIES) { List<Person> results = paginationQuery.execute().list(); results.stream().map(Person::getName).forEach(keys::add); idx += pageSize; paginationQuery = buildPaginationQuery(idx, pageSize, sortField); } assertEquals(NUM_ENTRIES, keys.size()); StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } private Query<Person> buildPaginationQuery(int offset, int pageSize, String sortField) { String sortedQuery = sortField != null ? allPersonsQuery + " ORDER BY " + sortField : allPersonsQuery; Query<Person> clusteredQuery = queryFactory1.create(sortedQuery); clusteredQuery.startOffset(offset); clusteredQuery.maxResults(pageSize); return clusteredQuery; } public void testQueryAll() { Query<Person> clusteredQuery = queryFactory1.create(allPersonsQuery); assertEquals(NUM_ENTRIES, clusteredQuery.execute().list().size()); StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } public void testFuzzyQuery() { populateCache(); String q = String.format("FROM %s WHERE name:'name1'~2", Person.class.getName()); Query<Person> clusteredQuery = queryFactory1.create(q); assertEquals(NUM_ENTRIES, clusteredQuery.execute().list().size()); StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } public void testBroadcastIckleMatchAllQuery() { Query<Person> everybody = queryFactory1.create(String.format("FROM %s", Person.class.getName())); assertEquals(NUM_ENTRIES, everybody.execute().list().size()); StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } public void testBroadcastIckleTermQuery() { String targetName = "name2"; Query<Person> singlePerson = queryFactory1.create(String.format("FROM %s p where p.name:'%s'", Person.class.getName(), targetName)); assertEquals(1, singlePerson.execute().list().size()); assertEquals(targetName, singlePerson.iterator().next().getName()); StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } public void testBroadcastFuzzyIckle() { Query<Person> persons0to10 = queryFactory1.create(String.format("FROM %s p where p.name:'nome'~2", Person.class.getName())); assertEquals(10, persons0to10.execute().list().size()); StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } public void testBroadcastNumericRangeQuery() { Query<Person> infants = queryFactory1 .create(String.format("FROM %s p where p.age between 0 and 5", Person.class.getName())); assertEquals(6, infants.execute().list().size()); StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } public void testBroadcastProjectionIckleQuery() { Query<Object[]> onlyNames = queryFactory2.create( String.format("Select p.name FROM %s p", Person.class.getName())); List<Object[]> results = onlyNames.execute().list(); assertEquals(NUM_ENTRIES, results.size()); Set<String> names = new HashSet<>(); results.iterator().forEachRemaining(s -> names.add((String) s[0])); Set<String> allNames = IntStream.range(0, NUM_ENTRIES).boxed().map(i -> "name" + i).collect(Collectors.toSet()); assertEquals(allNames, names); StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } public void testBroadcastSortedIckleQuery() { Query<Person> theLastWillBeFirst = queryFactory2.create( String.format("FROM %s p order by p.age desc", Person.class.getName())); List<Person> results = theLastWillBeFirst.execute().list(); assertEquals(NUM_ENTRIES, results.size()); assertEquals(NUM_ENTRIES - 1, results.iterator().next().getAge()); StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } public void testPaginatedIckleQuery() { Query<Person> q = queryFactory1.create(String.format("FROM %s p order by p.age", Person.class.getName())); q.startOffset(5); q.maxResults(10); List<Person> results = q.execute().list(); assertEquals(10, results.size()); assertEquals("name5", results.iterator().next().getName()); assertEquals("name14", results.get(9).getName()); } private int countLocalIndex(Cache<String, Person> cache) throws IOException { IndexReader indexReader = IndexAccessor.of(cache, Person.class).getIndexReader(); return indexReader.numDocs(); } @Test public void testHybridQueryWorks() { Query<Person> hybridQuery = queryFactory1 .create(String.format("FROM %s p where p.nonIndexedField = 'nothing'", Person.class.getName())); hybridQuery.execute(); } @Test public void testAggregationQueriesWork() { Query<Person> aggregationQuery = queryFactory1 .create(String.format("SELECT p.name FROM %s p where p.name:'name3' group by p.name", Person.class.getName())); aggregationQuery.execute().list(); } @Test public void testBroadcastNativeInfinispanHybridQuery() { String q = "FROM " + Person.class.getName() + " where age >= 40 and nonIndexedField = 'na'"; Query<?> query = queryFactory1.create(q); assertEquals(10, query.execute().list().size()); } @Test public void testBroadcastNativeInfinispanFuzzyQuery() { String q = String.format("FROM %s p where p.name:'nome'~2", Person.class.getName()); Query<?> query = Search.getQueryFactory(cacheAMachine1).create(q); assertEquals(10, query.execute().list().size()); } @Test public void testBroadcastSortedInfinispanQuery() { QueryFactory queryFactory = Search.getQueryFactory(cacheAMachine1); Query<Person> sortedQuery = queryFactory.create("FROM " + Person.class.getName() + " p order by p.age desc"); List<Person> results = sortedQuery.execute().list(); assertEquals(NUM_ENTRIES, results.size()); assertEquals(NUM_ENTRIES - 1, results.iterator().next().getAge()); StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } // TODO HSEARCH-3323 Restore support for scrolling @Test(enabled = false) public void testIckleProjectionsLazyRetrieval() { String query = String.format("SELECT name, blurb FROM %s p ORDER BY age", Person.class.getName()); Query<Object[]> cacheQuery = queryFactory1.create(query); CloseableIterator<Object[]> iterator = cacheQuery.iterator(); List<Object[]> values = toList(iterator); for (int i = 0; i < NUM_ENTRIES; i++) { Object[] projection = values.get(i); assertEquals(projection[0], "name" + i); assertEquals(projection[1], "blurb" + i); } } private <E> List<E> toList(Iterator<E> iterator) { return StreamSupport.stream(((Iterable<E>) () -> iterator).spliterator(), false) .collect(Collectors.toList()); } @Test public void testBroadcastAggregatedInfinispanQuery() { QueryFactory queryFactory = Search.getQueryFactory(cacheAMachine2); Query<Person> hybridQuery = queryFactory.create("select name FROM " + Person.class.getName() + " WHERE name : 'na*' group by name"); assertEquals(NUM_ENTRIES, hybridQuery.execute().list().size()); } @Test public void testNonIndexedBroadcastInfinispanQuery() { QueryFactory queryFactory = Search.getQueryFactory(cacheAMachine2); Query<Person> slowQuery = queryFactory.create("FROM " + Person.class.getName() + " WHERE nonIndexedField LIKE 'na%'"); assertEquals(NUM_ENTRIES, slowQuery.execute().list().size()); } protected void populateCache() { prepareTestData(); cacheQuery = Search.getQueryFactory(cacheAMachine1).create(queryString); StaticTestingErrorHandler.assertAllGood(cacheAMachine1, cacheAMachine2); } protected Query<Person> createSortedQuery() { String q = String.format("FROM %s p where p.blurb:'blurb1?' order by p.age'", Person.class.getName()); return Search.getQueryFactory(cacheAMachine1).create(q); } }
16,632
35.798673
138
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/OffHeapQueryTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.query.helper.TestQueryHelperFactory.createCacheQuery; import static org.testng.Assert.assertEquals; import java.io.IOException; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.helper.IndexAccessor; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = {"functional"}, testName = "query.blackbox.OffHeapQueryTest") public class OffHeapQueryTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(false); cfg.memory().storageType(StorageType.OFF_HEAP).size(10); cfg.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); return TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE, cfg); } @Test public void testQuery() throws Exception { cache.put("1", new Person("Donald", "MAGA", 78)); assertEquals(getIndexDocs(), 1); Query<Object> queryFromLucene = createCacheQuery(Person.class, cache, "name", "Donald"); assertEquals(1, queryFromLucene.execute().list().size()); Query<Object> queryFromIckle = Search.getQueryFactory(cache) .create("From org.infinispan.query.test.Person p where p.name:'Donald'"); assertEquals(1, queryFromIckle.execute().list().size()); } private long getIndexDocs() throws IOException { return IndexAccessor.of(cache, Person.class).getIndexReader().numDocs(); } }
2,035
38.153846
94
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/ClusteredCacheWithLongIndexNameTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.Cache; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Text; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * The test verifies the issue ISPN-3092. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.blackbox.ClusteredCacheWithLongIndexNameTest") @CleanupAfterMethod public class ClusteredCacheWithLongIndexNameTest extends MultipleCacheManagersTest { private Cache<String, ClassWithLongIndexName> cache0, cache1, cache2; @Override protected void createCacheManagers() throws Throwable { createClusteredCaches(3, SCI.INSTANCE, getDefaultConfiguration()); cache0 = cache(0); cache1 = cache(1); cache2 = cache(2); } private ConfigurationBuilder getDefaultConfiguration() { ConfigurationBuilder cacheCfg = TestCacheManagerFactory.getDefaultCacheConfiguration(transactionsEnabled(), false); cacheCfg. clustering() .cacheMode(getCacheMode()) .indexing() .storage(LOCAL_HEAP) .enable() .addIndexedEntity(ClassWithLongIndexName.class); return cacheCfg; } public boolean transactionsEnabled() { return false; } public CacheMode getCacheMode() { return CacheMode.REPL_SYNC; } public void testAdditionOfNewNode() { for (int i = 0; i < 100; i++) { cache0.put("key" + i, new ClassWithLongIndexName("value" + i)); } String q = String.format("FROM %s WHERE name:'value*'", ClassWithLongIndexName.class.getName()); Query cq = Search.getQueryFactory(cache2).create(q); assertEquals(100, cq.execute().count().value()); addClusterEnabledCacheManager(SCI.INSTANCE, getDefaultConfiguration()); TestingUtil.waitForNoRebalance(cache(0), cache(1), cache(2), cache(3)); cq = Search.getQueryFactory(cache(3)).create(q); assertEquals(100, cq.execute().count().value()); } // index name as in bug description @Indexed(index = "default_taskworker-java__com.google.appengine.api.datastore.Entity") public static class ClassWithLongIndexName { @ProtoField(1) String name; @ProtoFactory ClassWithLongIndexName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClassWithLongIndexName that = (ClassWithLongIndexName) o; return name != null ? name.equals(that.name) : that.name == null; } @Text public String getName() { return name; } @Override public int hashCode() { return name != null ? name.hashCode() : 0; } @Override public String toString() { return "ClassWithLongIndexName{name='" + name + "'}"; } } @AutoProtoSchemaBuilder( includeClasses = ClassWithLongIndexName.class, schemaFileName = "test.query.blackbox.ClusteredCacheWithLongIndexNameTest.proto", schemaFilePath = "proto/generated", schemaPackageName = "org.infinispan.test.ClusteredCacheWithLongIndexNameTest", service = false ) interface SCI extends SerializationContextInitializer { SCI INSTANCE = new SCIImpl(); } }
4,174
32.4
121
java
null
infinispan-main/query/src/test/java/org/infinispan/query/blackbox/ClusteredCacheFSDirectoryTest.java
package org.infinispan.query.blackbox; import static org.infinispan.configuration.cache.IndexStorage.FILESYSTEM; import static org.testng.AssertJUnit.assertTrue; import java.io.File; import java.nio.file.Paths; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.test.CustomKey3; import org.infinispan.query.test.CustomKey3Transformer; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Run the basic set of operations with filesystem-based index storage in replicated mode * with transactional caches. * * The default FSDirectory implementation for non Windows systems should be NIOFSDirectory. * SimpleFSDirectory implementation will be used on Windows. * * @author Martin Gencur */ @Test(groups = "functional", testName = "query.blackbox.ClusteredCacheFSDirectoryTest") public class ClusteredCacheFSDirectoryTest extends ClusteredCacheTest { private final String TMP_DIR = CommonsTestingUtil.tmpDirectory(getClass()); @Override protected void createCacheManagers() { addClusterEnabledCacheManager(QueryTestSCI.INSTANCE, buildCacheConfig("index1")); addClusterEnabledCacheManager(QueryTestSCI.INSTANCE, buildCacheConfig("index2")); waitForClusterToForm(); cache1 = cache(0); cache2 = cache(1); } private ConfigurationBuilder buildCacheConfig(String indexName) { ConfigurationBuilder cb = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true); cb.indexing() .enable() //index also changes originated on other nodes, the index is not shared .storage(FILESYSTEM).path(Paths.get(TMP_DIR, indexName).toString()) .addIndexedEntity(Person.class) .addKeyTransformer(CustomKey3.class, CustomKey3Transformer.class); return cb; } @BeforeClass protected void setUpTempDir() { Util.recursiveFileRemove(TMP_DIR); boolean created = new File(TMP_DIR).mkdirs(); assertTrue(created); } @Override @AfterMethod protected void clearContent() throws Throwable { try { //first stop cache managers, then clear the index super.clearContent(); } finally { //delete the index otherwise it will mess up the index for next tests Util.recursiveFileRemove(TMP_DIR); } } }
2,625
34.972603
93
java
null
infinispan-main/query/src/main/java/org/infinispan/search/mapper/common/impl/EntityReferenceImpl.java
package org.infinispan.search.mapper.common.impl; import java.util.Objects; import org.hibernate.search.engine.common.EntityReference; import org.hibernate.search.mapper.pojo.model.spi.PojoRawTypeIdentifier; public class EntityReferenceImpl implements EntityReference { public static EntityReference withDefaultName(Class<?> type, Object id) { return new EntityReferenceImpl(PojoRawTypeIdentifier.of(type), type.getSimpleName(), id); } private final PojoRawTypeIdentifier<?> typeIdentifier; private final String name; private final Object id; public EntityReferenceImpl(PojoRawTypeIdentifier<?> typeIdentifier, String name, Object id) { this.typeIdentifier = typeIdentifier; this.name = name; this.id = id; } @Override public Class<?> type() { return typeIdentifier.javaClass(); } @Override public String name() { return name; } @Override public Object id() { return id; } @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != getClass()) { return false; } EntityReferenceImpl other = (EntityReferenceImpl) obj; return name.equals(other.name) && Objects.equals(id, other.id); } @Override public int hashCode() { return Objects.hash(name, id); } @Override public String toString() { // Apparently this is the usual format for references to Hibernate ORM entities. // Let's use the same format here, even if we're not using Hibernate ORM: it's good enough. return name + "#" + id; } }
1,598
25.65
97
java
null
infinispan-main/query/src/main/java/org/infinispan/search/mapper/session/SearchSession.java
package org.infinispan.search.mapper.session; import java.util.Collection; import java.util.Collections; import org.hibernate.search.engine.common.EntityReference; import org.hibernate.search.engine.search.query.dsl.SearchQuerySelectStep; import org.hibernate.search.mapper.pojo.work.spi.PojoIndexer; import org.infinispan.search.mapper.scope.SearchScope; /** * @author Fabio Massimo Ercoli */ public interface SearchSession extends AutoCloseable { /** * Initiate the building of a search query. * <p> * The query will target the indexes in the given scope. * * @param scope A scope representing all indexed types that will be targeted by the search query. * @param <E> An entity type to include in the scope. * @return The initial step of a DSL where the search query can be defined. * @see SearchQuerySelectStep */ <E> SearchQuerySelectStep<?, EntityReference, E, ?, ?, ?> search(SearchScope<E> scope); /** * Create a {@link SearchScope} limited to the given type. * * @param type A type to include in the scope. * @param <E> An entity type to include in the scope. * @return The created scope. * @see SearchScope */ default <E> SearchScope<E> scope(Class<E> type) { return scope(Collections.singleton(type)); } /** * Create a {@link SearchScope} limited to the given types. * * @param types A collection of types to include in the scope. * @param <E> A supertype of all indexed entity types that will be targeted by the search query. * @return The created scope. * @see SearchScope */ <E> SearchScope<E> scope(Collection<? extends Class<? extends E>> types); /** * Create a {@link SearchScope} limited to entity types referenced by their name. * * @param expectedSuperType A supertype of all entity types to include in the scope. * @param entityName An entity name. * @param <T> A supertype of all entity types to include in the scope. * @return The created scope. * @see SearchScope */ default <T> SearchScope<T> scope(Class<T> expectedSuperType, String entityName) { return scope(expectedSuperType, Collections.singleton(entityName)); } /** * Create a {@link SearchScope} limited to entity types referenced by their name. * * @param expectedSuperType A supertype of all entity types to include in the scope. * @param entityNames A collection of entity names. * @param <T> A supertype of all entity types to include in the scope. * @return The created scope. * @see SearchScope */ <T> SearchScope<T> scope(Class<T> expectedSuperType, Collection<String> entityNames); PojoIndexer createIndexer(); }
2,767
34.948052
101
java
null
infinispan-main/query/src/main/java/org/infinispan/search/mapper/session/impl/InfinispanSearchSession.java
package org.infinispan.search.mapper.session.impl; import java.util.Collection; import org.hibernate.search.engine.common.EntityReference; import org.hibernate.search.engine.search.query.dsl.SearchQuerySelectStep; import org.hibernate.search.mapper.pojo.loading.spi.PojoSelectionEntityLoader; import org.hibernate.search.mapper.pojo.loading.spi.PojoSelectionLoadingContext; import org.hibernate.search.mapper.pojo.session.spi.AbstractPojoSearchSession; import org.hibernate.search.mapper.pojo.work.spi.ConfiguredSearchIndexingPlanFilter; import org.hibernate.search.mapper.pojo.work.spi.PojoIndexer; import org.infinispan.search.mapper.model.impl.InfinispanRuntimeIntrospector; import org.infinispan.search.mapper.scope.SearchScope; import org.infinispan.search.mapper.scope.impl.SearchScopeImpl; import org.infinispan.search.mapper.search.loading.context.impl.InfinispanLoadingContext; import org.infinispan.search.mapper.session.SearchSession; /** * @author Fabio Massimo Ercoli */ public class InfinispanSearchSession extends AbstractPojoSearchSession implements SearchSession { private static final ConfiguredSearchIndexingPlanFilter ACCEPT_ALL = typeIdentifier -> true; private final InfinispanSearchSessionMappingContext mappingContext; private final PojoSelectionEntityLoader<?> entityLoader; public InfinispanSearchSession(InfinispanSearchSessionMappingContext mappingContext, PojoSelectionEntityLoader<?> entityLoader) { super(mappingContext); this.mappingContext = mappingContext; this.entityLoader = entityLoader; } @Override public void close() { // Nothing to do } @Override public <E> SearchQuerySelectStep<?, EntityReference, E, ?, ?, ?> search(SearchScope<E> scope) { return search((SearchScopeImpl<E>) scope); } public <E> SearchScopeImpl<E> scope(Collection<? extends Class<? extends E>> types) { return mappingContext.createScope(types); } @Override public <T> SearchScope<T> scope(Class<T> expectedSuperType, Collection<String> entityNames) { return mappingContext.createScope(expectedSuperType, entityNames); } @Override public PojoIndexer createIndexer() { return super.createIndexer(); } private <E> SearchQuerySelectStep<?, EntityReference, E, ?, ?, ?> search(SearchScopeImpl<E> scope) { return scope.search(this); } @Override public String tenantIdentifier() { // tenant is not used by ISPN return null; } @Override public InfinispanRuntimeIntrospector runtimeIntrospector() { return new InfinispanRuntimeIntrospector(); } @Override public PojoSelectionLoadingContext defaultLoadingContext() { return new InfinispanLoadingContext.Builder<>(entityLoader).build(); } @Override public ConfiguredSearchIndexingPlanFilter configuredIndexingPlanFilter() { return ACCEPT_ALL; } }
2,933
33.928571
103
java
null
infinispan-main/query/src/main/java/org/infinispan/search/mapper/session/impl/InfinispanTypeContextProvider.java
package org.infinispan.search.mapper.session.impl; import java.util.Collection; import org.hibernate.search.mapper.pojo.model.spi.PojoRawTypeIdentifier; /** * @author Fabio Massimo Ercoli */ public interface InfinispanTypeContextProvider { <E> InfinispanIndexedTypeContext<E> indexedForExactType(Class<E> entityType); InfinispanIndexedTypeContext<?> indexedForEntityName(String indexName); Collection<PojoRawTypeIdentifier<?>> allTypeIdentifiers(); }
469
23.736842
80
java
null
infinispan-main/query/src/main/java/org/infinispan/search/mapper/session/impl/InfinispanIndexedTypeContext.java
package org.infinispan.search.mapper.session.impl; import org.hibernate.search.mapper.pojo.identity.spi.IdentifierMapping; import org.hibernate.search.mapper.pojo.model.spi.PojoRawTypeIdentifier; /** * @param <E> The entity type mapped to the index. * * @author Fabio Massimo Ercoli */ public interface InfinispanIndexedTypeContext<E> { PojoRawTypeIdentifier<E> typeIdentifier(); String name(); IdentifierMapping identifierMapping(); }
455
21.8
72
java
null
infinispan-main/query/src/main/java/org/infinispan/search/mapper/session/impl/InfinispanSearchSessionMappingContext.java
package org.infinispan.search.mapper.session.impl; import java.util.Collection; import org.hibernate.search.mapper.pojo.session.spi.PojoSearchSessionMappingContext; import org.infinispan.search.mapper.scope.SearchScope; import org.infinispan.search.mapper.scope.impl.SearchScopeImpl; public interface InfinispanSearchSessionMappingContext extends PojoSearchSessionMappingContext { <E> SearchScopeImpl<E> createScope(Collection<? extends Class<? extends E>> classes); <E> SearchScope<E> createScope(Class<E> expectedSuperType, Collection<String> entityNames); }
572
37.2
96
java
null
infinispan-main/query/src/main/java/org/infinispan/search/mapper/work/SearchIndexer.java
package org.infinispan.search.mapper.work; import java.util.concurrent.CompletableFuture; /** * @author Fabio Massimo Ercoli */ public interface SearchIndexer extends AutoCloseable { CompletableFuture<?> add(Object providedId, String routingKey, Object entity); CompletableFuture<?> addOrUpdate(Object providedId, String routingKey, Object entity); CompletableFuture<?> delete(Object providedId, String routingKey, Object entity); CompletableFuture<?> purge(Object providedId, String routingKey); @Override void close(); }
551
24.090909
89
java
null
infinispan-main/query/src/main/java/org/infinispan/search/mapper/work/impl/SearchIndexerImpl.java
package org.infinispan.search.mapper.work.impl; import java.util.concurrent.CompletableFuture; import org.hibernate.search.engine.backend.work.execution.DocumentCommitStrategy; import org.hibernate.search.engine.backend.work.execution.DocumentRefreshStrategy; import org.hibernate.search.engine.backend.work.execution.OperationSubmitter; import org.hibernate.search.engine.common.execution.spi.SimpleScheduledExecutor; import org.hibernate.search.mapper.pojo.model.spi.PojoRawTypeIdentifier; import org.hibernate.search.mapper.pojo.route.DocumentRoutesDescriptor; import org.hibernate.search.mapper.pojo.work.spi.PojoIndexer; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.query.concurrent.InfinispanIndexingExecutorProvider; import org.infinispan.search.mapper.mapping.EntityConverter; import org.infinispan.search.mapper.session.impl.InfinispanIndexedTypeContext; import org.infinispan.search.mapper.session.impl.InfinispanTypeContextProvider; import org.infinispan.search.mapper.work.SearchIndexer; import org.infinispan.util.concurrent.BlockingManager; /** * @author Fabio Massimo Ercoli */ public class SearchIndexerImpl implements SearchIndexer { private final PojoIndexer delegate; private final EntityConverter entityConverter; private final InfinispanTypeContextProvider typeContextProvider; private final SimpleScheduledExecutor offloadingExecutor; public SearchIndexerImpl(PojoIndexer delegate, EntityConverter entityConverter, InfinispanTypeContextProvider typeContextProvider, BlockingManager blockingManager) { this.delegate = delegate; this.entityConverter = entityConverter; this.typeContextProvider = typeContextProvider; this.offloadingExecutor = InfinispanIndexingExecutorProvider.writeExecutor(blockingManager); } @Override public CompletableFuture<?> add(Object providedId, String routingKey, Object entity) { ConvertedValue convertedValue = convertedValue(entity); if (convertedValue == null) { return CompletableFutures.completedNull(); } return delegate.add(convertedValue.typeIdentifier, providedId, DocumentRoutesDescriptor.fromLegacyRoutingKey(routingKey), convertedValue.value, DocumentCommitStrategy.NONE, DocumentRefreshStrategy.NONE, OperationSubmitter.offloading(offloadingExecutor::submit)); } @Override public CompletableFuture<?> addOrUpdate(Object providedId, String routingKey, Object entity) { ConvertedValue convertedValue = convertedValue(entity); if (convertedValue == null) { return CompletableFutures.completedNull(); } return delegate.addOrUpdate(convertedValue.typeIdentifier, providedId, DocumentRoutesDescriptor.fromLegacyRoutingKey(routingKey), convertedValue.value, DocumentCommitStrategy.NONE, DocumentRefreshStrategy.NONE, OperationSubmitter.offloading(offloadingExecutor::submit)); } @Override public CompletableFuture<?> delete(Object providedId, String routingKey, Object entity) { ConvertedValue convertedValue = convertedValue(entity); if (convertedValue == null) { return CompletableFutures.completedNull(); } return delegate.delete(convertedValue.typeIdentifier, providedId, DocumentRoutesDescriptor.fromLegacyRoutingKey(routingKey), convertedValue.value, DocumentCommitStrategy.NONE, DocumentRefreshStrategy.NONE, OperationSubmitter.offloading(offloadingExecutor::submit)); } @Override public CompletableFuture<?> purge(Object providedId, String routingKey) { return CompletableFuture.allOf(typeContextProvider.allTypeIdentifiers().stream() .map((typeIdentifier) -> delegate.delete(typeIdentifier, providedId, DocumentRoutesDescriptor.fromLegacyRoutingKey(routingKey), DocumentCommitStrategy.NONE, DocumentRefreshStrategy.NONE, OperationSubmitter.offloading(offloadingExecutor::submit))) .toArray(CompletableFuture[]::new)); } @Override public void close() { } private ConvertedValue convertedValue(Object entity) { if (entity == null) { return null; } if (entityConverter == null || !entity.getClass().equals(entityConverter.targetType())) { InfinispanIndexedTypeContext<?> typeContext = typeContextProvider.indexedForExactType(entity.getClass()); if (typeContext == null) { return null; } return new ConvertedValue(typeContext, entity); } EntityConverter.ConvertedEntity converted = entityConverter.convert(entity); if (converted.skip()) { return null; } InfinispanIndexedTypeContext<?> typeContext = typeContextProvider.indexedForEntityName(converted.entityName()); if (typeContext == null) { return null; } return new ConvertedValue(typeContext, converted.value()); } private static class ConvertedValue { private PojoRawTypeIdentifier<?> typeIdentifier; private Object value; public ConvertedValue(InfinispanIndexedTypeContext<?> typeContext, Object value) { this.typeIdentifier = typeContext.typeIdentifier(); this.value = value; } } }
5,348
40.465116
117
java
null
infinispan-main/query/src/main/java/org/infinispan/search/mapper/impl/InfinispanEntityTypeContributor.java
package org.infinispan.search.mapper.impl; import org.hibernate.search.mapper.pojo.mapping.building.spi.PojoTypeMetadataContributor; import org.hibernate.search.mapper.pojo.model.additionalmetadata.building.spi.PojoAdditionalMetadataCollectorTypeNode; import org.hibernate.search.mapper.pojo.model.spi.PojoRawTypeIdentifier; import org.infinispan.search.mapper.model.impl.InfinispanSimpleStringSetPojoPathFilterFactory; class InfinispanEntityTypeContributor implements PojoTypeMetadataContributor { private final PojoRawTypeIdentifier<?> typeIdentifier; private final String entityName; InfinispanEntityTypeContributor(PojoRawTypeIdentifier<?> typeIdentifier, String entityName) { this.typeIdentifier = typeIdentifier; this.entityName = entityName; } @Override public void contributeAdditionalMetadata(PojoAdditionalMetadataCollectorTypeNode collector) { if (!typeIdentifier.equals(collector.typeIdentifier())) { // Entity metadata is not inherited; only contribute it to the exact type. return; } collector.markAsEntity(entityName, new InfinispanSimpleStringSetPojoPathFilterFactory()); } }
1,166
42.222222
118
java
null
infinispan-main/query/src/main/java/org/infinispan/search/mapper/impl/InfinispanMappingInitiator.java
package org.infinispan.search.mapper.impl; import java.util.Collection; import org.hibernate.search.engine.mapper.mapping.building.spi.MappingBuildContext; import org.hibernate.search.engine.mapper.mapping.building.spi.MappingConfigurationCollector; import org.hibernate.search.mapper.pojo.loading.spi.PojoSelectionEntityLoader; import org.hibernate.search.mapper.pojo.mapping.building.spi.PojoMapperDelegate; import org.hibernate.search.mapper.pojo.mapping.building.spi.PojoTypeMetadataContributor; import org.hibernate.search.mapper.pojo.mapping.spi.AbstractPojoMappingInitiator; import org.hibernate.search.mapper.pojo.model.spi.PojoBootstrapIntrospector; import org.infinispan.query.concurrent.FailureCounter; import org.infinispan.search.mapper.mapping.EntityConverter; import org.infinispan.search.mapper.mapping.MappingConfigurationContext; import org.infinispan.search.mapper.mapping.ProgrammaticSearchMappingProvider; import org.infinispan.search.mapper.mapping.impl.InfinispanMapperDelegate; import org.infinispan.search.mapper.mapping.impl.InfinispanMappingPartialBuildState; import org.infinispan.util.concurrent.BlockingManager; public class InfinispanMappingInitiator extends AbstractPojoMappingInitiator<InfinispanMappingPartialBuildState> implements MappingConfigurationContext { private final InfinispanTypeConfigurationContributor typeConfigurationContributor; private final Collection<ProgrammaticSearchMappingProvider> mappingProviders; private final BlockingManager blockingManager; private final FailureCounter failureCounter; private PojoSelectionEntityLoader<?> entityLoader; private EntityConverter entityConverter; public InfinispanMappingInitiator(PojoBootstrapIntrospector introspector, Collection<ProgrammaticSearchMappingProvider> mappingProviders, BlockingManager blockingManager, FailureCounter failureCounter) { super(introspector); typeConfigurationContributor = new InfinispanTypeConfigurationContributor(introspector); addConfigurationContributor(typeConfigurationContributor); this.mappingProviders = mappingProviders; this.blockingManager = blockingManager; this.failureCounter = failureCounter; } public void addEntityType(Class<?> type, String entityName) { typeConfigurationContributor.addEntityType(type, entityName); } public void setEntityLoader(PojoSelectionEntityLoader<?> entityLoader) { this.entityLoader = entityLoader; } public void setEntityConverter(EntityConverter entityConverter) { this.entityConverter = entityConverter; } @Override public void configure(MappingBuildContext buildContext, MappingConfigurationCollector<PojoTypeMetadataContributor> configurationCollector) { super.configure(buildContext, configurationCollector); for (ProgrammaticSearchMappingProvider mappingProvider : mappingProviders) { mappingProvider.configure(this); } } @Override protected PojoMapperDelegate<InfinispanMappingPartialBuildState> createMapperDelegate() { return new InfinispanMapperDelegate(entityLoader, entityConverter, blockingManager, failureCounter); } }
3,265
46.333333
112
java
null
infinispan-main/query/src/main/java/org/infinispan/search/mapper/impl/InfinispanTypeConfigurationContributor.java
package org.infinispan.search.mapper.impl; import java.lang.invoke.MethodHandles; import java.util.LinkedHashMap; import java.util.Map; import org.hibernate.search.engine.mapper.mapping.building.spi.MappingBuildContext; import org.hibernate.search.engine.mapper.mapping.building.spi.MappingConfigurationCollector; import org.hibernate.search.mapper.pojo.mapping.building.spi.PojoTypeMetadataContributor; import org.hibernate.search.mapper.pojo.mapping.spi.PojoMappingConfigurationContext; import org.hibernate.search.mapper.pojo.mapping.spi.PojoMappingConfigurationContributor; import org.hibernate.search.mapper.pojo.model.spi.PojoBootstrapIntrospector; import org.hibernate.search.mapper.pojo.model.spi.PojoRawTypeModel; import org.hibernate.search.util.common.logging.impl.LoggerFactory; import org.infinispan.search.mapper.log.impl.Log; class InfinispanTypeConfigurationContributor implements PojoMappingConfigurationContributor { private static final Log log = LoggerFactory.make(Log.class, MethodHandles.lookup()); private final PojoBootstrapIntrospector introspector; // Use a LinkedHashMap for deterministic iteration private final Map<String, Class<?>> entityTypeByName = new LinkedHashMap<>(); public InfinispanTypeConfigurationContributor(PojoBootstrapIntrospector introspector) { this.introspector = introspector; } @Override public void configure(MappingBuildContext buildContext, PojoMappingConfigurationContext configurationContext, MappingConfigurationCollector<PojoTypeMetadataContributor> configurationCollector) { for (Map.Entry<String, Class<?>> entry : entityTypeByName.entrySet()) { PojoRawTypeModel<?> typeModel = identifiedByName(entry.getValue()) ? introspector.typeModel(entry.getKey()) : introspector.typeModel(entry.getValue()); configurationCollector.collectContributor(typeModel, new InfinispanEntityTypeContributor(typeModel.typeIdentifier(), entry.getKey())); } } void addEntityType(Class<?> type, String entityName) { Class<?> previousType = entityTypeByName.putIfAbsent(entityName, type); if (previousType != null && !previousType.equals(type)) { throw log.multipleEntityTypesWithSameName(entityName, previousType, type); } } private boolean identifiedByName(Class<?> type) { return byte[].class.equals(type); } }
2,408
44.45283
116
java
null
infinispan-main/query/src/main/java/org/infinispan/search/mapper/scope/SearchScope.java
package org.infinispan.search.mapper.scope; import java.util.function.Function; import org.hibernate.search.engine.common.EntityReference; import org.hibernate.search.engine.search.aggregation.AggregationKey; import org.hibernate.search.engine.search.aggregation.SearchAggregation; import org.hibernate.search.engine.search.aggregation.dsl.SearchAggregationFactory; import org.hibernate.search.engine.search.predicate.dsl.SearchPredicateFactory; import org.hibernate.search.engine.search.projection.dsl.SearchProjectionFactory; import org.hibernate.search.engine.search.query.dsl.SearchQueryOptionsStep; import org.hibernate.search.engine.search.query.dsl.SearchQuerySelectStep; import org.hibernate.search.engine.search.query.dsl.SearchQueryWhereStep; import org.hibernate.search.engine.search.sort.dsl.SearchSortFactory; import org.infinispan.search.mapper.session.SearchSession; /** * Represents a set of types and the corresponding indexes, allowing to build search-related objects (query, predicate, * ...) taking into account the relevant indexes and their metadata (underlying technology, field types, ...). * * @param <E> A supertype of all types in this scope. */ public interface SearchScope<E> { /** * Initiate the building of a search predicate. * <p> * The predicate will only be valid for {@link SearchSession#search(SearchScope) search queries} created using this * scope or another scope instance targeting the same indexes. * <p> * Note this method is only necessary if you do not want to use lambda expressions, since you can {@link * SearchQueryWhereStep#where(Function) define predicates with lambdas} within the search query DSL, removing the * need to create separate objects to represent the predicates. * * @return A predicate factory. * @see SearchPredicateFactory */ SearchPredicateFactory predicate(); /** * Initiate the building of a search sort. * <p> * The sort will only be valid for {@link SearchSession#search(SearchScope) search queries} created using this scope * or another scope instance targeting the same indexes. * <p> * Note this method is only necessary if you do not want to use lambda expressions, since you can {@link * SearchQueryOptionsStep#sort(Function) define sorts with lambdas} within the search query DSL, removing the need to * create separate objects to represent the sorts. * * @return A sort factory. * @see SearchSortFactory */ SearchSortFactory sort(); /** * Initiate the building of a search projection that will be valid for the indexes in this scope. * <p> * The projection will only be valid for {@link SearchSession#search(SearchScope) search queries} created using this * scope or another scope instance targeting the same indexes. * <p> * Note this method is only necessary if you do not want to use lambda expressions, since you can {@link * SearchQuerySelectStep#select(Function)} define projections with lambdas} within the search query DSL, * removing the need to create separate objects to represent the projections. * * @return A projection factory. * @see SearchProjectionFactory */ SearchProjectionFactory<EntityReference, E> projection(); /** * Initiate the building of a search aggregation that will be valid for the indexes in this scope. * <p> * The aggregation will only be usable in {@link SearchSession#search(SearchScope) search queries} created using this * scope or another scope instance targeting the same indexes. * <p> * Note this method is only necessary if you do not want to use lambda expressions, since you can {@link * SearchQueryOptionsStep#aggregation(AggregationKey, SearchAggregation)} define aggregations with lambdas} within * the search query DSL, removing the need to create separate objects to represent the aggregation. * * @return An aggregation factory. * @see SearchAggregationFactory */ SearchAggregationFactory aggregation(); /** * Create a {@link SearchWorkspace} for the indexes mapped to types in this scope, or to any of their sub-types. * * @return A {@link SearchWorkspace}. */ SearchWorkspace workspace(); }
4,276
44.989247
120
java
null
infinispan-main/query/src/main/java/org/infinispan/search/mapper/scope/SearchWorkspace.java
package org.infinispan.search.mapper.scope; import java.util.Set; /** * The entry point for explicit index operations. * <p> * A {@link SearchWorkspace} targets a pre-defined set of indexed types (and their indexes). */ public interface SearchWorkspace { /** * Delete all documents from indexes targeted by this workspace. * <p> * With multi-tenancy enabled, only documents of the current tenant will be removed: * the tenant that was targeted by the session from where this workspace originated. */ void purge(); /** * Delete documents from indexes targeted by this workspace * that were indexed with any of the given routing keys. * <p> * With multi-tenancy enabled, only documents of the current tenant will be removed: * the tenant that was targeted by the session from where this workspace originated. * * @param routingKeys The set of routing keys. * If non-empty, only documents that were indexed with these routing keys will be deleted. * If empty, documents will be deleted regardless of their routing key. */ void purge(Set<String> routingKeys); /** * Flush to disk the changes to indexes that were not committed yet. In the case of backends with a transaction log * (Elasticsearch), also apply operations from the transaction log that were not applied yet. * <p> * This is generally not useful as Hibernate Search commits changes automatically. Only to be used by experts fully * aware of the implications. * <p> * Note that some operations may still be waiting in a queue when {@link #flush()} is called, in particular * operations queued as part of automatic indexing before a transaction is committed. These operations will not be * applied immediately just because a call to {@link #flush()} is issued: the "flush" here is a very low-level * operation managed by the backend. */ void flush(); /** * Refresh the indexes so that all changes executed so far will be visible in search queries. * <p> * This is generally not useful as indexes are refreshed automatically, * either after every change (default for the Lucene backend) * or periodically (default for the Elasticsearch backend, * possible for the Lucene backend by setting a refresh interval). * Only to be used by experts fully aware of the implications. * <p> * Note that some operations may still be waiting in a queue when {@link #refresh()} is called, * in particular operations queued as part of automatic indexing before a transaction is committed. * These operations will not be applied immediately just because a call to {@link #refresh()} is issued: * the "refresh" here is a very low-level operation handled by the backend. */ void refresh(); /** * Merge all segments of the indexes targeted by this workspace into a single one. * <p> * Note this operation may affect performance positively as well as negatively. As a rule of thumb, if indexes are * read-only for extended periods of time, then calling {@link #mergeSegments()} may improve performance. If indexes * are written to, then calling {@link #mergeSegments()} is likely to degrade read/write performance overall. */ void mergeSegments(); }
3,309
44.342466
119
java