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/api/NotIndexedType.java
package org.infinispan.query.api; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; /** * A test value having a non-standard constructor, no setter and not indexed */ public class NotIndexedType { @ProtoFactory public NotIndexedType(String name) { this.name = name; } private final String name; @ProtoField(1) public String getName() { return name; } }
461
19.086957
76
java
null
infinispan-main/query/src/test/java/org/infinispan/query/api/TransactionalInfinispanDirectoryNonIndexedValuesTest.java
package org.infinispan.query.api; import org.testng.annotations.Test; /** * Testing non-indexed values on InfinispanDirectory in case of transactional cache. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.api.TransactionalInfinispanDirectoryNonIndexedValuesTest") public class TransactionalInfinispanDirectoryNonIndexedValuesTest extends InfinispanDirectoryNonIndexedValuesTest { protected boolean isTransactional() { return true; } }
483
27.470588
115
java
null
infinispan-main/query/src/test/java/org/infinispan/query/api/ReplaceTest.java
package org.infinispan.query.api; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.helper.StaticTestingErrorHandler; 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.api.ReplaceTest") public class ReplaceTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(TestEntity.class); return TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE, cfg); } public void testReplaceSimple() { //for comparison we use a non-indexing cache here: EmbeddedCacheManager simpleCacheManager = TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE, getDefaultStandaloneCacheConfig(true)); try { Cache<Object, Object> simpleCache = simpleCacheManager.getCache(); TestEntity se1 = new TestEntity("name1", "surname1", 10, "note"); TestEntity se2 = new TestEntity("name2", "surname2", 10, "note"); // same id simpleCache.put(se1.getId(), se1); TestEntity se1ret = (TestEntity) simpleCache.replace(se2.getId(), se2); assertEquals(se1, se1ret); } finally { TestingUtil.killCacheManagers(simpleCacheManager); } } public void testReplaceSimpleSearchable() { TestEntity se1 = new TestEntity("name1", "surname1", 10, "note"); TestEntity se2 = new TestEntity("name2", "surname2", 10, "note"); // same id cache.put(se1.getId(), se1); TestEntity se1ret = (TestEntity) cache.replace(se2.getId(), se2); assertEquals(se1, se1ret); StaticTestingErrorHandler.assertAllGood(cache); } public void testReplaceSimpleSearchableConditional() { TestEntity se1 = new TestEntity("name1", "surname1", 10, "note"); TestEntity se2 = new TestEntity("name2", "surname2", 10, "note"); // same id cache.put(se1.getId(), se1); // note we use conditional replace here assert cache.replace(se2.getId(), se1, se2); StaticTestingErrorHandler.assertAllGood(cache); } }
2,673
40.138462
153
java
null
infinispan-main/query/src/test/java/org/infinispan/query/api/PutAllTest.java
package org.infinispan.query.api; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Future; import org.infinispan.commons.test.annotation.TestForIssue; 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.dsl.QueryFactory; import org.infinispan.query.helper.StaticTestingErrorHandler; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.api.PutAllTest") @CleanupAfterMethod public class PutAllTest extends SingleCacheManagerTest { private StorageType storageType; @Override protected String parameters() { return "[" + storageType + "]"; } @Factory public Object[] factory() { return new Object[]{ new PutAllTest().storageType(StorageType.OFF_HEAP), new PutAllTest().storageType(StorageType.BINARY), new PutAllTest().storageType(StorageType.OBJECT), }; } PutAllTest storageType(StorageType storageType) { this.storageType = storageType; return this; } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg.indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(TestEntity.class) .addIndexedEntity(AnotherTestEntity.class) .writer().queueSize(1); cfg.memory() .storageType(storageType); return TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE, cfg); } public void testOverwriteNotIndexedValue() { final long id = 10; cache.put(id, new NotIndexedType("name1")); Map<Object, Object> map = new HashMap<>(); map.put(id, new TestEntity("name2", "surname2", id, "note")); cache.putAll(map); Query<AnotherTestEntity> q1 = queryByNameField("name2", AnotherTestEntity.class); Query<TestEntity> q2 = queryByNameField("name2", TestEntity.class); assertEquals(1, q1.execute().count().value() + q2.execute().count().value()); assertEquals(TestEntity.class, q2.list().get(0).getClass()); StaticTestingErrorHandler.assertAllGood(cache); } public void testAsyncOverwriteNotIndexedValue() throws Exception { final long id = 10; cache.put(id, new NotIndexedType("name1")); Map<Object, Object> map = new HashMap<>(); map.put(id, new TestEntity("name2", "surname2", id, "note")); Future<?> futureTask = cache.putAllAsync(map); futureTask.get(); assertTrue(futureTask.isDone()); Query<TestEntity> q1 = queryByNameField("name2", TestEntity.class); Query<AnotherTestEntity> q2 = queryByNameField("name2", AnotherTestEntity.class); assertEquals(1, q1.execute().count().value() + q2.execute().count().value()); assertEquals(TestEntity.class, q1.list().get(0).getClass()); StaticTestingErrorHandler.assertAllGood(cache); } public void testOverwriteWithNonIndexedValue() { final long id = 10; cache.put(id, new TestEntity("name1", "surname1", id, "note")); Query<TestEntity> q1 = queryByNameField("name1", TestEntity.class); Query<?> q2 = queryByNameField("name1", AnotherTestEntity.class); assertEquals(1, q1.execute().count().value() + q2.execute().count().value()); assertEquals(TestEntity.class, q1.list().get(0).getClass()); Map<Object, Object> map = new HashMap<>(); map.put(id, new NotIndexedType("name2")); cache.putAll(map); q2 = queryByNameField("name1", TestEntity.class); assertEquals(0, q2.execute().count().value()); Query<?> q3 = queryByNameField("name2", TestEntity.class); assertEquals(0, q3.execute().count().value()); StaticTestingErrorHandler.assertAllGood(cache); } public void testAsyncOverwriteWithNonIndexedValue() throws Exception { final long id = 10; cache.put(id, new TestEntity("name1", "surname1", id, "note")); Query<?> q1 = queryByNameField("name1", TestEntity.class); assertEquals(1, q1.execute().count().value()); assertEquals(TestEntity.class, q1.list().get(0).getClass()); Map<Object, Object> map = new HashMap<>(); map.put(id, new NotIndexedType("name2")); Future<?> futureTask = cache.putAllAsync(map); futureTask.get(); assertTrue(futureTask.isDone()); Query<TestEntity> q2 = queryByNameField("name1", TestEntity.class); assertEquals(0, q2.execute().count().value()); Query<TestEntity> q3 = queryByNameField("name2", TestEntity.class); assertEquals(0, q3.execute().count().value()); StaticTestingErrorHandler.assertAllGood(cache); } public void testOverwriteIndexedValue() { final long id = 10; cache.put(id, new TestEntity("name1", "surname1", id, "note")); Query<TestEntity> q1 = queryByNameField("name1", TestEntity.class); assertEquals(1, q1.execute().count().value()); assertEquals(TestEntity.class, q1.list().get(0).getClass()); Map<Object, Object> map = new HashMap<>(); map.put(id, new AnotherTestEntity("name2")); cache.putAll(map); Query<TestEntity> q2 = queryByNameField("name1", TestEntity.class); assertEquals(0, q2.execute().count().value()); Query<AnotherTestEntity> q3 = queryByNameField("name2", AnotherTestEntity.class); assertEquals(1, q3.execute().count().value()); assertEquals(AnotherTestEntity.class, q3.list().get(0).getClass()); StaticTestingErrorHandler.assertAllGood(cache); } @Test @TestForIssue(jiraKey = "ISPN-14115") public void testOverwriteIndexedValue_heavyLoad() { for (int i=0; i<1000; i++) { Map<Object, Object> map = new HashMap<>(); map.put(1, new TestEntity("name1", "surname1", 1, "note")); map.put(2, new AnotherTestEntity("name2")); cache.putAll(map); map.clear(); map.put(1, new AnotherTestEntity("name2")); map.put(2, new TestEntity("name1", "surname1", 1, "note")); cache.putAll(map); } } private <T> Query<T> queryByNameField(String name, Class<T> entity) { QueryFactory queryFactory = Search.getQueryFactory(cache); return queryFactory.create(String.format("FROM %s WHERE name = '%s'", entity.getName(), name)); } }
6,955
37.010929
101
java
null
infinispan-main/query/src/test/java/org/infinispan/query/api/NonIndexedValuesTest.java
package org.infinispan.query.api; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; 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.helper.StaticTestingErrorHandler; 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.api.NonIndexedValuesTest") public class NonIndexedValuesTest extends SingleCacheManagerTest { protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder c = getDefaultStandaloneCacheConfig(true); c.indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(TestEntity.class) .addIndexedEntity(AnotherTestEntity.class); return TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE, c); } private Query createISPNQuery(Class<?> entity) { return createQuery(entity, "ISPN-1949"); } private Query createHSearchQuery(Class<?> entity) { return createQuery(entity, "HSEARCH-1077"); } private Query createQuery(Class<?> entity, String issueValue) { QueryFactory queryFactory = Search.getQueryFactory(cache); String queryStr = "FROM %s WHERE name = '%s'"; return queryFactory.create(String.format(queryStr, entity.getName(), issueValue)); } @Test public void testReplaceSimpleSearchable() { TestEntity se1 = new TestEntity("ISPN-1949", "Allow non-indexed values in indexed caches", 10, "note"); cache.put(se1.getId(), se1); cache.put("name2", "some string value"); cache.put("name3", "some string value"); cache.put("name3", new NotIndexedType("some string value")); assertEquals(1, createISPNQuery(TestEntity.class).list().size()); cache.put(se1.getId(), "some string value"); assertEquals(0, createISPNQuery(TestEntity.class).list().size()); AnotherTestEntity indexBEntity = new AnotherTestEntity("ISPN-1949"); cache.put("name", indexBEntity); assertEquals(0, createISPNQuery(TestEntity.class).list().size()); assertEquals(1, createISPNQuery(AnotherTestEntity.class).list().size()); TestEntity se2 = new TestEntity("HSEARCH-1077", "Mutable SearchFactory should return which classes are actually going to be indexed", 10, "note"); cache.replace("name", indexBEntity, se2); assertEquals(0, createISPNQuery(TestEntity.class).list().size()); assertEquals(1, createHSearchQuery(TestEntity.class).list().size()); //a failing atomic replace should not change the index: cache.replace("name", "notMatching", "notImportant"); assertEquals(1, createHSearchQuery(TestEntity.class).list().size()); assertEquals(0, createISPNQuery(TestEntity.class).list().size()); cache.remove("name"); assertEquals(0, createHSearchQuery(TestEntity.class).list().size()); cache.put("name", se2); assertEquals(1, createHSearchQuery(TestEntity.class).list().size()); cache.put("name", "replacement String"); assertEquals(0, createHSearchQuery(TestEntity.class).list().size()); cache.put("name", se1); assertEquals(1, createISPNQuery(TestEntity.class).list().size()); cache.put("second name", se1); assertEquals(2, createISPNQuery(TestEntity.class).list().size()); assertEquals(0, createISPNQuery(AnotherTestEntity.class).list().size()); //now actually replace one with a different indexed type (matches same query) cache.replace("name", se1, indexBEntity); assertEquals(1, createISPNQuery(TestEntity.class).list().size()); assertEquals(1, createISPNQuery(AnotherTestEntity.class).list().size()); //replace with a non indexed type cache.replace("name", indexBEntity, new NotIndexedType("this is not indexed")); assertEquals(1, createISPNQuery(TestEntity.class).list().size()); StaticTestingErrorHandler.assertAllGood(cache); } }
4,301
42.454545
152
java
null
infinispan-main/query/src/test/java/org/infinispan/query/api/AnotherTestEntity.java
package org.infinispan.query.api; 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 = "indexB") public class AnotherTestEntity { private final String value; @ProtoFactory AnotherTestEntity(String value) { this.value = value; } @Basic(name = "name") @ProtoField(1) public String getValue() { return value; } }
543
21.666667
59
java
null
infinispan-main/query/src/test/java/org/infinispan/query/api/ManualIndexingTest.java
package org.infinispan.query.api; import static org.infinispan.util.concurrent.CompletionStages.join; import static org.testng.AssertJUnit.assertEquals; import java.util.ArrayList; import java.util.List; import org.infinispan.Cache; 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.queries.faceting.Car; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.api.ManualIndexingTest") public class ManualIndexingTest extends MultipleCacheManagersTest { protected static final int NUM_NODES = 4; protected List<Cache<String, Car>> caches = new ArrayList<>(NUM_NODES); @Override protected void createCacheManagers() throws Throwable { for (int i = 0; i < NUM_NODES; i++) { EmbeddedCacheManager cacheManager = TestCacheManagerFactory.fromXml("manual-indexing-distribution.xml"); registerCacheManager(cacheManager); Cache<String, Car> cache = cacheManager.getCache(); caches.add(cache); } waitForClusterToForm("default"); } public void testManualIndexing() { caches.get(0).put("car A", new Car("ford", "blue", 400)); caches.get(0).put("car B", new Car("megane", "white", 300)); caches.get(0).put("car C", new Car("megane", "red", 500)); assertNumberOfCars(0, "megane"); assertNumberOfCars(0, "ford"); // rebuild index join(Search.getIndexer(caches.get(0)).run()); assertNumberOfCars(2, "megane"); assertNumberOfCars(1, "ford"); } private void assertNumberOfCars(int expectedCount, String carMake) { for (Cache<?, ?> cache : caches) { QueryFactory queryFactory = Search.getQueryFactory(cache); Query<Car> query = queryFactory.create(String.format("FROM %s where make:'%s'", Car.class.getName(), carMake)); QueryResult<Car> queryResult = query.execute(); assertEquals("Expected count not met on cache " + cache, expectedCount, queryResult.count().value()); assertEquals("Expected count not met on cache " + cache, expectedCount, queryResult.list().size()); } } }
2,394
37.629032
120
java
null
infinispan-main/query/src/test/java/org/infinispan/query/statetransfer/PersistentStateTransferQueryDistributedIndexTest.java
package org.infinispan.query.statetransfer; 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.statetransfer.PersistentStateTransferQueryDistributedIndexTest") public class PersistentStateTransferQueryDistributedIndexTest extends PersistentStateTransferQueryIndexTest { @Override protected void configureCache(ConfigurationBuilder builder) { super.configureCache(builder); builder.indexing().enable().storage(LOCAL_HEAP); } }
675
28.391304
111
java
null
infinispan-main/query/src/test/java/org/infinispan/query/statetransfer/StateTransferQueryDistributedIndexTest.java
package org.infinispan.query.statetransfer; 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.statetransfer.StateTransferQueryDistributedIndexTest") public class StateTransferQueryDistributedIndexTest extends StateTransferQueryIndexTest { @Override protected void configureCache(ConfigurationBuilder builder) { super.configureCache(builder); builder.indexing().enable().storage(LOCAL_HEAP); } }
644
28.318182
101
java
null
infinispan-main/query/src/test/java/org/infinispan/query/statetransfer/BaseReIndexingTest.java
package org.infinispan.query.statetransfer; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.query.helper.TestQueryHelperFactory.createCacheQuery; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.testng.AssertJUnit.assertEquals; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.dsl.Query; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TransportFlags; /** * Base class for state transfer and query related tests * * @author Galder Zamarreño * @since 5.2 */ public abstract class BaseReIndexingTest extends MultipleCacheManagersTest { protected Person[] persons; protected ConfigurationBuilder builder; abstract protected void configureCache(ConfigurationBuilder builder); @Override protected void createCacheManagers() throws Throwable { builder = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); configureCache(builder); createClusteredCaches(2, QueryTestSCI.INSTANCE, builder); } private EmbeddedCacheManager createCacheManager() { return addClusterEnabledCacheManager(QueryTestSCI.INSTANCE, builder, new TransportFlags().withMerge(true)); } protected void executeSimpleQuery(Cache<String, Person> cache) { Query<?> cacheQuery = createCacheQuery(Person.class, cache, "blurb", "playing"); List<?> found = cacheQuery.execute().list(); int elems = found.size(); assertEquals(1, elems); Object val = found.get(0); Person expectedPerson = persons[0]; assertEquals(expectedPerson, val); } protected void loadCacheEntries(Cache<String, Person> cache) { Person person1 = new Person(); person1.setName("NavinSurtani"); person1.setBlurb("Likes playing WoW"); person1.setAge(45); Person person2 = new Person(); person2.setName("BigGoat"); person2.setBlurb("Eats grass"); person2.setAge(30); Person person3 = new Person(); person3.setName("MiniGoat"); person3.setBlurb("Eats cheese"); person3.setAge(35); Person person4 = new Person(); person4.setName("MightyGoat"); person4.setBlurb("Also eats grass"); person4.setAge(66); persons = new Person[]{person1, person2, person3, person4}; // Put the 3 created objects in the cache cache.put(person1.getName(), person1); cache.put(person2.getName(), person2); cache.put(person3.getName(), person3); cache.put(person4.getName(), person4); } protected void addNodeCheckingContentsAndQuery() { withCacheManager(new CacheManagerCallable(createCacheManager()) { @Override public void call() { // New node joining Cache<String, Person> newCache = cm.getCache(); TestingUtil.waitForNoRebalance(caches().get(0), caches().get(1), newCache); // Verify state transfer int size = newCache.size(); assertEquals(4, size); for (int i = 0; i < size; i++) assertEquals(persons[i], newCache.get(persons[i].getName())); // Repeat query on new node executeSimpleQuery(newCache); } }); } }
3,769
32.070175
87
java
null
infinispan-main/query/src/test/java/org/infinispan/query/statetransfer/PersistentStateTransferQueryIndexTest.java
package org.infinispan.query.statetransfer; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.query.test.Person; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; /** * Test that verifies that querying works even after multiple nodes have * started with unshared, passivated, cache stores, and a new node comes in * to fetch the persistent state from the other nodes. * * @author Galder Zamarreño * @since 5.2 */ @Test(groups = "functional", testName = "query.statetransfer.PersistentStateTransferQueryIndexTest") public class PersistentStateTransferQueryIndexTest extends BaseReIndexingTest { @Override protected void configureCache(ConfigurationBuilder builder) { // Explicitly disable fetching in-memory state in order // to fetch it from the persistence layer builder.clustering().stateTransfer().fetchInMemoryState(true) .persistence().passivation(true) .addStore(DummyInMemoryStoreConfigurationBuilder.class) .shared(false) .preload(true) .fetchPersistentState(true); } public void testFetchingPersistentStateUpdatesIndex() throws Exception { loadCacheEntries(this.<String, Person>caches().get(0)); // Before adding a node, verify that the query resolves properly Cache<String, Person> cache1 = this.<String, Person>caches().get(0); executeSimpleQuery(cache1); // Since passivation is enabled, cache stores should still be empty checkCacheStoresEmpty(); // Evict manually entries from both nodes for (Cache<Object, Object> cache : caches()) { for (Person p2 : persons) { cache.evict(p2.getName()); } } // After eviction, cache stores should be loaded with instances checkCacheStoresContainPersons(); // Finally add a node and verify that state transfer happens and query works addNodeCheckingContentsAndQuery(); } private void checkCacheStoresContainPersons() throws PersistenceException { for (Cache<Object, Object> cache : caches()) { DummyInMemoryStore store = TestingUtil.getFirstStore(cache); for (int i = 0; i < persons.length; i++) assertEquals(persons[i], store.loadEntry(persons[i].getName()).getValue()); } } private void checkCacheStoresEmpty() throws PersistenceException { for (Cache<Object, Object> cache : caches()) { DummyInMemoryStore store = TestingUtil.getFirstStore(cache); for (Person person : persons) { assert !store.contains(person.getName()); } } } }
2,968
36.582278
100
java
null
infinispan-main/query/src/test/java/org/infinispan/query/statetransfer/StateTransferQueryIndexTest.java
package org.infinispan.query.statetransfer; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.test.Person; import org.testng.annotations.Test; /** * Test that verifies that querying works even after a new node is added and * state transfer has provided it with the data belonging to that node. * * @author Galder Zamarreño * @since 5.2 */ @Test(groups = "functional", testName = "query.statetransfer.StateTransferQueryIndexTest") public class StateTransferQueryIndexTest extends BaseReIndexingTest { @Override protected void configureCache(ConfigurationBuilder builder) { builder.clustering().stateTransfer().fetchInMemoryState(true); } public void testQueryAfterAddingNewNode() throws Exception { loadCacheEntries(this.<String, Person>caches().get(0)); // Before adding a node, verify that the query resolves properly executeSimpleQuery(this.<String, Person>caches().get(0)); addNodeCheckingContentsAndQuery(); } }
1,016
30.78125
90
java
null
infinispan-main/query/src/test/java/org/infinispan/query/backend/QueryInterceptorIndexingOperationsTest.java
package org.infinispan.query.backend; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import java.io.IOException; import org.apache.lucene.index.SegmentInfos; import org.apache.lucene.store.Directory; import org.infinispan.Cache; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; 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.helper.TestQueryHelperFactory; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Tests to verify if unnecessary index operations are sent. * * @author gustavonalle * @since 7.0 */ @Test(groups = "functional", testName = "query.backend.QueryInterceptorIndexingOperationsTest") public class QueryInterceptorIndexingOperationsTest extends SingleCacheManagerTest { public QueryInterceptorIndexingOperationsTest() { cleanup = CleanupPhase.AFTER_METHOD; } public void testAvoidUnnecessaryRemoveForSimpleUpdate() throws Exception { Directory directory = initializeAndExtractDirectory(cache, Entity1.class); Entity1 entity1 = new Entity1("e1"); cache.put(1, entity1); long commits = doRecordingCommits(directory, cache, () -> cache.put(1, new Entity1("e2"))); assertEquals(1, commits); assertEquals(1, countIndexedDocuments(Entity1.class)); assertEquals(0, countIndexedDocuments(Entity2.class)); } public void testOverrideNonIndexedByIndexed() throws Exception { Directory directory = initializeAndExtractDirectory(cache, Entity1.class); cache.put(1, "string value"); long commits = doRecordingCommits(directory, cache, () -> cache.put(1, new Entity1("e1")) ); assertEquals(1, commits); assertEquals(1, countIndexedDocuments(Entity1.class)); assertEquals(0, countIndexedDocuments(Entity2.class)); } public void testOverrideIndexedByNonIndexed() throws Exception { Directory directory = initializeAndExtractDirectory(cache, Entity1.class); final Entity1 entity1 = new Entity1("title"); cache.put(1, entity1); long commits = doRecordingCommits(directory, cache, () -> cache.put(1, "another")); assertEquals(1, commits); assertEquals(0, countIndexedDocuments(Entity1.class)); assertEquals(0, countIndexedDocuments(Entity2.class)); } public void testOverrideIndexedByOtherIndexed() throws Exception { Directory directory1 = initializeAndExtractDirectory(cache, Entity1.class); Directory directory2 = initializeAndExtractDirectory(cache, Entity2.class); final Entity1 entity1 = new Entity1("title"); cache.put(1, entity1); long initialGenDir1 = SegmentInfos.getLastCommitGeneration(directory1); long commitsDir2 = doRecordingCommits(directory2, cache, () -> cache.put(1, new Entity2("title2"))); long commitsDir1 = SegmentInfos.getLastCommitGeneration(directory1) - initialGenDir1; assertEquals(3, commitsDir1 + commitsDir2); assertEquals(0, countIndexedDocuments(Entity1.class)); assertEquals(1, countIndexedDocuments(Entity2.class)); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { final ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(false); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Entity1.class) .addIndexedEntity(Entity2.class); ConfigurationBuilderHolder holder = new ConfigurationBuilderHolder(); holder.getGlobalConfigurationBuilder() .clusteredDefault() .defaultCacheName(TestCacheManagerFactory.DEFAULT_CACHE_NAME) .serialization().addContextInitializer(QueryTestSCI.INSTANCE); holder.getNamedConfigurationBuilders().put(TestCacheManagerFactory.DEFAULT_CACHE_NAME, builder); return TestCacheManagerFactory.newDefaultCacheManager(true, holder); } interface Operation { void execute(); } static long doRecordingCommits(Directory directory, Cache<Object, Object> cache, Operation operation) throws IOException { long initialGen = SegmentInfos.getLastCommitGeneration(directory); // if the file is not already present gen is -1, // after the first change it will become 1 if (initialGen == -1) { initialGen = 0; } operation.execute(); TestQueryHelperFactory.extractSearchMapping(cache).scopeAll().workspace().flush(); return SegmentInfos.getLastCommitGeneration(directory) - initialGen; } private Directory initializeAndExtractDirectory(Cache cache, Class<?> entityType) { return IndexAccessor.of(cache, entityType).getDirectory(); } private long countIndexedDocuments(Class<?> clazz) { Query<?> query = Search.getQueryFactory(cache).create("FROM " + clazz.getName()); return query.execute().count().value(); } @Indexed(index = "theIndex1") public static class Entity1 { @Basic private final String attribute; public Entity1(String attribute) { this.attribute = attribute; } public String getAttribute() { return attribute; } } @Indexed(index = "theIndex2") public static class Entity2 { @Basic private final String attribute; public Entity2(String attribute) { this.attribute = attribute; } public String getAttribute() { return attribute; } } }
5,929
34.508982
125
java
null
infinispan-main/query/src/test/java/org/infinispan/query/backend/MultipleEntitiesTest.java
package org.infinispan.query.backend; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.Assert.assertEquals; import java.util.Date; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; 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.QueryTestSCI; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Test for multiple entities types in the same cache sharing the same index * * @author gustavonalle * @since 7.1 */ @Test(groups = "functional", testName = "query.backend.MultipleEntitiesTest") public class MultipleEntitiesTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(false); cfg.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Bond.class) .addIndexedEntity(Debenture.class); return TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE, cfg); } @Test public void testIndexAndQuery() { QueryFactory queryFactory = Search.getQueryFactory(cache); cache.put(123405, new Bond(new Date(System.currentTimeMillis()), 450L)); cache.put(123502, new Debenture("GB", 116d)); cache.put(223456, new Bond(new Date(System.currentTimeMillis()), 550L)); Query<?> query = queryFactory.create("FROM " + Bond.class.getName()); Query<?> query2 = queryFactory.create("FROM " + Debenture.class.getName()); assertEquals(query.list().size() + query2.list().size(), 3); Query<?> queryBond = queryFactory.create("FROM " + Bond.class.getName()); assertEquals(queryBond.execute().count().value(), 2); Query<?> queryDeb = queryFactory.create("FROM " + Debenture.class.getName()); assertEquals(queryDeb.execute().count().value(), 1); } } @Indexed(index = "instruments") class Bond { @Basic Date maturity; @Basic Long price; public Bond(Date maturity, Long price) { this.maturity = maturity; this.price = price; } } @Indexed(index = "instruments_") class Debenture { @Basic String issuer; @Basic Double rate; public Debenture(String issuer, Double rate) { this.issuer = issuer; this.rate = rate; } }
2,667
29.318182
84
java
null
infinispan-main/query/src/test/java/org/infinispan/query/backend/QueryInterceptorTest.java
package org.infinispan.query.backend; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.io.File; import java.nio.file.Files; import java.util.concurrent.atomic.LongAdder; import org.apache.lucene.index.SegmentInfos; import org.infinispan.Cache; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.IndexStorage; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.eviction.EvictionType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated; import org.infinispan.notifications.cachelistener.event.CacheEntryActivatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryPassivatedEvent; import org.infinispan.query.Indexer; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.helper.TestQueryHelperFactory; import org.infinispan.query.queries.faceting.Car; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Test for interaction of activation and preload on indexing. * * @author gustavonalle * @since 7.0 */ @Test(groups = "functional", testName = "query.backend.QueryInterceptorTest") public class QueryInterceptorTest extends AbstractInfinispanTest { private static final int MAX_CACHE_ENTRIES = 1; private File indexDir; private File storeDir; private final Person person1 = new Person("p1", "b1", 12); private final Person person2 = new Person("p2", "b2", 22); private final Car car1 = new Car("subaru", "blue", 200); private final Car car2 = new Car("lamborghini", "yellow", 230); @BeforeMethod protected void setup() throws Exception { indexDir = Files.createTempDirectory("test-").toFile(); storeDir = Files.createTempDirectory("test-").toFile(); } @AfterMethod protected void tearDown() { Util.recursiveFileRemove(indexDir); Util.recursiveFileRemove(storeDir); } @Test public void shouldNotReindexOnActivation() throws Exception { withCacheManager(new CacheManagerCallable(createCacheManager(MAX_CACHE_ENTRIES)) { @Override public void call() { LuceneIndexTracker luceneIndexTracker = new LuceneIndexTracker(new File(indexDir + "/person")); luceneIndexTracker.mark(); Cache<String, Person> cache = cm.getCache(); CacheListener<String, Person> cacheListener = new CacheListener<>(); cache.addListener(cacheListener); cache.put("key1", person1); cache.put("key2", person2); forceCommit(cache); // Notification is non blocking eventuallyEquals(1, cacheListener::numberOfPassivations); assertEquals(cacheListener.numberOfActivations(), 0); assertTrue(luceneIndexTracker.indexChanged()); luceneIndexTracker.mark(); cache.get("key1"); assertEquals(cacheListener.numberOfActivations(), 1); assertFalse(luceneIndexTracker.indexChanged()); } }); } @Test public void shouldNotReindexOnPreload() throws Exception { final LuceneIndexTracker luceneIndexTracker = new LuceneIndexTracker(new File(indexDir + "/person")); luceneIndexTracker.mark(); withCacheManager(new CacheManagerCallable(createCacheManager(MAX_CACHE_ENTRIES)) { @Override public void call() { Cache<String, Person> cache = cm.getCache(); cache.put("key1", person1); cache.put("key2", person2); forceCommit(cache); assertTrue(luceneIndexTracker.indexChanged()); } }); luceneIndexTracker.mark(); withCacheManager(new CacheManagerCallable(createCacheManager(MAX_CACHE_ENTRIES + 10)) { @Override public void call() { Cache<String, Person> cache = cm.getCache(); CacheListener<String, Person> cacheListener = new CacheListener<>(); cache.addListener(cacheListener); assertTrue(cache.containsKey("key1")); assertTrue(cache.containsKey("key2")); assertEquals(cacheListener.numberOfPassivations(), 0); assertEquals(cacheListener.numberOfActivations(), 0); assertFalse(luceneIndexTracker.indexChanged()); } }); } @Test public void shouldDeleteSingleIndex() throws Exception { withCacheManager(new CacheManagerCallable(createCacheManager(MAX_CACHE_ENTRIES)) { @Override public void call() { Cache<String, Object> cache = cm.getCache(); cache.put("P1", person1); cache.put("P2", person2); cache.put("C1", car1); cache.put("C2", car2); forceCommit(cache); assertEquals(2, countIndex(Car.class, cache)); assertEquals(2, countIndex(Person.class, cache)); Indexer indexer = Search.getIndexer(cache); CompletionStages.join(indexer.remove(Car.class)); assertEquals(0, countIndex(Car.class, cache)); assertEquals(2, countIndex(Person.class, cache)); CompletionStages.join(indexer.remove(Person.class)); assertEquals(0, countIndex(Car.class, cache)); assertEquals(0, countIndex(Person.class, cache)); } }); } protected EmbeddedCacheManager createCacheManager(int maxEntries) throws Exception { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault(); globalBuilder.globalState().enable().persistentLocation(storeDir.getAbsolutePath()); globalBuilder.serialization().addContextInitializer(QueryTestSCI.INSTANCE); ConfigurationBuilder b = new ConfigurationBuilder(); b.memory().evictionType(EvictionType.COUNT).size(maxEntries) .persistence().passivation(true) .addSingleFileStore().preload(true) .indexing().enable() .storage(IndexStorage.FILESYSTEM).path(indexDir.getAbsolutePath()) .addIndexedEntity(Person.class) .addIndexedEntity(Car.class); return TestCacheManagerFactory.createCacheManager(globalBuilder, b); } private long countIndex(Class<?> entityType, Cache<?, ?> cache) { Query<?> query = Search.getQueryFactory(cache).create("FROM " + entityType.getName()); return query.execute().count().value(); } private void forceCommit(Cache<?, ?> cache) { TestQueryHelperFactory.extractSearchMapping(cache).scopeAll().workspace().flush(); } private static final class LuceneIndexTracker { private final File indexBase; private long indexVersion; public LuceneIndexTracker(File indexBase) { this.indexBase = indexBase; } public void mark() { indexVersion = getLuceneIndexVersion(); } public boolean indexChanged() { return getLuceneIndexVersion() != indexVersion; } private long getLuceneIndexVersion() { return indexBase.list() == null ? -1 : SegmentInfos.getLastCommitGeneration(indexBase.list()); } } @Listener @SuppressWarnings("unused") private static final class CacheListener<K, V> { private final LongAdder passivationCount = new LongAdder(); private final LongAdder activationCount = new LongAdder(); @CacheEntryPassivated public void onEvent(CacheEntryPassivatedEvent<K, V> payload) { if (!payload.isPre()) { passivationCount.increment(); } } @CacheEntryActivated public void onEvent(CacheEntryActivatedEvent<K, V> payload) { if (!payload.isPre()) { activationCount.increment(); } } public int numberOfPassivations() { return passivationCount.intValue(); } public int numberOfActivations() { return activationCount.intValue(); } } }
8,728
35.370833
107
java
null
infinispan-main/query/src/test/java/org/infinispan/query/backend/KeyTransformationHandlerTest.java
package org.infinispan.query.backend; import static org.testng.AssertJUnit.assertEquals; import java.util.Base64; import java.util.UUID; import org.infinispan.commons.CacheException; import org.infinispan.commons.util.Util; import org.infinispan.query.Transformer; import org.infinispan.query.test.CustomKey; import org.infinispan.query.test.CustomKey2; import org.infinispan.query.test.CustomKey3; import org.infinispan.query.test.CustomKey3Transformer; import org.infinispan.query.test.NonSerializableKey; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * This is the test class for {@link org.infinispan.query.backend.KeyTransformationHandler}. * * @author Navin Surtani * @author Marko Luksa */ @Test(groups = "functional", testName = "query.backend.KeyTransformationHandlerTest") public class KeyTransformationHandlerTest { private KeyTransformationHandler keyTransformationHandler; private final UUID randomUUID = Util.threadLocalRandomUUID(); @BeforeMethod public void beforeMethod() { keyTransformationHandler = new KeyTransformationHandler(null); } public void testKeyToStringWithStringAndPrimitives() { String s = keyTransformationHandler.keyToString("key"); assert s.equals("S:key"); s = keyTransformationHandler.keyToString(1); assert s.equals("I:1"); s = keyTransformationHandler.keyToString(true); assert s.equals("B:true"); s = keyTransformationHandler.keyToString((short) 1); assert s.equals("X:1"); s = keyTransformationHandler.keyToString((long) 1); assert s.equals("L:1"); s = keyTransformationHandler.keyToString((byte) 1); assert s.equals("Y:1"); s = keyTransformationHandler.keyToString((float) 1); assert s.equals("F:1.0"); s = keyTransformationHandler.keyToString('A'); assert s.equals("C:A"); s = keyTransformationHandler.keyToString(1.0); assert s.equals("D:1.0"); s = keyTransformationHandler.keyToString(randomUUID); assert s.equals("U:" + randomUUID); byte[] arr = new byte[]{1, 2, 3, 4, 5, 6}; s = keyTransformationHandler.keyToString(arr); assert s.equals("A:" + Base64.getEncoder().encodeToString(arr)); } public void testStringToKeyWithStringAndPrimitives() { Object key = keyTransformationHandler.stringToKey("S:key1"); assert key.getClass().equals(String.class); assert key.equals("key1"); key = keyTransformationHandler.stringToKey("I:2"); assert key.getClass().equals(Integer.class); assert key.equals(2); key = keyTransformationHandler.stringToKey("Y:3"); assert key.getClass().equals(Byte.class); assert key.equals((byte) 3); key = keyTransformationHandler.stringToKey("F:4.0"); assert key.getClass().equals(Float.class); assert key.equals((float) 4.0); key = keyTransformationHandler.stringToKey("L:5"); assert key.getClass().equals(Long.class); assert key.equals((long) 5); key = keyTransformationHandler.stringToKey("X:6"); assert key.getClass().equals(Short.class); assert key.equals((short) 6); key = keyTransformationHandler.stringToKey("B:true"); assert key.getClass().equals(Boolean.class); assert key.equals(true); key = keyTransformationHandler.stringToKey("D:8.0"); assert key.getClass().equals(Double.class); assert key.equals(8.0); key = keyTransformationHandler.stringToKey("C:9"); assert key.getClass().equals(Character.class); assert key.equals('9'); key = keyTransformationHandler.stringToKey("U:" + randomUUID); assert key.getClass().equals(UUID.class); assert key.equals(randomUUID); byte[] arr = new byte[]{1, 2, 3, 4, 5, 6}; key = keyTransformationHandler.stringToKey("A:" + Base64.getEncoder().encodeToString(arr)); assertEquals(arr, (byte[]) key); } @Test(expectedExceptions = CacheException.class) public void testStringToUnknownKey() { keyTransformationHandler.stringToKey("Z:someKey"); } @Test(expectedExceptions = CacheException.class) public void testStringToKeyWithInvalidTransformer() { keyTransformationHandler.stringToKey("T:org.infinispan.InexistentTransformer:key1"); } public void testStringToKeyWithCustomTransformable() { CustomKey customKey = new CustomKey(88, 8800, 12889976); String strRep = keyTransformationHandler.keyToString(customKey); Object keyAgain = keyTransformationHandler.stringToKey(strRep); assertEquals(customKey, keyAgain); } public void testStringToKeyWithDefaultTransformer() { CustomKey2 ck2 = new CustomKey2(Integer.MAX_VALUE, Integer.MIN_VALUE, 0); String strRep = keyTransformationHandler.keyToString(ck2); Object keyAgain = keyTransformationHandler.stringToKey(strRep); assertEquals(ck2, keyAgain); } public void testStringToKeyWithRegisteredTransformer() { keyTransformationHandler.registerTransformer(CustomKey3.class, CustomKey3Transformer.class); CustomKey3 key = new CustomKey3("str"); String string = keyTransformationHandler.keyToString(key); Object keyAgain = keyTransformationHandler.stringToKey(string); assertEquals(key, keyAgain); } @Test(expectedExceptions = CacheException.class) public void testStringToKeyWithNoAvailableTransformer() { CustomKey3 key = new CustomKey3("str"); String string = keyTransformationHandler.keyToString(key); Object keyAgain = keyTransformationHandler.stringToKey(string); assertEquals(key, keyAgain); } @Test(expectedExceptions = CacheException.class) public void testKeyToStringWithExceptionalTransformer() { keyTransformationHandler.registerTransformer(CustomKey2.class, ExceptionThrowingTransformer.class); CustomKey2 key = new CustomKey2(1, 2, 3); keyTransformationHandler.keyToString(key); } @Test(expectedExceptions = IllegalArgumentException.class) public void testKeyToStringWithDefaultTransformerForNonSerializableObject() { NonSerializableKey key = new NonSerializableKey("test"); keyTransformationHandler.keyToString(key); } public static class ExceptionThrowingTransformer implements Transformer { public ExceptionThrowingTransformer() { throw new RuntimeException("Shaka Laka Boom Boom"); } @Override public Object fromString(String s) { return null; } @Override public String toString(Object customType) { return null; } } }
6,625
33.691099
105
java
null
infinispan-main/query/src/test/java/org/infinispan/query/timeout/TestHelper.java
package org.infinispan.query.timeout; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.test.Person; class TestHelper { static void runFullTextQueryWithTimeout(Cache<?, ?> cache, long timeout, TimeUnit timeUnit) { QueryFactory queryFactory = Search.getQueryFactory(cache); String q = String.format("FROM %s WHERE name:'name_*'", Person.class.getName()); Query<?> query = queryFactory.create(q).timeout(timeout, timeUnit); query.execute(); } static void runRegularQueryWithTimeout(Cache<?, ?> cache, long timeout, TimeUnit timeUnit) { QueryFactory queryFactory = Search.getQueryFactory(cache); String q = String.format("FROM %s WHERE name LIKE 'name_%%'", Person.class.getName()); Query<?> query = queryFactory.create(q).timeout(timeout, timeUnit); query.execute(); } static void runRegularSortedQueryWithTimeout(Cache<?, ?> cache, long timeout, TimeUnit timeUnit) { QueryFactory queryFactory = Search.getQueryFactory(cache); String q = String.format("FROM %s WHERE name LIKE 'name_%%' ORDER BY name", Person.class.getName()); Query<?> query = queryFactory.create(q).timeout(timeout, timeUnit); query.execute(); } static void populate(Cache cache, int numEntries) { for (int i = 0; i < numEntries; i++) { cache.put(i, new Person("name_" + i, "", 0)); } } }
1,546
37.675
106
java
null
infinispan-main/query/src/test/java/org/infinispan/query/timeout/DistributedNonIndexedTimeoutTest.java
package org.infinispan.query.timeout; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.SearchTimeoutException; import org.infinispan.query.test.QueryTestSCI; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.timeout.DistributedNonIndexedTimeoutTest") public class DistributedNonIndexedTimeoutTest extends DistributedIndexedTimeoutTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); createClusteredCaches(2, QueryTestSCI.INSTANCE, cacheCfg); cache1 = cache(0); } @Test(expectedExceptions = SearchTimeoutException.class) public void testTimeout() { TestHelper.runRegularQueryWithTimeout(cache1, 1, TimeUnit.NANOSECONDS); } @Test(expectedExceptions = SearchTimeoutException.class) public void testTimeoutSortedQuery() { TestHelper.runRegularSortedQueryWithTimeout(cache1, 1, TimeUnit.NANOSECONDS); } }
1,142
35.870968
97
java
null
infinispan-main/query/src/test/java/org/infinispan/query/timeout/LocalIndexedTimeoutTest.java
package org.infinispan.query.timeout; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.SearchTimeoutException; 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; @Test(groups = "functional", testName = "query.timeout.LocalIndexedTimeoutTest") public class LocalIndexedTimeoutTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cacheCfg = getDefaultStandaloneCacheConfig(false); cacheCfg.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); return TestCacheManagerFactory.createCacheManager(cacheCfg); } @BeforeMethod public void populate() { TestHelper.populate(cache, 10000); } @Test(expectedExceptions = SearchTimeoutException.class) public void testTimeout() { TestHelper.runFullTextQueryWithTimeout(cache, 1, TimeUnit.NANOSECONDS); } }
1,321
33.789474
80
java
null
infinispan-main/query/src/test/java/org/infinispan/query/timeout/LocalNonIndexedTimeoutTest.java
package org.infinispan.query.timeout; import java.util.concurrent.TimeUnit; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.SearchTimeoutException; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.timeout.LocalNonIndexedTimeoutTest") public class LocalNonIndexedTimeoutTest extends LocalIndexedTimeoutTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE, getDefaultStandaloneCacheConfig(false)); } @Test(expectedExceptions = SearchTimeoutException.class) public void testTimeout() { TestHelper.runRegularQueryWithTimeout(cache, 1, TimeUnit.NANOSECONDS); } @Test(expectedExceptions = SearchTimeoutException.class) public void testTimeoutSortedQuery() { TestHelper.runRegularSortedQueryWithTimeout(cache, 1, TimeUnit.NANOSECONDS); } }
1,060
35.586207
119
java
null
infinispan-main/query/src/test/java/org/infinispan/query/timeout/DistributedIndexedTimeoutTest.java
package org.infinispan.query.timeout; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.SearchTimeoutException; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.timeout.DistributedIndexedTimeoutTest") public class DistributedIndexedTimeoutTest extends MultipleCacheManagersTest { protected Cache<Integer, Person> cache1; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); cacheCfg.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); createClusteredCaches(2, QueryTestSCI.INSTANCE, cacheCfg); cache1 = cache(0); } @BeforeMethod public void populate() { TestHelper.populate(cache1, 10000); } @Test(expectedExceptions = SearchTimeoutException.class) public void testTimeout() { TestHelper.runFullTextQueryWithTimeout(cache1, 1, TimeUnit.NANOSECONDS); } }
1,434
34
97
java
null
infinispan-main/query/src/test/java/org/infinispan/query/encoding/ProtobufEncodedIndexedCacheTest.java
package org.infinispan.query.encoding; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.commons.dataconversion.MediaType; 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.Book; import org.infinispan.query.model.Game; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "org.infinispan.query.encoding.ProtobufEncodedIndexedCacheTest") public class ProtobufEncodedIndexedCacheTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(false); builder .encoding() .mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE) .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity("org.infinispan.query.model.Game"); cacheManager = TestCacheManagerFactory.createCacheManager(Game.GameSchema.INSTANCE, null); cache = cacheManager.administration() .withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .getOrCreateCache("default", builder.build()); return cacheManager; } @Test public void test() { cache.put(1, new Game("Civilization 1", "The best video game of all time!")); // according to the contributor QueryFactory factory = Search.getQueryFactory(cache); Query<Book> query = factory.create("from org.infinispan.query.model.Game where description : 'game'"); QueryResult<Book> result = query.execute(); assertThat(result.count().isExact()).isTrue(); assertThat(result.count().value()).isEqualTo(1); assertThat(result.list()).extracting("name").contains("Civilization 1"); } }
2,251
40.703704
115
java
null
infinispan-main/query/src/test/java/org/infinispan/query/startup/IndexStartupModeTest.java
package org.infinispan.query.startup; import static org.assertj.core.api.Assertions.assertThat; import org.infinispan.Cache; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.IndexStartupMode; import org.infinispan.configuration.cache.IndexStorage; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.TotalHitCount; import org.infinispan.query.model.Developer; 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; @Test(groups = "functional", testName = "query.startup.IndexStartupModeTest") public class IndexStartupModeTest extends AbstractInfinispanTest { private final String fileStoreDataLocation = CommonsTestingUtil.tmpDirectory("IndexStartupModeTest", "fileStoreDataLocation"); private final String fileStoreIndexLocation = CommonsTestingUtil.tmpDirectory("IndexStartupModeTest", "fileStoreIndexLocation"); private final String indexesLocation = CommonsTestingUtil.tmpDirectory("IndexStartupModeTest", "indexes"); private EmbeddedCacheManager cacheManager; private Cache<String, Developer> cache; private QueryFactory queryFactory; public void volatileDataNonVolatileIndexes_purgeAtStartup() { execute(IndexStorage.FILESYSTEM, false, IndexStartupMode.PURGE, () -> { verifyMatches(0, "fax4ever"); cache.put("fabio", new Developer("fax4ever", "fax@redmail.io", "Infinispan developer", 0)); verifyMatches(1, "fax4ever"); }); execute(IndexStorage.FILESYSTEM, false, IndexStartupMode.NONE, () -> { // data is not present anymore assertThat(cache.get("fabio")).isNull(); // but by default no purge is applied on persisted indexes verifyMatches(1, "fax4ever"); }); execute(IndexStorage.FILESYSTEM, false, IndexStartupMode.PURGE, () -> { // with the initial purge the persisted indexes are wiped out at cache startup verifyMatches(0, "fax4ever"); cache.put("fabio", new Developer("fax4ever", "fax@redmail.io", "Infinispan developer", 0)); // recreate the index for the next executions verifyMatches(1, "fax4ever"); }); execute(IndexStorage.FILESYSTEM, false, IndexStartupMode.NONE, () -> { // data is not present anymore assertThat(cache.get("fabio")).isNull(); // but by default no purge is applied on persisted indexes verifyMatches(1, "fax4ever"); }); execute(IndexStorage.FILESYSTEM, false, IndexStartupMode.AUTO, () -> { // auto in this case is equivalent to purge verifyMatches(0, "fax4ever"); }); } public void nonVolatileDataVolatileIndexes_reindexAtStartup() { execute(IndexStorage.LOCAL_HEAP, true, IndexStartupMode.NONE, () -> { verifyMatches(0, "fax4ever"); cache.put("fabio", new Developer("fax4ever", "fax@redmail.io", "Infinispan developer", 0)); verifyMatches(1, "fax4ever"); }); execute(IndexStorage.LOCAL_HEAP, true, IndexStartupMode.NONE, () -> { // data is still present Developer fabio = cache.get("fabio"); assertThat(fabio).isNotNull(); assertThat(fabio.getNick()).isEqualTo("fax4ever"); // but indexes have gone! verifyMatches(0, "fax4ever"); }); execute(IndexStorage.LOCAL_HEAP, true, IndexStartupMode.REINDEX, () -> { // data is still present Developer fabio = cache.get("fabio"); assertThat(fabio).isNotNull(); assertThat(fabio.getNick()).isEqualTo("fax4ever"); eventually(() -> { // now indexes are aligned return matches(1, "fax4ever"); }); }); execute(IndexStorage.LOCAL_HEAP, true, IndexStartupMode.NONE, () -> { // data is still present Developer fabio = cache.get("fabio"); assertThat(fabio).isNotNull(); assertThat(fabio.getNick()).isEqualTo("fax4ever"); // but indexes have gone! verifyMatches(0, "fax4ever"); }); execute(IndexStorage.LOCAL_HEAP, true, IndexStartupMode.AUTO, () -> { // data is still present Developer fabio = cache.get("fabio"); assertThat(fabio).isNotNull(); assertThat(fabio.getNick()).isEqualTo("fax4ever"); // auto in this case is equivalent to reindex eventually(() -> { // now indexes are aligned return matches(1, "fax4ever"); }); }); } @BeforeClass(alwaysRun = true) public void setUp() { Util.recursiveFileRemove(fileStoreDataLocation); Util.recursiveFileRemove(fileStoreIndexLocation); Util.recursiveFileRemove(indexesLocation); } @AfterClass(alwaysRun = true) public void tearDown() { Util.recursiveFileRemove(fileStoreDataLocation); Util.recursiveFileRemove(fileStoreIndexLocation); Util.recursiveFileRemove(indexesLocation); } private void execute(IndexStorage storage, boolean cacheStorage, IndexStartupMode startupMode, Runnable runnable) { try { recreateCacheManager(storage, cacheStorage, startupMode); runnable.run(); } finally { eventually( () -> // Wait for a possible ongoing reindexing !Search.getSearchStatistics(cache).getIndexStatistics().reindexing() ); TestingUtil.killCacheManagers(cacheManager); } } private void recreateCacheManager(IndexStorage storage, boolean persistentCacheData, IndexStartupMode startupMode) { ConfigurationBuilder cfg = new ConfigurationBuilder(); cfg.indexing() .enable() .storage(storage) .path(indexesLocation) .startupMode(startupMode) .addIndexedEntity(Developer.class); if (persistentCacheData) { cfg.persistence() .addSoftIndexFileStore() .dataLocation(fileStoreDataLocation) .indexLocation(fileStoreIndexLocation) .preload(true); } cacheManager = TestCacheManagerFactory.createCacheManager(cfg); cache = cacheManager.getCache(); queryFactory = Search.getQueryFactory(cache); } private void verifyMatches(int i, String nick) { String query = String.format("from %s where nick = '%s'", Developer.class.getName(), nick); assertThat(queryFactory.create(query).execute().count().value()).isEqualTo(i); } private boolean matches(int i, String nick) { String query = String.format("from %s where nick = '%s'", Developer.class.getName(), nick); TotalHitCount hitCount = queryFactory.create(query).execute().count(); assertThat(hitCount.isExact()).isTrue(); return hitCount.value() == i; } }
7,203
36.717277
131
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/ClusteredListenerWithDslFilterTest.java
package org.infinispan.query.dsl.embedded; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.MagicKey; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.ParsingException; 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.MultipleCacheManagersTest; import org.testng.annotations.Test; /** * @author anistor@redhat.com * @since 7.2 */ @Test(groups = "functional", testName = "query.dsl.embedded.ClusteredListenerWithDslFilterTest") public class ClusteredListenerWithDslFilterTest extends MultipleCacheManagersTest { private final int NUM_NODES = 3; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfgBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); createClusteredCaches(NUM_NODES, DslSCI.INSTANCE, cfgBuilder); } public void testEventFilter() { QueryFactory qf = Search.getQueryFactory(cache(0)); Query<Person> query = qf.create("FROM " + Person.class.getName() + " WHERE age <= 31"); EntryListener listener = new EntryListener(); for (int i = 0; i < 5; ++i) { Person value = new Person(); value.setName("John"); value.setAge(i + 30); Cache<Object, Person> cache = cache(i % NUM_NODES); Object key = new MagicKey(cache); cache.put(key, value); } // we want our cluster listener to be notified only if the entity matches our query cache(0).addListener(listener, Search.makeFilter(query), null); for (int i = 0; i < 10; ++i) { Person value = new Person(); value.setName("John"); value.setAge(i + 25); Cache<Object, Person> cache = cache(i % NUM_NODES); Object key = new MagicKey(cache); cache.put(key, value); } assertEquals(9, listener.results.size()); for (ObjectFilter.FilterResult r : listener.results) { Person p = (Person) r.getInstance(); assertTrue(p.getAge() <= 31); } cache(0).removeListener(listener); // ensure no more invocations after the listener was removed listener.results.clear(); Person value = new Person(); value.setName("George"); value.setAge(30); Object key = new MagicKey(cache(0)); cache(0).put(key, value); assertEquals(0, listener.results.size()); } public void testEventFilterAndConverter() { QueryFactory qf = Search.getQueryFactory(cache(0)); Query<Object[]> query = qf.create("SELECT name, age FROM " + Person.class.getName() + " WHERE age <= 31"); EntryListener listener = new EntryListener(); for (int i = 0; i < 5; ++i) { Person value = new Person(); value.setName("John"); value.setAge(i + 30); Cache<Object, Person> cache = cache(i % NUM_NODES); Object key = new MagicKey(cache); cache.put(key, value); } // we want our cluster listener to be notified only if the entity matches our query cache(0).addListener(listener, Search.makeFilter(query), null); for (int i = 0; i < 10; ++i) { Person value = new Person(); value.setName("John"); value.setAge(i + 25); Cache<Object, Person> cache = cache(i % NUM_NODES); Object key = new MagicKey(cache); cache.put(key, value); } assertEquals(9, listener.results.size()); for (ObjectFilter.FilterResult r : listener.results) { assertTrue((Integer) r.getProjection()[1] <= 31); } cache(0).removeListener(listener); } /** * Using grouping and aggregation with event filters is not allowed. */ @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = ".*ISPN028509:.*") public void testDisallowGroupingAndAggregation() { QueryFactory qf = Search.getQueryFactory(cache(0)); Query<Object[]> query = qf.create("SELECT MAX(age) FROM " + Person.class.getName() + " WHERE age >= 20"); cache(0).addListener(new EntryListener(), Search.makeFilter(query), null); } @Listener(clustered = true, includeCurrentState = true) private static class EntryListener { // this is where we accumulate matches public final List<ObjectFilter.FilterResult> results = Collections.synchronizedList(new ArrayList<>()); @CacheEntryCreated public void handleEvent(CacheEntryCreatedEvent<?, ObjectFilter.FilterResult> event) { if (!event.isPre()) { ObjectFilter.FilterResult filterResult = event.getValue(); results.add(filterResult); } } @CacheEntryModified public void handleEvent(CacheEntryModifiedEvent<?, ObjectFilter.FilterResult> event) { if (!event.isPre()) { ObjectFilter.FilterResult filterResult = event.getValue(); results.add(filterResult); } } } }
5,742
34.233129
112
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/ClusteredListenerWithDslFilterProfilingTest.java
package org.infinispan.query.dsl.embedded; import java.util.ArrayList; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; 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.MultipleCacheManagersTest; import org.testng.annotations.Test; /** * @author anistor@redhat.com * @since 7.2 */ @Test(groups = "profiling", testName = "query.dsl.embedded.ClusteredListenerWithDslFilterProfilingTest") public class ClusteredListenerWithDslFilterProfilingTest extends MultipleCacheManagersTest { private static final int NUM_NODES = 10; private static final int NUM_OWNERS = 3; private static final int NUM_ENTRIES = 100000; private static final int NUM_LISTENERS = 1000; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfgBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); cfgBuilder.clustering().hash().numOwners(NUM_OWNERS); createClusteredCaches(NUM_NODES, DslSCI.INSTANCE, cfgBuilder); } public void testEventFilterPerformance() { long t1 = testEventFilterPerformance(false); long t2 = testEventFilterPerformance(true); log.infof("ClusteredListenerWithDslFilterProfilingTest.testEventFilterPerformance doRegisterListener=false took %d us\n", t1 / 1000); log.infof("ClusteredListenerWithDslFilterProfilingTest.testEventFilterPerformance doRegisterListener=true took %d us\n", t2 / 1000); } private long testEventFilterPerformance(boolean doRegisterListener) { List<NoOpEntryListener> listeners = new ArrayList<>(NUM_LISTENERS); if (doRegisterListener) { Query<Person> query = makeQuery(cache(0)); for (int i = 0; i < NUM_LISTENERS; i++) { NoOpEntryListener listener = new NoOpEntryListener(); listeners.add(listener); cache(0).addListener(listener, Search.makeFilter(query), null); } } long startTs = System.nanoTime(); // create entries for (int i = 0; i < NUM_ENTRIES; ++i) { Person value = new Person(); value.setName("John"); value.setAge(i + 25); Cache<Object, Person> cache = cache(i % NUM_NODES); cache.put(value.getName(), value); } // update entries (with same value) for (int i = 0; i < NUM_ENTRIES; ++i) { Person value = new Person(); value.setName("John"); value.setAge(i + 25); Cache<Object, Person> cache = cache(i % NUM_NODES); cache.put(value.getName(), value); } long endTs = System.nanoTime(); for (NoOpEntryListener listener : listeners) { cache(0).removeListener(listener); } return endTs - startTs; } private Query<Person> makeQuery(Cache<?, ?> c) { QueryFactory qf = Search.getQueryFactory(c); return qf.create("FROM org.infinispan.query.test.Person WHERE age >= 18"); } @Listener(clustered = true) private static class NoOpEntryListener { @CacheEntryCreated public void handleEvent(CacheEntryCreatedEvent<?, ?> event) { } @CacheEntryModified public void handleEvent(CacheEntryModifiedEvent<?, ?> event) { } } }
3,812
35.663462
139
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/NonIndexedListenerWithDslFilterTest.java
package org.infinispan.query.dsl.embedded; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.objectfilter.ParsingException; import org.testng.annotations.Test; /** * @author anistor@redhat.com * @since 8.0 */ @Test(groups = "functional", testName = "query.dsl.embedded.NonIndexedListenerWithDslFilterTest") public class NonIndexedListenerWithDslFilterTest extends ListenerWithDslFilterTest { @Override protected ConfigurationBuilder getConfigurationBuilder() { return new ConfigurationBuilder(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'name' in type org.infinispan.query.test.Person unless the property is indexed and analyzed.") public void testDisallowFullTextQuery() { super.testDisallowFullTextQuery(); } }
893
36.25
243
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/ObjectStorageQueryDslConditionsTest.java
package org.infinispan.query.dsl.embedded; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.IndexStorage; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Verify query DSL when configuring object storage. Just a smoke test that executes in embedded mode and no interaction is done * via a remote client. This just ensures nothing gets broken on the embedded side if encoding configuration is active. * * @author Martin Gencur * @since 6.0 */ @Test(groups = "functional", testName = "query.dsl.embedded.ObjectStorageQueryDslConditionsTest") public class ObjectStorageQueryDslConditionsTest extends QueryDslConditionsTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfg = TestCacheManagerFactory.getDefaultCacheConfiguration(true); cfg.encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE); cfg.encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE); cfg.indexing().enable() .storage(IndexStorage.LOCAL_HEAP) .addIndexedEntity(getModelFactory().getUserImplClass()) .addIndexedEntity(getModelFactory().getAccountImplClass()) .addIndexedEntity(getModelFactory().getTransactionImplClass()); createClusteredCaches(1, cfg); } }
1,441
44.0625
128
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/TxClusteredQueryDslConditionsTest.java
package org.infinispan.query.dsl.embedded; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Verifies the functionality of Query DSL in clustered environment for ISPN directory provider. * * @author Dan Berindei * @since 7.0 */ @Test(groups = "functional", testName = "query.dsl.embedded.TxClusteredQueryDslConditionsTest") public class TxClusteredQueryDslConditionsTest extends ClusteredQueryDslConditionsTest { @Override protected ConfigurationBuilder initialCacheConfiguration() { ConfigurationBuilder cfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true); cfg.transaction().useSynchronization(false); return cfg; } }
775
32.73913
96
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/DslSCI.java
package org.infinispan.query.dsl.embedded; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.query.dsl.embedded.testdomain.Account; import org.infinispan.query.dsl.embedded.testdomain.NotIndexed; import org.infinispan.query.dsl.embedded.testdomain.User; import org.infinispan.query.dsl.embedded.testdomain.hsearch.AccountHS; import org.infinispan.query.dsl.embedded.testdomain.hsearch.AddressHS; import org.infinispan.query.dsl.embedded.testdomain.hsearch.LimitsHS; import org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS; import org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS; import org.infinispan.query.test.QueryTestSCI; @AutoProtoSchemaBuilder( dependsOn = QueryTestSCI.class, includeClasses = { AccountHS.class, AddressHS.class, Account.Currency.class, User.Gender.class, LimitsHS.class, NotIndexed.class, TransactionHS.class, UserHS.class }, schemaFileName = "test.query.dsl.proto", schemaFilePath = "proto/generated", schemaPackageName = "org.infinispan.test.query.dsl", service = false ) public interface DslSCI extends SerializationContextInitializer { DslSCI INSTANCE = new DslSCIImpl(); }
1,384
38.571429
74
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/QueryDslConditionsTest.java
package org.infinispan.query.dsl.embedded; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.query.dsl.Expression.avg; import static org.infinispan.query.dsl.Expression.count; import static org.infinispan.query.dsl.Expression.max; import static org.infinispan.query.dsl.Expression.min; import static org.infinispan.query.dsl.Expression.param; import static org.infinispan.query.dsl.Expression.property; import static org.infinispan.query.dsl.Expression.sum; import static org.testng.Assert.assertNotEquals; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.objectfilter.ParsingException; import org.infinispan.query.core.impl.EmbeddedQueryFactory; import org.infinispan.query.dsl.FilterConditionContext; import org.infinispan.query.dsl.FilterConditionEndContext; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryBuilder; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.SortOrder; import org.infinispan.query.dsl.embedded.testdomain.Account; import org.infinispan.query.dsl.embedded.testdomain.Address; import org.infinispan.query.dsl.embedded.testdomain.NotIndexed; import org.infinispan.query.dsl.embedded.testdomain.Transaction; import org.infinispan.query.dsl.embedded.testdomain.User; import org.infinispan.search.mapper.mapping.SearchMapping; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test for query conditions (filtering). Exercises the whole query DSL on the sample domain model. Uses indexing, * although some fields are not indexed in order to test hybrid queries too. * * @author anistor@redhat.com * @author rvansa@redhat.com * @author jmarkos@redhat.com * @since 6.0 */ @Test(groups = {"functional", "smoke"}, testName = "query.dsl.embedded.QueryDslConditionsTest") public class QueryDslConditionsTest extends AbstractQueryDslTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfg = TestCacheManagerFactory.getDefaultCacheConfiguration(true); cfg.transaction() .transactionMode(TransactionMode.TRANSACTIONAL) .indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(getModelFactory().getUserImplClass()) .addIndexedEntity(getModelFactory().getAccountImplClass()) .addIndexedEntity(getModelFactory().getTransactionImplClass()); createClusteredCaches(1, DslSCI.INSTANCE, cfg); } protected boolean testNullCollections() { return true; } @BeforeClass(alwaysRun = true) protected void populateCache() throws Exception { // create the test objects User user1 = getModelFactory().makeUser(); user1.setId(1); user1.setName("John"); user1.setSurname("Doe"); user1.setGender(User.Gender.MALE); user1.setAge(22); user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2))); user1.setNotes("Lorem ipsum dolor sit amet"); user1.setCreationDate(Instant.parse("2011-12-03T10:15:30Z")); user1.setPasswordExpirationDate(Instant.parse("2011-12-03T10:15:30Z")); Address address1 = getModelFactory().makeAddress(); address1.setStreet("Main Street"); address1.setPostCode("X1234"); address1.setNumber(156); user1.setAddresses(Collections.singletonList(address1)); User user2 = getModelFactory().makeUser(); user2.setId(2); user2.setName("Spider"); user2.setSurname("Man"); user2.setSalutation("Mr."); user2.setGender(User.Gender.MALE); user2.setAccountIds(Collections.singleton(3)); user2.setCreationDate(Instant.parse("2011-12-03T10:15:30Z")); user2.setPasswordExpirationDate(Instant.parse("2011-12-03T10:15:30Z")); Address address2 = getModelFactory().makeAddress(); address2.setStreet("Old Street"); address2.setPostCode("Y12"); address2.setNumber(-12); Address address3 = getModelFactory().makeAddress(); address3.setStreet("Bond Street"); address3.setPostCode("ZZ"); address3.setNumber(312); user2.setAddresses(Arrays.asList(address2, address3)); User user3 = getModelFactory().makeUser(); user3.setId(3); user3.setName("Spider"); user3.setSurname("Woman"); user3.setSalutation("Ms."); user3.setGender(User.Gender.FEMALE); user3.setAccountIds(Collections.emptySet()); user3.setCreationDate(Instant.parse("2011-12-03T10:15:30Z")); user3.setPasswordExpirationDate(Instant.parse("2011-12-03T10:15:30Z")); if (!testNullCollections()) { user3.setAddresses(new ArrayList<>()); } Account account1 = getModelFactory().makeAccount(); account1.setId(1); account1.setDescription("John Doe's first bank account"); account1.setCreationDate(makeDate("2013-01-03")); Account account2 = getModelFactory().makeAccount(); account2.setId(2); account2.setDescription("John Doe's second bank account"); account2.setCreationDate(makeDate("2013-01-04")); Account account3 = getModelFactory().makeAccount(); account3.setId(3); account3.setCreationDate(makeDate("2013-01-20")); Transaction transaction0 = getModelFactory().makeTransaction(); transaction0.setId(0); transaction0.setDescription("Birthday present"); transaction0.setAccountId(1); transaction0.setAmount(1800); transaction0.setDate(makeDate("2012-09-07")); transaction0.setDebit(false); transaction0.setValid(true); Transaction transaction1 = getModelFactory().makeTransaction(); transaction1.setId(1); transaction1.setDescription("Feb. rent payment"); transaction1.setLongDescription("Feb. rent payment"); transaction1.setAccountId(1); transaction1.setAmount(1500); transaction1.setDate(makeDate("2013-01-05")); transaction1.setDebit(true); transaction1.setValid(true); Transaction transaction2 = getModelFactory().makeTransaction(); transaction2.setId(2); transaction2.setDescription("Starbucks"); transaction2.setLongDescription("Starbucks"); transaction2.setAccountId(1); transaction2.setAmount(23); transaction2.setDate(makeDate("2013-01-09")); transaction2.setDebit(true); transaction2.setValid(true); Transaction transaction3 = getModelFactory().makeTransaction(); transaction3.setId(3); transaction3.setDescription("Hotel"); transaction3.setAccountId(2); transaction3.setAmount(45); transaction3.setDate(makeDate("2013-02-27")); transaction3.setDebit(true); transaction3.setValid(true); Transaction transaction4 = getModelFactory().makeTransaction(); transaction4.setId(4); transaction4.setDescription("Last january"); transaction4.setLongDescription("Last january"); transaction4.setAccountId(2); transaction4.setAmount(95); transaction4.setDate(makeDate("2013-01-31")); transaction4.setDebit(true); transaction4.setValid(true); Transaction transaction5 = getModelFactory().makeTransaction(); transaction5.setId(5); transaction5.setDescription("-Popcorn"); transaction5.setLongDescription("-Popcorn"); transaction5.setAccountId(2); transaction5.setAmount(5); transaction5.setDate(makeDate("2013-01-01")); transaction5.setDebit(true); transaction5.setValid(true); // persist and index the test objects // we put all of them in the same cache for the sake of simplicity getCacheForWrite().put("user_" + user1.getId(), user1); getCacheForWrite().put("user_" + user2.getId(), user2); getCacheForWrite().put("user_" + user3.getId(), user3); getCacheForWrite().put("account_" + account1.getId(), account1); getCacheForWrite().put("account_" + account2.getId(), account2); getCacheForWrite().put("account_" + account3.getId(), account3); getCacheForWrite().put("transaction_" + transaction0.getId(), transaction0); getCacheForWrite().put("transaction_" + transaction1.getId(), transaction1); getCacheForWrite().put("transaction_" + transaction2.getId(), transaction2); getCacheForWrite().put("transaction_" + transaction3.getId(), transaction3); getCacheForWrite().put("transaction_" + transaction4.getId(), transaction4); getCacheForWrite().put("transaction_" + transaction5.getId(), transaction5); for (int i = 0; i < 50; i++) { Transaction transaction = getModelFactory().makeTransaction(); transaction.setId(50 + i); transaction.setDescription("Expensive shoes " + i); transaction.setLongDescription("Expensive shoes " + i); transaction.setAccountId(2); transaction.setAmount(100 + i); transaction.setDate(makeDate("2013-08-20")); transaction.setDebit(true); transaction.setValid(true); getCacheForWrite().put("transaction_" + transaction.getId(), transaction); } // this value should be ignored gracefully for indexing and querying because primitives are not currently supported getCacheForWrite().put("dummy", "a primitive value cannot be queried"); getCacheForWrite().put("notIndexed1", new NotIndexed("testing 123")); getCacheForWrite().put("notIndexed2", new NotIndexed("xyz")); } public void testIndexPresence() { SearchMapping searchMapping = TestingUtil.extractComponent((Cache<?, ?>) getCacheForQuery(), SearchMapping.class); verifyClassIsIndexed(searchMapping, getModelFactory().getUserImplClass()); verifyClassIsIndexed(searchMapping, getModelFactory().getAccountImplClass()); verifyClassIsIndexed(searchMapping, getModelFactory().getTransactionImplClass()); verifyClassIsNotIndexed(searchMapping, getModelFactory().getAddressImplClass()); } private void verifyClassIsNotIndexed(SearchMapping searchMapping, Class<?> type) { assertNull(searchMapping.indexedEntity(type)); } private void verifyClassIsIndexed(SearchMapping searchMapping, Class<?> type) { assertNotNull(searchMapping.indexedEntity(type)); } public void testQueryFactoryType() { assertEquals(EmbeddedQueryFactory.class, getQueryFactory().getClass()); } public void testEq1() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq("John") .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals("John", list.get(0).getName()); assertEquals("Doe", list.get(0).getSurname()); } public void testEqEmptyString() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq("") .build(); List<User> list = q.list(); assertTrue(list.isEmpty()); } public void testEqSentence() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getAccountImplClass()) .having("description").eq("John Doe's first bank account") .build(); List<Account> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getId()); } public void testEq() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq("Jacob") .build(); List<User> list = q.list(); assertEquals(0, list.size()); } public void testEqNonIndexedType() { QueryFactory qf = getQueryFactory(); Query q = qf.from(NotIndexed.class) .having("notIndexedField").eq("testing 123") .build(); List<NotIndexed> list = q.list(); assertEquals(1, list.size()); assertEquals("testing 123", list.get(0).notIndexedField); } public void testEqNonIndexedField() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("notes").eq("Lorem ipsum dolor sit amet") .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getId()); } public void testEqHybridQuery() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("notes").eq("Lorem ipsum dolor sit amet") .and().having("surname").eq("Doe") .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getId()); } public void testEqHybridQueryWithParam() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("notes").eq("Lorem ipsum dolor sit amet") .and().having("surname").eq(param("surnameParam")) .build(); q.setParameter("surnameParam", "Doe"); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getId()); } public void testEqHybridQueryWithPredicateOptimisation() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("notes").like("%ipsum%") .and(qf.having("name").eq("John").or().having("name").eq("Jane")) .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals("Lorem ipsum dolor sit amet", list.get(0).getNotes()); } public void testEqInNested1() { QueryFactory qf = getQueryFactory(); // all users in a given post code Query q = qf.from(getModelFactory().getUserImplClass()) .having("addresses.postCode").eq("X1234") .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals("X1234", list.get(0).getAddresses().get(0).getPostCode()); } public void testEqInNested2() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("addresses.postCode").eq("Y12") .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals(2, list.get(0).getAddresses().size()); } public void testLike() { QueryFactory qf = getQueryFactory(); // all rent payments made from a given account Query q = qf.from(getModelFactory().getTransactionImplClass()) .having("description").like("%rent%") .build(); List<Transaction> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getAccountId()); assertEquals(1500, list.get(0).getAmount(), 0); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "ISPN014802: 'from' must be an instance of java.lang.Comparable") public void testBetweenArgsAreComparable() { QueryFactory qf = getQueryFactory(); qf.from(getModelFactory().getTransactionImplClass()) .having("date").between(new Object(), new Object()) .build(); } public void testBetween1() throws Exception { QueryFactory qf = getQueryFactory(); // all the transactions that happened in January 2013 Query q = qf.from(getModelFactory().getTransactionImplClass()) .having("date").between(makeDate("2013-01-01"), makeDate("2013-01-31")) .build(); List<Transaction> list = q.list(); assertEquals(4, list.size()); for (Transaction t : list) { assertTrue(t.getDate().compareTo(makeDate("2013-01-31")) <= 0); assertTrue(t.getDate().compareTo(makeDate("2013-01-01")) >= 0); } } public void testBetween2() throws Exception { QueryFactory qf = getQueryFactory(); // all the transactions that happened in January 2013 Query q = qf.from(getModelFactory().getTransactionImplClass()) .having("date").between(makeDate("2013-01-01"), makeDate("2013-01-31")).includeUpper(false) .build(); List<Transaction> list = q.list(); assertEquals(3, list.size()); for (Transaction t : list) { assertTrue(t.getDate().compareTo(makeDate("2013-01-31")) < 0); assertTrue(t.getDate().compareTo(makeDate("2013-01-01")) >= 0); } } public void testBetween3() throws Exception { QueryFactory qf = getQueryFactory(); // all the transactions that happened in January 2013 Query q = qf.from(getModelFactory().getTransactionImplClass()) .having("date").between(makeDate("2013-01-01"), makeDate("2013-01-31")).includeLower(false) .build(); List<Transaction> list = q.list(); assertEquals(3, list.size()); for (Transaction t : list) { assertTrue(t.getDate().compareTo(makeDate("2013-01-31")) <= 0); assertTrue(t.getDate().compareTo(makeDate("2013-01-01")) > 0); } } public void testGt() { QueryFactory qf = getQueryFactory(); // all the transactions greater than a given amount Query q = qf.from(getModelFactory().getTransactionImplClass()) .having("amount").gt(1500) .build(); List<Transaction> list = q.list(); assertEquals(1, list.size()); assertTrue(list.get(0).getAmount() > 1500); } public void testGte() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .having("amount").gte(1500) .build(); List<Transaction> list = q.list(); assertEquals(2, list.size()); for (Transaction t : list) { assertTrue(t.getAmount() >= 1500); } } public void testLt() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .having("amount").lt(1500) .build(); List<Transaction> list = q.list(); assertEquals(54, list.size()); for (Transaction t : list) { assertTrue(t.getAmount() < 1500); } } public void testLte() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .having("amount").lte(1500) .build(); List<Transaction> list = q.list(); assertEquals(55, list.size()); for (Transaction t : list) { assertTrue(t.getAmount() <= 1500); } } // This tests against https://hibernate.atlassian.net/browse/HSEARCH-2030 public void testLteOnFieldWithNullToken() { QueryFactory qf = getQueryFactory(); // all the transactions that happened in January 2013 Query q = qf.from(getModelFactory().getTransactionImplClass()) .having("description").lte("-Popcorn") .build(); List<Transaction> list = q.list(); assertEquals(1, list.size()); assertEquals("-Popcorn", list.get(0).getDescription()); } public void testAnd1() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq("Spider") .and().having("surname").eq("Man") .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals(2, list.get(0).getId()); } public void testAnd2() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq("Spider") .and(qf.having("surname").eq("Man")) .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals(2, list.get(0).getId()); } public void testAnd3() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("gender").eq(User.Gender.MALE) .and().having("gender").eq(User.Gender.FEMALE) .build(); List<User> list = q.list(); assertEquals(0, list.size()); } public void testAnd4() { QueryFactory qf = getQueryFactory(); //test for parenthesis, "and" should have higher priority Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq("Spider") .or(qf.having("name").eq("John")) .and(qf.having("surname").eq("Man")) .build(); List<User> list = q.list(); assertEquals(2, list.size()); } public void testOr1() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("surname").eq("Man") .or().having("surname").eq("Woman") .build(); List<User> list = q.list(); assertEquals(2, list.size()); for (User u : list) { assertEquals("Spider", u.getName()); } } public void testOr2() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("surname").eq("Man") .or(qf.having("surname").eq("Woman")) .build(); List<User> list = q.list(); assertEquals(2, list.size()); for (User u : list) { assertEquals("Spider", u.getName()); } } public void testOr3() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("gender").eq(User.Gender.MALE) .or().having("gender").eq(User.Gender.FEMALE) .build(); List<User> list = q.list(); assertEquals(3, list.size()); } public void testOr4() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .orderBy("surname", SortOrder.DESC) .having("gender").eq(User.Gender.MALE) .or().having("name").eq("Spider") .and().having("gender").eq(User.Gender.FEMALE) .or().having("surname").like("%oe%") .build(); List<User> list = q.list(); assertEquals(2, list.size()); assertEquals("Woman", list.get(0).getSurname()); assertEquals("Doe", list.get(1).getSurname()); } public void testOr5() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("gender").eq(User.Gender.MALE) .or().having("name").eq("Spider") .or().having("gender").eq(User.Gender.FEMALE) .and().having("surname").like("%oe%") .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals("John", list.get(0).getName()); } public void testNot1() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .not().having("name").eq("Spider") .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals("John", list.get(0).getName()); } public void testNot2() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .not().not().having("surname").eq("Doe") .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals("John", list.get(0).getName()); } public void testNot3() { QueryFactory qf = getQueryFactory(); // NOT should have higher priority than AND Query q = qf.from(getModelFactory().getUserImplClass()) .not().having("name").eq("John") .and().having("surname").eq("Man") .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals("Spider", list.get(0).getName()); } public void testNot4() { QueryFactory qf = getQueryFactory(); // NOT should have higher priority than AND Query q = qf.from(getModelFactory().getUserImplClass()) .having("surname").eq("Man") .and().not().having("name").eq("John") .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals("Spider", list.get(0).getName()); } public void testNot5() { QueryFactory qf = getQueryFactory(); // NOT should have higher priority than OR Query q = qf.from(getModelFactory().getUserImplClass()) .not().having("name").eq("Spider") .or().having("surname").eq("Man") .build(); List<User> list = q.list(); assertEquals(2, list.size()); for (User u : list) { assertNotEquals(u.getSurname(), "Woman"); } } public void testNot6() { QueryFactory qf = getQueryFactory(); // QueryFactory.not() test Query q = qf.from(getModelFactory().getUserImplClass()) .not(qf.not(qf.having("gender").eq(User.Gender.FEMALE))) .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals("Woman", list.get(0).getSurname()); } public void testNot7() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("gender").eq(User.Gender.FEMALE) .and().not(qf.having("name").eq("Spider")) .build(); List<User> list = q.list(); assertTrue(list.isEmpty()); } public void testNot8() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .not( qf.having("name").eq("John") .or(qf.having("surname").eq("Man"))) .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals("Spider", list.get(0).getName()); assertEquals("Woman", list.get(0).getSurname()); } public void testNot9() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .not( qf.having("name").eq("John") .and(qf.having("surname").eq("Doe"))) .orderBy("id", SortOrder.ASC) .build(); List<User> list = q.list(); assertEquals(2, list.size()); assertEquals("Spider", list.get(0).getName()); assertEquals("Man", list.get(0).getSurname()); assertEquals("Spider", list.get(1).getName()); assertEquals("Woman", list.get(1).getSurname()); } public void testNot10() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .not().not( qf.having("name").eq("John") .or(qf.having("surname").eq("Man"))) .build(); List<User> list = q.list(); assertEquals(2, list.size()); assertNotEquals(list.get(0).getSurname(), "Woman"); } public void testNot11() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .not(qf.not( qf.having("name").eq("John") .or(qf.having("surname").eq("Man")))) .build(); List<User> list = q.list(); assertEquals(2, list.size()); assertNotEquals(list.get(0).getSurname(), "Woman"); } public void testEmptyQuery() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()).build(); List<User> list = q.list(); assertEquals(3, list.size()); } public void testTautology() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").gt("A").or().having("name").lte("A") .build(); List<User> list = q.list(); assertEquals(3, list.size()); } public void testContradiction() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").gt("A").and().having("name").lte("A") .build(); List<User> list = q.list(); assertTrue(list.isEmpty()); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028503:.*") public void testInvalidEmbeddedAttributeQuery() { QueryFactory qf = getQueryFactory(); QueryBuilder queryBuilder = qf.from(getModelFactory().getUserImplClass()) .select("addresses"); Query q = queryBuilder.build(); q.list(); // exception thrown only at execution time when in remote mode! } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN014027: The property path 'addresses.postCode' cannot be projected because it is multi-valued") public void testRejectProjectionOfRepeatedProperty() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select("addresses.postCode") .build(); q.list(); // exception thrown only at execution time } public void testIsNull1() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("surname").isNull() .build(); List<User> list = q.list(); assertEquals(0, list.size()); } public void testIsNull2() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .not().having("surname").isNull() .build(); List<User> list = q.list(); assertEquals(3, list.size()); } public void testIsNull3() { if (testNullCollections()) { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("addresses").isNull() .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals(3, list.get(0).getId()); } } public void testIsNullNumericWithProjection1() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select("name", "surname", "age") .orderBy("name", SortOrder.ASC) .orderBy("surname", SortOrder.ASC) .orderBy("age", SortOrder.ASC) .having("age").isNull() // if @Field#indexNullAs is defined null values for Search 6 are not null .or().having("age").equal(-1) .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals("Spider", list.get(0)[0]); assertEquals("Man", list.get(0)[1]); assertNull(list.get(0)[2]); assertEquals("Spider", list.get(1)[0]); assertEquals("Woman", list.get(1)[1]); assertNull(list.get(1)[2]); } public void testIsNullNumericWithProjection2() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select("name", "age") .not().having("age").isNull() // if @Field#indexNullAs is defined null values for Search 6 are not null .and().not().having("age").equal(-1) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals("John", list.get(0)[0]); assertEquals(22, list.get(0)[1]); } public void testContains1() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("accountIds").contains(2) .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getId()); } public void testContains2() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("accountIds").contains(42) .build(); List<User> list = q.list(); assertEquals(0, list.size()); } public void testContainsAll1() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("accountIds").containsAll(1, 2) .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getId()); } public void testContainsAll2() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("accountIds").containsAll(Collections.singleton(1)) .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getId()); } public void testContainsAll3() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("accountIds").containsAll(1, 2, 3) .build(); List<User> list = q.list(); assertEquals(0, list.size()); } public void testContainsAll4() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("accountIds").containsAll(Collections.emptySet()) .build(); List<User> list = q.list(); assertEquals(3, list.size()); } public void testContainsAny1() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .orderBy("id", SortOrder.ASC) .having("accountIds").containsAny(2, 3) .build(); List<User> list = q.list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).getId()); assertEquals(2, list.get(1).getId()); } public void testContainsAny2() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("accountIds").containsAny(4, 5) .build(); List<User> list = q.list(); assertEquals(0, list.size()); } public void testContainsAny3() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("accountIds").containsAny(Collections.emptySet()) .build(); List<User> list = q.list(); assertEquals(3, list.size()); } public void testIn1() { QueryFactory qf = getQueryFactory(); List<Integer> ids = Arrays.asList(1, 3); Query q = qf.from(getModelFactory().getUserImplClass()) .having("id").in(ids) .build(); List<User> list = q.list(); assertEquals(2, list.size()); for (User u : list) { assertTrue(ids.contains(u.getId())); } } public void testIn2() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("id").in(4) .build(); List<User> list = q.list(); assertEquals(0, list.size()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testIn3() { QueryFactory qf = getQueryFactory(); qf.from(getModelFactory().getUserImplClass()).having("id").in(Collections.emptySet()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testIn4() { QueryFactory qf = getQueryFactory(); qf.from(getModelFactory().getUserImplClass()).having("id").in((Collection) null); } @Test(expectedExceptions = IllegalArgumentException.class) public void testIn5() { QueryFactory qf = getQueryFactory(); qf.from(getModelFactory().getUserImplClass()).having("id").in((Object[]) null); } @Test(expectedExceptions = IllegalArgumentException.class) public void testIn6() { QueryFactory qf = getQueryFactory(); Object[] array = new Object[0]; qf.from(getModelFactory().getUserImplClass()).having("id").in(array); } public void testSampleDomainQuery1() { QueryFactory qf = getQueryFactory(); // all male users Query q = qf.from(getModelFactory().getUserImplClass()) .orderBy("name", SortOrder.ASC) .having("gender").eq(User.Gender.MALE) .build(); List<User> list = q.list(); assertEquals(2, list.size()); assertEquals("John", list.get(0).getName()); assertEquals("Spider", list.get(1).getName()); } public void testSampleDomainQuery2() { QueryFactory qf = getQueryFactory(); // all male users, but this time retrieved in a twisted manner Query q = qf.from(getModelFactory().getUserImplClass()) .orderBy("name", SortOrder.ASC) .not(qf.having("gender").eq(User.Gender.FEMALE)) .and(qf.not().not(qf.having("gender").eq(User.Gender.MALE))) .build(); List<User> list = q.list(); assertEquals(2, list.size()); assertEquals("John", list.get(0).getName()); assertEquals("Spider", list.get(1).getName()); } public void testStringLiteralEscape() { QueryFactory qf = getQueryFactory(); // all transactions that have a given description. the description contains characters that need to be escaped. Query q = qf.from(getModelFactory().getAccountImplClass()) .having("description").eq("John Doe's first bank account") .build(); List<Account> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getId()); } public void testSortByDate() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getAccountImplClass()) .orderBy("creationDate", SortOrder.DESC) .build(); List<Account> list = q.list(); assertEquals(3, list.size()); assertEquals(3, list.get(0).getId()); assertEquals(2, list.get(1).getId()); assertEquals(1, list.get(2).getId()); } public void testSampleDomainQuery3() { QueryFactory qf = getQueryFactory(); // all male users Query q = qf.from(getModelFactory().getUserImplClass()) .orderBy("name", SortOrder.ASC) .having("gender").eq(User.Gender.MALE) .build(); List<User> list = q.list(); assertEquals(2, list.size()); assertEquals("John", list.get(0).getName()); assertEquals("Spider", list.get(1).getName()); } public void testSampleDomainQuery4() { QueryFactory qf = getQueryFactory(); // all users ordered descendingly by name Query q = qf.from(getModelFactory().getUserImplClass()) .orderBy("name", SortOrder.DESC) .build(); List<User> list = q.list(); assertEquals(3, list.size()); assertEquals("Spider", list.get(0).getName()); assertEquals("Spider", list.get(1).getName()); assertEquals("John", list.get(2).getName()); } public void testSampleDomainQuery4With2SortingOptions() { QueryFactory qf = getQueryFactory(); // all users ordered descendingly by name Query q = qf.from(getModelFactory().getUserImplClass()) .orderBy("name", SortOrder.DESC) .orderBy("surname", SortOrder.ASC) .build(); List<User> list = q.list(); assertEquals(3, list.size()); assertEquals("Spider", list.get(0).getName()); assertEquals("Spider", list.get(1).getName()); assertEquals("John", list.get(2).getName()); assertEquals("Man", list.get(0).getSurname()); assertEquals("Woman", list.get(1).getSurname()); assertEquals("Doe", list.get(2).getSurname()); } public void testSampleDomainQuery5() { QueryFactory qf = getQueryFactory(); // name projection of all users ordered descendingly by name Query q = qf.from(getModelFactory().getUserImplClass()) .orderBy("name", SortOrder.DESC) .select("name") .build(); List<Object[]> list = q.list(); assertEquals(3, list.size()); assertEquals(1, list.get(0).length); assertEquals(1, list.get(1).length); assertEquals(1, list.get(2).length); assertEquals("Spider", list.get(0)[0]); assertEquals("Spider", list.get(1)[0]); assertEquals("John", list.get(2)[0]); } public void testSampleDomainQuery6() { QueryFactory qf = getQueryFactory(); // all users with a given name and surname Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq("John") .and().having("surname").eq("Doe") .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals("John", list.get(0).getName()); assertEquals("Doe", list.get(0).getSurname()); } public void testSampleDomainQuery7() { QueryFactory qf = getQueryFactory(); // all rent payments made from a given account Query q = qf.from(getModelFactory().getTransactionImplClass()) .having("accountId").eq(1) .and().having("description").like("%rent%") .build(); List<Transaction> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getId()); assertEquals(1, list.get(0).getAccountId()); assertTrue(list.get(0).getDescription().contains("rent")); } public void testSampleDomainQuery8() throws Exception { QueryFactory qf = getQueryFactory(); // all the transactions that happened in January 2013 Query q = qf.from(getModelFactory().getTransactionImplClass()) .having("date").between(makeDate("2013-01-01"), makeDate("2013-01-31")) .build(); List<Transaction> list = q.list(); assertEquals(4, list.size()); for (Transaction t : list) { assertTrue(t.getDate().compareTo(makeDate("2013-01-31")) <= 0); assertTrue(t.getDate().compareTo(makeDate("2013-01-01")) >= 0); } } public void testSampleDomainQuery9() throws Exception { QueryFactory qf = getQueryFactory(); // all the transactions that happened in January 2013, projected by date field only Query q = qf.from(getModelFactory().getTransactionImplClass()) .select("date") .having("date").between(makeDate("2013-01-01"), makeDate("2013-01-31")) .build(); List<Object[]> list = q.list(); assertEquals(4, list.size()); assertEquals(1, list.get(0).length); assertEquals(1, list.get(1).length); assertEquals(1, list.get(2).length); assertEquals(1, list.get(3).length); for (int i = 0; i < 4; i++) { Date d = (Date) list.get(i)[0]; assertTrue(d.compareTo(makeDate("2013-01-31")) <= 0); assertTrue(d.compareTo(makeDate("2013-01-01")) >= 0); } } public void testSampleDomainQuery10() { QueryFactory qf = getQueryFactory(); // all the transactions for a an account having amount greater than a given amount Query q = qf.from(getModelFactory().getTransactionImplClass()) .having("accountId").eq(2) .and().having("amount").gt(40) .build(); List<Transaction> list = q.list(); assertEquals(52, list.size()); assertTrue(list.get(0).getAmount() > 40); assertTrue(list.get(1).getAmount() > 40); } public void testSampleDomainQuery11() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq("John") .and().having("addresses.postCode").eq("X1234") .and(qf.having("accountIds").eq(1)) .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals("Doe", list.get(0).getSurname()); } public void testSampleDomainQuery12() { QueryFactory qf = getQueryFactory(); // all the transactions that represents credits to the account Query q = qf.from(getModelFactory().getTransactionImplClass()) .having("accountId").eq(1) .and() .not().having("isDebit").eq(true).build(); List<Transaction> list = q.list(); assertEquals(1, list.size()); assertFalse(list.get(0).isDebit()); } public void testSampleDomainQuery13() { QueryFactory qf = getQueryFactory(); // the user that has the bank account with id 3 Query q = qf.from(getModelFactory().getUserImplClass()) .having("accountIds").contains(3).build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals(2, list.get(0).getId()); assertTrue(list.get(0).getAccountIds().contains(3)); } public void testSampleDomainQuery14() { QueryFactory qf = getQueryFactory(); // the user that has all the specified bank accounts Query q = qf.from(getModelFactory().getUserImplClass()) .having("accountIds").containsAll(2, 1).build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getId()); assertTrue(list.get(0).getAccountIds().contains(1)); assertTrue(list.get(0).getAccountIds().contains(2)); } public void testSampleDomainQuery15() { QueryFactory qf = getQueryFactory(); // the user that has at least one of the specified accounts Query q = qf.from(getModelFactory().getUserImplClass()) .having("accountIds").containsAny(1, 3).build(); List<User> list = q.list(); assertEquals(2, list.size()); assertTrue(Arrays.asList(1, 2).contains(list.get(0).getId())); assertTrue(Arrays.asList(1, 2).contains(list.get(1).getId())); } public void testSampleDomainQuery16() { QueryFactory qf = getQueryFactory(); // third batch of 10 transactions for a given account Query q = qf.from(getModelFactory().getTransactionImplClass()) .startOffset(20).maxResults(10) .orderBy("id", SortOrder.ASC) .having("accountId").eq(2).and().having("description").like("Expensive%") .build(); List<Transaction> list = q.list(); assertEquals(50, q.getResultSize()); assertEquals(10, list.size()); for (int i = 0; i < 10; i++) { assertEquals("Expensive shoes " + (20 + i), list.get(i).getDescription()); } } public void testSampleDomainQuery17() { QueryFactory qf = getQueryFactory(); // all accounts for a user. first get the user by id and then get his account. Query q1 = qf.from(getModelFactory().getUserImplClass()) .having("id").eq(1).build(); List<User> users = q1.list(); Query q2 = qf.from(getModelFactory().getAccountImplClass()) .orderBy("description", SortOrder.ASC) .having("id").in(users.get(0).getAccountIds()).build(); List<Account> list = q2.list(); assertEquals(2, list.size()); assertEquals("John Doe's first bank account", list.get(0).getDescription()); assertEquals("John Doe's second bank account", list.get(1).getDescription()); } public void testSampleDomainQuery18() { QueryFactory qf = getQueryFactory(); // all transactions of account with id 2 which have an amount larger than 1600 or their description contains the word 'rent' Query q = qf.from(getModelFactory().getTransactionImplClass()) .orderBy("description", SortOrder.ASC) .having("accountId").eq(1) .and(qf.having("amount").gt(1600) .or().having("description").like("%rent%")).build(); List<Transaction> list = q.list(); assertEquals(2, list.size()); assertEquals("Birthday present", list.get(0).getDescription()); assertEquals("Feb. rent payment", list.get(1).getDescription()); } public void testProjectionOnOptionalField() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select("id", "age") .orderBy("id", SortOrder.ASC) .build(); List<Object[]> list = q.list(); assertEquals(3, list.size()); assertEquals(1, list.get(0)[0]); assertEquals(2, list.get(1)[0]); assertEquals(3, list.get(2)[0]); assertEquals(22, list.get(0)[1]); assertNull(list.get(1)[1]); assertNull(list.get(2)[1]); } public void testNullOnIntegerField() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("age").isNull() // if @Field#indexNullAs is defined null values for Search 6 are not null .or().having("age").equal(-1) .build(); List<User> list = q.list(); assertEquals(2, list.size()); assertNull(list.get(0).getAge()); assertNull(list.get(1).getAge()); } public void testIsNotNullOnIntegerField() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .not().having("age").isNull() // if @Field#indexNullAs is defined null values for Search 6 are not null .and().not().having("age").equal(-1) .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals("John", list.get(0).getName()); assertEquals("Doe", list.get(0).getSurname()); assertNotNull(list.get(0).getAge()); } public void testSampleDomainQuery19() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("addresses.postCode").in("ZZ", "X1234").build(); List<User> list = q.list(); assertEquals(2, list.size()); assertTrue(Arrays.asList(1, 2).contains(list.get(0).getId())); assertTrue(Arrays.asList(1, 2).contains(list.get(1).getId())); } public void testSampleDomainQuery20() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .not().having("addresses.postCode").in("X1234").build(); List<User> list = q.list(); assertEquals(2, list.size()); assertTrue(Arrays.asList(2, 3).contains(list.get(0).getId())); assertTrue(Arrays.asList(2, 3).contains(list.get(1).getId())); } public void testSampleDomainQuery21() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .not().having("addresses").isNull().build(); List<User> list = q.list(); assertEquals(2, list.size()); assertTrue(Arrays.asList(1, 2).contains(list.get(0).getId())); assertTrue(Arrays.asList(1, 2).contains(list.get(1).getId())); } public void testSampleDomainQuery22() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .not().having("addresses.postCode").like("%123%").build(); List<User> list = q.list(); assertEquals(2, list.size()); assertTrue(Arrays.asList(2, 3).contains(list.get(0).getId())); assertTrue(Arrays.asList(2, 3).contains(list.get(1).getId())); } public void testSampleDomainQuery23() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .not().having("id").between(1, 2) .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals(3, list.get(0).getId()); } public void testSampleDomainQuery24() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .not().having("id").between(1, 2).includeLower(false) .build(); List<User> list = q.list(); assertEquals(2, list.size()); assertTrue(Arrays.asList(1, 3).contains(list.get(0).getId())); assertTrue(Arrays.asList(1, 3).contains(list.get(1).getId())); } public void testSampleDomainQuery25() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .not().having("id").between(1, 2).includeUpper(false) .build(); List<User> list = q.list(); assertEquals(2, list.size()); assertTrue(Arrays.asList(2, 3).contains(list.get(0).getId())); assertTrue(Arrays.asList(2, 3).contains(list.get(1).getId())); } public void testSampleDomainQuery26() throws Exception { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getAccountImplClass()) .having("creationDate").eq(makeDate("2013-01-20")) .build(); List<Account> list = q.list(); assertEquals(1, list.size()); assertEquals(3, list.get(0).getId()); } public void testSampleDomainQuery27() throws Exception { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getAccountImplClass()) .orderBy("id", SortOrder.ASC) .having("creationDate").lt(makeDate("2013-01-20")) .build(); List<Account> list = q.list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).getId()); assertEquals(2, list.get(1).getId()); } public void testSampleDomainQuery28() throws Exception { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getAccountImplClass()) .orderBy("id", SortOrder.ASC) .having("creationDate").lte(makeDate("2013-01-20")) .build(); List<Account> list = q.list(); assertEquals(3, list.size()); assertEquals(1, list.get(0).getId()); assertEquals(2, list.get(1).getId()); assertEquals(3, list.get(2).getId()); } public void testSampleDomainQuery29() throws Exception { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getAccountImplClass()) .having("creationDate").gt(makeDate("2013-01-04")) .build(); List<Account> list = q.list(); assertEquals(1, list.size()); assertEquals(3, list.get(0).getId()); } @Test(expectedExceptions = IllegalStateException.class) public void testWrongQueryBuilding1() { QueryFactory qf = getQueryFactory(); qf.not().having("name").eq("John").build(); } @Test(expectedExceptions = IllegalStateException.class) public void testWrongQueryBuilding2() { QueryFactory qf = getQueryFactory(); qf.from(getModelFactory().getUserImplClass()) .having("name").eq("John") .having("surname").eq("Man") .build(); } @Test(expectedExceptions = IllegalStateException.class) public void testWrongQueryBuilding3() { QueryFactory qf = getQueryFactory(); qf.from(getModelFactory().getUserImplClass()) .not().having("name").eq("John") .not().having("surname").eq("Man") .build(); } @Test(expectedExceptions = IllegalStateException.class) public void testWrongQueryBuilding4() { QueryFactory qf = getQueryFactory(); qf.from(getModelFactory().getUserImplClass()) .not(qf.having("name").eq("John")) .not(qf.having("surname").eq("Man")) .build(); } @Test(expectedExceptions = IllegalStateException.class) public void testWrongQueryBuilding5() { QueryFactory qf = getQueryFactory(); qf.from(getModelFactory().getUserImplClass()) .not(qf.having("name").eq("John")) .not(qf.having("surname").eq("Man")) .build(); } @Test(expectedExceptions = IllegalArgumentException.class) public void testWrongQueryBuilding6() { QueryFactory qf = getQueryFactory(); qf.from(getModelFactory().getUserImplClass()) .having("gender").eq(null) .build(); } @Test(expectedExceptions = IllegalStateException.class) public void testWrongQueryBuilding7() { QueryFactory qf = getQueryFactory(); FilterConditionEndContext q1 = qf.from(getModelFactory().getUserImplClass()) .having("gender"); q1.eq(User.Gender.MALE); q1.eq(User.Gender.FEMALE); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "ISPN014823: maxResults must be greater than 0") public void testPagination1() { QueryFactory qf = getQueryFactory(); qf.from(getModelFactory().getUserImplClass()) .maxResults(0); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "ISPN014823: maxResults must be greater than 0") public void testPagination2() { QueryFactory qf = getQueryFactory(); qf.from(getModelFactory().getUserImplClass()) .maxResults(-4); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "ISPN014824: startOffset cannot be less than 0") public void testPagination3() { QueryFactory qf = getQueryFactory(); qf.from(getModelFactory().getUserImplClass()) .startOffset(-3); } public void testOrderedPagination4() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .orderBy("id", SortOrder.ASC) .maxResults(5) .build(); List<User> list = q.list(); assertEquals(3, q.getResultSize()); assertEquals(3, list.size()); } public void testUnorderedPagination4() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .maxResults(5) .build(); List<User> list = q.list(); assertEquals(3, q.getResultSize()); assertEquals(3, list.size()); } public void testOrderedPagination5() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .orderBy("id", SortOrder.ASC) .startOffset(20) .build(); List<User> list = q.list(); assertEquals(3, q.getResultSize()); assertEquals(0, list.size()); } public void testUnorderedPagination5() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .startOffset(20) .build(); List<User> list = q.list(); assertEquals(3, q.getResultSize()); assertEquals(0, list.size()); } public void testOrderedPagination6() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .orderBy("id", SortOrder.ASC) .startOffset(20).maxResults(10) .build(); List<User> list = q.list(); assertEquals(3, q.getResultSize()); assertEquals(0, list.size()); } public void testUnorderedPagination6() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .startOffset(20).maxResults(10) .build(); List<User> list = q.list(); assertEquals(3, q.getResultSize()); assertEquals(0, list.size()); } public void testOrderedPagination7() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .orderBy("id", SortOrder.ASC) .startOffset(1).maxResults(10) .build(); List<User> list = q.list(); assertEquals(3, q.getResultSize()); assertEquals(2, list.size()); } public void testUnorderedPagination7() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .startOffset(1).maxResults(10) .build(); List<User> list = q.list(); assertEquals(3, q.getResultSize()); assertEquals(2, list.size()); } public void testOrderedPagination8() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .orderBy("id", SortOrder.ASC) .startOffset(0).maxResults(2) .build(); List<User> list = q.list(); assertEquals(3, q.getResultSize()); assertEquals(2, list.size()); } public void testUnorderedPagination8() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .startOffset(0).maxResults(2) .build(); List<User> list = q.list(); assertEquals(3, q.getResultSize()); assertEquals(2, list.size()); } public void testGroupBy1() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select("name") .groupBy("name") .orderBy("name") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).length); assertEquals("John", list.get(0)[0]); assertEquals(1, list.get(1).length); assertEquals("Spider", list.get(1)[0]); } public void testGroupBy2() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(sum("age")) .groupBy("name") .orderBy("name") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).length); assertEquals(22L, list.get(0)[0]); assertEquals(1, list.get(1).length); assertNull(list.get(1)[0]); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN014026: The expression 'surname' must be part of an aggregate function or it should be included in the GROUP BY clause") public void testGroupBy3() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select("name") .groupBy("name") .orderBy("surname") .build(); q.list(); } public void testGroupBy4() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(max("addresses.postCode")) .groupBy("name") .orderBy("name") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).length); assertEquals("X1234", list.get(0)[0]); assertEquals(1, list.get(1).length); assertEquals("ZZ", list.get(1)[0]); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN014021: Queries containing grouping and aggregation functions must use projections.") public void testGroupBy5() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .groupBy("name") .build(); q.list(); } @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Aggregation SUM cannot be applied to property of type java.lang.String") public void testGroupBy6() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(sum("name")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(2, list.get(0)[0]); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028515: Cannot have aggregate functions in the WHERE clause : SUM.") public void testGroupBy7() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(sum("age")) .having(sum("age")).gt(10) .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(3, list.get(0).length); assertEquals(3, list.get(1).length); assertEquals(1500d, (Double) list.get(0)[2], 0.0001d); assertEquals(45d, (Double) list.get(1)[2], 0.0001d); } public void testHavingWithSum() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(property("accountId"), sum("amount")) .groupBy("accountId") .having(sum("amount")).gt(3324) .orderBy("accountId") .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(2, list.get(0)[0]); assertEquals(6370.0d, (Double) list.get(0)[1], 0.0001d); } public void testHavingWithAvg() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(property("accountId"), avg("amount")) .groupBy("accountId") .having(avg("amount")).lt(130.0) .orderBy("accountId") .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(2, list.get(0)[0]); assertEquals(120.188679d, (Double) list.get(0)[1], 0.0001d); } public void testHavingWithMin() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(property("accountId"), min("amount")) .groupBy("accountId") .having(min("amount")).lt(10) .orderBy("accountId") .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(2, list.get(0)[0]); assertEquals(5.0d, (Double) list.get(0)[1], 0.0001d); } public void testHavingWithMax() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(property("accountId"), max("amount")) .groupBy("accountId") .having(avg("amount")).lt(150) .orderBy("accountId") .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(2, list.get(0)[0]); assertEquals(149.0d, (Double) list.get(0)[1], 0.0001d); } public void testSum() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(sum("age")) .groupBy("name") .orderBy("name") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).length); assertEquals(22L, list.get(0)[0]); assertEquals(1, list.get(1).length); assertNull(list.get(1)[0]); } public void testEmbeddedSum() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(property("surname"), sum("addresses.number")) .groupBy("surname") .orderBy("surname") .build(); List<Object[]> list = q.list(); assertEquals(3, list.size()); assertEquals(2, list.get(0).length); assertEquals(2, list.get(1).length); assertEquals(2, list.get(2).length); assertEquals(156L, list.get(0)[1]); assertEquals(300L, list.get(1)[1]); assertNull(list.get(2)[1]); } public void testGlobalSum() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(sum("amount")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(9693d, (Double) list.get(0)[0], 0.0001d); } public void testEmbeddedGlobalSum() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(sum("addresses.number")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(456L, list.get(0)[0]); } public void testCount() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(property("surname"), count("age")) .groupBy("surname") .orderBy("surname") .build(); List<Object[]> list = q.list(); assertEquals(3, list.size()); assertEquals(2, list.get(0).length); assertEquals(2, list.get(1).length); assertEquals(2, list.get(2).length); assertEquals(1L, list.get(0)[1]); assertEquals(0L, list.get(1)[1]); assertEquals(0L, list.get(2)[1]); } public void testEmbeddedCount1() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(property("surname"), count("accountIds")) .groupBy("surname") .orderBy("surname") .build(); List<Object[]> list = q.list(); assertEquals(3, list.size()); assertEquals(2, list.get(0).length); assertEquals(2, list.get(1).length); assertEquals(2, list.get(2).length); assertEquals(2L, list.get(0)[1]); assertEquals(1L, list.get(1)[1]); assertEquals(0L, list.get(2)[1]); } public void testEmbeddedCount2() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(property("surname"), count("addresses.street")) .groupBy("surname") .orderBy("surname") .build(); List<Object[]> list = q.list(); assertEquals(3, list.size()); assertEquals(2, list.get(0).length); assertEquals(2, list.get(1).length); assertEquals(2, list.get(2).length); assertEquals(1L, list.get(0)[1]); assertEquals(2L, list.get(1)[1]); assertEquals(0L, list.get(2)[1]); } public void testGlobalCount() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getAccountImplClass()) .select(count("creationDate")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(3L, list.get(0)[0]); } public void testEmbeddedGlobalCount() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(count("accountIds")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(3L, list.get(0)[0]); } public void testAvg() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(property("accountId"), avg("amount")) .groupBy("accountId") .orderBy("accountId") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(2, list.get(0).length); assertEquals(2, list.get(1).length); assertEquals(1107.6666d, (Double) list.get(0)[1], 0.0001d); assertEquals(120.18867d, (Double) list.get(1)[1], 0.0001d); } public void testEmbeddedAvg() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(property("surname"), avg("addresses.number")) .groupBy("surname") .orderBy("surname") .build(); List<Object[]> list = q.list(); assertEquals(3, list.size()); assertEquals(2, list.get(0).length); assertEquals(2, list.get(1).length); assertEquals(2, list.get(2).length); assertEquals(156d, (Double) list.get(0)[1], 0.0001d); assertEquals(150d, (Double) list.get(1)[1], 0.0001d); assertNull(list.get(2)[1]); } public void testGlobalAvg() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(avg("amount")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(173.0892d, (Double) list.get(0)[0], 0.0001d); } public void testEmbeddedGlobalAvg() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(avg("addresses.number")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(152d, (Double) list.get(0)[0], 0.0001d); } public void testMin() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(property("accountId"), min("amount")) .groupBy("accountId") .orderBy("accountId") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(2, list.get(0).length); assertEquals(2, list.get(1).length); assertEquals(23d, list.get(0)[1]); assertEquals(5d, list.get(1)[1]); } public void testMinString() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(min("surname")) .groupBy("name") .orderBy("name") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).length); assertEquals(1, list.get(1).length); assertEquals("Doe", list.get(0)[0]); assertEquals("Man", list.get(1)[0]); } public void testEmbeddedMin() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(property("surname"), min("addresses.number")) .groupBy("surname") .orderBy("surname") .build(); List<Object[]> list = q.list(); assertEquals(3, list.size()); assertEquals(2, list.get(0).length); assertEquals(2, list.get(1).length); assertEquals(2, list.get(2).length); assertEquals(156, list.get(0)[1]); assertEquals(-12, list.get(1)[1]); assertNull(list.get(2)[1]); } public void testGlobalMinDouble() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(min("amount")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(5d, list.get(0)[0]); } public void testGlobalMinString() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(min("name")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals("John", list.get(0)[0]); } public void testEmbeddedGlobalMin() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(min("addresses.number")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(-12, list.get(0)[0]); } public void testMax() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(property("accountId"), max("amount")) .groupBy("accountId") .orderBy("accountId") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(2, list.get(0).length); assertEquals(2, list.get(1).length); assertEquals(1800d, list.get(0)[1]); assertEquals(149d, list.get(1)[1]); } public void testMaxString() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(max("surname")) .groupBy("name") .orderBy("name") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).length); assertEquals(1, list.get(1).length); assertEquals("Doe", list.get(0)[0]); assertEquals("Woman", list.get(1)[0]); } public void testEmbeddedMax() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(property("surname"), max("addresses.number")) .groupBy("surname") .orderBy("surname") .build(); List<Object[]> list = q.list(); assertEquals(3, list.size()); assertEquals(2, list.get(0).length); assertEquals(2, list.get(1).length); assertEquals(2, list.get(2).length); assertEquals(156, list.get(0)[1]); assertEquals(312, list.get(1)[1]); assertNull(list.get(2)[1]); } public void testEmbeddedMaxString() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(max("addresses.postCode")) .groupBy("name") .orderBy("name") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).length); assertEquals("X1234", list.get(0)[0]); assertEquals(1, list.get(1).length); assertEquals("ZZ", list.get(1)[0]); } public void testGlobalMaxDouble() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(max("amount")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(1800d, list.get(0)[0]); } public void testGlobalMaxString() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(max("name")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals("Spider", list.get(0)[0]); } public void testEmbeddedGlobalMax() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(max("addresses.number")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(312, list.get(0)[0]); } public void testOrderBySum() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(sum("age")) .orderBy(sum("age")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(22L, list.get(0)[0]); } public void testGroupingWithFilter() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select("name") .having("name").eq("John") .groupBy("name") .having("name").eq("John") .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals("John", list.get(0)[0]); } public void testCountNull() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(count("age")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(1L, list.get(0)[0]); // only non-null "age"s were counted } public void testCountNull2() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(property("name"), count("age")) .groupBy("name") .orderBy("name") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(2, list.get(0).length); assertEquals("John", list.get(0)[0]); assertEquals(1L, list.get(0)[1]); assertEquals(2, list.get(1).length); assertEquals("Spider", list.get(1)[0]); assertEquals(0L, list.get(1)[1]); } public void testCountNull3() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(property("name"), count("salutation")) .groupBy("name") .orderBy("name") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(2, list.get(0).length); assertEquals("John", list.get(0)[0]); assertEquals(0L, list.get(0)[1]); assertEquals(2, list.get(1).length); assertEquals("Spider", list.get(1)[0]); assertEquals(2L, list.get(1)[1]); } public void testAvgNull() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select(avg("age")) .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(22.0, list.get(0)[0]); // only non-null "age"s were used in the average } public void testDateGrouping1() throws Exception { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select("date") .having("date").between(makeDate("2013-02-15"), makeDate("2013-03-15")) .groupBy("date") .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(makeDate("2013-02-27"), list.get(0)[0]); } public void testDateGrouping2() throws Exception { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(count("date"), min("date")) .having("description").eq("Hotel") .groupBy("id") .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(2, list.get(0).length); assertEquals(1L, list.get(0)[0]); assertEquals(makeDate("2013-02-27"), list.get(0)[1]); } public void testDateGrouping3() throws Exception { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(min("date"), count("date")) .having("description").eq("Hotel") .groupBy("id") .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(2, list.get(0).length); assertEquals(makeDate("2013-02-27"), list.get(0)[0]); assertEquals(1L, list.get(0)[1]); } public void testParam() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("gender").eq(param("param2")) .build(); q.setParameter("param2", User.Gender.MALE); List<User> list = q.list(); assertEquals(2, list.size()); assertEquals(User.Gender.MALE, list.get(0).getGender()); assertEquals(User.Gender.MALE, list.get(1).getGender()); q.setParameter("param2", User.Gender.FEMALE); list = q.list(); assertEquals(1, list.size()); assertEquals(User.Gender.FEMALE, list.get(0).getGender()); } public void testWithParameterMap() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("gender").eq(param("param1")) .and() .having("name").eq(param("param2")) .build(); Map<String, Object> parameterMap = new HashMap<>(2); parameterMap.put("param1", User.Gender.MALE); parameterMap.put("param2", "John"); q.setParameters(parameterMap); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals(User.Gender.MALE, list.get(0).getGender()); assertEquals("John", list.get(0).getName()); parameterMap = new HashMap<>(2); parameterMap.put("param1", User.Gender.MALE); parameterMap.put("param2", "Spider"); q.setParameters(parameterMap); list = q.list(); assertEquals(1, list.size()); assertEquals(User.Gender.MALE, list.get(0).getGender()); assertEquals("Spider", list.get(0).getName()); } public void testDateParam() throws Exception { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getAccountImplClass()) .having("creationDate").eq(param("param1")) .build().setParameter("param1", makeDate("2013-01-03")); List<Account> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getId()); } public void testParamWithGroupBy() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(property("accountId"), property("date"), sum("amount")) .groupBy("accountId", "date") .having(sum("amount")).gt(param("param")) .build(); q.setParameter("param", 1801); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(3, list.get(0).length); assertEquals(6225d, list.get(0)[2]); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "ISPN014805: No parameter named 'param2' was found") public void testUnknownParam() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq(param("param1")) .build(); q.setParameter("param2", "John"); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "ISPN014806: No parameters named '\\[param2\\]' were found") public void testUnknownParamWithParameterMap() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq(param("param1")) .build(); Map<String, Object> parameterMap = new HashMap<>(1); parameterMap.put("param2", User.Gender.MALE); q.setParameters(parameterMap); } @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "ISPN014804: Query does not have parameters") public void testQueryWithNoParams() { QueryFactory qf = getQueryFactory(); qf.from(getModelFactory().getUserImplClass()) .having("name").eq("John") .build() .setParameter("param1", "John"); } @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "ISPN014804: Query does not have parameters") public void testQueryWithNoParamsWithParameterMap() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq("John") .build(); Map<String, Object> parameterMap = new HashMap<>(1); parameterMap.put("param1", User.Gender.MALE); q.setParameters(parameterMap); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "ISPN014803: Parameter name cannot be null or empty") public void testNullParamName() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq(param(null)) .build(); q.setParameter(null, "John"); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "ISPN014803: Parameter name cannot be null or empty") public void testEmptyParamName() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq(param("")) .build(); q.setParameter("", "John"); } @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "ISPN014825: Query parameter 'param2' was not set") public void testMissingParam() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq(param("param1")) .and().having("gender").eq(param("param2")) .build(); q.setParameter("param1", "John"); q.list(); } @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "ISPN014825: Query parameter 'param2' was not set") public void testMissingParamWithParameterMap() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq(param("param1")) .and().having("gender").eq(param("param2")) .build(); Map<String, Object> parameterMap = new HashMap<>(1); parameterMap.put("param1", "John"); q.setParameters(parameterMap); q.list(); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "ISPN014812: paramValues cannot be null") public void testQueryWithNoParamsWithNullParameterMap() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .having("name").eq("John") .build(); q.setParameters(null); } @Test public void testComplexQuery() throws Exception { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(avg("amount"), sum("amount"), count("date"), min("date"), max("accountId")) .having("isDebit").eq(param("param")) .orderBy(avg("amount"), SortOrder.DESC).orderBy(count("date"), SortOrder.DESC) .orderBy(max("amount"), SortOrder.ASC) .build(); q.setParameter("param", true); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(5, list.get(0).length); assertEquals(143.50909d, (Double) list.get(0)[0], 0.0001d); assertEquals(7893d, (Double) list.get(0)[1], 0.0001d); assertEquals(55L, list.get(0)[2]); assertEquals(Date.class, list.get(0)[3].getClass()); assertEquals(makeDate("2013-01-01"), list.get(0)[3]); assertEquals(2, list.get(0)[4]); } public void testDateFilteringWithGroupBy() throws Exception { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select("date") .having("date").between(makeDate("2013-02-15"), makeDate("2013-03-15")) .groupBy("date") .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(Date.class, list.get(0)[0].getClass()); assertEquals(makeDate("2013-02-27"), list.get(0)[0]); } public void testAggregateDate() throws Exception { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select(count("date"), min("date")) .having("description").eq("Hotel") .groupBy("id") .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(2, list.get(0).length); assertEquals(1L, list.get(0)[0]); assertEquals(java.util.Date.class, list.get(0)[1].getClass()); assertEquals(makeDate("2013-02-27"), list.get(0)[1]); } public void testNotIndexedProjection() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getTransactionImplClass()) .select("id", "isValid") .having("id").gte(98) .orderBy("id") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(2, list.get(0).length); assertEquals(98, list.get(0)[0]); assertEquals(true, list.get(0)[1]); assertEquals(2, list.get(1).length); assertEquals(99, list.get(1)[0]); assertEquals(true, list.get(1)[1]); } public void testNotStoredProjection() { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getTransactionImplClass()) .select("id", "description") .having("id").gte(98) .orderBy("id") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(2, list.get(0).length); assertEquals(98, list.get(0)[0]); assertEquals("Expensive shoes 48", list.get(0)[1]); assertEquals(2, list.get(1).length); assertEquals(99, list.get(1)[0]); assertEquals("Expensive shoes 49", list.get(1)[1]); } public void testNotIndexedOrderBy() { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getTransactionImplClass()) .select("id", "isValid") .having("id").gte(98) .orderBy("isValid") .orderBy("id") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(2, list.get(0).length); assertEquals(98, list.get(0)[0]); assertEquals(true, list.get(0)[1]); assertEquals(2, list.get(1).length); assertEquals(99, list.get(1)[0]); assertEquals(true, list.get(1)[1]); } public void testNotStoredOrderBy() { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getTransactionImplClass()) .select("id", "description") .having("id").gte(98) .orderBy("description") .orderBy("id") .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(2, list.get(0).length); assertEquals(98, list.get(0)[0]); assertEquals("Expensive shoes 48", list.get(0)[1]); assertEquals(2, list.get(1).length); assertEquals(99, list.get(1)[0]); assertEquals("Expensive shoes 49", list.get(1)[1]); } public void testDuplicateDateProjection() throws Exception { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getTransactionImplClass()) .select("id", "date", "date") .having("description").eq("Hotel") .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(3, list.get(0).length); assertEquals(3, list.get(0)[0]); assertEquals(makeDate("2013-02-27"), list.get(0)[1]); assertEquals(makeDate("2013-02-27"), list.get(0)[2]); } public void testDuplicateBooleanProjection() { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getTransactionImplClass()) .select("id", "isDebit", "isDebit") .having("description").eq("Hotel") .build(); List<Object[]> list = q.list(); assertEquals(1, list.size()); assertEquals(3, list.get(0).length); assertEquals(3, list.get(0)[0]); assertEquals(true, list.get(0)[1]); assertEquals(true, list.get(0)[2]); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN014023: Using the multi-valued property path 'addresses.street' in the GROUP BY clause is not currently supported") public void testGroupByMustNotAcceptRepeatedProperty() { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getUserImplClass()) .select(min("name")) .groupBy("addresses.street") .build(); q.list(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN014024: The property path 'addresses.street' cannot be used in the ORDER BY clause because it is multi-valued") public void testOrderByMustNotAcceptRepeatedProperty() { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getUserImplClass()) .select("name") .orderBy("addresses.street") .build(); q.list(); } public void testOrderByInAggregationQueryMustAcceptRepeatedProperty() { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getUserImplClass()) .select(avg("age"), property("name")) .having("name").gt("A") .groupBy("name") .having(max("addresses.street")).gt("A") .orderBy(min("addresses.street")) .build(); List<Object[]> list = q.list(); assertEquals(2, list.size()); assertEquals(2, list.get(0).length); assertNull(list.get(0)[0]); assertEquals("Spider", list.get(0)[1]); assertEquals(22.0, list.get(1)[0]); assertEquals("John", list.get(1)[1]); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028515: Cannot have aggregate functions in the WHERE clause : MIN.") public void testRejectAggregationsInWhereClause() { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select("name") .having("name").eq(min("addresses.street")) .build(); q.list(); } public void testAggregateRepeatedField() { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getUserImplClass()) .select(min("addresses.street")) .having("name").eq("Spider") .build(); List<Object[]> list = q.list(); assertEquals("Bond Street", list.get(0)[0]); } public void testGroupingAndAggregationOnSameField() { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getUserImplClass()) .select(count("surname")) .groupBy("surname") .build(); List<Object[]> list = q.list(); assertEquals(3, list.size()); assertEquals(1, list.get(0).length); assertEquals(1L, list.get(0)[0]); assertEquals(1L, list.get(1)[0]); assertEquals(1L, list.get(2)[0]); } public void testTwoPhaseGroupingAndAggregationOnSameField() { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getUserImplClass()) .select(count("surname"), sum("addresses.number")) .groupBy("surname") .orderBy("surname") .build(); List<Object[]> list = q.list(); assertEquals(3, list.size()); assertEquals(2, list.get(0).length); assertEquals(1L, list.get(0)[0]); assertEquals(156L, list.get(0)[1]); assertEquals(1L, list.get(1)[0]); assertEquals(300L, list.get(1)[1]); assertEquals(1L, list.get(2)[0]); assertNull(list.get(2)[1]); } /** * Test that 'like' accepts only % and _ as wildcards. */ public void testLuceneWildcardsAreEscaped() { QueryFactory qf = getQueryFactory(); // use a true wildcard Query<User> q1 = qf.from(getModelFactory().getUserImplClass()) .having("name").like("J%n") .build(); assertEquals(1, q1.list().size()); // use an improper wildcard Query<User> q2 = qf.from(getModelFactory().getUserImplClass()) .having("name").like("J*n") .build(); assertEquals(0, q2.list().size()); // use a true wildcard Query<User> q3 = qf.from(getModelFactory().getUserImplClass()) .having("name").like("Jo_n") .build(); assertEquals(1, q3.list().size()); // use an improper wildcard Query<User> q4 = qf.from(getModelFactory().getUserImplClass()) .having("name").like("Jo?n") .build(); assertEquals(0, q4.list().size()); } public void testCompareLongWithInt() { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getUserImplClass()) .select(sum("age")) .groupBy("name") .having(sum("age")).gt(50000) .build(); List<Object[]> list = q.list(); assertEquals(0, list.size()); } public void testCompareDoubleWithInt() { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getTransactionImplClass()) .select(sum("amount")) .groupBy("accountId") .having(sum("amount")).gt(50000) .build(); List<Object[]> list = q.list(); assertEquals(0, list.size()); } public void testFullTextTerm() { QueryFactory qf = getQueryFactory(); Query<Transaction> q = qf.create("from " + getModelFactory().getTransactionTypeName() + " where longDescription:'rent'"); List<Transaction> list = q.list(); assertEquals(1, list.size()); } public void testFullTextPhrase() { QueryFactory qf = getQueryFactory(); Query<Transaction> q = qf.create("from " + getModelFactory().getTransactionTypeName() + " where longDescription:'expensive shoes'"); List<Transaction> list = q.list(); assertEquals(50, list.size()); } public void testInstant1() { QueryFactory qf = getQueryFactory(); Query<User> q = qf.from(getModelFactory().getUserImplClass()) .having("creationDate").eq(Instant.parse("2011-12-03T10:15:30Z")) .build(); List<User> list = q.list(); assertEquals(3, list.size()); } public void testInstant2() { QueryFactory qf = getQueryFactory(); Query<User> q = qf.from(getModelFactory().getUserImplClass()) .having("passwordExpirationDate").eq(Instant.parse("2011-12-03T10:15:30Z")) .build(); List<User> list = q.list(); assertEquals(3, list.size()); } public void testManyClauses() { QueryFactory qf = getQueryFactory(); QueryBuilder qb = qf.from(getModelFactory().getUserImplClass()); FilterConditionContext fcc = qb.having("name").eq("test"); for (int i = 0; i < 1024; i++) { fcc = fcc.and().having("name").eq("test" + i); } // This query is a boolean contradiction, so our smart query engine does not really execute it, // it just returns 0 results and that is fine. We just wanted to check it is parsed correctly. List<User> list = qb.<User>build().list(); assertEquals(0, list.size()); } public void testSingleIN() { QueryFactory qf = getQueryFactory(); Query<User> q = qf.from(getModelFactory().getUserImplClass()) .having("surname").in("Man") .and() .having("gender").eq(User.Gender.MALE) .build(); List<User> list = q.list(); assertEquals(1, list.size()); assertEquals(2, list.get(0).getId()); assertEquals("Man", list.get(0).getSurname()); assertEquals(User.Gender.MALE, list.get(0).getGender()); } }
104,783
32.899709
213
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/NamedParamsPerfTest.java
package org.infinispan.query.dsl.embedded; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.util.List; import java.util.Random; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.core.impl.QueryCache; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.Test; /** * @author Matej Cimbora * @author anistor@gmail.com * @since 9.0 */ @Test(groups = "profiling", testName = "query.dsl.embedded.NamedParamsPerfTest") public class NamedParamsPerfTest extends AbstractQueryDslTest { private static final int ITERATIONS = 1000; @Indexed static class Person { @Basic(projectable = true, sortable = true) final int id; @Basic(projectable = true, sortable = true, indexNullAs = "_null_") final String firstName; @Basic(projectable = true, sortable = true, indexNullAs = "_null_") final String lastName; Person(int id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfg = TestCacheManagerFactory.getDefaultCacheConfiguration(true); cfg.transaction() .transactionMode(TransactionMode.TRANSACTIONAL) .indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); createClusteredCaches(1, cfg); } public void testNamedParamPerfComparison() { QueryFactory factory = getQueryFactory(); String[] fnames = {"Matej", "Roman", "Jakub", "Jiri", "Anna", "Martin", "Vojta", "Alan"}; String[] lnames = {"Cimbora", "Macor", "Markos", "Holusa", "Manukyan", "Gencur", "Vrabel", "Juranek", "Field"}; Random random = new Random(3); for (int i = 0; i < 999; i++) { cache(0).put(i, new Person(i, fnames[random.nextInt(fnames.length)], lnames[random.nextInt(lnames.length)])); } cache(0).put(1000, new Person(999, "Unnamed", "Unnamed")); QueryCache queryCache = manager(0).getGlobalComponentRegistry().getComponent(QueryCache.class); assertNotNull(queryCache); Query<Person> query = factory.create("FROM " + Person.class.getName() + " WHERE firstName = :nameParam1 OR lastName = :nameParam2 OR id >= :idParam1 OR id < :idParam2"); long t1 = 0; long t2 = 0; long t3 = 0; for (int i = 0; i < ITERATIONS; i++) { queryCache.clear(); long start = System.nanoTime(); query.setParameter("nameParam1", "Unnamed") .setParameter("nameParam2", "ww") .setParameter("idParam1", 1000) .setParameter("idParam2", 0); List<Person> list = query.execute().list(); t1 += (System.nanoTime() - start); // first run is expected to take much longer than subsequent runs assertEquals(1, list.size()); start = System.nanoTime(); query.setParameter("nameParam1", "Unnamed") .setParameter("nameParam2", "zz") .setParameter("idParam1", 2000) .setParameter("idParam2", -1000); list = query.execute().list(); t2 += (System.nanoTime() - start); assertEquals(1, list.size()); start = System.nanoTime(); query.setParameter("nameParam1", "Unnamed") .setParameter("nameParam2", "bb") .setParameter("idParam1", 5000) .setParameter("idParam2", -3000); list = query.execute().list(); t3 += (System.nanoTime() - start); assertEquals(1, list.size()); } System.out.println("NamedParamsPerfTest.testNamedParamPerfComparison t1 (avg, us) = " + (t1 / 1000.0 / ITERATIONS)); System.out.println("NamedParamsPerfTest.testNamedParamPerfComparison t2 (avg, us) = " + (t2 / 1000.0 / ITERATIONS)); System.out.println("NamedParamsPerfTest.testNamedParamPerfComparison t3 (avg, us) = " + (t3 / 1000.0 / ITERATIONS)); } }
4,447
37.017094
175
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/ListenerWithDslFilterProfilingTest.java
package org.infinispan.query.dsl.embedded; import java.util.ArrayList; import java.util.List; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; 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.testng.annotations.Test; /** * @author anistor@redhat.com * @since 7.2 */ @Test(groups = "profiling", testName = "query.dsl.embedded.ListenerWithDslFilterProfilingTest") public class ListenerWithDslFilterProfilingTest extends SingleCacheManagerTest { private static final int NUM_ENTRIES = 100000; private static final int NUM_LISTENERS = 1000; @Override protected EmbeddedCacheManager createCacheManager() { return TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE); } public void testEventFilterPerformance() { QueryFactory qf = Search.getQueryFactory(cache()); Query<Person> query = qf.create("FROM org.infinispan.query.test.Person WHERE age <= 31"); List<NoOpEntryListener> listeners = new ArrayList<>(NUM_LISTENERS); for (int i = 0; i < NUM_LISTENERS; i++) { NoOpEntryListener listener = new NoOpEntryListener(); listeners.add(listener); cache().addListener(listener, Search.makeFilter(query), null); } long startTs = System.nanoTime(); for (int i = 0; i < NUM_ENTRIES; ++i) { Person value = new Person(); value.setName("John"); value.setAge(i + 25); cache.put(i, value); } long endTs = System.nanoTime(); for (NoOpEntryListener listener : listeners) { cache().removeListener(listener); } log.infof("ListenerWithDslFilterProfilingTest.testEventFilterPerformance took %d us\n", (endTs - startTs) / 1000); } @Listener private static class NoOpEntryListener { @CacheEntryCreated public void handleEvent(CacheEntryCreatedEvent<?, ?> event) { } @CacheEntryModified public void handleEvent(CacheEntryModifiedEvent<?, ?> event) { } } }
2,625
32.666667
120
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/NonIndexedQueryDslConditionsTest.java
package org.infinispan.query.dsl.embedded; import static org.infinispan.test.TestingUtil.withTx; import static org.testng.AssertJUnit.assertEquals; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.objectfilter.ParsingException; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.embedded.testdomain.User; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Test for query conditions (filtering) on cache without indexing. Exercises the whole query DSL on the sample domain * model. * * @author anistor@redhat.com * @since 7.0 */ @Test(groups = "functional", testName = "query.dsl.embedded.NonIndexedQueryDslConditionsTest") public class NonIndexedQueryDslConditionsTest extends QueryDslConditionsTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfg = TestCacheManagerFactory.getDefaultCacheConfiguration(true); createClusteredCaches(1, QueryTestSCI.INSTANCE, cfg); } public void testInsertAndIterateInTx() throws Exception { final User newUser = getModelFactory().makeUser(); newUser.setId(15); newUser.setName("Test"); newUser.setSurname("User"); newUser.setGender(User.Gender.MALE); newUser.setAge(20); List<?> results = withTx(tm(0), () -> { Query<?> q = getQueryFactory().from(getModelFactory().getUserImplClass()) .not().having("age").eq(20) .build(); cache(0).put("new_user_" + newUser.getId(), newUser); return q.execute().list(); }); cache(0).remove("new_user_" + newUser.getId()); assertEquals(3, results.size()); } @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Indexing was not enabled on cache.*") @Override public void testIndexPresence() { // this is expected to throw an exception Search.getIndexer((Cache<?, ?>) getCacheForQuery()); } /** * This test uses fields that are not marked as @NumericField so it cannot work correctly with Lucene but should work * correctly for non-indexed. */ public void testAnd5() { QueryFactory qf = getQueryFactory(); Query<User> q = qf.from(getModelFactory().getUserImplClass()) .having("id").lt(1000) .and().having("age").lt(1000) .build(); List<User> list = q.execute().list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getId()); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextTerm() { super.testFullTextTerm(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextPhrase() { super.testFullTextPhrase(); } }
3,506
36.308511
288
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/NonIndexedSingleClassDSLQueryTest.java
package org.infinispan.query.dsl.embedded; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Test entities defined as inner classes and inheritance of fields using non-indexed query. Just a simple field equals * is tested. The purpose of this test is just to check class and property lookup correctness. * * @author anistor@redhat.com * @since 9.1 */ @Test(groups = "functional", testName = "query.dsl.embedded.NonIndexedSingleClassDSLQueryTest") public class NonIndexedSingleClassDSLQueryTest extends SingleClassDSLQueryTest { @Override protected void configureCache(ConfigurationBuilder builder) { // do nothing } }
698
32.285714
119
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/ObjectStorageNonIndexedQueryDslConditionsTest.java
package org.infinispan.query.dsl.embedded; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT_TYPE; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Verify non-indexed query when configuring application/x-java-object storage. * * @author anistor@redhat.com * @since 7.0 */ @Test(groups = "functional", testName = "query.dsl.embedded.ObjectStorageNonIndexedQueryDslConditionsTest") public class ObjectStorageNonIndexedQueryDslConditionsTest extends NonIndexedQueryDslConditionsTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfg = TestCacheManagerFactory.getDefaultCacheConfiguration(true); cfg.encoding().key().mediaType(APPLICATION_OBJECT_TYPE); cfg.encoding().value().mediaType(APPLICATION_OBJECT_TYPE); createClusteredCaches(1, cfg); } }
972
36.423077
107
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/NonIndexedClusteredDummyInMemoryStoreQueryDslConditionsTest.java
package org.infinispan.query.dsl.embedded; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.testng.annotations.Test; /** * @author anistor@redhat.com * @since 7.0 */ @Test(groups = "functional", testName = "query.dsl.embedded.NonIndexedClusteredDummyInMemoryStoreQueryDslConditionsTest") public class NonIndexedClusteredDummyInMemoryStoreQueryDslConditionsTest extends NonIndexedQueryDslConditionsTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true); cfg.clustering() .stateTransfer().fetchInMemoryState(true) .persistence() .addStore(DummyInMemoryStoreConfigurationBuilder.class) .purgeOnStartup(true); // ensure the data container contains minimal data so the store will need to be accessed to get the rest cfg.locking().concurrencyLevel(1).memory().size(1L); createClusteredCaches(2, DslSCI.INSTANCE, cfg); } }
1,176
38.233333
121
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/NonIndexedClusteredQueryDslConditionsTest.java
package org.infinispan.query.dsl.embedded; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author anistor@redhat.com * @since 7.0 */ @Test(groups = "functional", testName = "query.dsl.embedded.NonIndexedClusteredQueryDslConditionsTest") public class NonIndexedClusteredQueryDslConditionsTest extends NonIndexedQueryDslConditionsTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder defaultConfiguration = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true); defaultConfiguration.clustering() .stateTransfer().fetchInMemoryState(true); createClusteredCaches(2, DslSCI.INSTANCE, defaultConfiguration); } }
807
35.727273
108
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/FilesystemQueryDslConditionsTest.java
package org.infinispan.query.dsl.embedded; 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.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * Verifies the Query DSL functionality for Filesystem directory.type. * * @author Anna Manukyan * @author anistor@redhat.com * @since 6.0 */ @Test(groups = "functional", testName = "query.dsl.embedded.FilesystemQueryDslConditionsTest") public class FilesystemQueryDslConditionsTest extends QueryDslConditionsTest { private final String indexDirectory = CommonsTestingUtil.tmpDirectory(getClass()); @Override protected void createCacheManagers() throws Throwable { Util.recursiveFileRemove(indexDirectory); boolean created = new File(indexDirectory).mkdirs(); assertTrue(created); ConfigurationBuilder cfg = TestCacheManagerFactory.getDefaultCacheConfiguration(true); cfg.indexing().enable() .storage(IndexStorage.FILESYSTEM).path(indexDirectory) .addIndexedEntity(getModelFactory().getUserImplClass()) .addIndexedEntity(getModelFactory().getAccountImplClass()) .addIndexedEntity(getModelFactory().getTransactionImplClass()); createClusteredCaches(1, cfg); } @AfterClass @Override protected void destroy() { try { //first stop cache managers, then clear the index super.destroy(); } finally { //delete the index otherwise it will mess up the index for next tests Util.recursiveFileRemove(indexDirectory); } } }
1,853
33.333333
94
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/ClusteredQueryDslConditionsTest.java
package org.infinispan.query.dsl.embedded; import static org.testng.Assert.assertNotNull; import static org.testng.AssertJUnit.assertNull; 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.configuration.cache.IndexingConfigurationBuilder; import org.infinispan.query.helper.TestQueryHelperFactory; import org.infinispan.search.mapper.mapping.SearchMapping; import org.testng.annotations.Test; /** * Verifies the functionality of Query DSL in clustered environment for ISPN directory provider. * * @author anistor@redhat.com * @author Anna Manukyan * @since 6.0 */ @Test(groups = "functional", testName = "query.dsl.embedded.ClusteredQueryDslConditionsTest") public class ClusteredQueryDslConditionsTest extends QueryDslConditionsTest { protected static final String TEST_CACHE_NAME = "custom"; protected Cache<Object, Object> cache1, cache2; @Override protected Cache<Object, Object> getCacheForWrite() { return cache1; } @Override protected Cache<Object, Object> getCacheForQuery() { return cache2; } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder defaultConfiguration = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); defaultConfiguration.clustering() .stateTransfer().fetchInMemoryState(true); createClusteredCaches(2, DslSCI.INSTANCE, defaultConfiguration); ConfigurationBuilder cfg = initialCacheConfiguration(); IndexingConfigurationBuilder indexingConfigurationBuilder = cfg.clustering() .stateTransfer().fetchInMemoryState(true) .indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(getModelFactory().getUserImplClass()) .addIndexedEntity(getModelFactory().getAccountImplClass()) .addIndexedEntity(getModelFactory().getTransactionImplClass()); manager(0).defineConfiguration(TEST_CACHE_NAME, cfg.build()); manager(1).defineConfiguration(TEST_CACHE_NAME, cfg.build()); cache1 = manager(0).getCache(TEST_CACHE_NAME); cache2 = manager(1).getCache(TEST_CACHE_NAME); } protected ConfigurationBuilder initialCacheConfiguration() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); } @Override public void testIndexPresence() { checkIndexPresence(cache1); checkIndexPresence(cache2); } private void checkIndexPresence(Cache<?, ?> cache) { SearchMapping searchMapping = TestQueryHelperFactory.extractSearchMapping(cache); verifyClassIsIndexed(searchMapping, getModelFactory().getUserImplClass()); verifyClassIsIndexed(searchMapping, getModelFactory().getAccountImplClass()); verifyClassIsIndexed(searchMapping, getModelFactory().getTransactionImplClass()); verifyClassIsNotIndexed(searchMapping, getModelFactory().getAddressImplClass()); } private void verifyClassIsNotIndexed(SearchMapping searchMapping, Class<?> type) { assertNull(searchMapping.indexedEntity(type)); } private void verifyClassIsIndexed(SearchMapping searchMapping, Class<?> type) { assertNotNull(searchMapping.indexedEntity(type)); } }
3,371
37.318182
109
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/AbstractQueryDslTest.java
package org.infinispan.query.dsl.embedded; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import org.infinispan.Cache; import org.infinispan.commons.api.BasicCache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.Search; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.embedded.testdomain.ModelFactory; import org.infinispan.query.dsl.embedded.testdomain.hsearch.ModelFactoryHS; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.CleanupAfterTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; /** * Base for the DSL query tests. * * @author rvansa@redhat.com * @author anistor@redhat.com * @since 6.0 */ @CleanupAfterTest public abstract class AbstractQueryDslTest extends MultipleCacheManagersTest { protected final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); protected AbstractQueryDslTest() { DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT")); } protected Date makeDate(String dateStr) throws ParseException { return DATE_FORMAT.parse(dateStr); } /** * To be overridden by subclasses. */ protected BasicCache<Object, Object> getCacheForWrite() { return getCacheForQuery(); } /** * To be overridden by subclasses. */ protected BasicCache<Object, Object> getCacheForQuery() { return cache(0); } /** * To be overridden by subclasses that need a different query factory. */ protected QueryFactory getQueryFactory() { return Search.getQueryFactory((Cache) getCacheForQuery()); } /** * To be overridden by subclasses if they need to use a different model implementation. */ protected ModelFactory getModelFactory() { return ModelFactoryHS.INSTANCE; } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfg = TestCacheManagerFactory.getDefaultCacheConfiguration(true); cfg.transaction() .transactionMode(TransactionMode.TRANSACTIONAL) .indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(getModelFactory().getUserImplClass()) .addIndexedEntity(getModelFactory().getAccountImplClass()) .addIndexedEntity(getModelFactory().getTransactionImplClass()); createClusteredCaches(1, cfg); } @Override protected void clearContent() { // Don't clear, this is destroying the index } }
2,728
29.662921
92
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/SingleClassDSLQueryTest.java
package org.infinispan.query.dsl.embedded; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.Assert.assertEquals; import java.util.List; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; 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.QueryTestSCI; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test entities defined as inner classes and inheritance of fields using indexed query. Just a simple field equals is * tested. The purpose of this test is just to check class and property lookup correctness. * * @author gustavonalle * @author Tristan Tarrant * @author anistor@redhat.com * @since 8.0 */ @Test(groups = "functional", testName = "query.dsl.embedded.SingleClassDSLQueryTest") public class SingleClassDSLQueryTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); configureCache(builder); return TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE, builder); } protected void configureCache(ConfigurationBuilder builder) { builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); } @BeforeClass(alwaysRun = true) protected void populateCache() { cache.put("person1", new Person("William", "Shakespeare", 50, "ZZ3141592", "M")); } @Override protected void clearContent() { // Don't clear, this is destroying the index } /** * Test querying for entities defined as inner classes. */ public void testQueryInnerClass() { QueryFactory queryFactory = Search.getQueryFactory(cache); Query<Person> query = queryFactory.create("FROM " + Person.class.getName()); List<Person> matches = query.execute().list(); assertEquals(1, matches.size()); } /** * Test querying for a field - direct access to field. */ public void testField() { QueryFactory queryFactory = Search.getQueryFactory(cache); Query<Person> query = queryFactory.create("FROM " + Person.class.getName() + " WHERE driverLicenseId = 'ZZ3141592'"); List<Person> matches = query.execute().list(); assertEquals(1, matches.size()); } /** * Test querying for an inherited indexed field - direct inherited field access. */ public void testInheritedField() { QueryFactory queryFactory = Search.getQueryFactory(cache); Query<Person> query = queryFactory.create("FROM " + Person.class.getName() + " WHERE age <= 52"); List<Person> matches = query.execute().list(); assertEquals(1, matches.size()); } /** * Test querying for an inherited indexed field - interface method with inherited implementation. */ public void testInheritedField2() { QueryFactory queryFactory = Search.getQueryFactory(cache); Query<Person> query = queryFactory.create("FROM " + Person.class.getName() + " WHERE name <= 'William'"); List<Person> matches = query.execute().list(); assertEquals(1, matches.size()); } /** * Test querying for an inherited indexed field - interface method implemented in class. */ public void testInheritedField3() { QueryFactory queryFactory = Search.getQueryFactory(cache); Query<Person> query = queryFactory.create("FROM " + Person.class.getName() + " WHERE gender = 'M'"); List<Person> matches = query.execute().list(); assertEquals(1, matches.size()); } /** * Test querying for an inherited indexed field - method inherited from superclass. */ public void testInheritedField4() { QueryFactory queryFactory = Search.getQueryFactory(cache); Query<Person> query = queryFactory.create("FROM " + Person.class.getName() + " WHERE surname = 'Shakespeare'"); List<Person> matches = query.execute().list(); assertEquals(1, matches.size()); } interface PersonInterface { String getName(); String getGender(); } public static abstract class PersonBase implements PersonInterface { String name; String surname; int age; PersonBase(String name, String surname, int age) { this.name = name; this.surname = surname; this.age = age; } @Basic @Override public String getName() { return name; } @Basic public String getSurname() { return surname; } @Basic public int getAge() { return age; } } @Indexed public static class Person extends PersonBase { String driverLicenseId; String gender; public Person(String name, String surname, int age, String driverLicenseId, String gender) { super(name, surname, age); this.driverLicenseId = driverLicenseId; this.gender = gender; } @Basic public String getDriverLicenseId() { return driverLicenseId; } @Basic @Override public String getGender() { return gender; } } }
5,557
29.043243
123
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/IckleFilterAndConverterDistTest.java
package org.infinispan.query.dsl.embedded; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; import org.infinispan.Cache; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.Closeables; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.CacheEntry; import org.infinispan.distribution.MagicKey; import org.infinispan.filter.CacheFilters; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.impl.ReflectionMatcher; import org.infinispan.query.core.impl.eventfilter.IckleFilterAndConverter; import org.infinispan.query.test.Person; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.Test; /** * @author anistor@redhat.com * @since 7.0 */ @Test(groups = "functional", testName = "query.dsl.embedded.IckleFilterAndConverterDistTest") public class IckleFilterAndConverterDistTest extends MultipleCacheManagersTest { protected final int numNodes; protected IckleFilterAndConverterDistTest(int numNodes) { this.numNodes = numNodes; } public IckleFilterAndConverterDistTest() { this(3); } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfgBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); cfgBuilder.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL); createClusteredCaches(numNodes, DslSCI.INSTANCE, cfgBuilder); } @Test public void testFilter() { final boolean isClustered = cache(0).getCacheConfiguration().clustering().cacheMode().isClustered(); for (int i = 0; i < 10; ++i) { Person value = new Person(); value.setName("John"); value.setAge(i + 30); Cache<Object, Person> cache = cache(i % numNodes); Object key = isClustered ? new MagicKey(cache) : i; cache.put(key, value); } IckleFilterAndConverter filterAndConverter = new IckleFilterAndConverter<Object, Person>("from org.infinispan.query.test.Person where blurb is null and age <= 31", null, ReflectionMatcher.class); Stream<CacheEntry<Object, Object>> stream = cache(0).getAdvancedCache().cacheEntrySet().stream(); CloseableIterator<Map.Entry<Object, ObjectFilter.FilterResult>> iterator = Closeables.iterator(CacheFilters.filterAndConvert(stream, filterAndConverter).iterator()); Map<Object, ObjectFilter.FilterResult> results = mapFromIterator(iterator); assertEquals(2, results.size()); for (ObjectFilter.FilterResult p : results.values()) { assertNull(((Person) p.getInstance()).getBlurb()); assertTrue(((Person) p.getInstance()).getAge() <= 31); } } /** * Iterates over all the entries provided by the iterator and puts them in a Map. */ private Map<Object, ObjectFilter.FilterResult> mapFromIterator(CloseableIterator<Map.Entry<Object, ObjectFilter.FilterResult>> iterator) { try { Map<Object, ObjectFilter.FilterResult> result = new HashMap<>(); while (iterator.hasNext()) { Map.Entry<Object, ObjectFilter.FilterResult> entry = iterator.next(); result.put(entry.getKey(), entry.getValue()); } return result; } finally { iterator.close(); } } }
3,632
38.064516
201
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/NonIndexedQueryStringTest.java
package org.infinispan.query.dsl.embedded; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.objectfilter.ParsingException; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.Test; /** * Test string-based queries on a not indexed cache. * * @author anistor@redhat.com * @since 9.0 */ @Test(groups = {"functional", "smoke"}, testName = "query.dsl.embedded.NonIndexedQueryStringTest") public class NonIndexedQueryStringTest extends QueryStringTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfg = TestCacheManagerFactory.getDefaultCacheConfiguration(true); cfg.transaction().transactionMode(TransactionMode.TRANSACTIONAL); createClusteredCaches(1, cfg); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextTerm() { super.testFullTextTerm(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextTermRightOperandAnalyzed() { super.testFullTextTermRightOperandAnalyzed(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextTermBoost() { super.testFullTextTermBoost(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextPhrase() { super.testFullTextPhrase(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextWithAggregation() { super.testFullTextWithAggregation(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextTermBoostAndSorting() { super.testFullTextTermBoostAndSorting(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextTermOccur() { super.testFullTextTermOccur(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextTermDoesntOccur() { super.testFullTextTermDoesntOccur(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028527: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed.") @Override public void testFullTextRangeWildcard() { super.testFullTextRangeWildcard(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028527: Full-text queries cannot be applied to property 'amount' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed.") @Override public void testFullTextRange() { super.testFullTextRange(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextPrefix() { super.testFullTextPrefix(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextWildcard() { super.testFullTextWildcard(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextWildcardFuzzyNotAllowed() { super.testFullTextWildcardFuzzyNotAllowed(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextFuzzy() { super.testFullTextFuzzy(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextFuzzyDefaultEdits() { super.testFullTextFuzzyDefaultEdits(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextFuzzySpecifiedEdits() { super.testFullTextFuzzySpecifiedEdits(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextRegexp() { super.testFullTextRegexp(); } @Override public void testExactMatchOnAnalyzedFieldNotAllowed() { // Not applicable to non-indexed caches } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'description' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextTermOnNonAnalyzedFieldNotAllowed() { super.testFullTextTermOnNonAnalyzedFieldNotAllowed(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS unless the property is indexed and analyzed.") @Override public void testFullTextRegexp2() { super.testFullTextRegexp2(); } }
8,420
57.479167
288
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/QueryStringTest.java
package org.infinispan.query.dsl.embedded; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.objectfilter.ParsingException; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryResult; import org.infinispan.query.dsl.embedded.testdomain.Address; import org.infinispan.query.dsl.embedded.testdomain.NotIndexed; import org.infinispan.query.dsl.embedded.testdomain.Transaction; import org.infinispan.query.dsl.embedded.testdomain.User; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test string-based queries. * * @author anistor@redhat.com * @since 9.0 */ @Test(groups = {"functional", "smoke"}, testName = "query.dsl.embedded.QueryStringTest") public class QueryStringTest extends AbstractQueryDslTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfg = TestCacheManagerFactory.getDefaultCacheConfiguration(true); cfg.transaction() .transactionMode(TransactionMode.TRANSACTIONAL) .indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(getModelFactory().getUserImplClass()) .addIndexedEntity(getModelFactory().getAccountImplClass()) .addIndexedEntity(getModelFactory().getTransactionImplClass()); createClusteredCaches(1, cfg); } @BeforeClass(alwaysRun = true) protected void populateCache() throws Exception { User user1 = getModelFactory().makeUser(); user1.setId(1); user1.setName("John"); user1.setSurname("Doe"); user1.setGender(User.Gender.MALE); user1.setAge(22); user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2))); user1.setNotes("Lorem ipsum dolor sit amet"); user1.setCreationDate(Instant.parse("2011-12-03T10:15:30Z")); user1.setPasswordExpirationDate(Instant.parse("2011-12-03T10:15:30Z")); Address address1 = getModelFactory().makeAddress(); address1.setStreet("Main Street"); address1.setPostCode("X1234"); address1.setNumber(156); user1.setAddresses(Collections.singletonList(address1)); User user2 = getModelFactory().makeUser(); user2.setId(2); user2.setName("Spider"); user2.setSurname("Man"); user2.setGender(User.Gender.MALE); user2.setAccountIds(Collections.singleton(3)); user2.setCreationDate(Instant.parse("2011-12-03T10:15:30Z")); user2.setPasswordExpirationDate(Instant.parse("2011-12-03T10:15:30Z")); Address address2 = getModelFactory().makeAddress(); address2.setStreet("Old Street"); address2.setPostCode("Y12"); address2.setNumber(-12); Address address3 = getModelFactory().makeAddress(); address3.setStreet("Bond Street"); address3.setPostCode("ZZ"); address3.setNumber(312); user2.setAddresses(Arrays.asList(address2, address3)); User user3 = getModelFactory().makeUser(); user3.setId(3); user3.setName("Spider"); user3.setSurname("Woman"); user3.setGender(User.Gender.FEMALE); user3.setAccountIds(Collections.emptySet()); user3.setCreationDate(Instant.parse("2011-12-03T10:15:30Z")); user3.setPasswordExpirationDate(Instant.parse("2011-12-03T10:15:30Z")); user3.setAddresses(new ArrayList<>()); Transaction transaction0 = getModelFactory().makeTransaction(); transaction0.setId(0); transaction0.setDescription("Birthday present"); transaction0.setAccountId(1); transaction0.setAmount(1800); transaction0.setDate(makeDate("2012-09-07")); transaction0.setDebit(false); transaction0.setNotes("card was not present"); transaction0.setValid(true); Transaction transaction1 = getModelFactory().makeTransaction(); transaction1.setId(1); transaction1.setDescription("Feb. rent payment"); transaction1.setLongDescription("Feb. rent payment"); transaction1.setAccountId(1); transaction1.setAmount(1500); transaction1.setDate(makeDate("2013-01-05")); transaction1.setDebit(true); transaction1.setValid(true); Transaction transaction2 = getModelFactory().makeTransaction(); transaction2.setId(2); transaction2.setDescription("Starbucks"); transaction2.setLongDescription("Starbucks"); transaction2.setAccountId(1); transaction2.setAmount(23); transaction2.setDate(makeDate("2013-01-09")); transaction2.setDebit(true); transaction2.setValid(true); Transaction transaction3 = getModelFactory().makeTransaction(); transaction3.setId(3); transaction3.setDescription("Hotel"); transaction3.setAccountId(2); transaction3.setAmount(45); transaction3.setDate(makeDate("2013-02-27")); transaction3.setDebit(true); transaction3.setValid(true); Transaction transaction4 = getModelFactory().makeTransaction(); transaction4.setId(4); transaction4.setDescription("Last january"); transaction4.setLongDescription("Last january"); transaction4.setAccountId(2); transaction4.setAmount(95); transaction4.setDate(makeDate("2013-01-31")); transaction4.setDebit(true); transaction4.setValid(true); Transaction transaction5 = getModelFactory().makeTransaction(); transaction5.setId(5); transaction5.setDescription("-Popcorn"); transaction5.setLongDescription("-Popcorn"); transaction5.setAccountId(2); transaction5.setAmount(5); transaction5.setDate(makeDate("2013-01-01")); transaction5.setDebit(true); transaction5.setValid(true); // persist and index the test objects // we put all of them in the same cache for the sake of simplicity getCacheForWrite().put("user_" + user1.getId(), user1); getCacheForWrite().put("user_" + user2.getId(), user2); getCacheForWrite().put("user_" + user3.getId(), user3); getCacheForWrite().put("transaction_" + transaction0.getId(), transaction0); getCacheForWrite().put("transaction_" + transaction1.getId(), transaction1); getCacheForWrite().put("transaction_" + transaction2.getId(), transaction2); getCacheForWrite().put("transaction_" + transaction3.getId(), transaction3); getCacheForWrite().put("transaction_" + transaction4.getId(), transaction4); getCacheForWrite().put("transaction_" + transaction5.getId(), transaction5); for (int i = 0; i < 50; i++) { Transaction transaction = getModelFactory().makeTransaction(); transaction.setId(50 + i); transaction.setDescription("Expensive shoes " + i); transaction.setLongDescription("Expensive shoes. Just beer, really " + i); transaction.setAccountId(2); transaction.setAmount(100 + i); transaction.setDate(makeDate("2013-08-20")); transaction.setDebit(true); transaction.setValid(true); getCacheForWrite().put("transaction_" + transaction.getId(), transaction); } getCacheForWrite().put("notIndexed1", new NotIndexed("testing 123")); getCacheForWrite().put("notIndexed2", new NotIndexed("xyz")); } public void testParam() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " where id = :idParam"); q.setParameter("idParam", 1); List<Transaction> list = q.execute().list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getId()); q.setParameter("idParam", 2); list = q.execute().list(); assertEquals(1, list.size()); assertEquals(2, list.get(0).getId()); } @Test(enabled = false) public void testParamWithSpacePadding() { //todo [anistor] need special tree nodes for all literal types (and for params) to be able to distinguish them better; QueryRendererDelegate.predicateXXX should receive such a tree node instead of a string Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " where id = : idParam"); List<Transaction> list = q.execute().list(); assertEquals(1, list.size()); } public void testExactMatch() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " where description = 'Birthday present'"); List<Transaction> list = q.execute().list(); assertEquals(1, list.size()); } public void testFullTextTerm() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " where longDescription:'rent'"); List<Transaction> list = q.execute().list(); assertEquals(1, list.size()); } public void testFullTextTermRightOperandAnalyzed() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " where longDescription:'RENT'"); List<Transaction> list = q.execute().list(); assertEquals(1, list.size()); } public void testFullTextTermBoost() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " where longDescription:('rent'^8 'shoes')"); List<Transaction> list = q.execute().list(); assertEquals(51, list.size()); } public void testFullTextPhrase() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " where longDescription:'expensive shoes'"); List<Transaction> list = q.execute().list(); assertEquals(50, list.size()); } public void testFullTextWithAggregation() { Query<Object[]> q = createQueryFromString("select t.accountId, max(t.amount), max(t.description) from " + getModelFactory().getTransactionTypeName() + " t where t.longDescription : (+'beer' && -'food') group by t.accountId"); List<Object[]> list = q.execute().list(); assertEquals(1, list.size()); assertEquals(2, list.get(0)[0]); assertEquals(149.0, list.get(0)[1]); assertEquals("Expensive shoes 9", list.get(0)[2]); } public void testFullTextTermBoostAndSorting() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " where longDescription:('rent'^8 'shoes') order by amount"); List<Transaction> list = q.execute().list(); assertEquals(51, list.size()); } public void testFullTextTermOccur() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " t where not (t.longDescription : (+'failed') or t.longDescription : 'blocked')"); List<Transaction> list = q.execute().list(); assertEquals(56, list.size()); } public void testFullTextTermDoesntOccur() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " t where t.longDescription : (-'really')"); List<Transaction> list = q.execute().list(); assertEquals(6, list.size()); } public void testFullTextRangeWildcard() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " t where t.longDescription : [* to *]"); List<Transaction> list = q.execute().list(); assertEquals(54, list.size()); } public void testFullTextRange() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " t where t.amount : [23 to 45]"); List<Transaction> list = q.execute().list(); assertEquals(2, list.size()); } public void testFullTextPrefix() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " t where t.longDescription : 'ren*'"); List<Transaction> list = q.execute().list(); assertEquals(1, list.size()); } public void testFullTextWildcard() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " t where t.longDescription : 're?t'"); List<Transaction> list = q.execute().list(); assertEquals(1, list.size()); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN014036: Prefix, wildcard or regexp queries cannot be fuzzy.*") public void testFullTextWildcardFuzzyNotAllowed() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " t where t.longDescription : 're?t'~2"); q.execute(); } public void testFullTextFuzzy() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " t where t.longDescription : 'retn'~"); List<Transaction> list = q.execute().list(); assertEquals(1, list.size()); } public void testFullTextFuzzyDefaultEdits() { // default number of edits should be 2 Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " t where t.longDescription : 'ertn'~"); List<Transaction> list = q.execute().list(); assertEquals(1, list.size()); q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " t where t.longDescription : 'ajunayr'~"); list = q.execute().list(); assertEquals(0, list.size()); } public void testFullTextFuzzySpecifiedEdits() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " t where t.longDescription : 'ajnuary'~1"); List<Transaction> list = q.execute().list(); assertEquals(1, list.size()); q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " t where t.longDescription : 'ajunary'~1"); list = q.execute().list(); assertEquals(0, list.size()); } public void testFullTextRegexp() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " t where t.longDescription : /[R|r]ent/"); List<Transaction> list = q.execute().list(); assertEquals(1, list.size()); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028526: Invalid query.*") public void testFullTextRegexpFuzzyNotAllowed() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " t where t.longDescription : /[R|r]ent/~2"); q.execute(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028522: .*property is analyzed.*") public void testExactMatchOnAnalyzedFieldNotAllowed() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " where longDescription = 'Birthday present'"); q.execute(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028521: .*unless the property is indexed and analyzed.*") public void testFullTextTermOnNonAnalyzedFieldNotAllowed() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " where description:'rent'"); q.execute(); } @Test(enabled = false) //TODO [anistor] fix! public void testFullTextRegexp2() { Query<Transaction> q = createQueryFromString("from " + getModelFactory().getTransactionTypeName() + " t where t.longDescription : ( -'beer' and '*')"); List<Transaction> list = q.execute().list(); assertEquals(1, list.size()); } public void testInstant1() { Query<User> q = createQueryFromString("from " + getModelFactory().getUserTypeName() + " u where u.creationDate = '2011-12-03T10:15:30Z'"); List<User> list = q.execute().list(); assertEquals(3, list.size()); } public void testInstant2() { Query<User> q = createQueryFromString("from " + getModelFactory().getUserTypeName() + " u where u.passwordExpirationDate = '2011-12-03T10:15:30Z'"); List<User> list = q.execute().list(); assertEquals(3, list.size()); } public void testEqNonIndexedType() { Query<NotIndexed> q = createQueryFromString("FROM " + NotIndexed.class.getName() + " WHERE notIndexedField = 'testing 123'"); List<NotIndexed> list = q.execute().list(); assertEquals(1, list.size()); assertEquals("testing 123", list.get(0).notIndexedField); } /** * See <a href="https://issues.jboss.org/browse/ISPN-7863">ISPN-7863</a> */ public void testAliasContainingLetterV() { Query<Transaction> q = createQueryFromString("FROM " + getModelFactory().getTransactionTypeName() + " vvv WHERE vvv.description = 'Birthday present'"); assertEquals(1, q.execute().list().size()); } public void testDeleteByQueryOnNonIndexedType() { getCacheForWrite().put("notIndexedToBeDeleted", new NotIndexed("testing delete")); Query<NotIndexed> select = createQueryFromString("FROM " + NotIndexed.class.getName() + " WHERE notIndexedField = 'testing delete'"); QueryResult<NotIndexed> result = select.execute(); assertEquals(1, result.count().value()); assertEquals(true, result.count().isExact()); Query<Transaction> delete = createQueryFromString("DELETE FROM " + NotIndexed.class.getName() + " WHERE notIndexedField = 'testing delete'"); assertEquals(1, delete.executeStatement()); result = select.execute(); assertEquals(0, result.count().value()); assertEquals(true, result.count().isExact()); } public void testDeleteByQueryOnIndexedField() throws Exception { Transaction tx = getModelFactory().makeTransaction(); tx.setId(9999); tx.setDescription("Holiday booking"); tx.setAccountId(1); tx.setAmount(1800); tx.setDate(makeDate("2021-09-07")); tx.setDebit(false); tx.setNotes("will be cancelled because of COVID"); tx.setValid(true); getCacheForWrite().put("transaction_" + tx.getId(), tx); Query<Transaction> select = createQueryFromString("FROM " + getModelFactory().getTransactionTypeName() + " WHERE description = 'Holiday booking'"); QueryResult<Transaction> result = select.execute(); assertEquals(1, result.count().value()); assertEquals(true, result.count().isExact()); Query<Transaction> delete = createQueryFromString("DELETE FROM " + getModelFactory().getTransactionTypeName() + " WHERE description = 'Holiday booking'"); assertEquals(1, delete.executeStatement()); result = select.execute(); assertEquals(0, result.count().value()); assertEquals(true, result.count().isExact()); } public void testDeleteByHybridQuery() throws Exception { Transaction tx = getModelFactory().makeTransaction(); tx.setId(9999); tx.setDescription("Holiday booking"); tx.setAccountId(1); tx.setAmount(1800); tx.setDate(makeDate("2021-09-07")); tx.setDebit(false); tx.setNotes("will be cancelled because of COVID"); tx.setValid(false); getCacheForWrite().put("transaction_" + tx.getId(), tx); Query<Transaction> select = createQueryFromString("FROM " + getModelFactory().getTransactionTypeName() + " WHERE description = 'Holiday booking' AND isValid = false"); QueryResult<Transaction> result = select.execute(); assertThat(result.count().value()).isEqualTo(1); assertThat(result.count().isExact()).isTrue(); Query<Transaction> delete = createQueryFromString("DELETE FROM " + getModelFactory().getTransactionTypeName() + " WHERE description = 'Holiday booking' AND isValid = false"); assertEquals(1, delete.executeStatement()); result = select.execute(); assertThat(result.count().value()).isEqualTo(0); assertThat(result.count().isExact()).isTrue(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028526: Invalid query.*") public void testDeleteWithProjections() { // exception thrown on create when in embedded mode Query<Transaction> delete = createQueryFromString("DELETE t.description FROM " + getModelFactory().getTransactionTypeName() + " as t WHERE t.description = 'bogus' ORDER BY amount"); // exception thrown just on execute when in remote mode delete.executeStatement(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028526: Invalid query.*") public void testDeleteWithOrderBy() { Query<Transaction> delete = createQueryFromString("DELETE FROM " + getModelFactory().getTransactionTypeName() + " WHERE description = 'bogus' ORDER BY amount"); delete.executeStatement(); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028526: Invalid query.*") public void testDeleteWithGroupBy() { Query<Transaction> delete = createQueryFromString("DELETE FROM " + getModelFactory().getTransactionTypeName() + " WHERE description = 'bogus' GROUP BY accountId"); delete.executeStatement(); } @Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "ISPN014057: DELETE statements cannot use paging \\(firstResult/maxResults\\)") public void testDeleteWithPaging() { Query<Transaction> delete = createQueryFromString("DELETE FROM " + getModelFactory().getTransactionTypeName() + " WHERE description = 'bogus'"); delete.maxResults(5); delete.executeStatement(); } protected final <T> Query<T> createQueryFromString(String queryString) { return getQueryFactory().create(queryString); } }
22,175
42.56778
211
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/NonIndexedSingleFileStoreQueryDslConditionsTest.java
package org.infinispan.query.dsl.embedded; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.SingleFileStoreConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * Test for non-indexed query on a cache with a single-file store. * * @author anistor@redhat.com * @since 7.0 */ @Test(groups = "functional", testName = "query.dsl.embedded.NonIndexedSingleFileStoreQueryDslConditionsTest") public class NonIndexedSingleFileStoreQueryDslConditionsTest extends NonIndexedQueryDslConditionsTest { private final String tmpDirectory = CommonsTestingUtil.tmpDirectory(getClass()); @AfterClass @Override protected void destroy() { try { super.destroy(); } finally { Util.recursiveFileRemove(tmpDirectory); } } @Override protected void createCacheManagers() throws Throwable { Util.recursiveFileRemove(tmpDirectory); GlobalConfigurationBuilder globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); globalBuilder.serialization().addContextInitializer(DslSCI.INSTANCE); globalBuilder.globalState().enable().persistentLocation(tmpDirectory); ConfigurationBuilder cfg = TestCacheManagerFactory.getDefaultCacheConfiguration(true); cfg.persistence().addStore(SingleFileStoreConfigurationBuilder.class); // ensure the data container contains minimal data so the store will need to be accessed to get the rest cfg.locking().concurrencyLevel(1).memory().size(1L); createClusteredCaches(1, globalBuilder, cfg, false); } }
1,869
38.787234
110
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/ListenerWithDslFilterTest.java
package org.infinispan.query.dsl.embedded; 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.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.objectfilter.ObjectFilter; import org.infinispan.objectfilter.ParsingException; 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.testng.annotations.Test; /** * @author anistor@redhat.com * @since 7.2 */ @Test(groups = "functional", testName = "query.dsl.embedded.ListenerWithDslFilterTest") public class ListenerWithDslFilterTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() { return TestCacheManagerFactory.createCacheManager(QueryTestSCI.INSTANCE, getConfigurationBuilder()); } protected ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder cfgBuilder = new ConfigurationBuilder(); cfgBuilder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class); return cfgBuilder; } public void testEventFilter() { for (int i = 0; i < 10; ++i) { Person value = new Person(); value.setName("John"); value.setAge(99); cache().put(i, value); } assertEquals(10, cache.size()); QueryFactory qf = Search.getQueryFactory(cache()); Query<Person> query = qf.<Person>create("FROM " + Person.class.getName() + " WHERE age <= :ageParam") .setParameter("ageParam", 31); EntryListener listener = new EntryListener(); // we want our cluster listener to be notified only if the entity matches our query cache().addListener(listener, Search.makeFilter(query), null); assertTrue(listener.createEvents.isEmpty()); assertTrue(listener.modifyEvents.isEmpty()); for (int i = 0; i < 10; ++i) { Person value = new Person(); value.setName("John"); value.setAge(i + 25); cache().put(i, value); } assertEquals(10, cache.size()); assertTrue(listener.createEvents.isEmpty()); assertEquals(7, listener.modifyEvents.size()); for (ObjectFilter.FilterResult r : listener.modifyEvents) { Person p = (Person) r.getInstance(); assertTrue(p.getAge() <= 31); } cache().removeListener(listener); // ensure no more invocations after the listener was removed listener.createEvents.clear(); listener.modifyEvents.clear(); Person value = new Person(); value.setName("George"); value.setAge(30); cache().put(-1, value); assertTrue(listener.createEvents.isEmpty()); assertTrue(listener.modifyEvents.isEmpty()); } public void testEventFilterChangingParameter() { for (int i = 0; i < 10; ++i) { Person value = new Person(); value.setName("John"); value.setAge(99); cache().put(i, value); } assertEquals(10, cache.size()); QueryFactory qf = Search.getQueryFactory(cache()); Query<Person> query = qf.<Person>create("FROM " + Person.class.getName() + " WHERE age <= :ageParam") .setParameter("ageParam", 31); EntryListener listener = new EntryListener(); // we want our cluster listener to be notified only if the entity matches our query cache().addListener(listener, Search.makeFilter(query), null); assertTrue(listener.createEvents.isEmpty()); assertTrue(listener.modifyEvents.isEmpty()); for (int i = 0; i < 10; ++i) { Person value = new Person(); value.setName("John"); value.setAge(i + 25); cache().put(i, value); } assertEquals(10, cache.size()); assertTrue(listener.createEvents.isEmpty()); assertEquals(7, listener.modifyEvents.size()); for (ObjectFilter.FilterResult r : listener.modifyEvents) { Person p = (Person) r.getInstance(); assertTrue(p.getAge() <= 31); } cache().removeListener(listener); query.setParameter("ageParam", 30); listener = new EntryListener(); cache().addListener(listener, Search.makeFilter(query), null); assertTrue(listener.createEvents.isEmpty()); assertTrue(listener.modifyEvents.isEmpty()); for (int i = 0; i < 10; ++i) { Person value = new Person(); value.setName("John"); value.setAge(i + 25); cache().put(i, value); } assertEquals(10, cache.size()); assertTrue(listener.createEvents.isEmpty()); assertEquals(6, listener.modifyEvents.size()); for (ObjectFilter.FilterResult r : listener.modifyEvents) { Person p = (Person) r.getInstance(); assertTrue(p.getAge() <= 30); } } public void testEventFilterAndConverter() { QueryFactory qf = Search.getQueryFactory(cache()); Query<Object[]> query = qf.create("SELECT name, age FROM " + Person.class.getName() + " WHERE age <= 31"); EntryListener listener = new EntryListener(); // we want our cluster listener to be notified only if the entity matches our query cache().addListener(listener, Search.makeFilter(query), null); for (int i = 0; i < 10; ++i) { Person value = new Person(); value.setName("John"); value.setAge(i + 25); cache.put(i, value); } assertEquals(10, cache.size()); assertEquals(7, listener.createEvents.size()); assertTrue(listener.modifyEvents.isEmpty()); for (ObjectFilter.FilterResult r : listener.createEvents) { assertNotNull(r.getProjection()); assertEquals(2, r.getProjection().length); assertTrue((Integer) r.getProjection()[1] <= 31); } cache().removeListener(listener); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028523: Filters cannot use full-text searches") public void testDisallowFullTextQuery() { QueryFactory qf = Search.getQueryFactory(cache()); Query<Person> query = qf.create("FROM " + Person.class.getName() + " WHERE name : 'john'"); cache().addListener(new EntryListener(), Search.makeFilter(query), null); } /** * Using grouping and aggregation with event filters is not allowed. */ @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = ".*ISPN028509:.*") public void testDisallowGroupingAndAggregation() { QueryFactory qf = Search.getQueryFactory(cache()); Query<Object[]> query = qf.create("SELECT MAX(age) FROM " + Person.class.getName() + " WHERE age >= 20"); cache().addListener(new EntryListener(), Search.makeFilter(query), null); } @Listener(observation = Listener.Observation.POST) private static class EntryListener { // this is where we accumulate matches public final List<ObjectFilter.FilterResult> createEvents = Collections.synchronizedList(new ArrayList<>()); public final List<ObjectFilter.FilterResult> modifyEvents = Collections.synchronizedList(new ArrayList<>()); @CacheEntryCreated public void handleEvent(CacheEntryCreatedEvent<?, ObjectFilter.FilterResult> event) { ObjectFilter.FilterResult filterResult = event.getValue(); createEvents.add(filterResult); } @CacheEntryModified public void handleEvent(CacheEntryModifiedEvent<?, ObjectFilter.FilterResult> event) { ObjectFilter.FilterResult filterResult = event.getValue(); modifyEvents.add(filterResult); } } }
8,519
34.206612
140
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/IckleFilterAndConverterLocalTest.java
package org.infinispan.query.dsl.embedded; import org.infinispan.configuration.cache.ConfigurationBuilder; 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.dsl.embedded.IckleFilterAndConverterLocalTest") public class IckleFilterAndConverterLocalTest extends IckleFilterAndConverterDistTest { public IckleFilterAndConverterLocalTest() { super(1); } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfgBuilder = TestCacheManagerFactory.getDefaultCacheConfiguration(true); cfgBuilder.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL); createClusteredCaches(numNodes, cfgBuilder); } }
870
32.5
99
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/Author.java
package org.infinispan.query.dsl.embedded.testdomain; import java.io.Serializable; import org.infinispan.api.annotations.indexing.Basic; /** * @author anistor@redhat.com * @since 9.0 */ public class Author implements Serializable { private String name; private String surname; public Author(String name, String surname) { this.name = name; this.surname = surname; } @Basic(projectable = true) public String getName() { return name; } public void setName(String name) { this.name = name; } @Basic public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } @Override public String toString() { return "Author{" + "name='" + name + '\'' + ", surname='" + surname + '\'' + '}'; } }
876
17.270833
53
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/Account.java
package org.infinispan.query.dsl.embedded.testdomain; import java.io.Serializable; import java.util.Date; import java.util.List; import org.infinispan.protostream.annotations.ProtoEnumValue; /** * @author anistor@redhat.com * @since 6.0 */ public interface Account extends Serializable { enum Currency { @ProtoEnumValue(number = 0) EUR, @ProtoEnumValue(number = 1) GBP, @ProtoEnumValue(number = 2) USD, @ProtoEnumValue(number = 3) BRL } int getId(); void setId(int id); String getDescription(); void setDescription(String description); Date getCreationDate(); void setCreationDate(Date creationDate); Limits getLimits(); void setLimits(Limits limits); Limits getHardLimits(); void setHardLimits(Limits hardLimits); List<byte[]> getBlurb(); void setBlurb(List<byte[]> blurb); Currency[] getCurrencies(); void setCurrencies(Currency[] currencies); }
965
16.888889
61
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/NotIndexed.java
package org.infinispan.query.dsl.embedded.testdomain; import java.io.Serializable; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; /** * @author anistor@redhat.com * @since 7.2 */ public class NotIndexed implements Serializable { @ProtoField(1) public String notIndexedField; @ProtoFactory public NotIndexed(String notIndexedField) { this.notIndexedField = notIndexedField; } }
477
20.727273
59
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/Limits.java
package org.infinispan.query.dsl.embedded.testdomain; /** * @author anistor@redhat.com * @since 9.4.1 */ public interface Limits { Double getMaxDailyLimit(); void setMaxDailyLimit(Double maxDailyLimit); Double getMaxTransactionLimit(); void setMaxTransactionLimit(Double maxTransactionLimit); String[] getPayees(); void setPayees(String[] payees); }
378
17.047619
59
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/Book.java
package org.infinispan.query.dsl.embedded.testdomain; import java.io.Serializable; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Embedded; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Text; /** * @author anistor@redhat.com * @since 9.0 */ @Indexed public class Book implements Serializable { private String title; private String publisher; private String isbn; private String preface; private Author author; public Book(String title, String publisher, Author author, String preface) { this.title = title; this.publisher = publisher; this.author = author; this.preface = preface; } @Basic public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Text public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } @Basic public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } @Text public String getPreface() { return preface; } public void setPreface(String preface) { this.preface = preface; } @Embedded public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } @Override public String toString() { return "Book{" + "title='" + title + '\'' + ", publisher='" + publisher + '\'' + ", isbn='" + isbn + '\'' + ", author=" + author + ", preface='" + preface + '\'' + '}'; } }
1,776
18.744444
79
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/Address.java
package org.infinispan.query.dsl.embedded.testdomain; /** * @author anistor@redhat.com * @since 6.0 */ public interface Address { String getStreet(); void setStreet(String street); String getPostCode(); void setPostCode(String postCode); int getNumber(); void setNumber(int number); boolean isCommercial(); void setCommercial(boolean isCommercial); }
387
14.52
53
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/Transaction.java
package org.infinispan.query.dsl.embedded.testdomain; import java.util.Date; /** * @author anistor@redhat.com * @since 6.0 */ public interface Transaction { int getId(); void setId(int id); String getDescription(); void setDescription(String description); String getLongDescription(); void setLongDescription(String longDescription); String getNotes(); void setNotes(String notes); int getAccountId(); void setAccountId(int accountId); Date getDate(); void setDate(Date date); double getAmount(); void setAmount(double amount); boolean isDebit(); void setDebit(boolean isDebit); boolean isValid(); void setValid(boolean isValid); }
709
14.106383
53
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/ModelFactory.java
package org.infinispan.query.dsl.embedded.testdomain; /** * @author anistor@redhat.com * @since 7.0 */ public interface ModelFactory { Account makeAccount(); Limits makeLimits(); Class<?> getAccountImplClass(); String getAccountTypeName(); User makeUser(); Class<?> getUserImplClass(); String getUserTypeName(); Address makeAddress(); Class<?> getAddressImplClass(); String getAddressTypeName(); Transaction makeTransaction(); Class<?> getTransactionImplClass(); String getTransactionTypeName(); }
554
14.857143
53
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/User.java
package org.infinispan.query.dsl.embedded.testdomain; import java.time.Instant; import java.util.List; import java.util.Set; import org.infinispan.protostream.annotations.ProtoEnumValue; /** * @author anistor@redhat.com * @since 6.0 */ public interface User { enum Gender { @ProtoEnumValue(number = 0) MALE, @ProtoEnumValue(number = 1) FEMALE } int getId(); void setId(int id); Set<Integer> getAccountIds(); void setAccountIds(Set<Integer> accountIds); String getName(); void setName(String name); String getSurname(); void setSurname(String surname); String getSalutation(); void setSalutation(String salutation); Integer getAge(); void setAge(Integer age); Gender getGender(); void setGender(Gender gender); List<Address> getAddresses(); void setAddresses(List<Address> addresses); String getNotes(); void setNotes(String notes); Instant getCreationDate(); void setCreationDate(Instant creationDate); Instant getPasswordExpirationDate(); void setPasswordExpirationDate(Instant passwordExpirationDate); }
1,131
16.151515
66
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/hsearch/ModelFactoryHS.java
package org.infinispan.query.dsl.embedded.testdomain.hsearch; import org.infinispan.query.dsl.embedded.testdomain.Account; import org.infinispan.query.dsl.embedded.testdomain.Address; import org.infinispan.query.dsl.embedded.testdomain.Limits; import org.infinispan.query.dsl.embedded.testdomain.ModelFactory; import org.infinispan.query.dsl.embedded.testdomain.Transaction; import org.infinispan.query.dsl.embedded.testdomain.User; /** * @author anistor@redhat.com * @since 7.0 */ public class ModelFactoryHS implements ModelFactory { public static final ModelFactory INSTANCE = new ModelFactoryHS(); private ModelFactoryHS() { } @Override public Account makeAccount() { return new AccountHS(); } @Override public Limits makeLimits() { return new LimitsHS(); } @Override public Class<AccountHS> getAccountImplClass() { return AccountHS.class; } @Override public String getAccountTypeName() { return getAccountImplClass().getName(); } @Override public User makeUser() { return new UserHS(); } @Override public Class<UserHS> getUserImplClass() { return UserHS.class; } @Override public String getUserTypeName() { return getUserImplClass().getName(); } @Override public Transaction makeTransaction() { return new TransactionHS(); } @Override public Class<TransactionHS> getTransactionImplClass() { return TransactionHS.class; } @Override public String getTransactionTypeName() { return getTransactionImplClass().getName(); } @Override public Address makeAddress() { return new AddressHS(); } @Override public Class<AddressHS> getAddressImplClass() { return AddressHS.class; } @Override public String getAddressTypeName() { return getAddressImplClass().getName(); } }
1,889
20.976744
68
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/hsearch/AccountHS.java
package org.infinispan.query.dsl.embedded.testdomain.hsearch; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Embedded; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.query.dsl.embedded.testdomain.Account; import org.infinispan.query.dsl.embedded.testdomain.Limits; /** * @author anistor@redhat.com * @since 7.0 */ @Indexed public class AccountHS implements Account, Serializable { @ProtoField(number = 1, defaultValue = "0") int id; @ProtoField(number = 2) String description; @ProtoField(number = 3) Date creationDate; @ProtoField(number = 4) LimitsHS limits; @ProtoField(number = 5) LimitsHS hardLimits; // not indexed @ProtoField(number = 6, collectionImplementation = ArrayList.class) List<byte[]> blurb = new ArrayList<>(); @ProtoField(number = 7) Currency[] currencies = new Currency[0]; public AccountHS() { // hardLimits is a required field, so we make our life easy by providing defaults here hardLimits = new LimitsHS(); hardLimits.setMaxTransactionLimit(5000.0); hardLimits.setMaxDailyLimit(10000.0); } @Override @Basic(projectable = true, sortable = true) public int getId() { return id; } @Override public void setId(int id) { this.id = id; } @Override @Basic(projectable = true, sortable = true) public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = description; } @Override @Basic(projectable = true, sortable = true) public Date getCreationDate() { return creationDate; } @Override public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } @Override @Embedded public LimitsHS getLimits() { return limits; } @Override public void setLimits(Limits limits) { this.limits = (LimitsHS) limits; } @Override @Embedded public LimitsHS getHardLimits() { return hardLimits; } @Override public void setHardLimits(Limits hardLimits) { this.hardLimits = (LimitsHS) hardLimits; } @Override public List<byte[]> getBlurb() { return blurb; } @Override public void setBlurb(List<byte[]> blurb) { this.blurb = blurb; } private boolean blurbEquals(List<byte[]> otherBlurbs) { if (otherBlurbs == blurb) { return true; } if (otherBlurbs == null || blurb == null || otherBlurbs.size() != blurb.size()) { return false; } for (int i = 0; i < blurb.size(); i++) { if (!Arrays.equals(blurb.get(i), otherBlurbs.get(i))) { return false; } } return true; } @Override @Basic(projectable = true) public Currency[] getCurrencies() { return currencies; } @Override public void setCurrencies(Currency[] currencies) { this.currencies = currencies; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AccountHS account = (AccountHS) o; return id == account.id && Objects.equals(description, account.description) && Objects.equals(creationDate, account.creationDate) && Objects.equals(limits, account.limits) && Objects.equals(hardLimits, account.hardLimits) && blurbEquals(account.blurb) && Arrays.equals(currencies, account.currencies); } @Override public int hashCode() { int blurbHash = 0; if (blurb != null) { for (byte[] b : blurb) { blurbHash = 31 * blurbHash + Arrays.hashCode(b); } } return Objects.hash(id, description, creationDate, limits, hardLimits, blurbHash, Arrays.hashCode(currencies)); } @Override public String toString() { return "AccountHS{" + "id=" + id + ", description='" + description + '\'' + ", creationDate='" + creationDate + '\'' + ", limits=" + limits + ", hardLimits=" + hardLimits + ", blurb=" + (blurb != null ? blurb.stream().map(Arrays::toString).collect(Collectors.toList()) : "null") + ", currencies=" + Arrays.toString(currencies) + '}'; } }
4,684
24.883978
119
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/hsearch/UserBase.java
package org.infinispan.query.dsl.embedded.testdomain.hsearch; import java.io.Serializable; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.query.dsl.embedded.testdomain.User; /** * Parent class for UserHS to demonstrate inheritance of indexed attributes. */ public abstract class UserBase implements User, Serializable { protected String name; @Override @Basic(projectable = true, sortable = true) @ProtoField(number = 1) public String getName() { return name; } @Override public void setName(String name) { this.name = name; } }
663
22.714286
76
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/hsearch/UserHS.java
package org.infinispan.query.dsl.embedded.testdomain.hsearch; import java.time.Instant; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Embedded; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.query.dsl.embedded.testdomain.Address; /** * @author anistor@redhat.com * @since 7.0 */ @Indexed public class UserHS extends UserBase { private int id; private Set<Integer> accountIds; private String surname; private String salutation; private Integer age; // yes, not the birth date :) private Gender gender; private List<Address> addresses; private Instant creationDate; private Instant passwordExpirationDate; /** * This is not indexed! */ private String notes; @Override @Basic(projectable = true, sortable = true) @ProtoField(number = 2, defaultValue = "0") public int getId() { return id; } @Override public void setId(int id) { this.id = id; } @Override @Basic(projectable = true) @ProtoField(number = 3, collectionImplementation = HashSet.class) public Set<Integer> getAccountIds() { return accountIds; } @Override public void setAccountIds(Set<Integer> accountIds) { this.accountIds = accountIds; } @Override @Basic(projectable = true, sortable = true) @ProtoField(number = 4) public String getSurname() { return surname; } @Override public void setSurname(String surname) { this.surname = surname; } @Override @Basic(projectable = true) @ProtoField(number = 5) public String getSalutation() { return salutation; } @Override public void setSalutation(String salutation) { this.salutation = salutation; } @Override @Basic(projectable = true, sortable = true) @ProtoField(number = 6) public Integer getAge() { return age; } @Override public void setAge(Integer age) { this.age = age; } @Override @Basic(projectable = true) @ProtoField(number = 7) public Gender getGender() { return gender; } @Override public void setGender(Gender gender) { this.gender = gender; } @Override public List<Address> getAddresses() { return addresses; } @Override public void setAddresses(List<Address> addresses) { this.addresses = addresses; } @Embedded(name = "addresses") @ProtoField(number = 8, collectionImplementation = ArrayList.class) public List<AddressHS> getHSAddresses() { return addresses == null ? null : addresses.stream().map(AddressHS.class::cast).collect(Collectors.toList()); } void setHSAddresses(List<AddressHS> addresses) { // IPROTO-120 means that an empty list is always returned, so we need to force a null value this.addresses = addresses == null || addresses.isEmpty() ? null : new ArrayList<>(addresses); } @Override @ProtoField(number = 9) public String getNotes() { return notes; } @Override public void setNotes(String notes) { this.notes = notes; } @Override @ProtoField(number = 10) @Basic(projectable = true) public Instant getCreationDate() { return creationDate; } @Override public void setCreationDate(Instant creationDate) { this.creationDate = creationDate; } @Override @ProtoField(number = 11) public Instant getPasswordExpirationDate() { return passwordExpirationDate; } @Override public void setPasswordExpirationDate(Instant passwordExpirationDate) { this.passwordExpirationDate = passwordExpirationDate; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserHS other = (UserHS) o; if (age != null ? !age.equals(other.age) : other.age != null) return false; if (id != other.id) return false; if (accountIds != null ? !accountIds.equals(other.accountIds) : other.accountIds != null) return false; if (addresses != null ? !addresses.equals(other.addresses) : other.addresses != null) return false; if (gender != other.gender) return false; if (name != null ? !name.equals(other.name) : other.name != null) return false; if (surname != null ? !surname.equals(other.surname) : other.surname != null) return false; if (salutation != null ? !salutation.equals(other.salutation) : other.salutation != null) return false; if (notes != null ? !notes.equals(other.notes) : other.notes != null) return false; if (creationDate != null ? !creationDate.equals(other.creationDate) : other.creationDate != null) return false; if (passwordExpirationDate != null ? !passwordExpirationDate.equals(other.passwordExpirationDate) : other.passwordExpirationDate != null) return false; return true; } @Override public int hashCode() { int result = id; result = 31 * result + (accountIds != null ? accountIds.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (surname != null ? surname.hashCode() : 0); result = 31 * result + (salutation != null ? salutation.hashCode() : 0); result = 31 * result + (age != null ? age : 0); result = 31 * result + (gender != null ? gender.hashCode() : 0); result = 31 * result + (addresses != null ? addresses.hashCode() : 0); result = 31 * result + (notes != null ? notes.hashCode() : 0); result = 31 * result + (creationDate != null ? creationDate.hashCode() : 0); result = 31 * result + (passwordExpirationDate != null ? passwordExpirationDate.hashCode() : 0); return result; } @Override public String toString() { return "UserHS{" + "id=" + id + ", name='" + name + '\'' + ", surname='" + surname + '\'' + ", salutation='" + salutation + '\'' + ", accountIds=" + accountIds + ", addresses=" + addresses + ", age=" + age + ", gender=" + gender + ", notes=" + notes + ", creationDate='" + creationDate + '\'' + ", passwordExpirationDate=" + passwordExpirationDate + '}'; } }
6,528
27.635965
157
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/hsearch/TransactionHS.java
package org.infinispan.query.dsl.embedded.testdomain.hsearch; import java.io.Serializable; import java.util.Date; import java.util.Objects; 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.ProtoField; import org.infinispan.query.dsl.embedded.testdomain.Transaction; /** * @author anistor@redhat.com * @since 7.0 */ @Indexed public class TransactionHS implements Transaction, Serializable { private int id; private String description; private String longDescription; private String notes; private int accountId; private Date date; private double amount; private boolean isDebit; // not indexed! private boolean isValid; @Override @Basic(projectable = true, sortable = true) @ProtoField(number = 1, defaultValue = "0") public int getId() { return id; } @Override public void setId(int id) { this.id = id; } @Override @Basic(projectable = true, sortable = true) @ProtoField(number = 2) public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = description; } @Override @Text @ProtoField(number = 3) public String getLongDescription() { return longDescription; } @Override public void setLongDescription(String longDescription) { this.longDescription = longDescription; } @Override @Text(analyzer = "ngram") @ProtoField(number = 4) public String getNotes() { return notes; } @Override public void setNotes(String notes) { this.notes = notes; } @Override @Basic(projectable = true) @ProtoField(number = 5, defaultValue = "0") public int getAccountId() { return accountId; } @Override public void setAccountId(int accountId) { this.accountId = accountId; } @Override @Basic(projectable = true) @ProtoField(number = 6) public Date getDate() { return date; } @Override public void setDate(Date date) { this.date = date; } @Override @Basic(projectable = true, sortable = true) @ProtoField(number = 7, defaultValue = "0") public double getAmount() { return amount; } @Override public void setAmount(double amount) { this.amount = amount; } @Override @Basic(projectable = true) @ProtoField(number = 8, defaultValue = "false") public boolean isDebit() { return isDebit; } @Override public void setDebit(boolean isDebit) { this.isDebit = isDebit; } @Override @ProtoField(number = 9, defaultValue = "false") public boolean isValid() { return isValid; } @Override public void setValid(boolean isValid) { this.isValid = isValid; } @Override public String toString() { return "TransactionHS{" + "id=" + id + ", description='" + description + '\'' + ", longDescription='" + longDescription + '\'' + ", notes='" + notes + '\'' + ", accountId=" + accountId + ", date='" + date + '\'' + ", amount=" + amount + ", isDebit=" + isDebit + ", isValid=" + isValid + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TransactionHS that = (TransactionHS) o; return id == that.id && accountId == that.accountId && Double.compare(that.amount, amount) == 0 && isDebit == that.isDebit && isValid == that.isValid && Objects.equals(description, that.description) && Objects.equals(longDescription, that.longDescription) && Objects.equals(notes, that.notes) && Objects.equals(date, that.date); } @Override public int hashCode() { return Objects.hash(id, description, longDescription, notes, accountId, date, amount, isDebit, isValid); } }
4,108
22.48
187
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/hsearch/LimitsHS.java
package org.infinispan.query.dsl.embedded.testdomain.hsearch; import java.io.Serializable; import java.util.Arrays; import java.util.Objects; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.query.dsl.embedded.testdomain.Limits; /** * @author anistor@redhat.com * @since 9.4.1 */ public class LimitsHS implements Limits, Serializable { private Double maxDailyLimit; private Double maxTransactionLimit; private String[] payees = new String[0]; @Override @ProtoField(number = 1) @Basic(projectable = true) public Double getMaxDailyLimit() { return maxDailyLimit; } @Override public void setMaxDailyLimit(Double maxDailyLimit) { this.maxDailyLimit = maxDailyLimit; } @Override @ProtoField(number = 2) @Basic(projectable = true) public Double getMaxTransactionLimit() { return maxTransactionLimit; } @Override public void setMaxTransactionLimit(Double maxTransactionLimit) { this.maxTransactionLimit = maxTransactionLimit; } @Override @ProtoField(number = 3) @Basic(projectable = true) public String[] getPayees() { return payees; } @Override public void setPayees(String[] payees) { this.payees = payees; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LimitsHS limits = (LimitsHS) o; return Objects.equals(maxDailyLimit, limits.maxDailyLimit) && Objects.equals(maxTransactionLimit, limits.maxTransactionLimit) && Arrays.equals(payees, limits.payees); } @Override public int hashCode() { return Objects.hash(maxDailyLimit, maxTransactionLimit, Arrays.hashCode(payees)); } @Override public String toString() { return "LimitsHS{" + "maxDailyLimit=" + maxDailyLimit + ", maxTransactionLimit=" + maxTransactionLimit + ", payees=" + Arrays.toString(payees) + '}'; } }
2,100
24.313253
87
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/testdomain/hsearch/AddressHS.java
package org.infinispan.query.dsl.embedded.testdomain.hsearch; import java.io.Serializable; import java.util.Objects; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.query.dsl.embedded.testdomain.Address; /** * @author anistor@redhat.com * @since 7.0 */ public class AddressHS implements Address, Serializable { private String street; private String postCode; private int number; private boolean isCommercial; @Override @ProtoField(number = 1) @Basic(projectable = true) public String getStreet() { return street; } @Override public void setStreet(String street) { this.street = street; } @Override @ProtoField(number = 2) @Basic(projectable = true, sortable = true) public String getPostCode() { return postCode; } @Override public void setPostCode(String postCode) { this.postCode = postCode; } @Override @ProtoField(number = 3, defaultValue = "0") @Basic(projectable = true) public int getNumber() { return number; } @Override public void setNumber(int number) { this.number = number; } @Override @ProtoField(number = 4, defaultValue = "false") public boolean isCommercial() { return isCommercial; } @Override public void setCommercial(boolean isCommercial) { this.isCommercial = isCommercial; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AddressHS address = (AddressHS) o; return number == address.number && isCommercial == address.isCommercial && Objects.equals(street, address.street) && Objects.equals(postCode, address.postCode); } @Override public int hashCode() { return Objects.hash(street, postCode, number, isCommercial); } @Override public String toString() { return "AddressHS{" + "street='" + street + '\'' + ", postCode='" + postCode + '\'' + ", number=" + number + ", isCommercial=" + isCommercial + '}'; } }
2,233
22.030928
66
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/impl/HibernateSearchPropertyHelperTest.java
package org.infinispan.query.dsl.embedded.impl; import static org.assertj.core.api.Assertions.assertThat; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.DocumentId; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Text; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.objectfilter.impl.syntax.parser.ReflectionEntityNamesResolver; import org.infinispan.query.helper.SearchMappingHelper; import org.infinispan.search.mapper.mapping.SearchMapping; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.BlockingManager; import org.testng.annotations.Test; /** * @author anistor@redhat.com * @since 9.0 */ public class HibernateSearchPropertyHelperTest extends SingleCacheManagerTest { private SearchMapping searchMapping; private HibernateSearchPropertyHelper propertyHelper; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(); GlobalComponentRegistry componentRegistry = cacheManager.getGlobalComponentRegistry(); BlockingManager blockingManager = componentRegistry.getComponent(BlockingManager.class); // the cache manager is created only to provide manager instances to the search mapping searchMapping = SearchMappingHelper.createSearchMappingForTests(blockingManager, TestEntity.class); propertyHelper = new HibernateSearchPropertyHelper(searchMapping, new ReflectionEntityNamesResolver(null)); return cacheManager; } @Override protected void teardown() { if (searchMapping != null) { searchMapping.close(); } super.teardown(); } private Object convertToPropertyType(Class<?> type, String propertyName, String value) { return propertyHelper.convertToPropertyType(type, new String[]{propertyName}, value); } @Test public void testConvertIdProperty() { assertThat(convertToPropertyType(TestEntity.class, "id", "42")).isEqualTo("42"); } @Test public void testConvertStringProperty() { assertThat(convertToPropertyType(TestEntity.class, "name", "42")).isEqualTo("42"); } @Test public void testConvertIntProperty() { assertThat(convertToPropertyType(TestEntity.class, "i", "42")).isEqualTo(42); } @Test public void testConvertLongProperty() { assertThat(convertToPropertyType(TestEntity.class, "l", "42")).isEqualTo(42L); } @Test public void testConvertFloatProperty() { assertThat(convertToPropertyType(TestEntity.class, "f", "42.0")).isEqualTo(42.0F); } @Test public void testConvertDoubleProperty() { assertThat(convertToPropertyType(TestEntity.class, "d", "42.0")).isEqualTo(42.0D); } @Test public void testRecognizeAnalyzedField() { assertThat(propertyHelper.getIndexedFieldProvider().get(TestEntity.class).isAnalyzed(new String[]{"description"})).isTrue(); } @Test public void testRecognizeStoredField() { assertThat(propertyHelper.getIndexedFieldProvider().get(TestEntity.class).isProjectable(new String[]{"description"})).isTrue(); assertThat(propertyHelper.getIndexedFieldProvider().get(TestEntity.class).isSortable(new String[]{"description"})).isFalse(); } @Test public void testRecognizeUnanalyzedField() { assertThat(propertyHelper.getIndexedFieldProvider().get(TestEntity.class).isAnalyzed(new String[]{"i"})).isFalse(); } @Indexed public static class TestEntity { public String id; @Basic public String name; @Text(projectable = true) public String description; public int i; public long l; public float f; public double d; // When an entity is created with Infinispan, // the document id is reserved to link the cache entry key to the value. // In this case Hibernate Search is used standalone, // so we need to provide explicitly the document id, // using the Search annotation. @DocumentId public String getId() { return id; } @Basic public int getI() { return i; } @Basic public long getL() { return l; } @Basic public float getF() { return f; } @Basic public double getD() { return d; } } }
4,634
29.695364
133
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/impl/LuceneTransformationTest.java
package org.infinispan.query.dsl.embedded.impl; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.query.helper.IndexAccessor.extractSort; import java.util.HashMap; import java.util.Map; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.hibernate.search.engine.search.query.SearchQuery; import org.hibernate.search.util.common.SearchException; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.objectfilter.ParsingException; import org.infinispan.objectfilter.impl.syntax.parser.IckleParser; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.objectfilter.impl.syntax.parser.ReflectionEntityNamesResolver; import org.infinispan.query.dsl.embedded.impl.model.Employee; import org.infinispan.query.helper.SearchMappingHelper; import org.infinispan.search.mapper.mapping.SearchMapping; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.BlockingManager; import org.testng.annotations.Test; /** * Test the parsing and transformation of Ickle queries to Lucene queries. * * @author anistor@redhat.com * @since 9.0 */ public class LuceneTransformationTest extends SingleCacheManagerTest { private SearchMapping searchMapping; private HibernateSearchPropertyHelper propertyHelper; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(); GlobalComponentRegistry componentRegistry = cacheManager.getGlobalComponentRegistry(); BlockingManager blockingManager = componentRegistry.getComponent(BlockingManager.class); // the cache manager is created only to provide manager instances to the search mapping searchMapping = SearchMappingHelper.createSearchMappingForTests(blockingManager, Employee.class); propertyHelper = new HibernateSearchPropertyHelper(searchMapping, new ReflectionEntityNamesResolver(null)); return cacheManager; } @Override protected void teardown() { if (searchMapping != null) { searchMapping.close(); } super.teardown(); } @Test(expectedExceptions = { ParsingException.class }, expectedExceptionsMessageRegExp = "ISPN028502: Unknown alias: a.") public void testRaiseExceptionDueToUnknownAlias() { parseAndTransform("from org.infinispan.query.dsl.embedded.impl.model.Employee e where a.name = 'same'"); } @Test public void testMatchAllQuery() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee", "+*:*"); assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e", "+*:*"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e", "+*:*"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where true", "+*:*"); } @Test public void testRejectAllQuery() { assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where false", "+(-*:* #*:*)"); //TODO [anistor] maybe this should be "-*:*" } @Test public void testFullTextKeyword() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : 'bicycle'", "+text:bicycle"); } @Test public void testFullTextWildcard() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : 'geo*e'", "+text:geo*e"); } @Test public void testFullTextFuzzy() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : 'jonh'~2", "+text:jonh~2"); } @Test public void testFullTextPhrase() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : 'twisted cables'", "+text:\"twisted cables\""); } @Test public void testFullTextRegexp() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : /te?t/", "+text:/te?t/"); } @Test public void testFullTextRegexp_boosted() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : /te?t/^3", "+(text:/te?t/)^3.0"); } @Test public void testFullTextRange() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : ['AAA' 'ZZZ']", "+text:[aaa TO zzz]"); assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : ['AAA' to 'ZZZ']", "+text:[aaa TO zzz]"); assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : [* to 'eeee']", "+text:[* TO eeee]"); assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : ['eeee' to *]", "+text:[eeee TO *]"); assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : [* *]", "+ConstantScore(NormsFieldExistsQuery [field=text])"); } @Test public void testFullTextFieldBoost() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : 'foo'^3.0'", "+(text:foo)^3.0"); assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : ('foo')^3.0'", "+(text:foo)^3.0"); assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : ('foo' and 'bar')^3.0'", "+(+text:foo +text:bar)^3.0"); assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : 'foo'^3.0 || e.analyzedInfo : 'bar'", "+((text:foo)^3.0 analyzedInfo:bar)"); } @Test public void testFullTextFieldOccur() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : (-'foo') ", "+(-text:foo #*:*)"); assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : (-'foo' +'bar')", "+((-text:foo #*:*) (+text:bar))"); assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where not e.text : (-'foo' +'bar')", "+(-((-text:foo #*:*) (+text:bar)) #*:*)"); // TODO [anistor] fix this // assertGeneratedLuceneQuery( // "from org.infinispan.query.dsl.embedded.impl.model.Employee e where !e.text : (-'foo' +'bar')", // "-((-text:foo) (+text:bar)) #*:*"); assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text : (-'foo' '*')", "+((-text:foo #*:*) *:*)"); } @Test public void testRestrictedQueryUsingSelect() { assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name = 'same' or e.id = 5", "+(name:same id:5)"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name = 'same' and e.id = 5", "+(+name:same +id:5)"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name = 'same' and not e.id = 5", "+(+name:same +(-id:5 #*:*))"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name = 'same' or not e.id = 5", "+(name:same (-id:5 #*:*))"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where not e.id = 5", "+(-id:5 #*:*)"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.id != 5", "+(-id:5 #*:*)"); } @Test public void testFieldMapping() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.someMoreInfo = 'foo'", "+someMoreInfo:foo"); assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.sameInfo = 'foo'", "+sameInfo:foo"); } @Test(expectedExceptions = { SearchException.class }, expectedExceptionsMessageRegExp = "HSEARCH000610: Unknown field 'otherInfo'.*Context: indexes \\[org.infinispan.query.dsl.embedded.impl.model.Employee\\]") public void testWrongFieldName() { parseAndTransform("from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.otherInfo = 'foo'"); } @Test public void testProjectionQuery() { String ickle = "select e.id, e.name from org.infinispan.query.dsl.embedded.impl.model.Employee e"; IckleParsingResult<Class<?>> parsed = parse(ickle); SearchQuery<?> query = transform(parsed); assertThat(query.queryString()).isEqualTo("+*:*"); assertThat(parsed.getProjections()).isEqualTo(new String[]{"id", "name"}); } @Test public void testEmbeddedProjectionQuery() { String ickle = "select e.author.name from org.infinispan.query.dsl.embedded.impl.model.Employee e"; IckleParsingResult<Class<?>> parsed = parse(ickle); SearchQuery<?> query = transform(parsed); assertThat(query.queryString()).isEqualTo("+*:*"); assertThat(parsed.getProjections()).isEqualTo(new String[]{"author.name"}); } @Test public void testNestedEmbeddedProjectionQuery() { String ickle = "select e.author.address.street from org.infinispan.query.dsl.embedded.impl.model.Employee e"; IckleParsingResult<Class<?>> parsed = parse(ickle); SearchQuery<?> query = transform(parsed); assertThat(query.queryString()).isEqualTo("+*:*"); assertThat(parsed.getProjections()).isEqualTo(new String[]{"author.address.street"}); } @Test public void testQueryWithUnqualifiedPropertyReferences() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where name = 'same' and not id = 5", "+(+name:same +(-id:5 #*:*))"); } @Test public void testNegatedQuery() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where NOT e.name = 'same'", "+(-name:same #*:*)"); // JPQL syntax assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name <> 'same'", "+(-name:same #*:*)"); // HQL syntax assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name != 'same'", "+(-name:same #*:*)"); } @Test public void testNegatedQueryOnNumericProperty() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.position <> 3", "+(-position:[3 TO 3] #*:*)"); } @Test public void testNegatedRangeQuery() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee where name = 'Bob' and not position between 1 and 3", "+(+name:Bob +(-position:[1 TO 3] #*:*))"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name = 'Bob' and not e.position between 1 and 3", "+(+name:Bob +(-position:[1 TO 3] #*:*))"); } @Test public void testQueryWithNamedParameter() { Map<String, Object> namedParameters = new HashMap<>(); namedParameters.put("nameParameter", "Bob"); assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee where name = :nameParameter", namedParameters, "+name:Bob"); assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name = :nameParameter", namedParameters, "+name:Bob"); } @Test public void testBooleanQuery() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name = 'same' or (e.id = 4 and e.name = 'Bob')", "+(name:same (+id:4 +name:Bob))"); } @Test public void testBooleanQueryUsingSelect() { assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name = 'same' or (e.id = 4 and e.name = 'Bob')", "+(name:same (+id:4 +name:Bob))"); } @Test public void testBetweenQuery() { assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name between 'aaa' and 'zzz'", "+name:[aaa TO zzz]"); } @Test public void testNotBetweenQuery() { assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name not between 'aaa' and 'zzz'", "+(-name:[aaa TO zzz] #*:*)"); } @Test public void testNumericNotBetweenQuery() { assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where not e.position between 1 and 3", "+(-position:[1 TO 3] #*:*)"); } @Test public void testBetweenQueryForCharacterLiterals() { assertGeneratedLuceneQuery("select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name between 'a' and 'z'", "+name:[a TO z]"); } @Test public void testBetweenQueryWithNamedParameters() { Map<String, Object> namedParameters = new HashMap<>(); namedParameters.put("p1", "aaa"); namedParameters.put("p2", "zzz"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name between :p1 and :p2", namedParameters, "+name:[aaa TO zzz]"); } @Test public void testNumericBetweenQuery() { Map<String, Object> namedParameters = new HashMap<>(); namedParameters.put("p1", 10L); namedParameters.put("p2", 20L); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.position between :p1 and :p2", namedParameters, "+position:[10 TO 20]"); } @Test public void testQueryWithEmbeddedPropertyInFromClause() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.author.name = 'Bob'", "+author.name:Bob"); } @Test public void testLessThanQuery() { assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.position < 100", "+position:[-9223372036854775808 TO 99]"); } @Test public void testLessThanOrEqualsToQuery() { assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.position <= 100", "+position:[-9223372036854775808 TO 100]"); } @Test public void testGreaterThanOrEqualsToQuery() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee where position >= 100", "+position:[100 TO 9223372036854775807]"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.position >= 100", "+position:[100 TO 9223372036854775807]"); } @Test public void testGreaterThanQuery() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee where position > 100", "+position:[101 TO 9223372036854775807]"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.position > 100", "+position:[101 TO 9223372036854775807]"); } @Test public void testInQuery() { assertGeneratedLuceneQuery( "from org.infinispan.query.dsl.embedded.impl.model.Employee where name in ('Bob', 'Alice')", "+(name:Bob name:Alice)"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name in ('Bob', 'Alice')", "+(name:Bob name:Alice)"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.position in (10, 20, 30, 40)", "+(position:[10 TO 10] position:[20 TO 20] position:[30 TO 30] position:[40 TO 40])"); } @Test public void testInQueryWithNamedParameters() { Map<String, Object> namedParameters = new HashMap<>(); namedParameters.put("name1", "Bob"); namedParameters.put("name2", "Alice"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name in (:name1, :name2)", namedParameters, "+(name:Bob name:Alice)"); namedParameters = new HashMap<>(); namedParameters.put("pos1", 10); namedParameters.put("pos2", 20); namedParameters.put("pos3", 30); namedParameters.put("pos4", 40); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.position in (:pos1, :pos2, :pos3, :pos4)", namedParameters, "+(position:[10 TO 10] position:[20 TO 20] position:[30 TO 30] position:[40 TO 40])"); } @Test public void testNotInQuery() { assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name not in ('Bob', 'Alice')", "+(-(name:Bob name:Alice) #*:*)"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.position not in (10, 20, 30, 40)", "+(-(position:[10 TO 10] position:[20 TO 20] position:[30 TO 30] position:[40 TO 40]) #*:*)"); } @Test public void testLikeQuery() { assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name LIKE 'Al_ce'", "+name:Al?ce"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name LIKE 'Ali%'", "+name:Ali*"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name LIKE 'Ali%%'", "+name:Ali**"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name LIKE '_l_ce'", "+name:?l?ce"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name LIKE '___ce'", "+name:???ce"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name LIKE '_%_ce'", "+name:?*?ce"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name LIKE 'Alice in wonderl%'", "+name:Alice in wonderl*"); } @Test public void testNotLikeQuery() { assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name NOT LIKE 'Al_ce'", "+(-name:Al?ce #*:*)"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name NOT LIKE 'Ali%'", "+(-name:Ali* #*:*)"); assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name NOT LIKE '_l_ce' and not (e.title LIKE '%goo' and e.position = '5')", "+(+(-name:?l?ce #*:*) +(-(+title:*goo +position:[5 TO 5]) #*:*))"); } @Test public void testIsNullQuery() { assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name IS null", "+(-ConstantScore(NormsFieldExistsQuery [field=name]) #*:*)"); } @Test public void testIsNullQueryForEmbeddedEntity() { // Meta-field added as part of HSEARCH-3905 assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.author IS null", "+(-((ConstantScore(NormsFieldExistsQuery [field=author.address.city]) ConstantScore(NormsFieldExistsQuery [field=author.address.street]) __HSEARCH_field_names:author.address) ConstantScore(NormsFieldExistsQuery [field=author.name]) __HSEARCH_field_names:author) #*:*)"); } @Test public void testIsNotNullQuery() { assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name IS NOT null", "+ConstantScore(NormsFieldExistsQuery [field=name])"); } @Test public void testCollectionOfEmbeddableQuery() { assertGeneratedLuceneQuery( "select e from org.infinispan.query.dsl.embedded.impl.model.Employee e JOIN e.contactDetails d WHERE d.email = 'ninja647@mailinator.com' ", "+contactDetails.email:ninja647@mailinator.com"); } @Test public void testCollectionOfEmbeddableInEmbeddedQuery() { assertGeneratedLuceneQuery( "SELECT e FROM org.infinispan.query.dsl.embedded.impl.model.Employee e " + " JOIN e.contactDetails d" + " JOIN d.address.alternatives as a " + "WHERE a.postCode = '90210' ", "+contactDetails.address.alternatives.postCode:90210"); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028501: The type org.infinispan.query.dsl.embedded.impl.model.Employee does not have an accessible property named 'foobar'.") public void testRaiseExceptionDueToUnknownQualifiedProperty() { parseAndTransform("from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.foobar = 'same'"); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028501: The type org.infinispan.query.dsl.embedded.impl.model.Employee does not have an accessible property named 'foobar'.") public void testRaiseExceptionDueToUnknownUnqualifiedProperty() { parseAndTransform("from org.infinispan.query.dsl.embedded.impl.model.Employee e where foobar = 'same'"); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028522: No relational queries can be applied to property 'text' in type org.infinispan.query.dsl.embedded.impl.model.Employee since the property is analyzed.") public void testRaiseExceptionDueToAnalyzedPropertyInFromClause() { parseAndTransform("from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.text = 'foo'"); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028501: The type org.infinispan.query.dsl.embedded.impl.model.Employee does not have an accessible property named 'foobar'.") public void testRaiseExceptionDueToUnknownPropertyInSelectClause() { parseAndTransform("select e.foobar from org.infinispan.query.dsl.embedded.impl.model.Employee e"); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028501: The type org.infinispan.query.dsl.embedded.impl.model.Employee does not have an accessible property named 'foo'.") public void testRaiseExceptionDueToUnknownPropertyInEmbeddedSelectClause() { parseAndTransform("select e.author.foo from org.infinispan.query.dsl.embedded.impl.model.Employee e"); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028503: Property author can not be selected from type org.infinispan.query.dsl.embedded.impl.model.Employee since it is an embedded entity.") public void testRaiseExceptionDueToSelectionOfCompleteEmbeddedEntity() { parseAndTransform("select e.author from org.infinispan.query.dsl.embedded.impl.model.Employee e"); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028503: Property author can not be selected from type org.infinispan.query.dsl.embedded.impl.model.Employee since it is an embedded entity.") public void testRaiseExceptionDueToUnqualifiedSelectionOfCompleteEmbeddedEntity() { parseAndTransform("select author from org.infinispan.query.dsl.embedded.impl.model.Employee e"); } @Test public void testDetermineTargetEntityType() { IckleParsingResult<Class<?>> parsed = parse("select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name = 'same' and not e.id = 5"); assertThat(parsed.getTargetEntityMetadata()).isSameAs(Employee.class); assertThat(parsed.getTargetEntityName()).isEqualTo("org.infinispan.query.dsl.embedded.impl.model.Employee"); parsed = parse("select e from org.infinispan.query.dsl.embedded.impl.model.Employee e"); assertThat(parsed.getTargetEntityMetadata()).isSameAs(Employee.class); assertThat(parsed.getTargetEntityName()).isEqualTo("org.infinispan.query.dsl.embedded.impl.model.Employee"); } @Test public void testBuildOneFieldSort() { SearchQuery<?> result = parseAndTransform("select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name = 'same' order by e.title"); Sort sort = extractSort(result); assertThat(sort).isNotNull(); assertThat(sort.getSort().length).isEqualTo(1); assertThat(sort.getSort()[0].getField()).isEqualTo("title"); assertThat(sort.getSort()[0].getReverse()).isEqualTo(false); assertThat(sort.getSort()[0].getType()).isEqualTo(SortField.Type.CUSTOM); } @Test public void testBuildTwoFieldsSort() { SearchQuery<?> result = parseAndTransform("select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name = 'same' order by e.title, e.position DESC"); Sort sort = extractSort(result); assertThat(sort).isNotNull(); assertThat(sort.getSort().length).isEqualTo(2); assertThat(sort.getSort()[0].getField()).isEqualTo("title"); assertThat(sort.getSort()[0].getReverse()).isEqualTo(false); assertThat(sort.getSort()[0].getType()).isEqualTo(SortField.Type.CUSTOM); assertThat(sort.getSort()[1].getField()).isEqualTo("position"); assertThat(sort.getSort()[1].getReverse()).isEqualTo(true); assertThat(sort.getSort()[1].getType()).isEqualTo(SortField.Type.CUSTOM); } @Test public void testBuildSortForNullEncoding() { SearchQuery<?> result = parseAndTransform("select e from org.infinispan.query.dsl.embedded.impl.model.Employee e order by e.code DESC"); Sort sort = extractSort(result); assertThat(sort).isNotNull(); assertThat(sort.getSort().length).isEqualTo(1); assertThat(sort.getSort()[0].getField()).isEqualTo("code"); assertThat(sort.getSort()[0].getType()).isEqualTo(SortField.Type.CUSTOM); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028526: Invalid query: select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name = 'same' order by e.title DESblah, e.name ASC.*") public void testRaiseExceptionDueToUnrecognizedSortDirection() { parseAndTransform("select e from org.infinispan.query.dsl.embedded.impl.model.Employee e where e.name = 'same' order by e.title DESblah, e.name ASC"); } @Test public void testBeAbleToJoinOnCollectionOfEmbedded() { String ickle = "select d.email from org.infinispan.query.dsl.embedded.impl.model.Employee e JOIN e.contactDetails d"; SearchQuery<?> result = parseAndTransform(ickle); assertThat(result.queryString()).isEqualTo("+*:*"); assertThat(parse(ickle).getProjections()).containsOnly("contactDetails.email"); } @Test public void testBeAbleToJoinOnCollectionOfEmbeddedWithEmbedded() { String ickle = "select d.email from org.infinispan.query.dsl.embedded.impl.model.Employee e JOIN e.contactDetails d WHERE d.address.postCode='EA123'"; IckleParsingResult<Class<?>> parsed = parse(ickle); SearchQuery<?> query = transform(parsed); assertThat(query.queryString()).isEqualTo("+contactDetails.address.postCode:EA123"); assertThat(parsed.getProjections()).containsOnly("contactDetails.email"); } @Test public void testBeAbleToJoinOnCollectionOfEmbeddedWithEmbeddedAndUseInOperator() { String ickle = "select d.email from org.infinispan.query.dsl.embedded.impl.model.Employee e JOIN e.contactDetails d WHERE d.address.postCode IN ('EA123')"; IckleParsingResult<Class<?>> parsed = parse(ickle); SearchQuery<?> query = transform(parsed); assertThat(query.queryString()).isEqualTo("+contactDetails.address.postCode:EA123"); assertThat(parsed.getProjections()).containsOnly("contactDetails.email"); } @Test public void testBeAbleToJoinOnCollectionOfEmbeddedWithEmbeddedAndUseBetweenOperator() { String ickle = "select d.email from org.infinispan.query.dsl.embedded.impl.model.Employee e JOIN e.contactDetails d WHERE d.address.postCode BETWEEN '0000' AND 'ZZZZ'"; IckleParsingResult<Class<?>> parsed = parse(ickle); SearchQuery<?> query = transform(parsed); assertThat(query.queryString()).isEqualTo("+contactDetails.address.postCode:[0000 TO ZZZZ]"); assertThat(parsed.getProjections()).containsOnly("contactDetails.email"); } @Test public void testBeAbleToJoinOnCollectionOfEmbeddedWithEmbeddedAndUseGreaterOperator() { String ickle = "select d.email from org.infinispan.query.dsl.embedded.impl.model.Employee e JOIN e.contactDetails d WHERE d.address.postCode > '0000'"; IckleParsingResult<Class<?>> parsed = parse(ickle); SearchQuery<?> query = transform(parsed); assertThat(query.queryString()).isEqualTo("+contactDetails.address.postCode:{0000 TO *]"); assertThat(parsed.getProjections()).containsOnly("contactDetails.email"); } @Test public void testBeAbleToJoinOnCollectionOfEmbeddedWithEmbeddedAndUseLikeOperator() { String ickle = "select d.email from org.infinispan.query.dsl.embedded.impl.model.Employee e JOIN e.contactDetails d WHERE d.address.postCode LIKE 'EA1%'"; IckleParsingResult<Class<?>> parsed = parse(ickle); SearchQuery<?> query = transform(parsed); assertThat(query.queryString()).isEqualTo("+contactDetails.address.postCode:EA1*"); assertThat(parsed.getProjections()).containsOnly("contactDetails.email"); } @Test public void testBeAbleToProjectUnqualifiedField() { String ickle = "SELECT name, text FROM org.infinispan.query.dsl.embedded.impl.model.Employee e JOIN e.contactDetails d"; IckleParsingResult<Class<?>> parsed = parse(ickle); SearchQuery<?> query = transform(parsed); assertThat(query.queryString()).isEqualTo("+*:*"); assertThat(parsed.getProjections()).containsOnly("name", "text"); } @Test public void testBeAbleToProjectUnqualifiedFieldAndQualifiedField() { String ickle = "SELECT name, text, d.email FROM org.infinispan.query.dsl.embedded.impl.model.Employee e JOIN e.contactDetails d"; IckleParsingResult<Class<?>> parsed = parse(ickle); SearchQuery<?> query = transform(parsed); assertThat(query.queryString()).isEqualTo("+*:*"); assertThat(parsed.getProjections()).containsOnly("name", "text", "contactDetails.email"); } @Test public void testBeAbleToProjectQualifiedField() { String ickle = "SELECT e.name, e.text, d.email FROM org.infinispan.query.dsl.embedded.impl.model.Employee e JOIN e.contactDetails d"; IckleParsingResult<Class<?>> parsed = parse(ickle); SearchQuery<?> query = transform(parsed); assertThat(query.queryString()).isEqualTo("+*:*"); assertThat(parsed.getProjections()).containsOnly("name", "text", "contactDetails.email"); } @Test public void testBeAbleToJoinOnCollectionOfEmbeddedWithTwoEmbeddedCollections() { IckleParsingResult<Class<?>> parsed = parse( " SELECT d.email " + " FROM org.infinispan.query.dsl.embedded.impl.model.Employee e " + " JOIN e.contactDetails d " + " JOIN e.alternativeContactDetails a" + " WHERE d.address.postCode='EA123' AND a.email='ninja647@mailinator.com'"); SearchQuery<?> query = transform(parsed); assertThat(query.queryString()) .isEqualTo("+(+contactDetails.address.postCode:EA123 +alternativeContactDetails.email:ninja647@mailinator.com)"); assertThat(parsed.getProjections()).containsOnly("contactDetails.email"); } private void assertGeneratedLuceneQuery(String queryString, String expectedLuceneQuery) { assertGeneratedLuceneQuery(queryString, null, expectedLuceneQuery); } private void assertGeneratedLuceneQuery(String queryString, Map<String, Object> namedParameters, String expectedLuceneQuery) { SearchQuery<?> result = parseAndTransform(queryString, namedParameters); assertThat(result.queryString()).isEqualTo(expectedLuceneQuery); } private SearchQuery<?> parseAndTransform(String queryString) { return parseAndTransform(queryString, null); } private SearchQuery<?> parseAndTransform(String queryString, Map<String, Object> namedParameters) { IckleParsingResult<Class<?>> ickleParsingResult = parse(queryString); return transform(ickleParsingResult, namedParameters); } private IckleParsingResult<Class<?>> parse(String queryString) { return IckleParser.parse(queryString, propertyHelper); } private SearchQuery<?> transform(IckleParsingResult<Class<?>> ickleParsingResult) { return transform(ickleParsingResult, null); } private SearchQuery<?> transform(IckleParsingResult<Class<?>> ickleParsingResult, Map<String, Object> parameters) { SearchQueryMaker<Class<?>> searchQueryMaker = new SearchQueryMaker<>(searchMapping, propertyHelper, 10_000); return searchQueryMaker .transform(ickleParsingResult, parameters, Employee.class, null) .builder(searchMapping.getMappingSession()).build(); } }
35,751
42.760098
283
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/impl/EmbeddedQueryEngineTest.java
package org.infinispan.query.dsl.embedded.impl; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.TimeZone; import org.hibernate.search.util.common.SearchException; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.objectfilter.ParsingException; import org.infinispan.objectfilter.impl.syntax.parser.IckleParser; import org.infinispan.objectfilter.impl.syntax.parser.IckleParsingResult; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.embedded.DslSCI; import org.infinispan.query.dsl.embedded.impl.model.TheEntity; import org.infinispan.query.dsl.embedded.testdomain.Account; import org.infinispan.query.dsl.embedded.testdomain.Address; import org.infinispan.query.dsl.embedded.testdomain.Author; import org.infinispan.query.dsl.embedded.testdomain.Book; import org.infinispan.query.dsl.embedded.testdomain.NotIndexed; import org.infinispan.query.dsl.embedded.testdomain.Transaction; import org.infinispan.query.dsl.embedded.testdomain.User; import org.infinispan.query.dsl.embedded.testdomain.hsearch.AccountHS; import org.infinispan.query.dsl.embedded.testdomain.hsearch.AddressHS; import org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS; import org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS; import org.infinispan.query.impl.IndexedQuery; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.CleanupAfterTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * @author anistor@redhat.com * @since 8.0 */ @Test(groups = "functional", testName = "query.dsl.embedded.impl.EmbeddedQueryEngineTest") @CleanupAfterTest public class EmbeddedQueryEngineTest extends MultipleCacheManagersTest { private final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); private QueryEngine<Class<?>> qe; public EmbeddedQueryEngineTest() { DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT")); } private Date makeDate(String dateStr) throws ParseException { return DATE_FORMAT.parse(dateStr); } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfg = TestCacheManagerFactory.getDefaultCacheConfiguration(true); cfg.transaction() .transactionMode(TransactionMode.TRANSACTIONAL) .indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(UserHS.class) .addIndexedEntity(AccountHS.class) .addIndexedEntity(TransactionHS.class) .addIndexedEntity(TheEntity.class) .addIndexedEntity(Book.class); createClusteredCaches(1, DslSCI.INSTANCE, cfg); } @BeforeClass(alwaysRun = true) protected void init() throws Exception { qe = new QueryEngine<>(cache(0).getAdvancedCache(), true); // create the test objects User user1 = new UserHS(); user1.setId(1); user1.setName("John"); user1.setSurname("Doe"); user1.setGender(User.Gender.MALE); user1.setAge(22); user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2))); user1.setNotes("Lorem ipsum dolor sit amet"); Address address1 = new AddressHS(); address1.setStreet("Main Street"); address1.setPostCode("X1234"); user1.setAddresses(Collections.singletonList(address1)); User user2 = new UserHS(); user2.setId(2); user2.setName("Spider"); user2.setSurname("Man"); user2.setGender(User.Gender.MALE); user2.setAge(44); user2.setAccountIds(Collections.singleton(3)); Address address2 = new AddressHS(); address2.setStreet("Old Street"); address2.setPostCode("Y12"); Address address3 = new AddressHS(); address3.setStreet("Bond Street"); address3.setPostCode("ZZ"); user2.setAddresses(Arrays.asList(address2, address3)); User user3 = new UserHS(); user3.setId(3); user3.setName("Spider"); user3.setSurname("Woman"); user3.setGender(User.Gender.FEMALE); user3.setAccountIds(Collections.emptySet()); Account account1 = new AccountHS(); account1.setId(1); account1.setDescription("John Doe's first bank account"); account1.setCreationDate(makeDate("2013-01-03")); Account account2 = new AccountHS(); account2.setId(2); account2.setDescription("John Doe's second bank account"); account2.setCreationDate(makeDate("2013-01-04")); Account account3 = new AccountHS(); account3.setId(3); account3.setCreationDate(makeDate("2013-01-20")); Transaction transaction0 = new TransactionHS(); transaction0.setId(0); transaction0.setDescription("Birthday present"); transaction0.setAccountId(1); transaction0.setAmount(1800); transaction0.setDate(makeDate("2012-09-07")); transaction0.setDebit(false); transaction0.setValid(true); Transaction transaction1 = new TransactionHS(); transaction1.setId(1); transaction1.setDescription("Feb. rent payment"); transaction1.setAccountId(1); transaction1.setAmount(1500); transaction1.setDate(makeDate("2013-01-05")); transaction1.setDebit(true); transaction1.setValid(true); Transaction transaction2 = new TransactionHS(); transaction2.setId(2); transaction2.setDescription("Starbucks"); transaction2.setAccountId(1); transaction2.setAmount(23); transaction2.setDate(makeDate("2013-01-09")); transaction2.setDebit(true); transaction2.setValid(true); Transaction transaction3 = new TransactionHS(); transaction3.setId(3); transaction3.setDescription("Hotel"); transaction3.setAccountId(2); transaction3.setAmount(45); transaction3.setDate(makeDate("2013-02-27")); transaction3.setDebit(true); transaction3.setValid(true); Transaction transaction4 = new TransactionHS(); transaction4.setId(4); transaction4.setDescription("Last january"); transaction4.setAccountId(2); transaction4.setAmount(95); transaction4.setDate(makeDate("2013-01-31")); transaction4.setDebit(true); transaction4.setValid(true); Transaction transaction5 = new TransactionHS(); transaction5.setId(5); transaction5.setDescription("Popcorn"); transaction5.setAccountId(2); transaction5.setAmount(5); transaction5.setDate(makeDate("2013-01-01")); transaction5.setDebit(true); transaction5.setValid(true); // persist and index the test objects // we put all of them in the same cache for the sake of simplicity cache(0).put("user_" + user1.getId(), user1); cache(0).put("user_" + user2.getId(), user2); cache(0).put("user_" + user3.getId(), user3); cache(0).put("account_" + account1.getId(), account1); cache(0).put("account_" + account2.getId(), account2); cache(0).put("account_" + account3.getId(), account3); cache(0).put("transaction_" + transaction0.getId(), transaction0); cache(0).put("transaction_" + transaction1.getId(), transaction1); cache(0).put("transaction_" + transaction2.getId(), transaction2); cache(0).put("transaction_" + transaction3.getId(), transaction3); cache(0).put("transaction_" + transaction4.getId(), transaction4); cache(0).put("transaction_" + transaction5.getId(), transaction5); for (int i = 0; i < 50; i++) { Transaction transaction = new TransactionHS(); transaction.setId(50 + i); transaction.setDescription("Expensive shoes " + i); transaction.setAccountId(2); transaction.setAmount(100 + i); transaction.setDate(makeDate("2013-08-20")); transaction.setDebit(true); transaction.setValid(true); cache(0).put("transaction_" + transaction.getId(), transaction); } // this value should be ignored gracefully cache(0).put("dummy", "a primitive value cannot be queried"); cache(0).put("notIndexed1", new NotIndexed("testing 123")); cache(0).put("notIndexed2", new NotIndexed("xyz")); cache(0).put("entity1", new TheEntity("test value 1", new TheEntity.TheEmbeddedEntity("test embedded value 1"))); cache(0).put("entity2", new TheEntity("test value 2", new TheEntity.TheEmbeddedEntity("test embedded value 2"))); cache(0).put("book1", new Book("Java Performance: The Definitive Guide", "O'Reilly Media", new Author("Scott", "Oaks"), "Still, it turns out that every day, I think about GC performance, or the\n" + "performance of the JVM compiler, or how to get the best performance from Java Enterprise Edition APIs.")); cache(0).put("book2", new Book("Functional Programming for Java Developers", "O'Reilly Media", new Author("Dean", "Wampler"), "Why should a Java developer learn about functional programming (FP)? After all, hasn’t\n" + "functional programming been safely hidden in academia for decades? Isn’t object-\n" + "oriented programming (OOP) all we really need?")); cache(0).put("book3", new Book("The Java ® Virtual Machine Specification Java SE 8 Edition", "Oracle", new Author("Tim", "Lindholm"), "The Java SE 8 Edition of The Java Virtual Machine Specification incorporates all the changes that have " + "been made to the Java Virtual Machine since the Java SE 7 Edition in 2011. In addition, numerous " + "corrections and clarifications have been made to align with popular implementations of the Java Virtual Machine.")); } @Override protected void clearContent() { // Don't clear, this is destroying the index } private <E> Query<E> buildQuery(String queryString) { return (Query<E>) qe.buildQuery(null, qe.parse(queryString), null, -1, -1, false); } public void testSimpleProjection1() { IckleParsingResult<Class<?>> parsingResult = IckleParser.parse("select b.author.name from org.infinispan.query.dsl.embedded.testdomain.Book b", qe.getPropertyHelper()); IndexedQuery<?> q = qe.buildLuceneQuery(parsingResult, null, -1, -1, false); List<?> list = q.list(); assertEquals(3, list.size()); } @Test(enabled = false, description = "Disabled due to https://issues.jboss.org/browse/ISPN-8564") public void testSimpleProjection2() { IckleParsingResult<Class<?>> parsingResult = IckleParser.parse("select author.name from org.infinispan.query.dsl.embedded.testdomain.Book", qe.getPropertyHelper()); IndexedQuery<?> q = qe.buildLuceneQuery(parsingResult, null, -1, -1, false); List<?> list = q.list(); assertEquals(3, list.size()); } public void testGrouping() { Query<User> q = buildQuery("select name from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS " + "where surname is not null group by name having name >= 'A'"); List<User> list = q.execute().list(); assertEquals(2, list.size()); } public void testNoGroupingOrAggregation() { Query<User> q = buildQuery("from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS"); assertTrue(q instanceof EmbeddedLuceneQuery); List<User> list = q.execute().list(); assertEquals(3, list.size()); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028516: Cannot have aggregate functions in the GROUP BY clause : SUM.") public void testDisallowAggregationInGroupBy() { buildQuery("select sum(age) from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS group by sum(age) "); } public void testDuplicatesAcceptedInGroupBy() { Query<Object[]> q = buildQuery("select name from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS group by name, name"); List<Object[]> list = q.execute().list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).length); assertEquals(1, list.get(1).length); } public void testDuplicatesAcceptedInSelect1() { Query<Object[]> q = buildQuery("select name, name from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS group by name"); List<Object[]> list = q.execute().list(); assertEquals(2, list.size()); assertEquals(2, list.get(0).length); assertEquals(2, list.get(1).length); } public void testDuplicatesAcceptedInSelect2() { Query<Object[]> q = buildQuery("select max(name), max(name) from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS"); List<Object[]> list = q.execute().list(); assertEquals(1, list.size()); assertEquals(2, list.get(0).length); } public void testDuplicatesAcceptedInSelect3() { Query<Object[]> q = buildQuery("select min(name), max(name) from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS"); List<Object[]> list = q.execute().list(); assertEquals(1, list.size()); assertEquals(2, list.get(0).length); } public void testDuplicatesAcceptedInOrderBy1() { Query<User> q = buildQuery("from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS order by age, age"); List<User> list = q.execute().list(); assertEquals(3, list.size()); } public void testDuplicatesAcceptedInOrderBy2() { Query<User> q = buildQuery("from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS order by age, name, age"); List<User> list = q.execute().list(); assertEquals(3, list.size()); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN014024: The property path 'addresses.postCode' cannot be used in the ORDER BY clause because it is multi-valued") public void testRejectMultivaluedOrderBy() { buildQuery("from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS u order by u.addresses.postCode"); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN014023: Using the multi-valued property path 'addresses.postCode' in the GROUP BY clause is not currently supported") public void testRejectMultivaluedGroupBy() { buildQuery("select u.addresses.postCode from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS u group by u.addresses.postCode"); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN014026: The expression 'age' must be part of an aggregate function or it should be included in the GROUP BY clause") public void testMissingAggregateInSelect() { buildQuery("select age from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS group by name"); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN014026: The expression 'age' must be part of an aggregate function or it should be included in the GROUP BY clause") public void testMissingAggregateInOrderBy() { buildQuery("select name, sum(age) from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS group by name order by age"); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028515: Cannot have aggregate functions in the WHERE clause : SUM.") public void testDisallowAggregatesInWhereClause() { buildQuery("select name from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS where sum(age) > 33 group by name"); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN014026: The expression 'age' must be part of an aggregate function or it should be included in the GROUP BY clause") public void testHavingClauseAllowsAggregationsAndGroupByColumnsOnly() { buildQuery("select name from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS group by name having age >= 18"); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN014026: The expression 'name' must be part of an aggregate function or it should be included in the GROUP BY clause") public void testDisallowNonAggregatedProjectionWithGlobalAggregation() { buildQuery("select name, count(name) from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS"); } public void testBuildLuceneQuery() { IckleParsingResult<Class<?>> parsingResult = IckleParser.parse("select name from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS", qe.getPropertyHelper()); IndexedQuery<UserHS> q = qe.buildLuceneQuery(parsingResult, null, -1, -1, false); List<?> list = q.list(); assertEquals(3, list.size()); } @Test(expectedExceptions = SearchException.class) public void testBuildLuceneQueryOnNonIndexedField() { IckleParsingResult<Class<?>> parsingResult = IckleParser.parse("select notes from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS where notes like 'TBD%'", qe.getPropertyHelper()); qe.buildLuceneQuery(parsingResult, null, -1, -1, false); } public void testGlobalCount() { Query<Object[]> q = buildQuery("select count(name), count(age) from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS"); List<Object[]> list = q.execute().list(); assertEquals(1, list.size()); assertEquals(2, list.get(0).length); assertEquals(3L, list.get(0)[0]); assertEquals(2L, list.get(0)[1]); } public void testGlobalAvg() { Query<Object[]> q = buildQuery("select avg(age) from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS"); List<Object[]> list = q.execute().list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(33.0d, list.get(0)[0]); } public void testGlobalSum() { Query<Object[]> q = buildQuery("select sum(age) from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS"); List<Object[]> list = q.execute().list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(66L, list.get(0)[0]); } public void testGlobalMin() { Query<Object[]> q = buildQuery("select min(age) from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS"); List<Object[]> list = q.execute().list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(22, list.get(0)[0]); } public void testGlobalMax() { Query<Object[]> q = buildQuery("select max(age) from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS"); List<Object[]> list = q.execute().list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(44, list.get(0)[0]); } public void testAggregateGroupingField() { Query<Object[]> q = buildQuery("select count(name) from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS group by name order by count(name)"); List<Object[]> list = q.execute().list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).length); assertEquals(1L, list.get(0)[0]); assertEquals(1, list.get(1).length); assertEquals(2L, list.get(1)[0]); } public void testAggregateEmbedded1() { Query<Object[]> q = buildQuery("select max(accountIds) from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS group by name order by name"); List<Object[]> list = q.execute().list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).length); assertEquals(2, list.get(0)[0]); assertEquals(1, list.get(1).length); assertEquals(3, list.get(1)[0]); } public void testAggregateEmbedded2() { Query<Object[]> q = buildQuery("select max(u.addresses.postCode) from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS u group by u.name order by u.name"); List<Object[]> list = q.execute().list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).length); assertEquals("X1234", list.get(0)[0]); assertEquals(1, list.get(1).length); assertEquals("ZZ", list.get(1)[0]); } @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Aggregation SUM cannot be applied to property of type java.lang.String") public void testIncompatibleAggregator() { buildQuery("select sum(name) from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS"); } public void testAggregateNulls() { Query<User> q = buildQuery("select name, sum(age), avg(age) from org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS " + "where surname is not null " + "group by name " + "having name >= 'A' and count(age) >= 1"); List<User> list = q.execute().list(); assertEquals(2, list.size()); } public void testRenamedFields1() { Query<Object[]> q = buildQuery("select theField from org.infinispan.query.dsl.embedded.impl.model.TheEntity where theField >= 'a' order by theField"); List<Object[]> list = q.execute().list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).length); assertEquals("test value 1", list.get(0)[0]); assertEquals("test value 2", list.get(1)[0]); } public void testRenamedFields2() { Query<Object[]> q = buildQuery("select theField from org.infinispan.query.dsl.embedded.impl.model.TheEntity order by theField"); List<Object[]> list = q.execute().list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).length); assertEquals("test value 1", list.get(0)[0]); assertEquals("test value 2", list.get(1)[0]); } public void testRenamedFields3() { Query<Object[]> q = buildQuery("select e.embeddedEntity.anotherField from org.infinispan.query.dsl.embedded.impl.model.TheEntity e where e.embeddedEntity.anotherField >= 'a' order by e.theField"); List<Object[]> list = q.execute().list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).length); assertEquals("test embedded value 1", list.get(0)[0]); assertEquals("test embedded value 2", list.get(1)[0]); } public void testRenamedFields4() { Query<Object[]> q = buildQuery("select e.embeddedEntity.anotherField from org.infinispan.query.dsl.embedded.impl.model.TheEntity e order by e.theField"); List<Object[]> list = q.execute().list(); assertEquals(2, list.size()); assertEquals(1, list.get(0).length); assertEquals("test embedded value 1", list.get(0)[0]); assertEquals("test embedded value 2", list.get(1)[0]); } @Test(expectedExceptions = ParsingException.class, expectedExceptionsMessageRegExp = "ISPN028507: Invalid boolean literal '90'") public void testInvalidNotIndexedBooleanComparison() { buildQuery("from org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS where isValid = 90"); } @Test(expectedExceptions = ParsingException.class) public void testInvalidIndexedBooleanComparison() { buildQuery("from org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS where isDebit = 90"); } public void testBooleanComparison() { IckleParsingResult<Class<?>> parsingResult = IckleParser.parse("from org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS " + "WHERE debit = false", qe.getPropertyHelper()); IndexedQuery<?> q = qe.buildLuceneQuery(parsingResult, null, -1, -1, false); List<?> list = q.list(); assertEquals(1, list.size()); } public void testConstantBooleanExpression() { IckleParsingResult<Class<?>> parsingResult = IckleParser.parse("from org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS " + "WHERE true", qe.getPropertyHelper()); IndexedQuery<?> q = qe.buildLuceneQuery(parsingResult, null, -1, -1, false); List<?> list = q.list(); assertEquals(56, list.size()); parsingResult = IckleParser.parse("from org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS " + "WHERE false", qe.getPropertyHelper()); q = qe.buildLuceneQuery(parsingResult, null, -1, -1, false); list = q.list(); assertEquals(0, list.size()); } public void testFullTextKeyword() { IckleParsingResult<Class<?>> parsingResult = IckleParser.parse("from org.infinispan.query.dsl.embedded.testdomain.Book b " + "where b.preface:('java se'^7 -('bicycle' 'ski')) and b.publisher:'Oracel'~2", qe.getPropertyHelper()); IndexedQuery<?> q = qe.buildLuceneQuery(parsingResult, null, -1, -1, false); List<?> list = q.list(); assertEquals(1, list.size()); } }
25,271
45.8
210
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/impl/model/Employee.java
package org.infinispan.query.dsl.embedded.impl.model; import java.util.ArrayList; import java.util.List; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.DocumentId; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Embedded; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Keyword; import org.infinispan.api.annotations.indexing.Text; import org.infinispan.api.annotations.indexing.option.Structure; /** * @author anistor@redhat.com * @since 9.0 */ @Indexed public class Employee { public String id; public String name; public long position; public Long code; public String text; public String title; public String otherInfo; public Company author; public List<ContactDetails> contactDetails = new ArrayList<>(); public List<ContactDetails> alternativeContactDetails = new ArrayList<>(); // When an entity is created with Infinispan, // the document id is reserved to link the cache entry key to the value. // In this case Hibernate Search is used standalone, // so we need to provide explicitly the document id, // using the Search annotation. @DocumentId @Basic(projectable = true) public String getId() { return id; } @Keyword(projectable = true) public String getName() { return name; } @Basic(sortable = true) public Long getPosition() { return position; } @Basic(sortable = true, indexNullAs = "-1") public Long getCode() { return code; } @Text(projectable = true) public String getText() { return text; } @Basic(sortable = true) public String getTitle() { return title; } @Text(name = "analyzedInfo") @Basic(name = "someMoreInfo") @Basic(name = "sameInfo") public String getOtherInfo() { return otherInfo; } @Embedded(structure = Structure.FLATTENED) public Company getAuthor() { return author; } @Embedded(structure = Structure.FLATTENED) public List<ContactDetails> getContactDetails() { return contactDetails; } @Embedded(structure = Structure.FLATTENED) public List<ContactDetails> getAlternativeContactDetails() { return alternativeContactDetails; } public static class ContactDetails { public String email; public String phoneNumber; public ContactAddress address; @Basic(projectable = true) public String getEmail() { return email; } @Basic public String getPhoneNumber() { return phoneNumber; } @Embedded(structure = Structure.FLATTENED) public ContactAddress getAddress() { return address; } public static class ContactAddress { public String address; public String postCode; public List<ContactAddress> alternatives = new ArrayList<>(); @Basic public String getAddress() { return address; } @Basic public String getPostCode() { return postCode; } @Embedded(structure = Structure.FLATTENED) public List<ContactAddress> getAlternatives() { return alternatives; } } } }
3,317
21.571429
81
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/impl/model/TheEntity.java
package org.infinispan.query.dsl.embedded.impl.model; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Embedded; import org.infinispan.api.annotations.indexing.Indexed; /** * @author anistor@redhat.com * @since 9.0 */ @Indexed public class TheEntity { /** * Set a different name to demonstrate field mapping. */ private String fieldX; private TheEmbeddedEntity embeddedEntity; public TheEntity(String fieldX, TheEmbeddedEntity embeddedEntity) { this.fieldX = fieldX; this.embeddedEntity = embeddedEntity; } @Basic(name = "theField", projectable = true, sortable = true) public String getField() { return fieldX; } @Embedded public TheEmbeddedEntity getEmbeddedEntity() { return embeddedEntity; } public static class TheEmbeddedEntity { private String fieldY; public TheEmbeddedEntity(String fieldY) { this.fieldY = fieldY; } @Basic(name = "anotherField", projectable = true) public String getFieldY() { return fieldY; } } }
1,115
21.32
70
java
null
infinispan-main/query/src/test/java/org/infinispan/query/dsl/embedded/impl/model/Company.java
package org.infinispan.query.dsl.embedded.impl.model; import java.util.Set; import org.infinispan.api.annotations.indexing.Embedded; import org.infinispan.api.annotations.indexing.Keyword; import org.infinispan.api.annotations.indexing.Text; import org.infinispan.api.annotations.indexing.option.Structure; /** * @author anistor@redhat.com * @since 9.0 */ public class Company { private Long id; private String name; private Set<Employee> employees; private Address address; @Keyword(projectable = true) public String getName() { return name; } public Set<Employee> getEmployees() { return employees; } @Embedded(structure = Structure.FLATTENED) public Address getAddress() { return address; } public class Address { public Long id; public String street; public String city; public Set<Company> companies; @Text(projectable = true) public String getStreet() { return street; } @Text public String getCity() { return city; } public Set<Company> getCompanies() { return companies; } } }
1,165
17.507937
64
java
null
infinispan-main/query/src/test/java/org/infinispan/query/field/MultipleIndexFieldAnnotationsTest.java
package org.infinispan.query.field; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; 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.Book; import org.infinispan.query.model.Color; 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.parameter.IndexFieldNameTest") public class MultipleIndexFieldAnnotationsTest extends SingleCacheManagerTest { // descriptions taken are from Wikipedia https://en.wikipedia.org/wiki/* public static final String RED_DESCRIPTION = "Red is the color at the long wavelength end of the visible spectrum of light"; public static final String GREEN_DESCRIPTION = "Green is the color between cyan and yellow on the visible spectrum."; public static final String BLUE_DESCRIPTION = "Blue is one of the three primary colours in the RYB colour model (traditional color theory), as well as in the RGB (additive) colour model."; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(false); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Color.class); return TestCacheManagerFactory.createCacheManager(builder); } @BeforeMethod(alwaysRun = true) public void beforeMethod() { cache.put(1, new Color("red", RED_DESCRIPTION)); cache.put(2, new Color("green", GREEN_DESCRIPTION)); cache.put(3, new Color("blue", BLUE_DESCRIPTION)); } @Test public void testTargetingDifferentIndexFields() { QueryFactory factory = Search.getQueryFactory(cache); Query<Book> query = factory.create("from org.infinispan.query.model.Color where name = 'red'"); QueryResult<Book> result = query.execute(); assertThat(result.count().value()).isEqualTo(1L); assertThat(result.list()).extracting("name").contains("red"); query = factory.create(String.format("from %s where desc1 = '%s'", Color.class.getName(), RED_DESCRIPTION)); result = query.execute(); assertThat(result.count().value()).isEqualTo(1L); assertThat(result.list()).extracting("name").contains("red"); query = factory.create(String.format("from %s where desc2 = '%s'", Color.class.getName(), BLUE_DESCRIPTION)); result = query.execute(); assertThat(result.count().value()).isEqualTo(1L); assertThat(result.list()).extracting("name").contains("blue"); query = factory.create(String.format("from %s where desc3 : 'cyan'", Color.class.getName())); result = query.execute(); assertThat(result.count().value()).isEqualTo(1L); assertThat(result.list()).extracting("name").contains("green"); } }
3,204
43.513889
191
java
null
infinispan-main/query/src/test/java/org/infinispan/query/parameter/IndexFieldNameTest.java
package org.infinispan.query.parameter; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; 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.Book; 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.parameter.IndexFieldNameTest") public class IndexFieldNameTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(false); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Book.class); return TestCacheManagerFactory.createCacheManager(builder); } @BeforeMethod(alwaysRun = true) public void beforeMethod() { Book book1 = new Book(); book1.setTitle("is*and"); book1.setDescription("A pl*ce surrounded by the sea."); cache.put(1, book1); Book book2 = new Book(); book2.setTitle("home"); book2.setDescription("The pl*ce where I'm staying."); cache.put(2, book2); } public void useDifferentIndexFieldNames() { QueryFactory factory = Search.getQueryFactory(cache); Query<Book> query = factory.create("from org.infinispan.query.model.Book where naming : 'pl*ce' order by label"); QueryResult<Book> result = query.execute(); assertThat(result.count().isExact()).isTrue(); assertThat(result.count().value()).isEqualTo(2); assertThat(result.list()).extracting("title").contains("is*and", "home"); } }
2,022
36.462963
119
java
null
infinispan-main/query/src/test/java/org/infinispan/query/parameter/FullTextParameterTest.java
package org.infinispan.query.parameter; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; 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.Book; 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.parameter.FullTextParameterTest") public class FullTextParameterTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(false); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Book.class); return TestCacheManagerFactory.createCacheManager(builder); } @BeforeMethod(alwaysRun = true) public void beforeMethod() { Book book = new Book(); book.setTitle("island"); book.setDescription("A place surrounded by the sea."); cache.put(1, book); } public void fulltext() { QueryFactory factory = Search.getQueryFactory(cache); Query<Book> query = factory.create("from org.infinispan.query.model.Book where naming : :description"); query.setParameter("description", "place"); QueryResult<Book> result = query.execute(); assertThat(result.count().value()).isEqualTo(1); assertThat(result.list()).extracting("title").contains("island"); } public void generic() { QueryFactory factory = Search.getQueryFactory(cache); Query<Book> query = factory.create("from org.infinispan.query.model.Book where title = :title"); query.setParameter("title", "island"); QueryResult<Book> result = query.execute(); assertThat(result.count().value()).isEqualTo(1); assertThat(result.list()).extracting("title").contains("island"); } }
2,254
37.220339
109
java
null
infinispan-main/query/src/test/java/org/infinispan/query/parameter/SpecialCharTextTest.java
package org.infinispan.query.parameter; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; 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.Book; 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.parameter.SpecialCharTextTest") public class SpecialCharTextTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(false); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Book.class); return TestCacheManagerFactory.createCacheManager(builder); } @BeforeMethod(alwaysRun = true) public void beforeMethod() { Book book = new Book(); book.setTitle("is*and"); book.setDescription("A pl*ce surrounded by the sea."); cache.put(1, book); } public void fulltext() { QueryFactory factory = Search.getQueryFactory(cache); Query<Book> query = factory.create("from org.infinispan.query.model.Book where naming : 'pl*ce'"); QueryResult<Book> result = query.execute(); assertThat(result.count().value()).isEqualTo(1); assertThat(result.list()).extracting("title").contains("is*and"); } public void generic() { QueryFactory factory = Search.getQueryFactory(cache); Query<Book> query = factory.create("from org.infinispan.query.model.Book where title = 'is*and'"); QueryResult<Book> result = query.execute(); assertThat(result.count().value()).isEqualTo(1); assertThat(result.list()).extracting("title").contains("is*and"); } }
2,152
36.77193
104
java
null
infinispan-main/query/src/test/java/org/infinispan/query/test/CustomTransformer.java
package org.infinispan.query.test; import java.util.StringTokenizer; import org.infinispan.query.Transformer; public class CustomTransformer implements Transformer { @Override public Object fromString(String s) { StringTokenizer strtok = new StringTokenizer(s, ","); int[] ints = new int[3]; int i = 0; while (strtok.hasMoreTokens()) { String token = strtok.nextToken(); String[] contents = token.split("="); ints[i++] = Integer.parseInt(contents[1]); } return new CustomKey(ints[0], ints[1], ints[2]); } @Override public String toString(Object customType) { CustomKey ck = (CustomKey) customType; return "i=" + ck.i + ",j=" + ck.j + ",k=" + ck.k; } }
749
26.777778
59
java
null
infinispan-main/query/src/test/java/org/infinispan/query/test/AnotherGrassEater.java
package org.infinispan.query.test; import java.io.Serializable; 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.ProtoField; @Indexed(index = "anotherclass") public class AnotherGrassEater implements Serializable { private String name; private String blurb; private int age; public AnotherGrassEater() { } public AnotherGrassEater(String name, String blurb) { this.name = name; this.blurb = blurb; } @Basic(projectable = true) @ProtoField(number = 1) public String getName() { return name; } public void setName(String name) { this.name = name; } @Text @ProtoField(number = 2) public String getBlurb() { return blurb; } public void setBlurb(String blurb) { this.blurb = blurb; } @Basic(projectable = true, sortable = true) public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AnotherGrassEater that = (AnotherGrassEater) o; if (blurb != null ? !blurb.equals(that.blurb) : that.blurb != null) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; return true; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (blurb != null ? blurb.hashCode() : 0); return result; } @Override public String toString() { return "AnotherGrassEater{" + "name='" + name + '\'' + ", blurb='" + blurb + '\'' + '}'; } }
1,883
21.428571
87
java
null
infinispan-main/query/src/test/java/org/infinispan/query/test/CustomKey.java
package org.infinispan.query.test; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.query.Transformable; @Transformable(transformer = CustomTransformer.class) public class CustomKey { final int i, j, k; @ProtoFactory public CustomKey(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } @ProtoField(number = 1, defaultValue = "0") public int getI() { return i; } @ProtoField(number = 2, defaultValue = "0") public int getJ() { return j; } @ProtoField(number = 3, defaultValue = "0") public int getK() { return k; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomKey other = (CustomKey) o; return i == other.i && j == other.j && k == other.k; } @Override public int hashCode() { return 31 * (31 * i + j) + k; } }
1,033
21
64
java
null
infinispan-main/query/src/test/java/org/infinispan/query/test/CustomKey3Transformer.java
package org.infinispan.query.test; import org.infinispan.query.Transformer; public class CustomKey3Transformer implements Transformer { @Override public Object fromString(String s) { return new CustomKey3(s); } @Override public String toString(Object customType) { CustomKey3 key = (CustomKey3) customType; return key.getStr(); } }
372
19.722222
59
java
null
infinispan-main/query/src/test/java/org/infinispan/query/test/CustomKey3.java
package org.infinispan.query.test; import java.io.Serializable; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; public class CustomKey3 implements Serializable { private final String str; @ProtoFactory public CustomKey3(String str) { this.str = str; } @ProtoField(number = 1) public String getStr() { return str; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomKey3 that = (CustomKey3) o; return str != null ? str.equals(that.str) : that.str == null; } @Override public int hashCode() { return str != null ? str.hashCode() : 0; } }
782
21.371429
67
java
null
infinispan-main/query/src/test/java/org/infinispan/query/test/Person.java
package org.infinispan.query.test; import java.io.Serializable; import java.util.Date; 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.ProtoField; /** * @author Navin Surtani */ @Indexed(index = "person") public class Person implements Serializable { private String name; private String blurb; private int age; private Date dateOfGraduation; private String nonIndexedField; public Person() { } public Person(String name, String blurb, int age) { this.name = name; this.blurb = blurb; this.age = age; this.nonIndexedField = name != null && name.length() >= 2 ? name.substring(0, 2) : null; } public Person(String name, String blurb, int age, Date dateOfGraduation) { this.name = name; this.blurb = blurb; this.age = age; this.dateOfGraduation = dateOfGraduation; } @Text @ProtoField(number = 1) public String getName() { return name; } public void setName(String name) { this.name = name; } @Text @ProtoField(number = 2) public String getBlurb() { return blurb; } public void setBlurb(String blurb) { this.blurb = blurb; } @Basic(projectable = true, sortable = true) @ProtoField(number = 3, defaultValue = "0") public int getAge() { return age; } public void setAge(int age) { this.age = age; } @ProtoField(number = 4) public String getNonIndexedField() { return nonIndexedField; } public void setNonIndexedField(String nonIndexedField) { this.nonIndexedField = nonIndexedField; } @Basic(projectable = true) @ProtoField(number = 5) public Date getDateOfGraduation() { return dateOfGraduation; } public void setDateOfGraduation(Date dateOfGraduation) { this.dateOfGraduation = dateOfGraduation; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; if (age != person.age) return false; if (blurb != null ? !blurb.equals(person.blurb) : person.blurb != null) return false; if (name != null ? !name.equals(person.name) : person.name != null) return false; if (nonIndexedField != null ? !nonIndexedField.equals(person.nonIndexedField) : person.nonIndexedField != null) return false; return dateOfGraduation != null ? dateOfGraduation.equals(person.dateOfGraduation) : person.dateOfGraduation == null; } @Override public int hashCode() { int result = (name != null ? name.hashCode() : 0); result = 31 * result + (blurb != null ? blurb.hashCode() : 0); result = 31 * result + (nonIndexedField != null ? nonIndexedField.hashCode() : 0); result = 31 * result + (dateOfGraduation != null ? dateOfGraduation.hashCode() : 0); result = 31 * result + age; return result; } @Override public String toString() { return "Person{name='" + name + "', blurb='" + blurb + "', age=" + age + ", dateOfGraduation=" + dateOfGraduation + ", nonIndexedField='" + nonIndexedField + "'}"; } }
3,325
26.04065
123
java
null
infinispan-main/query/src/test/java/org/infinispan/query/test/CustomKey2.java
package org.infinispan.query.test; import java.io.Serializable; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.query.Transformable; @Transformable public class CustomKey2 implements Serializable { private static final long serialVersionUID = -1; private final int i, j, k; @ProtoFactory public CustomKey2(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } @ProtoField(number = 1, defaultValue = "0") public int getI() { return i; } @ProtoField(number = 2, defaultValue = "0") public int getJ() { return j; } @ProtoField(number = 3, defaultValue = "0") public int getK() { return k; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomKey2 other = (CustomKey2) o; return i == other.i && j == other.j && k == other.k; } @Override public int hashCode() { return 31 * (31 * i + j) + k; } }
1,113
20.843137
64
java
null
infinispan-main/query/src/test/java/org/infinispan/query/test/Author.java
package org.infinispan.query.test; import java.util.Objects; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Text; @Indexed public class Author { private String name; private String surname; public Author(String name, String surname) { this.name = name; this.surname = surname; } @Text public String getName() { return name; } public void setName(String name) { this.name = name; } @Basic public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } @Override public int hashCode() { return Objects.hash(name, surname); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Author other = (Author) obj; return Objects.equals(name, other.name) && Objects.equals(surname, other.surname); } }
1,095
19.296296
88
java
null
infinispan-main/query/src/test/java/org/infinispan/query/test/QueryTestSCI.java
package org.infinispan.query.test; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.query.api.AnotherTestEntity; import org.infinispan.query.api.NotIndexedType; import org.infinispan.query.api.TestEntity; import org.infinispan.query.distributed.NonSerializableKeyType; import org.infinispan.query.indexedembedded.City; import org.infinispan.query.indexedembedded.Country; import org.infinispan.query.queries.faceting.Car; @AutoProtoSchemaBuilder( dependsOn = org.infinispan.test.TestDataSCI.class, includeClasses = { AnotherGrassEater.class, AnotherTestEntity.class, Block.class, Car.class, City.class, Country.class, CustomKey.class, CustomKey2.class, CustomKey3.class, NonSerializableKeyType.class, NotIndexedType.class, Person.class, TestEntity.class, Transaction.class, }, schemaFileName = "test.query.proto", schemaFilePath = "proto/generated", schemaPackageName = "org.infinispan.test.query", service = false ) public interface QueryTestSCI extends SerializationContextInitializer { QueryTestSCI INSTANCE = new QueryTestSCIImpl(); }
1,364
34
71
java
null
infinispan-main/query/src/test/java/org/infinispan/query/test/Book.java
package org.infinispan.query.test; import java.util.Objects; import java.util.Set; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Embedded; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Text; @Indexed public class Book { private String title; private String description; private Set<Author> authors; public Book(String title, String description, Set<Author> authors) { this.title = title; this.description = description; this.authors = authors; } @Basic public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Text public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Embedded public Set<Author> getAuthors() { return authors; } public void setAuthors(Set<Author> authors) { this.authors = authors; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Book)) return false; Book other = (Book) o; return Objects.equals(title, other.title) && Objects.equals(description, other.description) && Objects.equals(authors, other.authors); } @Override public int hashCode() { return Objects.hash(title, description, authors); } }
1,506
21.161765
71
java
null
infinispan-main/query/src/test/java/org/infinispan/query/test/Block.java
package org.infinispan.query.test; import java.io.Serializable; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Embedded; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; @Indexed(index = "blockIndex") public class Block implements Serializable { @Basic private final int height; private final Transaction latest; @ProtoFactory public Block(int height, Transaction latest) { this.height = height; this.latest = latest; } @ProtoField(number = 1, defaultValue = "0") public int getHeight() { return height; } @Embedded @ProtoField(number = 2) public Transaction getLatest() { return latest; } @Override public String toString() { return "Block{" + "height=" + height + ", latest=" + latest + '}'; } }
1,000
21.75
59
java
null
infinispan-main/query/src/test/java/org/infinispan/query/test/NonSerializableKey.java
package org.infinispan.query.test; import org.infinispan.query.Transformable; /** * Non serializable key for testing DefaultTransformer. * * @author Anna Manukyan */ @Transformable public class NonSerializableKey { private String key; public NonSerializableKey(String key) { this.key = key; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NonSerializableKey other = (NonSerializableKey) o; return key != null ? key.equals(other.key) : other.key == null; } @Override public int hashCode() { return key != null ? key.hashCode() : 0; } }
693
20.6875
69
java
null
infinispan-main/query/src/test/java/org/infinispan/query/test/Transaction.java
package org.infinispan.query.test; import java.io.Serializable; 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 = "transactionIndex") public class Transaction implements Serializable { private final int size; private final String script; @ProtoFactory public Transaction(int size, String script) { this.size = size; this.script = script; } @Basic @ProtoField(number = 1, defaultValue = "0") public int getSize() { return size; } @Basic @ProtoField(number = 2) public String getScript() { return script; } @Override public String toString() { return "Transaction{" + "size=" + size + ", script='" + script + '\'' + '}'; } }
941
20.906977
59
java
null
infinispan-main/query/src/test/java/org/infinispan/query/jmx/QueryMBeanTest.java
package org.infinispan.query.jmx; import static org.infinispan.test.fwk.TestCacheManagerFactory.configureJmx; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.List; import java.util.Set; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.infinispan.Cache; import org.infinispan.commons.CacheException; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.IndexStorage; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.Search; import org.infinispan.query.core.stats.SearchStatistics; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.test.AnotherGrassEater; import org.infinispan.query.test.Person; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.Test; /** * Test search statistics MBean. * * @author Galder Zamarreño * @since 5.2 */ @Test(groups = "functional", testName = "query.jmx.QueryMBeanTest") public class QueryMBeanTest extends SingleCacheManagerTest { private static final String TEST_JMX_DOMAIN = QueryMBeanTest.class.getSimpleName(); private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); private static final String CACHE_NAME = "queryable-cache"; private static final int numberOfEntries = 100; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder globalConfiguration = new GlobalConfigurationBuilder().nonClusteredDefault(); globalConfiguration.jmx().enabled(true).domain(TEST_JMX_DOMAIN).mBeanServerLookup(mBeanServerLookup); ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(true); builder.statistics().enable(); builder.indexing().storage(IndexStorage.LOCAL_HEAP) .enable() .addIndexedEntities(Person.class, AnotherGrassEater.class); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(globalConfiguration, builder); cm.defineConfiguration(CACHE_NAME, builder.build()); return cm; } public void testQueryStatsMBean() throws Exception { cacheManager.getCache(CACHE_NAME); ObjectName name = getQueryStatsObjectName(TEST_JMX_DOMAIN, CACHE_NAME); MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); assertTrue(mBeanServer.isRegistered(name)); assertTrue((Boolean) mBeanServer.getAttribute(name, "StatisticsEnabled")); } public void testQueryStats() throws Exception { Cache<String, Object> cache = cacheManager.getCache(CACHE_NAME); // start cache ObjectName name = getQueryStatsObjectName(TEST_JMX_DOMAIN, CACHE_NAME); MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); assertTrue(mBeanServer.isRegistered(name)); // check that our settings are not ignored QueryFactory queryFactory = Search.getQueryFactory(cache); SearchStatistics searchStatistics = Search.getSearchStatistics(cache); assertTrue(searchStatistics.getQueryStatistics().isEnabled()); // add some test data for (int i = 0; i < numberOfEntries; i++) { Person person = new Person(); person.setName("key" + i); person.setAge(i); person.setBlurb("value " + i); person.setNonIndexedField("i: " + i); cache.put(person.getName(), person); } assertEquals(0L, mBeanServer.getAttribute(name, "SearchQueryExecutionCount")); String q = String.format("FROM %s WHERE blurb:'value'", Person.class.getName()); Query<?> cacheQuery = queryFactory.create(q); List<?> found = cacheQuery.execute().list(); //Executing first query assertEquals(1L, mBeanServer.getAttribute(name, "SearchQueryExecutionCount")); assertEquals(numberOfEntries, found.size()); assertEquals(numberOfEntries, mBeanServer.invoke(name, "getNumberOfIndexedEntities", new Object[]{Person.class.getName()}, new String[]{String.class.getName()})); assertEquals(2, CompletionStages.join(searchStatistics.getIndexStatistics().computeIndexInfos()).size()); // add more test data AnotherGrassEater anotherGrassEater = new AnotherGrassEater("Another grass-eater", "Eats grass"); cache.put("key101", anotherGrassEater); found = cacheQuery.execute().list(); //Executing second query assertEquals(numberOfEntries, found.size()); assertEquals(1, mBeanServer.invoke(name, "getNumberOfIndexedEntities", new Object[]{AnotherGrassEater.class.getName()}, new String[]{String.class.getName()})); Set<String> classNames = (Set<String>) mBeanServer.getAttribute(name, "IndexedClassNames"); assertEquals(2, classNames.size()); assertTrue("The set should contain the Person class name.", classNames.contains(Person.class.getName())); assertTrue("The set should contain the AnotherGrassEater class name.", classNames.contains(AnotherGrassEater.class.getName())); assertEquals(2, CompletionStages.join(searchStatistics.getIndexStatistics().computeIndexInfos()).size()); // check the statistics and see they have reasonable values assertTrue("The query execution total time should be > 0.", (Long) mBeanServer.getAttribute(name, "SearchQueryTotalTime") > 0); assertEquals(2L, mBeanServer.getAttribute(name, "SearchQueryExecutionCount")); assertEquals(q, mBeanServer.getAttribute(name, "SearchQueryExecutionMaxTimeQueryString")); assertTrue((Long) mBeanServer.getAttribute(name, "SearchQueryExecutionMaxTime") > 0); assertTrue((Long) mBeanServer.getAttribute(name, "SearchQueryExecutionAvgTime") > 0); mBeanServer.invoke(name, "clear", new Object[0], new String[0]); // after "clear" everything must be reset assertEquals(0L, mBeanServer.getAttribute(name, "SearchQueryExecutionCount")); assertEquals("", mBeanServer.getAttribute(name, "SearchQueryExecutionMaxTimeQueryString")); assertEquals(0L, mBeanServer.getAttribute(name, "SearchQueryExecutionMaxTime")); assertEquals(0L, mBeanServer.getAttribute(name, "SearchQueryExecutionAvgTime")); assertEquals(0L, mBeanServer.getAttribute(name, "ObjectsLoadedCount")); assertEquals(0L, mBeanServer.getAttribute(name, "ObjectLoadingTotalTime")); assertEquals(0L, mBeanServer.getAttribute(name, "ObjectLoadingExecutionMaxTime")); assertEquals(0L, mBeanServer.getAttribute(name, "ObjectLoadingExecutionAvgTime")); } /** * Tests that shutting down a cache manager does not interfere with the query related MBeans belonging to a second * one that is still alive and shares the same JMX domain (see issue ISPN-3531). */ public void testJmxUnregistration() throws Exception { cacheManager.getCache(CACHE_NAME); // Start the cache belonging to first cache manager ObjectName queryStatsObjectName = getQueryStatsObjectName(TEST_JMX_DOMAIN, CACHE_NAME); MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); Set<ObjectName> matchingNames = mBeanServer.queryNames(new ObjectName(TEST_JMX_DOMAIN + ":type=Query,component=Statistics,cache=" + ObjectName.quote(CACHE_NAME) + ",*"), null); assertEquals(1, matchingNames.size()); assertTrue(matchingNames.contains(queryStatsObjectName)); EmbeddedCacheManager cm2 = null; try { GlobalConfigurationBuilder globalConfig2 = GlobalConfigurationBuilder.defaultClusteredBuilder(); globalConfig2.cacheManagerName("cm2"); configureJmx(globalConfig2, TEST_JMX_DOMAIN, mBeanServerLookup); ConfigurationBuilder defaultCacheConfig2 = new ConfigurationBuilder(); defaultCacheConfig2 .indexing().enable().storage(IndexStorage.LOCAL_HEAP) .addIndexedEntities(Person.class, AnotherGrassEater.class); cm2 = TestCacheManagerFactory.createClusteredCacheManager(globalConfig2, defaultCacheConfig2); cm2.defineConfiguration(CACHE_NAME, defaultCacheConfig2.build()); cm2.getCache(CACHE_NAME); // Start the cache belonging to second cache manager matchingNames = mBeanServer.queryNames(new ObjectName(TEST_JMX_DOMAIN + ":type=Query,component=Statistics,cache=" + ObjectName.quote(CACHE_NAME) + ",*"), null); assertEquals(2, matchingNames.size()); assertTrue(matchingNames.contains(queryStatsObjectName)); } finally { TestingUtil.killCacheManagers(cm2); } matchingNames = mBeanServer.queryNames(new ObjectName(TEST_JMX_DOMAIN + ":type=Query,component=Statistics,cache=" + ObjectName.quote(CACHE_NAME) + ",*"), null); assertEquals(1, matchingNames.size()); assertTrue(matchingNames.contains(queryStatsObjectName)); } private ObjectName getQueryStatsObjectName(String jmxDomain, String cacheName) { String cacheManagerName = cacheManager.getCacheManagerConfiguration().cacheManagerName(); try { return new ObjectName(jmxDomain + ":type=Query,manager=" + ObjectName.quote(cacheManagerName) + ",cache=" + ObjectName.quote(cacheName) + ",component=Statistics"); } catch (MalformedObjectNameException e) { throw new CacheException("Malformed object name", e); } } }
9,802
47.771144
182
java
null
infinispan-main/query/src/test/java/org/infinispan/query/jmx/DistributedMassIndexingViaJmxTest.java
package org.infinispan.query.jmx; import static org.infinispan.test.fwk.TestCacheManagerFactory.configureJmx; import java.net.URL; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.infinispan.commons.CacheException; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.commons.util.FileLookupFactory; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.distributed.DistributedMassIndexingTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Test reindexing happens when executed via JMX * * @author Galder Zamarreño * @since 5.2 */ @Test(groups = "functional", testName = "query.jmx.DistributedMassIndexingViaJmxTest") public class DistributedMassIndexingViaJmxTest extends DistributedMassIndexingTest { private static final String BASE_JMX_DOMAIN = DistributedMassIndexingViaJmxTest.class.getName(); private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); @Override protected void createCacheManagers() throws Throwable { for (int i = 0; i < NUM_NODES; i++) { URL url = FileLookupFactory.newInstance().lookupFileLocation( "dynamic-indexing-distribution.xml", Thread.currentThread().getContextClassLoader()); ParserRegistry parserRegistry = new ParserRegistry(Thread.currentThread().getContextClassLoader()); ConfigurationBuilderHolder holder = parserRegistry.parse(url); configureJmx(holder.getGlobalConfigurationBuilder(), BASE_JMX_DOMAIN + i, mBeanServerLookup); EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(holder); registerCacheManager(cm); cm.getCache(); } waitForClusterToForm(); } @Override protected void rebuildIndexes() throws Exception { String cacheManagerName = manager(0).getCacheManagerConfiguration().cacheManagerName(); String defaultCacheName = manager(0).getCacheManagerConfiguration().defaultCacheName().orElse(null); ObjectName massIndexerObjName = getMassIndexerObjectName( BASE_JMX_DOMAIN + 0, cacheManagerName, defaultCacheName); mBeanServerLookup.getMBeanServer().invoke(massIndexerObjName, "start", new Object[0], new String[0]); } private ObjectName getMassIndexerObjectName(String jmxDomain, String cacheManagerName, String cacheName) { try { return new ObjectName(jmxDomain + ":type=Query,manager=" + ObjectName.quote(cacheManagerName) + ",cache=" + ObjectName.quote(cacheName) + ",component=MassIndexer"); } catch (MalformedObjectNameException e) { throw new CacheException("Malformed object name", e); } } }
3,001
41.885714
109
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/SharedReplMassIndexTest.java
package org.infinispan.query.distributed; import org.testng.annotations.Test; /** * Test the mass indexer on a REPL cache and shared index * @author gustavonalle * @since 7.1 */ @Test(groups = "functional", testName = "query.distributed.SharedReplMassIndexTest") public class SharedReplMassIndexTest extends DistributedMassIndexingTest { protected String getConfigurationFile() { return "shared-repl-mass-index.xml"; } }
440
24.941176
84
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/MassIndexingOffHeapIndexOnlyTest.java
package org.infinispan.query.distributed; import org.testng.annotations.Test; /** * Tests for Mass Indexing with data cache on heap, but index caches off-heap. * * @since 9.2 */ @Test(groups = "functional", testName = "query.distributed.MassIndexingOffHeapIndexOnlyTest") public class MassIndexingOffHeapIndexOnlyTest extends DistributedMassIndexingTest { @Override protected String getConfigurationFile() { return "mass-index-offheap-index-only.xml"; } }
479
24.263158
93
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/DegeneratedClusterMassIndexingTest.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.AssertJUnit.assertEquals; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.query.Search; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.queries.faceting.Car; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.Test; /** * @author anistor@redhat.com * @since 6.1 */ @Test(groups = "functional", testName = "query.distributed.DegeneratedClusterMassIndexingTest") public class DegeneratedClusterMassIndexingTest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true); cfg.indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Car.class); addClusterEnabledCacheManager(cfg); waitForClusterToForm(); } public void testReindexing() { Cache<String, Car> cache = this.<String, Car>cache(0).getAdvancedCache().withFlags(Flag.SKIP_INDEXING); cache.put("car1", new Car("ford", "white", 300)); cache.put("car2", new Car("ford", "blue", 300)); cache.put("car3", new Car("ford", "red", 300)); QueryFactory queryFactory = Search.getQueryFactory(cache); // ensure these were not indexed String q = String.format("FROM %s where make:'ford'", Car.class.getName()); Query<Car> query = queryFactory.create(q); assertEquals(0, query.execute().count().value()); //reindex join(Search.getIndexer(cache).run()); // check that the indexing is complete immediately assertEquals(3, query.execute().count().value()); } }
2,059
35.140351
109
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/MultipleEntitiesMassIndexTest.java
package org.infinispan.query.distributed; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.Assert.assertNull; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; 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.queries.faceting.Car; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.testng.annotations.Test; /** * Test the MassIndexer in a configuration of multiple entity types per cache. * * @author gustavonalle * @since 7.1 */ @Test(groups = "functional", testName = "query.distributed.MultipleEntitiesMassIndexTest") public class MultipleEntitiesMassIndexTest extends DistributedMassIndexingTest { protected void createCacheManagers() throws Throwable { // Person goes to RAM, Cars goes to Infinispan ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); cacheCfg .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Car.class) .addIndexedEntity(Person.class); createClusteredCaches(2, QueryTestSCI.INSTANCE, cacheCfg); waitForClusterToForm(); } @Override public void testReindexing() throws Exception { cache(0).put(key("C1"), new Car("megane", "white", 300)); cache(1).put(key("P1"), new Person("james", "blurb", 23)); cache(1).put(key("P2"), new Person("tony", "blurb", 28)); cache(1).put(key("P3"), new Person("chris", "blurb", 26)); cache(1).put(key("P4"), new Person("iker", "blurb", 23)); cache(1).put(key("P5"), new Person("sergio", "blurb", 29)); checkIndex(5, Person.class); checkIndex(1, Car.class); checkIndex(1, "make", "megane", Car.class); checkIndex(1, "name", "james", Person.class); cache(1).put(key("C2"), new Car("megane", "blue", 300)); checkIndex(2, "make", "megane", Car.class); //add an entry without indexing it: cache(1).getAdvancedCache().withFlags(Flag.SKIP_INDEXING).put(key("C3"), new Car("megane", "blue", 300)); checkIndex(2, "make", "megane", Car.class); //re-sync datacontainer with indexes: rebuildIndexes(); checkIndex(5, Person.class); checkIndex(3, Car.class); checkIndex(3, "make", "megane", Car.class); checkIndex(1, "name", "tony", Person.class); //verify we cleanup old stale index values by removing the data but avoid touching the index cache(1).getAdvancedCache().withFlags(Flag.SKIP_INDEXING).remove(key("C2")); cache(1).getAdvancedCache().withFlags(Flag.SKIP_INDEXING).remove(key("P3")); assertNull(cache(1).get(key("P3"))); assertNull(cache(1).get(key("C2"))); checkIndex(3, "make", "megane", Car.class); checkIndex(5, Person.class); //re-sync rebuildIndexes(); checkIndex(2, Car.class); checkIndex(2, "make", "megane", Car.class); checkIndex(4, Person.class); } private void checkIndex(int expectedCount, String fieldName, String fieldValue, Class<?> entity) { String q = String.format("FROM %s where %s:'%s'", entity.getName(), fieldName, fieldValue); checkIndex(expectedCount, q); } private void checkIndex(int expectedCount, Class<?> entity) { checkIndex(expectedCount, "FROM " + entity.getName()); } private void checkIndex(int expectedCount, String q) { for (Cache<?, ?> cache : caches()) { StaticTestingErrorHandler.assertAllGood(cache); QueryFactory searchManager = Search.getQueryFactory(cache); Query cacheQuery = searchManager.create(q); QueryResult result = cacheQuery.execute(); assertThat(result.count().isExact()).isTrue(); assertThat(result.count().value()).isEqualTo(expectedCount); } } }
4,226
37.779817
111
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/TopologyAwareDistMassIndexingTest.java
package org.infinispan.query.distributed; import static org.infinispan.query.helper.TestQueryHelperFactory.createTopologyAwareCacheNodes; import java.util.List; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.manager.CacheContainer; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.queries.faceting.Car; import org.testng.annotations.Test; /** * Tests verifying that Mass Indexer works properly on Topology Aware nodes. */ @Test(groups = "functional", testName = "query.distributed.TopologyAwareDistMassIndexingTest") public class TopologyAwareDistMassIndexingTest extends DistributedMassIndexingTest { @Override protected void createCacheManagers() throws Throwable { List<EmbeddedCacheManager> managers = createTopologyAwareCacheNodes(NUM_NODES, CacheMode.DIST_SYNC, false, true, false, getClass().getSimpleName(), Car.class); registerCacheManager(managers.toArray(new CacheContainer[0])); waitForClusterToForm(); } }
1,044
33.833333
95
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/ReplRamMassIndexingTest.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 static org.testng.Assert.assertNotNull; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.Indexer; import org.infinispan.query.Search; import org.infinispan.query.queries.faceting.Car; import org.infinispan.query.test.QueryTestSCI; import org.testng.annotations.Test; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ @Test(groups = "functional", testName = "query.distributed.ReplRamMassIndexingTest") public class ReplRamMassIndexingTest extends DistributedMassIndexingTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); cacheCfg .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Car.class) .clustering() .hash().numSegments(10 * NUM_NODES); cacheCfg.clustering().stateTransfer().fetchInMemoryState(true); createClusteredCaches(NUM_NODES, QueryTestSCI.INSTANCE, cacheCfg); waitForClusterToForm(getDefaultCacheName()); } @Override public void testReindexing() throws Exception { final int NUM_CARS = 100; for (int i = 0; i < NUM_CARS; ++i) { cache(i % NUM_NODES).put("car" + i, new Car("skoda", "white", 42)); } for (Cache cache : caches()) { assertEquals(cache.size(), NUM_CARS); verifyFindsCar(cache, NUM_CARS, "skoda"); } rebuildIndexes(); for (int i = 0; i < NUM_CARS; ++i) { String key = "car" + i; for (Cache cache : caches()) { assertNotNull(cache.get(key)); } } verifyFindsCar(NUM_CARS, "skoda"); } @Override protected void rebuildIndexes() { for (Cache<?, ?> cache : caches()) { Indexer indexer = Search.getIndexer(cache); eventually(() -> !indexer.isRunning()); join(indexer.run()); } } }
2,286
33.134328
97
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/AsyncMassIndexPerfTest.java
package org.infinispan.query.distributed; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.test.fwk.TestCacheManagerFactory.getDefaultCacheConfiguration; import java.util.Collections; import java.util.Scanner; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.Cache; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.IndexStorage; 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.impl.ComponentRegistryUtils; import org.infinispan.query.impl.massindex.IndexUpdater; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.query.test.Transaction; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.TestCacheManagerFactory; /** * Long running test for the async MassIndexer, specially regarding cancellation. Supposed to be run as a main class. * @author gustavonalle * @since 7.1 */ public class AsyncMassIndexPerfTest extends MultipleCacheManagersTest { /** * Number of entries to write */ private static final int OBJECT_COUNT = 1_000_000; /** * Number of threads to do the initial load */ private static final int WRITING_THREADS = 5; /** * If should SKIP_INDEX during initial load */ private static final boolean DISABLE_INDEX_WHEN_INSERTING = true; private static final boolean TX_ENABLED = false; private static final String MERGE_FACTOR = "30"; private static final CacheMode CACHE_MODE = CacheMode.LOCAL; private static final IndexStorage INDEX_STORAGE = LOCAL_HEAP; /** * For status report during insertion */ private static final int PRINT_EACH = 10; private Cache<Integer, Transaction> cache1, cache2; private Indexer indexer; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cacheCfg; boolean local = CACHE_MODE == CacheMode.LOCAL; if (local) { cacheCfg = getDefaultCacheConfiguration(TX_ENABLED); } else { cacheCfg = getDefaultClusteredCacheConfig(CACHE_MODE, TX_ENABLED); cacheCfg.clustering().remoteTimeout(120000); } cacheCfg.indexing().enable() .storage(INDEX_STORAGE) .addIndexedEntity(Transaction.class) .writer().merge().factor(Integer.parseInt(MERGE_FACTOR)); if (!local) { createClusteredCaches(2, QueryTestSCI.INSTANCE, cacheCfg); cache2 = cache(1); cache1 = cache(0); } else { EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(cacheCfg); cache1 = cacheManager.getCache(); cache2 = cacheManager.getCache(); } indexer = Search.getIndexer(cache1); } private void writeData() throws InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(WRITING_THREADS, getTestThreadFactory("Worker")); final AtomicInteger counter = new AtomicInteger(0); for (int i = 0; i < OBJECT_COUNT; i++) { executorService.submit(() -> { Cache<Integer, Transaction> insertCache = cache1; if (DISABLE_INDEX_WHEN_INSERTING) { insertCache = insertCache.getAdvancedCache().withFlags(Flag.SKIP_INDEXING); } int key = counter.incrementAndGet(); insertCache.put(key, new Transaction(key * 100, "0eab" + key)); if (key != 0 && key % PRINT_EACH == 0) { System.out.printf("\rInserted %d", key); } }); } executorService.shutdown(); executorService.awaitTermination(3, TimeUnit.MINUTES); if (!DISABLE_INDEX_WHEN_INSERTING) { waitForIndexSize(OBJECT_COUNT); } System.out.println(); } /** * Waits until the index reaches a certain size. Useful for async backend */ private void waitForIndexSize(final int expected) { eventually(() -> { long idxCount = countIndex(); System.out.printf("\rWaiting for indexing completion (%d): %d indexed so far", expected, +idxCount); return idxCount == expected; }); System.out.println("\nIndexing done."); } public static void main(String[] args) throws Throwable { AsyncMassIndexPerfTest test = new AsyncMassIndexPerfTest(); TestResourceTracker.testThreadStarted(test.getTestName()); test.createBeforeClass(); test.createBeforeMethod(); test.populate(); } public void populate() throws Exception { StopTimer stopTimer = new StopTimer(); writeData(); stopTimer.stop(); System.out.printf("\rData inserted in %d seconds.", stopTimer.getElapsedIn(TimeUnit.SECONDS)); info(); new Thread(new EventLoop(indexer)).start(); } private void info() { System.out.println("\rr: Run MassIndexer\nc: Cancel MassIndexer\ni: Put new entry\ns: Current index size\np: Purge indexes\nf: flush\nh: This menu\nx: Exit"); } private enum IndexManager { NRT("10000"), DIRECTORY("0"); private final String cfg; IndexManager(String cfg) { this.cfg = cfg; } @Override public String toString() { return cfg; } } protected long countIndex() { Query<?> q = Search.getQueryFactory(cache1).create("FROM " + Transaction.class.getName()); return q.execute().count().value(); } protected void clearIndex() { Search.getIndexer(cache1).remove(); } class EventLoop implements Runnable { private Indexer indexer; private CompletionStage<Void> future; private AtomicInteger nexIndex = new AtomicInteger(OBJECT_COUNT); public EventLoop(Indexer indexer) { this.indexer = indexer; } void startMassIndexer() { System.out.println("Running MassIndexer"); final StopTimer stopTimer = new StopTimer(); future = indexer.run().toCompletableFuture(); future.whenComplete((v, t) -> { stopTimer.stop(); if (t != null) { System.out.println("Error executing massindexer"); t.printStackTrace(); } System.out.printf("\nMass indexer run in %d seconds", stopTimer.getElapsedIn(TimeUnit.SECONDS)); System.out.println(); waitForIndexSize(nexIndex.get()); System.out.println("Mass Indexing complete."); }); } @Override public void run() { Scanner scanner = new Scanner(System.in); while (!Thread.interrupted()) { String next = scanner.next(); if ("c".equals(next)) { if (future == null) { System.out.println("\rMassIndexer not started"); continue; } else { // Mass Indexer doesn't provide cancellation currently // https://issues.redhat.com/browse/ISPN-11735 // future.cancel(true); System.out.println("Mass Indexer cancelled"); } } if ("r".equals(next)) { startMassIndexer(); } if ("f".equals(next)) { flushIndex(); System.out.println("Index flushed."); } if ("s".equals(next)) { System.out.printf("Index size is %d\n", countIndex()); } if ("p".equals(next)) { clearIndex(); System.out.println("Index cleared."); } if ("i".equals(next)) { int nextIndex = nexIndex.incrementAndGet(); cache2.put(nextIndex, new Transaction(nextIndex, "0" + nextIndex)); System.out.println("New entry inserted"); } if ("h".equals(next)) { info(); } if ("x".equals(next)) { System.exit(0); } } } } private void flushIndex() { IndexUpdater indexUpdater = new IndexUpdater(ComponentRegistryUtils.getSearchMapping(cache1)); indexUpdater.flush(Collections.singleton(Transaction.class)); } static class StopTimer { private long start; private long elapsed; public StopTimer() { start = currentTime(); } private long currentTime() { return System.currentTimeMillis(); } public void reset() { start = currentTime(); } public void stop() { elapsed = currentTime() - start; } public long getElapsedIn(TimeUnit unit) { return unit.convert(elapsed, TimeUnit.MILLISECONDS); } } }
9,206
32.358696
164
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/SecureMassIndexingTest.java
package org.infinispan.query.distributed; import javax.security.auth.Subject; import org.infinispan.security.Security; import org.infinispan.test.TestingUtil; import org.junit.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; @Test(groups = "functional", testName = "query.distributed.SecureMassIndexingTest") public class SecureMassIndexingTest extends DistributedMassIndexingTest { private static final Subject ADMIN = TestingUtil.makeSubject("admin", "admin"); @Override protected String getConfigurationFile() { return "mass-index-with-security.xml"; } @Override protected void createCacheManagers() throws Throwable { runAs(ADMIN, super::createCacheManagers); } @AfterMethod @Override protected void clearContent() { runAs(ADMIN, super::clearContent); } @Override public void testPartiallyReindex() { runAs(ADMIN, super::testPartiallyReindex); } @Override public void testReindexing() { runAs(ADMIN, super::testReindexing); } interface TestExecution { void apply() throws Throwable; } private void runAs(Subject subject, TestExecution execution) { Security.doAs(subject, () -> { try { execution.apply(); } catch (Throwable e) { e.printStackTrace(); Assert.fail(); } }); } }
1,401
23.596491
83
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/UnsharedDistMassIndexTest.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.dsl.QueryFactory; import org.infinispan.query.queries.faceting.Car; import org.testng.annotations.Test; /** * Test for MassIndexer on DIST caches with unshared infinispan indexes * * @author gustavonalle * @since 7.1 */ @Test(groups = "functional", testName = "query.distributed.UnsharedDistMassIndexTest") public class UnsharedDistMassIndexTest extends DistributedMassIndexingTest { @Override protected String getConfigurationFile() { return "unshared-indexing-distribution.xml"; } @Override protected void verifyFindsCar(Cache cache, int expectedCount, String carMake) { QueryFactory queryFactory = Search.getQueryFactory(cache); String q = String.format("FROM %s WHERE make:'%s'", Car.class.getName(), carMake); Query cacheQuery = queryFactory.create(q); assertEquals(expectedCount, cacheQuery.execute().list().size()); } }
1,110
31.676471
88
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/IndexManagerLocalTxTest.java
package org.infinispan.query.distributed; import org.testng.annotations.Test; /** * Similiar to MultiNodeLocalTest, only uses transactional infinispan configuration. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.distributed.IndexManagerLocalTxTest") public class IndexManagerLocalTxTest extends IndexManagerLocalTest { public boolean transactionsEnabled() { return true; } }
425
22.666667
84
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/OverlappingIndexMassIndexTest.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.AssertJUnit.assertEquals; import java.util.ArrayList; import java.util.List; 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.test.Block; 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 MassIndexer for different entities sharing the same cache. * * @author gustavonalle * @since 7.1 */ @Test(groups = "functional", testName = "query.distributed.OverlappingIndexMassIndexTest") public class OverlappingIndexMassIndexTest extends MultipleCacheManagersTest { protected static final int NUM_NODES = 3; protected List<Cache<String, Object>> caches = new ArrayList<>(NUM_NODES); @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); cacheCfg .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity(Transaction.class) .addIndexedEntity(Block.class); createClusteredCaches(NUM_NODES, QueryTestSCI.INSTANCE, cacheCfg); waitForClusterToForm(getDefaultCacheName()); caches = caches(); } public void testReindex() { Transaction t1 = new Transaction(302, "04a27"); Transaction t2 = new Transaction(256, "ae461"); Transaction t3 = new Transaction(257, "ac537"); Block b1 = new Block(1, t1); Block b2 = new Block(2, t2); Block b3 = new Block(3, t3); caches.get(0).put("T1", t1); caches.get(0).put("T2", t2); caches.get(0).put("T3", t3); caches.get(0).put("B1", b1); caches.get(0).put("B2", b2); caches.get(0).put("B3", b3); checkIndex(3, Transaction.class, 3, Block.class); runMassIndexer(); checkIndex(3, Transaction.class, 3, Block.class); caches.get(0).clear(); runMassIndexer(); checkIndex(0, Transaction.class, 0, Block.class); } protected void checkIndex(int expectedNumber, Class<?> entity, int otherExpected, Class<?> otherEntity) { for (Cache<?, ?> c : caches) { int query1ResultSize = TestQueryHelperFactory.queryAll(c, entity).size(); int query2ResultSize = TestQueryHelperFactory.queryAll(c, otherEntity).size(); assertEquals(expectedNumber, query1ResultSize); assertEquals(otherExpected, query2ResultSize); } } protected void runMassIndexer() { Cache<?, ?> cache = caches.get(0); join((Search.getIndexer(cache)).run()); } }
3,029
31.934783
108
java
null
infinispan-main/query/src/test/java/org/infinispan/query/distributed/StatsTest.java
package org.infinispan.query.distributed; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.hibernate.search.backend.lucene.index.LuceneIndexManager; 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.QueryStatistics; import org.infinispan.query.core.stats.SearchStatistics; import org.infinispan.query.impl.ComponentRegistryUtils; import org.infinispan.query.test.Person; import org.infinispan.query.test.QueryTestSCI; import org.infinispan.query.test.Transaction; import org.infinispan.search.mapper.mapping.SearchIndexedEntity; import org.infinispan.search.mapper.mapping.SearchMapping; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @since 12.0 */ @Test(groups = "functional", testName = "query.distributed.StatsTest") public class StatsTest extends MultipleCacheManagersTest { // Wild guess: an empty index shouldn't be more than this many bytes private static final long MAX_EMPTY_INDEX_SIZE = 300L; private Cache<String, Object> cache0; private Cache<String, Object> cache1; private Cache<String, Object> cache2; private QueryStatistics queryStatistics0; private QueryStatistics queryStatistics1; private QueryStatistics queryStatistics2; private final String indexedQuery = String.format("From %s where name : 'Donald'", Person.class.getName()); private final String nonIndexedQuery = String.format("From %s where nonIndexedField = 'first'", Person.class.getName()); private final String hybridQuery = String.format("From %s where nonIndexedField = 'first' and age > 50", Person.class.getName()); @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cacheCfg = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); cacheCfg.statistics().enable(); cacheCfg.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(Person.class) .addIndexedEntity(Transaction.class); createClusteredCaches(3, QueryTestSCI.INSTANCE, cacheCfg); cache0 = cache(0); cache1 = cache(1); cache2 = cache(2); queryStatistics0 = Search.getSearchStatistics(cache0).getQueryStatistics(); queryStatistics1 = Search.getSearchStatistics(cache1).getQueryStatistics(); queryStatistics2 = Search.getSearchStatistics(cache2).getQueryStatistics(); } @BeforeMethod public void setUp() { cache0.clear(); } @Test public void testQueryStats() { addData(); testNonIndexedQueryStats(); testIndexedQueryStats(); testHybridQueryStats(); testClean(); } @Test public void testEmptyIndexStats() { Set<String> expectedEntities = new HashSet<>(Arrays.asList(Person.class.getName(), Transaction.class.getName())); Set<String> totalEntities = new HashSet<>(); for (int i = 0; i < cacheManagers.size(); i++) { SearchStatistics searchStatistics = Search.getSearchStatistics(cache(i)); Map<String, IndexInfo> indexInfos = await(searchStatistics.getIndexStatistics().computeIndexInfos()); totalEntities.addAll(indexInfos.keySet()); for (IndexInfo indexInfo : indexInfos.values()) { assertEquals(indexInfo.count(), 0L); assertThat(indexInfo.size()).isLessThan(MAX_EMPTY_INDEX_SIZE); } } assertEquals(totalEntities, expectedEntities); SearchStatistics clusteredStats = await(Search.getClusteredSearchStatistics(cache0)); Map<String, IndexInfo> classIndexInfoMap = await(clusteredStats.getIndexStatistics().computeIndexInfos()); assertEquals(classIndexInfoMap.keySet(), expectedEntities); Long reduceCount = classIndexInfoMap.values().stream().map(IndexInfo::count).reduce(0L, Long::sum); assertEquals(reduceCount.intValue(), 0L); Long reduceSize = classIndexInfoMap.values().stream().map(IndexInfo::size).reduce(0L, Long::sum); assertThat(reduceSize.longValue()).isLessThan(MAX_EMPTY_INDEX_SIZE * 2); // 2 indexes } @Test public void testNonEmptyIndexStats() { addData(); Set<String> expectedEntities = new HashSet<>(Arrays.asList(Person.class.getName(), Transaction.class.getName())); int expectDocuments = cacheManagers.size() * cache0.getCacheConfiguration().clustering().hash().numOwners(); flushAll(); Set<String> totalEntities = new HashSet<>(); int totalCount = 0; long totalSize = 0L; for (int i = 0; i < cacheManagers.size(); i++) { SearchStatistics searchStatistics = Search.getSearchStatistics(cache(i)); Map<String, IndexInfo> indexInfos = await(searchStatistics.getIndexStatistics().computeIndexInfos()); totalEntities.addAll(indexInfos.keySet()); for (IndexInfo indexInfo : indexInfos.values()) { totalCount += indexInfo.count(); totalSize += indexInfo.size(); } } assertEquals(totalEntities, expectedEntities); assertEquals(totalCount, expectDocuments); assertEquals(totalSize, totalIndexSize()); SearchStatistics clusteredStats = await(Search.getClusteredSearchStatistics(cache0)); Map<String, IndexInfo> classIndexInfoMap = await(clusteredStats.getIndexStatistics().computeIndexInfos()); assertEquals(classIndexInfoMap.keySet(), expectedEntities); Long reduceCount = classIndexInfoMap.values().stream().map(IndexInfo::count).reduce(0L, Long::sum); int clusteredExpectDocuments = cacheManagers.size() * cache0.getCacheConfiguration().clustering().hash().numOwners(); assertEquals(reduceCount.intValue(), clusteredExpectDocuments); Long reduceSize = classIndexInfoMap.values().stream().map(IndexInfo::size).reduce(0L, Long::sum); assertEquals(reduceSize.longValue(), totalIndexSize()); } private void testClean() { queryStatistics0.clear(); queryStatistics1.clear(); queryStatistics2.clear(); SearchStatistics clustered = await(Search.getClusteredSearchStatistics(cache0)); QueryStatistics localQueryStatistics = clustered.getQueryStatistics(); assertEquals(localQueryStatistics.getNonIndexedQueryCount(), 0); assertEquals(localQueryStatistics.getHybridQueryCount(), 0); assertEquals(localQueryStatistics.getDistributedIndexedQueryCount(), 0); assertEquals(localQueryStatistics.getLocalIndexedQueryCount(), 0); } private void testNonIndexedQueryStats() { executeQuery(nonIndexedQuery, cache0); assertEquals(queryStatistics0.getNonIndexedQueryCount(), 1); assertEquals(queryStatistics1.getNonIndexedQueryCount(), 0); assertEquals(queryStatistics2.getNonIndexedQueryCount(), 0); SearchStatistics clustered1 = await(Search.getClusteredSearchStatistics(cache1)); assertEquals(clustered1.getQueryStatistics().getNonIndexedQueryCount(), 1); executeQuery(nonIndexedQuery, cache1); assertEquals(queryStatistics0.getNonIndexedQueryCount(), 1); assertEquals(queryStatistics1.getNonIndexedQueryCount(), 1); assertEquals(queryStatistics2.getNonIndexedQueryCount(), 0); SearchStatistics clustered2 = await(Search.getClusteredSearchStatistics(cache2)); assertEquals(clustered2.getQueryStatistics().getNonIndexedQueryCount(), 2); executeQuery(nonIndexedQuery, cache2); assertEquals(queryStatistics0.getNonIndexedQueryCount(), 1); assertEquals(queryStatistics1.getNonIndexedQueryCount(), 1); assertEquals(queryStatistics2.getNonIndexedQueryCount(), 1); SearchStatistics clustered0 = await(Search.getClusteredSearchStatistics(cache0)); assertEquals(clustered0.getQueryStatistics().getNonIndexedQueryCount(), 3); } private void testIndexedQueryStats() { executeQuery(indexedQuery, cache0); assertEquals(queryStatistics0.getLocalIndexedQueryCount(), 1); assertEquals(queryStatistics0.getDistributedIndexedQueryCount(), 1); assertEquals(queryStatistics1.getLocalIndexedQueryCount(), 1); assertEquals(queryStatistics1.getDistributedIndexedQueryCount(), 0); assertEquals(queryStatistics2.getLocalIndexedQueryCount(), 1); assertEquals(queryStatistics2.getDistributedIndexedQueryCount(), 0); SearchStatistics clustered = await(Search.getClusteredSearchStatistics(cache1)); assertEquals(clustered.getQueryStatistics().getLocalIndexedQueryCount(), 3); assertEquals(clustered.getQueryStatistics().getDistributedIndexedQueryCount(), 1); executeQuery(indexedQuery, cache1); assertEquals(queryStatistics0.getLocalIndexedQueryCount(), 2); assertEquals(queryStatistics0.getDistributedIndexedQueryCount(), 1); assertEquals(queryStatistics1.getLocalIndexedQueryCount(), 2); assertEquals(queryStatistics1.getDistributedIndexedQueryCount(), 1); assertEquals(queryStatistics2.getLocalIndexedQueryCount(), 2); assertEquals(queryStatistics2.getDistributedIndexedQueryCount(), 0); clustered = await(Search.getClusteredSearchStatistics(cache1)); assertEquals(clustered.getQueryStatistics().getLocalIndexedQueryCount(), 6); assertEquals(clustered.getQueryStatistics().getDistributedIndexedQueryCount(), 2); executeQuery(indexedQuery, cache2); assertEquals(queryStatistics0.getLocalIndexedQueryCount(), 3); assertEquals(queryStatistics0.getDistributedIndexedQueryCount(), 1); assertEquals(queryStatistics1.getLocalIndexedQueryCount(), 3); assertEquals(queryStatistics1.getDistributedIndexedQueryCount(), 1); assertEquals(queryStatistics2.getLocalIndexedQueryCount(), 3); assertEquals(queryStatistics2.getDistributedIndexedQueryCount(), 1); clustered = await(Search.getClusteredSearchStatistics(cache1)); assertEquals(clustered.getQueryStatistics().getLocalIndexedQueryCount(), 9); assertEquals(clustered.getQueryStatistics().getDistributedIndexedQueryCount(), 3); } private void testHybridQueryStats() { executeQuery(hybridQuery, cache0); assertEquals(queryStatistics0.getHybridQueryCount(), 1); assertEquals(queryStatistics0.getLocalIndexedQueryCount(), 4); assertEquals(queryStatistics0.getDistributedIndexedQueryCount(), 2); assertEquals(queryStatistics1.getHybridQueryCount(), 0); assertEquals(queryStatistics1.getLocalIndexedQueryCount(), 4); assertEquals(queryStatistics1.getDistributedIndexedQueryCount(), 1); assertEquals(queryStatistics2.getHybridQueryCount(), 0); assertEquals(queryStatistics2.getLocalIndexedQueryCount(), 4); assertEquals(queryStatistics2.getDistributedIndexedQueryCount(), 1); SearchStatistics clustered = await(Search.getClusteredSearchStatistics(cache1)); assertEquals(clustered.getQueryStatistics().getHybridQueryCount(), 1); assertEquals(clustered.getQueryStatistics().getLocalIndexedQueryCount(), 12); assertEquals(clustered.getQueryStatistics().getDistributedIndexedQueryCount(), 4); executeQuery(hybridQuery, cache1); assertEquals(queryStatistics0.getHybridQueryCount(), 1); assertEquals(queryStatistics0.getLocalIndexedQueryCount(), 5); assertEquals(queryStatistics0.getDistributedIndexedQueryCount(), 2); assertEquals(queryStatistics1.getHybridQueryCount(), 1); assertEquals(queryStatistics1.getLocalIndexedQueryCount(), 5); assertEquals(queryStatistics1.getDistributedIndexedQueryCount(), 2); assertEquals(queryStatistics2.getHybridQueryCount(), 0); assertEquals(queryStatistics2.getLocalIndexedQueryCount(), 5); assertEquals(queryStatistics2.getDistributedIndexedQueryCount(), 1); clustered = await(Search.getClusteredSearchStatistics(cache1)); assertEquals(clustered.getQueryStatistics().getHybridQueryCount(), 2); assertEquals(clustered.getQueryStatistics().getLocalIndexedQueryCount(), 15); assertEquals(clustered.getQueryStatistics().getDistributedIndexedQueryCount(), 5); executeQuery(hybridQuery, cache2); assertEquals(queryStatistics0.getHybridQueryCount(), 1); assertEquals(queryStatistics0.getLocalIndexedQueryCount(), 6); assertEquals(queryStatistics0.getDistributedIndexedQueryCount(), 2); assertEquals(queryStatistics1.getHybridQueryCount(), 1); assertEquals(queryStatistics1.getLocalIndexedQueryCount(), 6); assertEquals(queryStatistics1.getDistributedIndexedQueryCount(), 2); assertEquals(queryStatistics2.getHybridQueryCount(), 1); assertEquals(queryStatistics2.getLocalIndexedQueryCount(), 6); assertEquals(queryStatistics2.getDistributedIndexedQueryCount(), 2); clustered = await(Search.getClusteredSearchStatistics(cache1)); assertEquals(clustered.getQueryStatistics().getHybridQueryCount(), 3); assertEquals(clustered.getQueryStatistics().getLocalIndexedQueryCount(), 18); assertEquals(clustered.getQueryStatistics().getDistributedIndexedQueryCount(), 6); } private void executeQuery(String q, Cache<String, Object> fromCache) { List<Person> list = Search.getQueryFactory(fromCache).<Person>create(q).execute().list(); assertFalse(list.isEmpty()); } private void addData() { Person person1 = new Person("Donald", "Duck", 86); person1.setNonIndexedField("second"); Person person2 = new Person("Mickey", "Mouse", 92); person2.setNonIndexedField("first"); cache0.put("1", person1); cache0.put("2", person2); cache0.put("3", new Transaction(12, "sss")); } private void flushAll() { caches().forEach(c -> ComponentRegistryUtils.getSearchMapping(c).scopeAll().workspace().flush()); } private long totalIndexSize() { long totalSize = 0; for (Cache<?, ?> cache : caches()) { SearchMapping searchMapping = ComponentRegistryUtils.getSearchMapping(cache); for (SearchIndexedEntity indexedEntity : searchMapping.allIndexedEntities()) { totalSize += indexedEntity.indexManager().unwrap(LuceneIndexManager.class).computeSizeInBytes(); } } return totalSize; } }
14,721
44.578947
132
java