repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/iteration/ProtobufRemoteIteratorIndexingTest.java
package org.infinispan.client.hotrod.impl.iteration; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.Set; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.query.testdomain.protobuf.AccountPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.MultiHotRodServersTest; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.embedded.testdomain.Account; import org.testng.annotations.Test; /** * @since 9.1 */ @Test(groups = "functional", testName = "client.hotrod.iteration.ProtobufRemoteIteratorIndexingTest") public class ProtobufRemoteIteratorIndexingTest extends MultiHotRodServersTest implements AbstractRemoteIteratorTest { private static final int NUM_NODES = 2; private static final int CACHE_SIZE = 10; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); cfg.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.Account"); createHotRodServers(NUM_NODES, hotRodCacheConfiguration(cfg)); waitForClusterToForm(); } @Override protected SerializationContextInitializer contextInitializer() { return TestDomainSCI.INSTANCE; } public void testSimpleIteration() { RemoteCache<Integer, AccountPB> cache = clients.get(0).getCache(); populateCache(CACHE_SIZE, this::newAccountPB, cache); List<AccountPB> results = new ArrayList<>(); cache.retrieveEntries(null, null, CACHE_SIZE).forEachRemaining(e -> results.add((AccountPB) e.getValue())); assertEquals(CACHE_SIZE, results.size()); } public void testFilteredIterationWithQuery() { RemoteCache<Integer, AccountPB> remoteCache = clients.get(0).getCache(); populateCache(CACHE_SIZE, this::newAccountPB, remoteCache); QueryFactory queryFactory = Search.getQueryFactory(remoteCache); int lowerId = 5; int higherId = 8; Query<Account> simpleQuery = queryFactory.<Account>create("FROM sample_bank_account.Account WHERE id BETWEEN :lowerId AND :higherId") .setParameter("lowerId", lowerId) .setParameter("higherId", higherId); Set<Entry<Object, Object>> entries = extractEntries(remoteCache.retrieveEntriesByQuery(simpleQuery, null, 10)); Set<Integer> keys = extractKeys(entries); assertEquals(4, keys.size()); assertForAll(keys, key -> key >= lowerId && key <= higherId); assertForAll(entries, e -> e.getValue() instanceof AccountPB); Query<Object[]> projectionsQuery = queryFactory.<Object[]>create("SELECT id, description FROM sample_bank_account.Account WHERE id BETWEEN :lowerId AND :higherId") .setParameter("lowerId", lowerId) .setParameter("higherId", higherId); Set<Entry<Integer, Object[]>> entriesWithProjection = extractEntries(remoteCache.retrieveEntriesByQuery(projectionsQuery, null, 10)); assertEquals(4, entriesWithProjection.size()); assertForAll(entriesWithProjection, entry -> { Integer id = entry.getKey(); Object[] projection = entry.getValue(); return projection[0].equals(id) && projection[1].equals("description for " + id); }); } }
4,013
43.6
169
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/iteration/ReplFailOverRemoteIteratorTest.java
package org.infinispan.client.hotrod.impl.iteration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author gustavonalle * @since 8.0 */ @Test(groups = "functional", testName = "client.hotrod.iteration.ReplFailOverRemoteIteratorTest") public class ReplFailOverRemoteIteratorTest extends BaseIterationFailOverTest { @Override public ConfigurationBuilder getCacheConfiguration() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); } }
582
31.388889
97
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/iteration/PreferredServerBalancingStrategy.java
package org.infinispan.client.hotrod.impl.iteration; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Collection; import java.util.Set; import org.infinispan.client.hotrod.FailoverRequestBalancingStrategy; import org.infinispan.client.hotrod.impl.transport.tcp.RoundRobinBalancingStrategy; public class PreferredServerBalancingStrategy implements FailoverRequestBalancingStrategy { private final InetSocketAddress preferredServer; private final RoundRobinBalancingStrategy roundRobinBalancingStrategy = new RoundRobinBalancingStrategy(); public PreferredServerBalancingStrategy(InetSocketAddress preferredServer) { this.preferredServer = preferredServer; } @Override public void setServers(Collection<SocketAddress> servers) { roundRobinBalancingStrategy.setServers(servers); } @Override public SocketAddress nextServer(Set<SocketAddress> failedServers) { if (failedServers != null && !failedServers.isEmpty() && failedServers.contains(preferredServer)) { return roundRobinBalancingStrategy.nextServer(failedServers); } return preferredServer; } }
1,158
34.121212
109
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/iteration/AbstractRemoteIteratorTest.java
package org.infinispan.client.hotrod.impl.iteration; import static org.testng.Assert.assertTrue; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.query.testdomain.protobuf.AccountPB; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.query.dsl.embedded.testdomain.hsearch.AccountHS; /** * @author gfernandes * @since 8.0 */ @SuppressWarnings("unchecked") public interface AbstractRemoteIteratorTest { default <T> Set<T> setOf(T... values) { return Stream.of(values).collect(Collectors.toSet()); } default <T> void populateCache(int numElements, Function<Integer, T> supplier, RemoteCache<Integer, T> remoteCache) { IntStream.range(0, numElements).parallel().forEach(i -> remoteCache.put(i, supplier.apply(i))); } default <T> void assertForAll(Collection<T> elements, Predicate<? super T> condition) { assertTrue(elements.stream().allMatch(condition)); } default AccountHS newAccount(int id) { AccountHS account = new AccountHS(); account.setId(id); account.setDescription("description for " + id); account.setCreationDate(new Date()); return account; } default AccountPB newAccountPB(int id) { AccountPB account = new AccountPB(); account.setId(id); account.setDescription("description for " + id); account.setCreationDate(new Date()); return account; } default Set<Integer> rangeAsSet(int minimum, int maximum) { return IntStream.range(minimum, maximum).boxed().collect(Collectors.toSet()); } default <K> Set<K> extractKeys(Collection<Map.Entry<Object, Object>> entries) { return entries.stream().map(e -> (K) e.getKey()).collect(Collectors.toSet()); } default <V> Set<V> extractValues(Collection<Map.Entry<Object, Object>> entries) { return entries.stream().map(e -> (V) e.getValue()).collect(Collectors.toSet()); } default byte[] toByteBuffer(Object key, Marshaller marshaller) { try { return marshaller.objectToByteBuffer(key); } catch (Exception ignored) { } return null; } default void assertKeysInSegment(Set<Map.Entry<Object, Object>> entries, Set<Integer> segments, Marshaller marshaller, Function<byte[], Integer> segmentCalculator) { entries.forEach(e -> { Integer key = (Integer) e.getKey(); int segment = segmentCalculator.apply(toByteBuffer(key, marshaller)); assertTrue(segments.contains(segment)); }); } default <K,V> Set<Map.Entry<K, V>> extractEntries(CloseableIterator<Map.Entry<Object, Object>> iterator) { Set<Map.Entry<K, V>> entries = new HashSet<>(); try { while (iterator.hasNext()) { entries.add((Map.Entry<K, V>) iterator.next()); } } finally { iterator.close(); } return entries; } }
3,273
32.752577
120
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/iteration/MultiServerObjectStoreTest.java
package org.infinispan.client.hotrod.impl.iteration; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import java.util.Map; import java.util.Set; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.test.MultiHotRodServersTest; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.iteration.MultiServerObjectStoreTest") public class MultiServerObjectStoreTest extends MultiHotRodServersTest implements AbstractRemoteIteratorTest { private static final int NUM_SERVERS = 2; private static final int CACHE_SIZE = 10; @Override protected void createCacheManagers() throws Throwable { createHotRodServers(NUM_SERVERS, getCacheConfiguration()); } private org.infinispan.configuration.cache.ConfigurationBuilder getCacheConfiguration() { ConfigurationBuilder builder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false)); builder.clustering().hash().numSegments(60).numOwners(1); builder.encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE); builder.encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE); return builder; } @Test public void testIteration() { RemoteCache<Integer, String> remoteCache = clients.get(0).getCache(); populateCache(CACHE_SIZE, i -> "value", remoteCache); Set<Map.Entry<Object, Object>> entries = extractEntries(remoteCache.retrieveEntries(null, 5)); assertEquals(CACHE_SIZE, entries.size()); } }
1,806
40.068182
122
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/iteration/MultiServerDistRemoteIteratorTest.java
package org.infinispan.client.hotrod.impl.iteration; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import java.net.InetSocketAddress; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.commons.util.Closeables; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.dsl.embedded.testdomain.hsearch.AccountHS; import org.infinispan.test.TestingUtil; import org.mockito.Mockito; import org.reactivestreams.Publisher; import org.testng.annotations.Test; import io.reactivex.rxjava3.core.Flowable; /** * @author gustavonalle * @since 8.0 */ @Test(groups = "functional", testName = "client.hotrod.iteration.MultiServerDistRemoteIteratorTest") public class MultiServerDistRemoteIteratorTest extends BaseMultiServerRemoteIteratorTest { private static final int NUM_SERVERS = 3; @Override protected void createCacheManagers() throws Throwable { createHotRodServers(NUM_SERVERS, getCacheConfiguration()); } private ConfigurationBuilder getCacheConfiguration() { ConfigurationBuilder builder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false)); builder.clustering().hash().numSegments(60).numOwners(2); return builder; } private static class TestSegmentKeyTracker implements KeyTracker { final IntSet finished = IntSets.mutableEmptySet(); @Override public boolean track(byte[] key, short status, ClassAllowList allowList) { return true; } @Override public void segmentsFinished(IntSet finishedSegments) { finished.addAll(finishedSegments); } @Override public Set<Integer> missedSegments() { return null; } } public void testSegmentFinishedCallback() { RemoteCache<Integer, AccountHS> cache = clients.get(0).getCache(); populateCache(CACHE_SIZE, this::newAccount, cache); TestSegmentKeyTracker testSegmentKeyTracker = new TestSegmentKeyTracker(); Publisher<Map.Entry<Integer, AccountHS>> publisher = cache.publishEntries(null, null, null, 3); try (CloseableIterator<Map.Entry<Integer, AccountHS>> iterator = Closeables.iterator(publisher, 3)) { TestingUtil.replaceField(testSegmentKeyTracker, "segmentKeyTracker", publisher, RemotePublisher.class); while (iterator.hasNext()) iterator.next(); assertEquals(60, testSegmentKeyTracker.finished.size()); } } @Override protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(String host, int serverPort) { org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServer() .host("localhost") .port(serverPort) .maxRetries(maxRetries()) .balancingStrategy(() -> new PreferredServerBalancingStrategy(new InetSocketAddress("localhost", serverPort))); return clientBuilder; } @Test public void testIterationRouting() throws Exception { for (int i = 0; i < clients.size(); i++) { int clientOffset = i; RemoteCacheManager client = client(i); KeyTracker segmentKeyTracker = Mockito.mock(KeyTracker.class); Mockito.when(segmentKeyTracker.track(Mockito.any(), Mockito.anyShort(), Mockito.any())) .then(invocation -> { assertIterationActiveOnlyOnServer(clientOffset); return invocation.callRealMethod(); }); Publisher<Map.Entry<Object, Object>> publisher = client.getCache().publishEntries(null, null, null, 10); TestingUtil.replaceField(segmentKeyTracker, "segmentKeyTracker", publisher, RemotePublisher.class); Flowable.fromPublisher(publisher) .lastStage(null) .toCompletableFuture() .get(10, TimeUnit.SECONDS); } } private void assertIterationActiveOnlyOnServer(int index) { for (int i = 0; i < servers.size(); i++) { int activeIterations = server(i).getIterationManager().activeIterations(); if (i == index) { assertEquals(1L, activeIterations); } else { assertEquals(0L, activeIterations); } } } }
4,903
37.614173
146
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/iteration/SingleServerRemoteIteratorTest.java
package org.infinispan.client.hotrod.impl.iteration; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.Assert.assertFalse; import static org.testng.AssertJUnit.assertEquals; import java.util.Collections; import java.util.HashSet; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.InternalRemoteCacheManager; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.filter.AbstractKeyValueFilterConverter; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.metadata.Metadata; import org.infinispan.query.dsl.embedded.DslSCI; import org.infinispan.query.dsl.embedded.testdomain.hsearch.AccountHS; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * @author gustavonalle * @since 8.0 */ @Test(groups = "functional", testName = "client.hotrod.iteration.SingleServerRemoteIteratorTest") public class SingleServerRemoteIteratorTest extends SingleHotRodServerTest implements AbstractRemoteIteratorTest { public static final String FILTER_CONVERTER_FACTORY_NAME = "even-accounts-descriptions"; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.createCacheManager(DslSCI.INSTANCE, hotRodCacheConfiguration()); } @Override protected RemoteCacheManager getRemoteCacheManager() { ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); builder.addServer().host("127.0.0.1").port(hotrodServer.getPort()).addContextInitializer(DslSCI.INSTANCE); return new InternalRemoteCacheManager(builder.build()); } @Test public void testEmptyCache() { try (CloseableIterator<Entry<Object, Object>> iterator = remoteCacheManager.getCache().retrieveEntries(null, null, 100)) { assertFalse(iterator.hasNext()); } } @Test public void testEmptySegments() { populateCache(1, i -> "value " + i, remoteCacheManager.getCache()); try (CloseableIterator<Entry<Object, Object>> iterator = remoteCacheManager.getCache().retrieveEntries(null, Collections.emptySet(), 100)) { assertFalse(iterator.hasNext()); } } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN006016.*") public void testEmptyFilter() { try (CloseableIterator<Entry<Object, Object>> iterator = remoteCacheManager.getCache().retrieveEntries("", null, 100)) { assertFalse(iterator.hasNext()); } } @Test(expectedExceptions = NoSuchElementException.class) public void testException1() { CloseableIterator<Entry<Object, Object>> iterator = null; try { iterator = remoteCacheManager.getCache().retrieveEntries(null, null, 100); iterator.next(); } finally { if (iterator != null) { iterator.close(); } } } @Test(expectedExceptions = NoSuchElementException.class) public void testException2() { populateCache(3, i -> "value " + i, remoteCacheManager.getCache()); CloseableIterator<Entry<Object, Object>> iterator = remoteCacheManager.getCache().retrieveEntries(null, null, 100); iterator.close(); iterator.next(); } public void testResultsSingleFetch() { RemoteCache<Integer, String> cache = remoteCacheManager.getCache(); populateCache(3, i -> "value " + i, cache); Set<Entry<Object, Object>> entries = new HashSet<>(); try (CloseableIterator<Entry<Object, Object>> iterator = cache.retrieveEntries(null, null, 5)) { entries.add(iterator.next()); entries.add(iterator.next()); entries.add(iterator.next()); } Set<Integer> keys = extractKeys(entries); Set<String> values = extractValues(entries); assertEquals(keys, setOf(0, 1, 2)); assertEquals(values, setOf("value 0", "value 1", "value 2")); } public void testResultsMultipleFetches() { RemoteCache<Integer, String> cache = remoteCacheManager.getCache(); int cacheSize = 100; populateCache(cacheSize, i -> "value " + i, cache); Set<Entry<Object, Object>> entries = new HashSet<>(); try (CloseableIterator<Entry<Object, Object>> iterator = cache.retrieveEntries(null, null, 5)) { while (iterator.hasNext()) { entries.add(iterator.next()); } } Set<Integer> keys = extractKeys(entries); assertEquals(rangeAsSet(0, cacheSize), keys); } public void testEntities() { RemoteCache<Integer, AccountHS> cache = remoteCacheManager.getCache(); int cacheSize = 50; populateCache(cacheSize, this::newAccount, cache); Set<Entry<Object, Object>> entries = new HashSet<>(); try (CloseableIterator<Entry<Object, Object>> iterator = cache.retrieveEntries(null, null, 5)) { while (iterator.hasNext()) { entries.add(iterator.next()); } } assertEquals(cacheSize, entries.size()); Set<AccountHS> values = extractValues(entries); assertForAll(values, v -> v != null); assertForAll(values, v -> v.getId() < cacheSize); } public void testFilterConverter() { hotrodServer.addKeyValueFilterConverterFactory(FILTER_CONVERTER_FACTORY_NAME, () -> new AbstractKeyValueFilterConverter<Integer, AccountHS, String>() { @Override public String filterAndConvert(Integer key, AccountHS value, Metadata metadata) { if (!(key % 2 == 0)) { return null; } return value.getDescription(); } }); RemoteCache<Integer, AccountHS> cache = remoteCacheManager.getCache(); int cacheSize = 50; populateCache(cacheSize, this::newAccount, cache); Set<Entry<Object, Object>> entries = new HashSet<>(); try (CloseableIterator<Entry<Object, Object>> iterator = cache.retrieveEntries(FILTER_CONVERTER_FACTORY_NAME, null, 5)) { while (iterator.hasNext()) { entries.add(iterator.next()); } } assertEquals(cacheSize / 2, entries.size()); Set<Integer> keys = extractKeys(entries); assertForAll(keys, v -> v % 2 == 0); } }
6,791
35.913043
146
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/iteration/BaseIterationFailOverTest.java
package org.infinispan.client.hotrod.impl.iteration; import static org.testng.AssertJUnit.assertEquals; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.MultiHotRodServersTest; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.dsl.embedded.DslSCI; import org.infinispan.query.dsl.embedded.testdomain.hsearch.AccountHS; import org.testng.annotations.Test; /** * @author gustavonalle * @since 8.0 */ public abstract class BaseIterationFailOverTest extends MultiHotRodServersTest implements AbstractRemoteIteratorTest { protected final int SERVERS = 3; @Override protected void createCacheManagers() throws Throwable { createHotRodServers(SERVERS, getCacheConfiguration()); } @Override protected SerializationContextInitializer contextInitializer() { return DslSCI.INSTANCE; } public abstract ConfigurationBuilder getCacheConfiguration(); @Override protected int maxRetries() { // We kill one node in many tests - let it failover in that case return 1; } @Test(groups = "functional") public void testFailOver() throws InterruptedException { int cacheSize = 1_000; int batch = 17; RemoteCache<Integer, AccountHS> cache = clients.get(0).getCache(); populateCache(cacheSize, this::newAccount, cache); List<Map.Entry<Object, Object>> entries = new ArrayList<>(); CloseableIterator<Map.Entry<Object, Object>> iterator = cache.retrieveEntries(null, null, batch); for (int i = 0; i < cacheSize / 2; i++) { Map.Entry<Object, Object> next = iterator.next(); entries.add(next); } killAnIterationServer(); while (iterator.hasNext()) { Map.Entry<Object, Object> next = iterator.next(); entries.add(next); } assertEquals(cacheSize, entries.size()); Set<Integer> keys = extractKeys(entries); assertEquals(rangeAsSet(0, cacheSize), keys); } protected void killAnIterationServer() { servers.stream() .filter(s -> s.getIterationManager().activeIterations() > 0) .findFirst().ifPresent(HotRodClientTestingUtil::killServers); } }
2,515
30.45
118
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/iteration/DistFailOverRemoteIteratorTest.java
package org.infinispan.client.hotrod.impl.iteration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author gustavonalle * @since 8.0 */ @Test(groups = "functional", testName = "client.hotrod.iteration.DistFailOverRemoteIteratorTest") public class DistFailOverRemoteIteratorTest extends BaseIterationFailOverTest { @Override public ConfigurationBuilder getCacheConfiguration() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } }
584
28.25
97
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/transport/netty/CloseBeforeEnqueuingTest.java
package org.infinispan.client.hotrod.impl.transport.netty; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertTrue; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.operations.RetryOnFailureOperation; import org.infinispan.client.hotrod.impl.protocol.CodecHolder; import org.infinispan.client.hotrod.retry.AbstractRetryTest; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.InternalRemoteCacheManager; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.annotations.Test; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; @CleanupAfterMethod @Test(testName = "client.hotrod.impl.transport.netty.CloseBeforeEnqueuingTest", groups = "functional") public class CloseBeforeEnqueuingTest extends AbstractRetryTest { @Override protected ConfigurationBuilder getCacheConfig() { ConfigurationBuilder builder = hotRodCacheConfiguration( getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false)); builder.clustering().hash().numOwners(1); return builder; } protected RemoteCacheManager createRemoteCacheManager(int port) { org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); amendRemoteCacheManagerConfiguration(builder); builder .forceReturnValues(true) .connectionTimeout(5) .connectionPool().maxActive(1) // This ensures that only one server is active at a time .addServer().host("127.0.0.1").port(port); Configuration configuration = builder.build(); RemoteCacheManager remoteCacheManager = new InternalRemoteCacheManager(configuration, new CustomChannelFactory(configuration)); remoteCacheManager.start(); return remoteCacheManager; } public void testClosingAndEnqueueing() throws Exception { ChannelFactory channelFactory = remoteCacheManager.getChannelFactory(); InetSocketAddress address = InetSocketAddress.createUnresolved(hotRodServer1.getHost(), hotRodServer1.getPort()); CountDownLatch operationLatch = new CountDownLatch(1); AtomicReference<Channel> channelRef = new AtomicReference<>(); ExecutorService operationsExecutor = Executors.newSingleThreadExecutor(); NoopRetryingOperation firstOperation = new NoopRetryingOperation(0, channelFactory, remoteCacheManager.getConfiguration(), channelRef, operationLatch); operationsExecutor.submit(() -> channelFactory.fetchChannelAndInvoke(address, firstOperation)); eventually(() -> channelRef.get() != null); Channel channel = channelRef.get(); assertTrue(channelFactory instanceof CustomChannelFactory); AtomicBoolean closedServer = new AtomicBoolean(false); ((CustomChannelFactory) channelFactory).setExecuteInstead(() -> { HotRodClientTestingUtil.killServers(hotRodServer1); eventually(() -> !channel.isActive()); eventually(() -> channelFactory.getNumActive(address) == 0); return !closedServer.compareAndSet(false, true); }); operationLatch.countDown(); NoopRetryingOperation secondOperation = new NoopRetryingOperation(0, channelFactory, remoteCacheManager.getConfiguration(), channelRef, null); operationsExecutor.submit(() -> channelFactory.fetchChannelAndInvoke(address, secondOperation)); secondOperation.get(10, TimeUnit.SECONDS); operationsExecutor.shutdownNow(); } private static class NoopRetryingOperation extends RetryOnFailureOperation<Void> { private final AtomicReference<Channel> channelRef; private final CountDownLatch firstOp; private final int id; protected NoopRetryingOperation(int nbr, ChannelFactory channelFactory, Configuration cfg, AtomicReference<Channel> channelRef, CountDownLatch firstOp) { super((short) 0, (short) 0, null, channelFactory, null, new AtomicReference<>(new ClientTopology(-1, cfg.clientIntelligence())), 0, cfg, DataFormat.builder().build(), null); this.channelRef = channelRef; this.firstOp = firstOp; this.id = nbr; } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { complete(null); } @Override protected void executeOperation(Channel channel) { if (channelRef.compareAndSet(null, channel)) { try { scheduleRead(channel); firstOp.await(); } catch (InterruptedException e) { completeExceptionally(e); } assert isDone() : "Should be done"; return; } complete(null); } @Override public String toString() { return "id = " + id; } } private static class CustomChannelFactory extends ChannelFactory { private final Configuration configuration; private Supplier<Boolean> executeInstead; public CustomChannelFactory(Configuration cfg) { super(new CodecHolder(cfg.version().getCodec())); this.configuration = cfg; this.executeInstead = null; } public void setExecuteInstead(Supplier<Boolean> supplier) { this.executeInstead = supplier; } @Override protected ChannelPool createChannelPool(Bootstrap bootstrap, ChannelInitializer channelInitializer, SocketAddress address) { int maxConnections = configuration.connectionPool().maxActive(); if (maxConnections < 0) { maxConnections = Integer.MAX_VALUE; } return new ChannelPool(bootstrap.config().group().next(), address, channelInitializer, configuration.connectionPool().exhaustedAction(), this::onConnectionEvent, configuration.connectionPool().maxWait(), maxConnections, configuration.connectionPool().maxPendingRequests()) { @Override boolean executeDirectlyIfPossible(ChannelOperation callback) { if (executeInstead != null && !executeInstead.get()) { return false; } return super.executeDirectlyIfPossible(callback); } }; } } }
7,200
40.624277
133
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/transport/netty/CrashMidOperationTest.java
package org.infinispan.client.hotrod.impl.transport.netty; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertTrue; import java.net.ConnectException; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.exceptions.TransportException; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.operations.RetryOnFailureOperation; import org.infinispan.client.hotrod.retry.AbstractRetryTest; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.annotations.Test; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; @CleanupAfterMethod @Test(testName = "client.hotrod.impl.transport.netty.CrashMidOperationTest", groups = "functional") public class CrashMidOperationTest extends AbstractRetryTest { @Override protected ConfigurationBuilder getCacheConfig() { ConfigurationBuilder builder = hotRodCacheConfiguration( getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false)); builder.clustering().hash().numOwners(1); return builder; } @Override protected void amendRemoteCacheManagerConfiguration(org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder) { builder.maxRetries(0); } public void killServerMidOperation() throws Exception { ChannelFactory channelFactory = remoteCacheManager.getChannelFactory(); InetSocketAddress address = InetSocketAddress.createUnresolved(hotRodServer1.getHost(), hotRodServer1.getPort()); CountDownLatch operationLatch = new CountDownLatch(1); AtomicReference<Channel> channelRef = new AtomicReference<>(); ExecutorService operationsExecutor = Executors.newFixedThreadPool(2); NoopRetryingOperation firstOperation = new NoopRetryingOperation(0, channelFactory, remoteCacheManager.getConfiguration(), channelRef, operationLatch); operationsExecutor.submit(() -> channelFactory.fetchChannelAndInvoke(address, firstOperation)); eventually(() -> channelRef.get() != null); Channel channel = channelRef.get(); HotRodClientTestingUtil.killServers(hotRodServer1); eventually(() -> !channel.isActive()); eventually(firstOperation::isDone); Exceptions.expectExecutionException(TransportException.class, firstOperation); // Since the first operation failed midway execution, we don't know if the server has failed or only the channel. // The second operation will try to connect and fail, and then update the failed list. NoopRetryingOperation secondOperation = new NoopRetryingOperation(1, channelFactory, remoteCacheManager.getConfiguration(), channelRef, operationLatch); channelFactory.fetchChannelAndInvoke(address, remoteCache.getName().getBytes(StandardCharsets.UTF_8), secondOperation); eventually(secondOperation::isDone); try { secondOperation.get(10, TimeUnit.SECONDS); } catch (Throwable t) { assertTrue(t.getCause() instanceof ConnectException); } // We only release the latch now, but notice that all the other operations were able to finish. operationLatch.countDown(); // The failed list was update, the next operation should succeed. NoopRetryingOperation thirdOperation = new NoopRetryingOperation(2, channelFactory, remoteCacheManager.getConfiguration(), channelRef, operationLatch); channelFactory.fetchChannelAndInvoke(address, remoteCache.getName().getBytes(StandardCharsets.UTF_8), thirdOperation); eventually(thirdOperation::isDone); thirdOperation.get(10, TimeUnit.SECONDS); operationsExecutor.shutdown(); } private static class NoopRetryingOperation extends RetryOnFailureOperation<Void> { private final AtomicReference<Channel> channelRef; private final CountDownLatch firstOp; private final int id; protected NoopRetryingOperation(int nbr, ChannelFactory channelFactory, Configuration cfg, AtomicReference<Channel> channelRef, CountDownLatch firstOp) { super((short) 0, (short) 0, null, channelFactory, null, new AtomicReference<>(new ClientTopology(-1, cfg.clientIntelligence())), 0, cfg, DataFormat.builder().build(), null); this.channelRef = channelRef; this.firstOp = firstOp; this.id = nbr; } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { complete(null); } @Override protected void executeOperation(Channel channel) { if (channelRef.compareAndSet(null, channel)) { try { scheduleRead(channel); firstOp.await(); } catch (InterruptedException e) { completeExceptionally(e); } assert isDone() : "Should be done"; return; } try { firstOp.await(); complete(null); } catch (InterruptedException e) { completeExceptionally(e); } } @Override public String toString() { return "id = " + id; } } }
5,884
41.035714
129
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/transport/netty/ChannelPoolTest.java
package org.infinispan.client.hotrod.impl.transport.netty; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import java.net.ConnectException; import java.net.InetSocketAddress; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.operations.RetryOnFailureOperation; import org.infinispan.client.hotrod.retry.AbstractRetryTest; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.util.concurrent.AggregateCompletionStage; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.Test; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; @CleanupAfterMethod @Test(groups = "functional", testName = "client.hotrod.impl.transport.netty.ChannelPoolTest") public class ChannelPoolTest extends AbstractRetryTest { private int retries = 0; public ChannelPoolTest() {} public ChannelPoolTest(int nbrOfServers) { this.nbrOfServers = nbrOfServers; } @Override protected ConfigurationBuilder getCacheConfig() { ConfigurationBuilder builder = hotRodCacheConfiguration( getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false)); builder.clustering().hash().numOwners(1); return builder; } @Override protected void amendRemoteCacheManagerConfiguration(org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder) { builder.maxRetries(retries); } public void testClosingSockAndKillingServerFinishesOperations() throws Exception { doTest(true); } public void testClosingSockAndKeepingServerFinishesOperations() throws Exception { doTest(false); } private void doTest(boolean killServer) throws Exception { ChannelFactory channelFactory = remoteCacheManager.getChannelFactory(); InetSocketAddress address = InetSocketAddress.createUnresolved(hotRodServer1.getHost(), hotRodServer1.getPort()); AggregateCompletionStage<Void> pendingOperations = CompletionStages.aggregateCompletionStage(); AtomicReference<Channel> channelRef = new AtomicReference<>(); CountDownLatch firstOp = new CountDownLatch(1); ExecutorService operationsExecutor = Executors.newFixedThreadPool(2); // The fist operation blocks. for (int i = 0; i < 10; i++) { NoopRetryingOperation op = new NoopRetryingOperation(i, channelFactory, remoteCacheManager.getConfiguration(), channelRef, firstOp); operationsExecutor.submit(() -> channelFactory.fetchChannelAndInvoke(address, op)); pendingOperations.dependsOn(op); } eventually(() -> channelRef.get() != null); Channel channel = channelRef.get(); if (killServer) HotRodClientTestingUtil.killServers(hotRodServer1); channel.close().awaitUninterruptibly(); // The first one completes successfully on server1. firstOp.countDown(); if (nbrOfServers == 1 && killServer) { assertConnectException(pendingOperations); operationsExecutor.shutdown(); return; } if (retries == 0 && killServer) { assertConnectException(pendingOperations); operationsExecutor.shutdown(); return; } pendingOperations.freeze().toCompletableFuture().get(10, TimeUnit.SECONDS); operationsExecutor.shutdown(); } private void assertConnectException(AggregateCompletionStage<Void> ops) { try { ops.freeze().toCompletableFuture().get(10, TimeUnit.SECONDS); } catch (Exception e) { Throwable cause = e.getCause(); if (cause instanceof ConnectException) { return; } throw new AssertionError("Expected ConnectException, but got " + cause, cause); } } private static class NoopRetryingOperation extends RetryOnFailureOperation<Void> { private final AtomicReference<Channel> channelRef; private final CountDownLatch firstOp; private final int id; protected NoopRetryingOperation(int nbr, ChannelFactory channelFactory, Configuration cfg, AtomicReference<Channel> channelRef, CountDownLatch firstOp) { super((short) 0, (short) 0, null, channelFactory, null, new AtomicReference<>(new ClientTopology(-1, cfg.clientIntelligence())), 0, cfg, DataFormat.builder().build(), null); this.channelRef = channelRef; this.firstOp = firstOp; this.id = nbr; } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { complete(null); } @Override protected void executeOperation(Channel channel) { if (channelRef.compareAndSet(null, channel)) { try { firstOp.await(); complete(null); } catch (InterruptedException e) { completeExceptionally(e); } } else { complete(null); } } @Override public String toString() { return "id = " + id; } } private ChannelPoolTest withRetries(int retries) { this.retries = retries; return this; } @Override protected String parameters() { return "[retries=" + retries + ", nbrServers=" + nbrOfServers + "]"; } @Override public Object[] factory() { return new Object[] { new ChannelPoolTest().withRetries(0), new ChannelPoolTest(1).withRetries(0), new ChannelPoolTest().withRetries(10), new ChannelPoolTest(1).withRetries(10), }; } }
6,163
34.425287
141
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/transport/netty/NativeTransportTest.java
package org.infinispan.client.hotrod.impl.transport.netty; import static org.testng.AssertJUnit.assertTrue; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.layout.PatternLayout; import org.infinispan.commons.test.skip.OS; import org.infinispan.commons.test.skip.SkipTestNG; import org.infinispan.commons.test.skip.StringLogAppender; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.CherryPickClassLoader; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.impl.transport.netty.NativeTransportTest") public class NativeTransportTest extends AbstractInfinispanTest { public static final String NATIVE_TRANSPORT_CLASS = "org.infinispan.client.hotrod.impl.transport.netty.NativeTransport"; public static final String LOG_FORMAT = "%-5p (%t) [%c{1}] %m%throwable{10}%n"; public void testEpollNotAvailable() throws Exception { SkipTestNG.onlyOnOS(OS.LINUX); Thread testThread = Thread.currentThread(); StringLogAppender logAppender = new StringLogAppender("org.infinispan.HOTROD", Level.TRACE, t -> t == testThread, PatternLayout.newBuilder().withPattern(LOG_FORMAT).build()); logAppender.install(); try { CherryPickClassLoader classLoader = new CherryPickClassLoader( new String[]{NATIVE_TRANSPORT_CLASS}, null, new String[]{"io.netty.channel.epoll.Epoll"}, this.getClass().getClassLoader() ); Class.forName(NATIVE_TRANSPORT_CLASS, true, classLoader); String firstLine = logAppender.getLog(0); assertTrue(firstLine, firstLine.contains("io.netty.channel.epoll.Epoll")); } finally { logAppender.uninstall(); } } }
1,797
42.853659
123
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/impl/transport/netty/TestChannelFactory.java
package org.infinispan.client.hotrod.impl.transport.netty; import java.net.SocketAddress; import org.infinispan.client.hotrod.impl.protocol.CodecHolder; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.handler.codec.FixedLengthFrameDecoder; public class TestChannelFactory extends ChannelFactory { public TestChannelFactory(CodecHolder codecHolder) { super(codecHolder); } @Override public ChannelInitializer createChannelInitializer(SocketAddress address, Bootstrap bootstrap) { return new ChannelInitializer(bootstrap, address, getOperationsFactory(), getConfiguration(), this) { @Override protected void initChannel(Channel channel) throws Exception { super.initChannel(channel); channel.pipeline().addFirst("1frame", new FixedLengthFrameDecoder(1)); } }; } }
889
31.962963
107
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/transcoding/DataFormatIndexedTest.java
package org.infinispan.client.hotrod.transcoding; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Tests for the Hot Rod client using multiple data formats with indexing enabled * * @since 9.3 */ @Test(groups = "functional", testName = "client.hotrod.transcoding.DataFormatIndexedTest") public class DataFormatIndexedTest extends DataFormatTest { @Override protected ConfigurationBuilder buildCacheConfig() { ConfigurationBuilder parentBuilder = hotRodCacheConfiguration(); parentBuilder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntities("org.infinispan.test.client.DataFormatTest.ComplexValue"); return parentBuilder; } }
916
34.269231
91
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/transcoding/DataFormatTest.java
package org.infinispan.client.hotrod.transcoding; import static java.nio.charset.StandardCharsets.UTF_8; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withClientListener; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM; import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.infinispan.test.fwk.TestCacheManagerFactory.createServerModeCacheManager; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.event.EventLogListener; import org.infinispan.client.hotrod.event.EventLogListener.RawStaticFilteredEventLogListener; import org.infinispan.client.hotrod.event.EventLogListener.StaticFilteredEventLogListener; import org.infinispan.client.hotrod.query.RemoteQueryTestUtils; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.io.ByteBuffer; import org.infinispan.commons.io.ByteBufferImpl; import org.infinispan.commons.marshall.AbstractMarshaller; import org.infinispan.commons.marshall.IdentityMarshaller; import org.infinispan.commons.marshall.UTF8StringMarshaller; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoDoc; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.testng.annotations.Test; /** * Tests for the Hot Rod client using multiple data formats when interacting with the server. * * @since 9.3 */ @Test(groups = "functional", testName = "client.hotrod.transcoding.DataFormatTest") public class DataFormatTest extends SingleHotRodServerTest { private static final String CACHE_NAME = "test"; private RemoteCache<Object, Object> remoteCache; protected ConfigurationBuilder buildCacheConfig() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.encoding().key().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); builder.encoding().value().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); return builder; } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { cacheManager = createServerModeCacheManager(contextInitializer(), hotRodCacheConfiguration()); cacheManager.defineConfiguration(CACHE_NAME, hotRodCacheConfiguration(buildCacheConfig()).build()); return cacheManager; } @Override protected HotRodServer createHotRodServer() { HotRodServer server = HotRodClientTestingUtil.startHotRodServer(cacheManager, new HotRodServerConfigurationBuilder()); server.addCacheEventFilterFactory("static-filter-factory", new EventLogListener.StaticCacheEventFilterFactory<>(42)); server.addCacheEventFilterFactory("raw-static-filter-factory", new EventLogListener.RawStaticCacheEventFilterFactory()); return server; } @Override protected SerializationContextInitializer contextInitializer() { return SCI.INSTANCE; } @Override protected void setup() throws Exception { super.setup(); remoteCache = remoteCacheManager.getCache(CACHE_NAME); } @Test public void testValueInMultipleFormats() throws Exception { remoteCache.clear(); String quote = "I find your lack of faith disturbing"; byte[] protostreamMarshalledQuote = marshall(quote); // Write to the cache using the default marshaller remoteCache.put(1, quote); // Read it back as raw bytes using the same key Object asBinary = remoteCache.withDataFormat(DataFormat.builder().valueMarshaller(IdentityMarshaller.INSTANCE).build()).get(1); assertArrayEquals(protostreamMarshalledQuote, ((byte[]) asBinary)); // Read it back as UTF-8 byte[] using the same key Object asUTF8 = remoteCache .withDataFormat(DataFormat.builder().valueType(TEXT_PLAIN).valueMarshaller(IdentityMarshaller.INSTANCE).build()) .get(1); assertArrayEquals(quote.getBytes(UTF_8), (byte[]) asUTF8); // Read it back as String using the default marshaller for text/plain Object asString = remoteCache.withDataFormat(DataFormat.builder().valueType(TEXT_PLAIN).build()).get(1); assertEquals(quote, asString); // Same, but with metadata MetadataValue<Object> metadataValue = remoteCache .withDataFormat(DataFormat.builder().valueType(TEXT_PLAIN).build()) .getWithMetadata(1); assertEquals(quote, metadataValue.getValue()); // Get all entries avoiding de-serialization Map<Object, Object> allEntries = remoteCache .withDataFormat(DataFormat.builder().valueMarshaller(IdentityMarshaller.INSTANCE).build()) .getAll(new HashSet<>(Collections.singletonList(1))); assertArrayEquals(protostreamMarshalledQuote, (byte[]) allEntries.get(1)); // Read value as JSON in the byte[] form, using the same key Json expectedJson = Json.object("_type", "string").set("_value", quote); Object asJSon = remoteCache.withDataFormat(DataFormat.builder().valueType(APPLICATION_JSON).build()).get(1); assertEquals(expectedJson, Json.read(new String((byte[]) asJSon))); Json asJsonNode = (Json) remoteCache .withDataFormat(DataFormat.builder().valueType(APPLICATION_JSON).valueMarshaller(new JsonMarshaller()).build()) .get(1); assertEquals(expectedJson, asJsonNode); // Iterate values without unmarshalling Object raw = remoteCache .withDataFormat(DataFormat.builder().valueType(APPLICATION_PROTOSTREAM).valueMarshaller(IdentityMarshaller.INSTANCE).build()) .values().iterator().next(); assertArrayEquals(protostreamMarshalledQuote, ((byte[]) raw)); // Iterate values converting to JsonNode objects asJsonNode = (Json) remoteCache .withDataFormat(DataFormat.builder().valueType(APPLICATION_JSON).valueMarshaller(new JsonMarshaller()).build()) .values().iterator().next(); assertEquals(expectedJson, asJsonNode); } @Test public void testKeysInMultipleFormats() throws Exception { remoteCache.clear(); String value = "infinispan.org:8080"; // Write using String using default Marshaller remoteCache.put("1", value); assertEquals(value, remoteCache.get("1")); // Use UTF-8 key directly as byte[], bypassing the marshaller. remoteCache.withDataFormat(DataFormat.builder().keyType(TEXT_PLAIN).keyMarshaller(IdentityMarshaller.INSTANCE).build()) .put("utf-key".getBytes(), value); assertEquals(value, remoteCache.get("utf-key")); // Use UTF-8 key with the default UTF8Marshaller RemoteCache<Object, Object> remoteCacheUTFKey = this.remoteCache.withDataFormat(DataFormat.builder().keyType(TEXT_PLAIN).build()); remoteCache.put("temp-key", value); assertTrue(remoteCacheUTFKey.containsKey("temp-key")); remoteCacheUTFKey.remove("temp-key"); assertFalse(remoteCacheUTFKey.containsKey("temp-key")); assertEquals(value, remoteCacheUTFKey.get("1")); // Read value as UTF-8 using a UTF-8 key Object asString = this.remoteCache .withDataFormat(DataFormat.builder().keyType(TEXT_PLAIN).valueType(TEXT_PLAIN).build()) .get("1"); assertEquals(asString, "infinispan.org:8080"); // Write using manually marshalled values remoteCache.withDataFormat(DataFormat.builder() .keyType(APPLICATION_PROTOSTREAM).keyMarshaller(IdentityMarshaller.INSTANCE) .valueType(APPLICATION_PROTOSTREAM).valueMarshaller(IdentityMarshaller.INSTANCE) .build()) .put(marshall(1024), marshall(value)); assertEquals(value, this.remoteCache.get(1024)); // Remove using UTF-8 values boolean removed = this.remoteCache .withDataFormat(DataFormat.builder().valueType(TEXT_PLAIN).build()) .remove(1024, "wrong-address.com"); assertFalse(removed); removed = this.remoteCache .withDataFormat(DataFormat.builder().valueType(TEXT_PLAIN).build()) .remove(1024, "infinispan.org:8080"); assertTrue(removed); assertFalse(this.remoteCache.containsKey(1024)); } @Test public void testBatchOperations() { remoteCache.clear(); Map<ComplexKey, ComplexValue> entries = new HashMap<>(); IntStream.range(0, 50).forEach(i -> { ComplexKey key = new ComplexKey(String.valueOf(i), (float) i); ComplexValue value = new ComplexValue(Util.threadLocalRandomUUID()); entries.put(key, value); }); remoteCache.putAll(entries); // Read all keys as JSON Strings RemoteCache<String, String> jsonCache = this.remoteCache.withDataFormat(DataFormat.builder() .keyType(APPLICATION_JSON).keyMarshaller(new UTF8StringMarshaller()).build()); Set<String> jsonKeys = new HashSet<>(jsonCache.keySet()); jsonKeys.forEach(k -> assertTrue(k, k.contains("\"_type\":\"org.infinispan.test.client.DataFormatTest.ComplexKey\""))); Map<String, String> newEntries = new HashMap<>(); // Write using JSON IntStream.range(50, 100).forEach(i -> { Json key = Json.object("_type", "org.infinispan.test.client.DataFormatTest.ComplexKey") .set("id", i) .set("ratio", i); Json value = Json.object("_type", "org.infinispan.test.client.DataFormatTest.ComplexValue") .set("uuid", Util.threadLocalRandomUUID().toString()); newEntries.put(key.toString(), value.toString()); }); jsonCache.putAll(newEntries); // Read it back as regular objects Set<ComplexKey> keys = new HashSet<>(); IntStream.range(60, 70).forEach(i -> keys.add(new ComplexKey(String.valueOf(i), (float) i))); Set<ComplexKey> returned = remoteCache.getAll(keys).keySet().stream().map(ComplexKey.class::cast).collect(Collectors.toSet()); assertEquals(keys, returned); } @Test public void testListenersWithDifferentFormats() { remoteCache.clear(); ComplexKey complexKey = new ComplexKey("Key-1", 89.88f); ComplexValue complexValue = new ComplexValue(Util.threadLocalRandomUUID()); // Receive events as JSON Strings DataFormat jsonStringFormat = DataFormat.builder().keyType(APPLICATION_JSON).keyMarshaller(new UTF8StringMarshaller()).build(); EventLogListener<Object> l = new EventLogListener<>(remoteCache.withDataFormat(jsonStringFormat)); withClientListener(l, remote -> { remoteCache.put(complexKey, complexValue); l.expectOnlyCreatedEvent("{\"_type\":\"org.infinispan.test.client.DataFormatTest.ComplexKey\",\"id\":\"Key-1\",\"ratio\":89.88}"); }); } @Test public void testNonRawFilteredListeners() { remoteCache.clear(); RemoteCache<Integer, String> remoteCache = this.remoteCache.withDataFormat(DataFormat.builder().valueType(TEXT_PLAIN).build()); StaticFilteredEventLogListener<Integer> l = new StaticFilteredEventLogListener<>(remoteCache); withClientListener(l, remote -> { remoteCache.put(1, "value1"); l.expectNoEvents(); remoteCache.put(42, "value2"); l.expectOnlyCreatedEvent(42); }); } @Test public void testRawFilteredListeners() { remoteCache.clear(); RemoteCache<Object, Object> jsonCache = this.remoteCache .withDataFormat(DataFormat.builder().keyType(APPLICATION_JSON).keyMarshaller(new UTF8StringMarshaller()).build()); RawStaticFilteredEventLogListener<Object> l = new RawStaticFilteredEventLogListener<>(jsonCache); withClientListener(l, remote -> { jsonCache.put("{\"_type\":\"int32\",\"_value\":1}", Util.threadLocalRandomUUID().toString()); l.expectNoEvents(); jsonCache.put("{\"_type\":\"int32\",\"_value\":2}", Util.threadLocalRandomUUID().toString()); l.expectOnlyCreatedEvent("{\"_type\":\"int32\",\"_value\":2}"); }); } @Test public void testJsonFromDefaultCache() { RemoteCache<String, String> schemaCache = remoteCacheManager.getCache(PROTOBUF_METADATA_CACHE_NAME); schemaCache.put("schema.proto", "message M { optional string json_key = 1; }"); RemoteQueryTestUtils.checkSchemaErrors(schemaCache); DataFormat jsonValues = DataFormat.builder() .valueType(APPLICATION_JSON) .valueMarshaller(new UTF8StringMarshaller()).build(); RemoteCache<Integer, String> cache = remoteCacheManager.getCache().withDataFormat(jsonValues); String value = "{\"_type\":\"M\",\"json_key\":\"json_value\"}"; cache.put(1, value); String valueAsJson = cache.get(1); Json node = Json.read(valueAsJson); assertEquals("json_value", node.at("json_key").asString()); } private byte[] marshall(Object o) throws Exception { return remoteCache.getRemoteCacheContainer().getMarshaller().objectToByteBuffer(o); } @AutoProtoSchemaBuilder( includeClasses = {ComplexKey.class, ComplexValue.class}, schemaFileName = "test.client.DataFormatTest.proto", schemaFilePath = "proto/generated", schemaPackageName = "org.infinispan.test.client.DataFormatTest" ) interface SCI extends SerializationContextInitializer { SCI INSTANCE = new SCIImpl(); } } class JsonMarshaller extends AbstractMarshaller { @Override protected ByteBuffer objectToBuffer(Object o, int estimatedSize) { byte[] bytes = Json.make(o).asString().getBytes(UTF_8); return ByteBufferImpl.create(bytes); } @Override public Object objectFromByteBuffer(byte[] buf, int offset, int length) { return Json.read(new String(buf, offset, length, UTF_8)); } @Override public boolean isMarshallable(Object o) { return true; } @Override public MediaType mediaType() { return APPLICATION_JSON; } } class ComplexKey { @ProtoField(1) String id; @ProtoField(number = 2, defaultValue = "0") Float ratio; @ProtoFactory ComplexKey(String id, Float ratio) { this.id = id; this.ratio = ratio; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ComplexKey that = (ComplexKey) o; return Objects.equals(id, that.id) && Objects.equals(ratio, that.ratio); } @Override public int hashCode() { return Objects.hash(id, ratio); } } @ProtoDoc("@Indexed") class ComplexValue { private UUID uuid; @ProtoFactory ComplexValue(String uuid) { setUuid(uuid); } ComplexValue(UUID uuid) { this.uuid = uuid; } @ProtoField(1) @ProtoDoc("@Field(store = Store.YES)") public String getUuid() { return uuid.toString(); } public void setUuid(String uuid) { this.uuid = UUID.fromString(uuid); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ComplexValue that = (ComplexValue) o; return Objects.equals(uuid, that.uuid); } @Override public int hashCode() { return uuid.hashCode(); } }
16,723
37.983683
139
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/xsite/AbstractHotRodSiteFailoverTest.java
package org.infinispan.client.hotrod.xsite; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.infinispan.Cache; import org.infinispan.client.hotrod.HitsAwareCacheManagersTest.HitCountInterceptor; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.InternalRemoteCacheManager; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.configuration.cache.BackupConfiguration.BackupStrategy; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.infinispan.test.TestingUtil; import org.infinispan.xsite.AbstractXSiteTest; import org.testng.annotations.AfterClass; abstract class AbstractHotRodSiteFailoverTest extends AbstractXSiteTest { static final String SITE_A = "LON-1"; static final String SITE_B = "NYC-2"; static final int NODES_PER_SITE = 2; static final String CACHE_NAME = "testCache"; protected final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); private Map<String, List<HotRodServer>> siteServers = new HashMap<>(); RemoteCacheManager client(String siteName, Optional<String> backupSiteName) { HotRodServer server = siteServers.get(siteName).get(0); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); /* * Use 127.0.0.1 as host address to avoid the first PING after a cluster switch causing an invalidation of the * channel pools just to switch from localhost -> 127.0.0.1. This causes immediately subsequent ops to be * executed twice. */ clientBuilder .addServer().host("127.0.0.1").port(server.getPort()) .maxRetries(3); // Some retries so that shutdown nodes can be skipped clientBuilder.statistics().jmxEnable().jmxName(backupSiteName.orElse("default")).mBeanServerLookup(mBeanServerLookup); clientBuilder.asyncExecutorFactory().addExecutorProperty(ConfigurationProperties.DEFAULT_EXECUTOR_FACTORY_THREADNAME_PREFIX, TestResourceTracker.getCurrentTestShortName()); Optional<Integer> backupPort = backupSiteName.map(name -> { HotRodServer backupServer = siteServers.get(name).get(0); clientBuilder.addCluster(name).addClusterNode("127.0.0.1", backupServer.getPort()); return backupServer.getPort(); }); if (backupPort.isPresent()) log.debugf("Client for site '%s' connecting to main server in port %d, and backup cluster node port is %d", siteName, server.getPort(), backupPort.get()); else log.debugf("Client for site '%s' connecting to main server in port %d", siteName, server.getPort()); return new InternalRemoteCacheManager(clientBuilder.build()); } int findServerPort(String siteName) { return siteServers.get(siteName).get(0).getPort(); } protected void killSite(String siteName) { log.debugf("Kill site '%s' with ports: %s", siteName, siteServers.get(siteName).stream().map(s -> String.valueOf(s.getPort())).collect(Collectors.joining(", "))); siteServers.get(siteName).forEach(HotRodClientTestingUtil::killServers); site(siteName).cacheManagers().forEach(TestingUtil::killCacheManagers); } @Override protected void createSites() { createHotRodSite(SITE_A, SITE_B, Optional.empty()); createHotRodSite(SITE_B, SITE_A, Optional.empty()); } @AfterClass(alwaysRun = true) // run even if the test failed protected void destroy() { try { siteServers.values().forEach(servers -> servers.forEach(HotRodClientTestingUtil::killServers)); siteServers.clear(); } finally { super.destroy(); } } protected void createHotRodSite(String siteName, String backupSiteName, Optional<Integer> serverPort) { ConfigurationBuilder builder = hotRodCacheConfiguration( getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false)); BackupConfigurationBuilder backup = builder.sites().addBackup(); backup.site(backupSiteName).strategy(BackupStrategy.SYNC); GlobalConfigurationBuilder globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); TestSite site = createSite(siteName, NODES_PER_SITE, globalBuilder, CACHE_NAME, builder); Collection<EmbeddedCacheManager> cacheManagers = site.cacheManagers(); List<HotRodServer> servers = cacheManagers.stream().map(cm -> serverPort .map(port -> HotRodClientTestingUtil.startHotRodServer(cm, port, new HotRodServerConfigurationBuilder())) .orElseGet(() -> HotRodClientTestingUtil.startHotRodServer(cm, new HotRodServerConfigurationBuilder()))).collect(Collectors.toList()); siteServers.put(siteName, servers); log.debugf("Create site '%s' with ports: %s", siteName, servers.stream().map(s -> String.valueOf(s.getPort())).collect(Collectors.joining(", "))); } protected void addHitCountInterceptors() { siteServers.forEach((name, servers) -> servers.forEach(server -> { HitCountInterceptor interceptor = new HitCountInterceptor(); server.getCacheManager().getCache(CACHE_NAME).getAdvancedCache().getAsyncInterceptorChain() .addInterceptor(interceptor, 1); }) ); } protected void assertNoHits() { siteServers.forEach((name, servers) -> servers.forEach(server -> { Cache<?, ?> cache = server.getCacheManager().getCache(CACHE_NAME); HitCountInterceptor interceptor = getHitCountInterceptor(cache); assertEquals(0, interceptor.getHits()); }) ); } protected void resetHitCounters() { siteServers.forEach((name, servers) -> servers.forEach(server -> { Cache<?, ?> cache = server.getCacheManager().getCache(CACHE_NAME); HitCountInterceptor interceptor = getHitCountInterceptor(cache); interceptor.reset(); }) ); } protected void assertSiteHit(String siteName, int expectedHits) { Stream<HotRodServer> serversHit = siteServers.get(siteName).stream().filter(server -> { Cache<?, ?> cache = server.getCacheManager().getCache(CACHE_NAME); HitCountInterceptor interceptor = getHitCountInterceptor(cache); return interceptor.getHits() == expectedHits; }); assertEquals(1, serversHit.count()); } protected void assertSiteNotHit(String siteName) { siteServers.get(siteName).forEach(server -> { Cache<?, ?> cache = server.getCacheManager().getCache(CACHE_NAME); HitCountInterceptor interceptor = getHitCountInterceptor(cache); assertEquals(0, interceptor.getHits()); }); } protected HitCountInterceptor getHitCountInterceptor(Cache<?, ?> cache) { return cache.getAdvancedCache().getAsyncInterceptorChain().findInterceptorWithClass(HitCountInterceptor.class); } }
7,911
44.211429
178
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/xsite/SiteManualSwitchTest.java
package org.infinispan.client.hotrod.xsite; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.remoteCacheManagerObjectName; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.Optional; import javax.management.MBeanServer; import javax.management.ObjectName; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.xsite.SiteManualSwitchTest") public class SiteManualSwitchTest extends AbstractHotRodSiteFailoverTest { private RemoteCacheManager clientA; private RemoteCacheManager clientB; @Override protected void createSites() { super.createSites(); addHitCountInterceptors(); } @AfterMethod(alwaysRun = true) public void killClients() { HotRodClientTestingUtil.killRemoteCacheManagers(clientA, clientB); } public void testManualClusterSwitch() { clientA = client(SITE_A, Optional.of(SITE_B)); clientB = client(SITE_B, Optional.empty()); RemoteCache<Integer, String> cacheA = clientA.getCache(CACHE_NAME); RemoteCache<Integer, String> cacheB = clientB.getCache(CACHE_NAME); assertNoHits(); assertSingleSiteHit(SITE_A, SITE_B, () -> assertNull(cacheA.put(1, "v1"))); assertSingleSiteHit(SITE_A, SITE_B, () -> assertEquals("v1", cacheA.get(1))); assertSingleSiteHit(SITE_B, SITE_A, () -> assertNull(cacheB.put(2, "v2"))); assertSingleSiteHit(SITE_B, SITE_A, () -> assertEquals("v2", cacheB.get(2))); assertTrue(clientA.switchToCluster(SITE_B)); assertSingleSiteHit(SITE_B, SITE_A, () -> assertNull(cacheA.put(3, "v3"))); assertSingleSiteHit(SITE_B, SITE_A, () -> assertEquals("v3", cacheA.get(3))); assertTrue(clientA.switchToDefaultCluster()); assertSingleSiteHit(SITE_A, SITE_B, () -> assertNull(cacheA.put(4, "v4"))); assertSingleSiteHit(SITE_A, SITE_B, () -> assertEquals("v4", cacheA.get(4))); } public void testManualClusterSwitchViaJMX() throws Exception { clientA = client(SITE_A, Optional.of(SITE_B)); clientB = client(SITE_B, Optional.empty()); MBeanServer mbeanServer = mBeanServerLookup.getMBeanServer(); ObjectName objectName = remoteCacheManagerObjectName(clientA); RemoteCache<Integer, String> cacheA = clientA.getCache(CACHE_NAME); RemoteCache<Integer, String> cacheB = clientB.getCache(CACHE_NAME); assertNoHits(); assertSingleSiteHit(SITE_A, SITE_B, () -> assertNull(cacheA.put(1, "v1"))); assertSingleSiteHit(SITE_A, SITE_B, () -> assertEquals("v1", cacheA.get(1))); assertSingleSiteHit(SITE_B, SITE_A, () -> assertNull(cacheB.put(2, "v2"))); assertSingleSiteHit(SITE_B, SITE_A, () -> assertEquals("v2", cacheB.get(2))); Object switched = mbeanServer.invoke(objectName, "switchToCluster", new Object[]{SITE_B}, new String[]{String.class.getName()}); assertEquals(Boolean.TRUE, switched); assertSingleSiteHit(SITE_B, SITE_A, () -> assertNull(cacheA.put(3, "v3"))); assertSingleSiteHit(SITE_B, SITE_A, () -> assertEquals("v3", cacheA.get(3))); switched = mbeanServer.invoke(objectName, "switchToDefaultCluster", new Object[]{}, new String[]{}); assertEquals(Boolean.TRUE, switched); assertSingleSiteHit(SITE_A, SITE_B, () -> assertNull(cacheA.put(4, "v4"))); assertSingleSiteHit(SITE_A, SITE_B, () -> assertEquals("v4", cacheA.get(4))); } private void assertSingleSiteHit(String siteHit, String siteNotHit, Runnable r) { r.run(); assertSiteHit(siteHit, 1); assertSiteNotHit(siteNotHit); resetHitCounters(); } }
3,924
40.755319
134
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/xsite/ClientIntelligenceClusterTest.java
package org.infinispan.client.hotrod.xsite; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.newRemoteConfigurationBuilder; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.infinispan.client.hotrod.CacheTopologyInfo; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.configuration.ClientIntelligence; import org.infinispan.client.hotrod.configuration.ClusterConfigurationBuilder; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.configuration.ServerConfigurationBuilder; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.InternalRemoteCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.xsite.AbstractMultipleSitesTest; import org.testng.AssertJUnit; import org.testng.annotations.Test; /** * Tests independent {@link ClientIntelligence} per cluster. * * @since 14.0 */ @Test(groups = "functional", testName = "client.hotrod.xsite.ClientIntelligenceClusterTest") public class ClientIntelligenceClusterTest extends AbstractMultipleSitesTest { private final Map<String, List<HotRodServer>> siteServers = new HashMap<>(defaultNumberOfSites()); @Override protected void afterSitesCreated() { super.afterSitesCreated(); for (TestSite site : sites) { siteServers.put(site.getSiteName(), site.cacheManagers().stream().map(HotRodClientTestingUtil::startHotRodServer).collect(Collectors.toList())); } } @Override protected void killSites() { siteServers.values().forEach(hotRodServers -> hotRodServers.forEach(HotRodClientTestingUtil::killServers)); siteServers.clear(); super.killSites(); } public void testClusterInheritsIntelligence() { try (InternalRemoteCacheManager irc = createClient(ClientIntelligence.BASIC, null)) { RemoteCache<String, String> cache0 = irc.getCache(); byte[] cacheNameBytes = cache0.getName().getBytes(); cache0.put("key", "value"); AssertJUnit.assertEquals("value", cache0.get("key")); assertBasicIntelligence(irc, cacheNameBytes); irc.switchToCluster("backup"); cache0.put("key1", "value1"); AssertJUnit.assertEquals("value1", cache0.get("key1")); assertBasicIntelligence(irc, cacheNameBytes); irc.switchToDefaultCluster(); cache0.put("key2", "value2"); AssertJUnit.assertEquals("value2", cache0.get("key2")); assertBasicIntelligence(irc, cacheNameBytes); } } public void testBackupClusterUsesBasicIntelligence() { try (InternalRemoteCacheManager irc = createClient(ClientIntelligence.HASH_DISTRIBUTION_AWARE, ClientIntelligence.BASIC)) { RemoteCache<String, String> cache0 = irc.getCache(); byte[] cacheNameBytes = cache0.getName().getBytes(); cache0.put("key", "value"); AssertJUnit.assertEquals("value", cache0.get("key")); assertHashAwareIntelligence(irc, cacheNameBytes); irc.switchToCluster("backup"); cache0.put("key1", "value1"); AssertJUnit.assertEquals("value1", cache0.get("key1")); assertBasicIntelligence(irc, cacheNameBytes); irc.switchToDefaultCluster(); cache0.put("key2", "value2"); AssertJUnit.assertEquals("value2", cache0.get("key2")); assertHashAwareIntelligence(irc, cacheNameBytes); } } public void testBackupClusterUsesTopologyIntelligence() { try (InternalRemoteCacheManager irc = createClient(ClientIntelligence.BASIC, ClientIntelligence.TOPOLOGY_AWARE)) { RemoteCache<String, String> cache0 = irc.getCache(); byte[] cacheNameBytes = cache0.getName().getBytes(); cache0.put("key", "value"); AssertJUnit.assertEquals("value", cache0.get("key")); assertBasicIntelligence(irc, cacheNameBytes); irc.switchToCluster("backup"); cache0.put("key1", "value1"); AssertJUnit.assertEquals("value1", cache0.get("key1")); assertTopologyAwareIntelligence(irc, cacheNameBytes); irc.switchToDefaultCluster(); cache0.put("key2", "value2"); AssertJUnit.assertEquals("value2", cache0.get("key2")); assertBasicIntelligence(irc, cacheNameBytes); } } private InternalRemoteCacheManager createClient(ClientIntelligence globalIntelligence, ClientIntelligence backupIntelligence) { ConfigurationBuilder builder = newRemoteConfigurationBuilder(); if (globalIntelligence != null) { builder.clientIntelligence(globalIntelligence); } // first site addServer(builder.addServer(), siteName(0)); // second site addServer(builder.addCluster("backup").clusterClientIntelligence(backupIntelligence), siteName(1)); return new InternalRemoteCacheManager(builder.build()); } private HotRodServer getFirstServer(String siteName) { return siteServers.get(siteName).get(0); } private void addServer(ServerConfigurationBuilder builder, String siteName) { HotRodServer server = getFirstServer(siteName); builder.host(server.getHost()).port(server.getPort()); } private void addServer(ClusterConfigurationBuilder builder, String siteName) { HotRodServer server = getFirstServer(siteName); builder.addClusterNode(server.getHost(), server.getPort()); } private static void assertHashAwareIntelligence(InternalRemoteCacheManager ircm, byte[] cacheNameBytes) { ChannelFactory factory = ircm.getChannelFactory(); log.debugf("Server list: %s", factory.getServers(cacheNameBytes)); log.debugf("Topology Info: %s", factory.getCacheTopologyInfo(cacheNameBytes)); log.debugf("Consistent Hash: %s", factory.getConsistentHash(cacheNameBytes)); AssertJUnit.assertEquals(2, factory.getServers(cacheNameBytes).size()); CacheTopologyInfo topologyInfo = factory.getCacheTopologyInfo(cacheNameBytes); AssertJUnit.assertNotNull(topologyInfo); AssertJUnit.assertEquals(2, topologyInfo.getSegmentsPerServer().size()); AssertJUnit.assertNotNull(topologyInfo.getNumSegments()); AssertJUnit.assertNotNull(factory.getConsistentHash(cacheNameBytes)); } private static void assertTopologyAwareIntelligence(InternalRemoteCacheManager ircm, byte[] cacheNameBytes) { ChannelFactory factory = ircm.getChannelFactory(); log.debugf("Server list: %s", factory.getServers(cacheNameBytes)); log.debugf("Topology Info: %s", factory.getCacheTopologyInfo(cacheNameBytes)); log.debugf("Consistent Hash: %s", factory.getConsistentHash(cacheNameBytes)); AssertJUnit.assertEquals(2, factory.getServers(cacheNameBytes).size()); CacheTopologyInfo topologyInfo = factory.getCacheTopologyInfo(cacheNameBytes); AssertJUnit.assertNotNull(topologyInfo); AssertJUnit.assertEquals(2, topologyInfo.getSegmentsPerServer().size()); AssertJUnit.assertNull(topologyInfo.getNumSegments()); AssertJUnit.assertNull(factory.getConsistentHash(cacheNameBytes)); } private static void assertBasicIntelligence(InternalRemoteCacheManager ircm, byte[] cacheNameBytes) { ChannelFactory factory = ircm.getChannelFactory(); log.debugf("Server list: %s", factory.getServers(cacheNameBytes)); log.debugf("Topology Info: %s", factory.getCacheTopologyInfo(cacheNameBytes)); log.debugf("Consistent Hash: %s", factory.getConsistentHash(cacheNameBytes)); AssertJUnit.assertEquals(1, factory.getServers(cacheNameBytes).size()); CacheTopologyInfo topologyInfo = factory.getCacheTopologyInfo(cacheNameBytes); AssertJUnit.assertNotNull(topologyInfo); AssertJUnit.assertEquals(1, topologyInfo.getSegmentsPerServer().size()); AssertJUnit.assertNull(topologyInfo.getNumSegments()); AssertJUnit.assertNull(factory.getConsistentHash(cacheNameBytes)); } }
8,135
43.703297
153
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/xsite/SiteDownFailoverTest.java
package org.infinispan.client.hotrod.xsite; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import java.util.Optional; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.xsite.SiteDownFailoverTest") public class SiteDownFailoverTest extends AbstractHotRodSiteFailoverTest { private RemoteCacheManager clientA; private RemoteCacheManager clientB; public void testFailoverAfterSiteShutdown() { clientA = client(SITE_A, Optional.of(SITE_B)); clientB = client(SITE_B, Optional.empty()); RemoteCache<Integer, String> cacheA = clientA.getCache(CACHE_NAME); RemoteCache<Integer, String> cacheB = clientB.getCache(CACHE_NAME); assertNull(cacheA.put(1, "v1")); assertEquals("v1", cacheA.get(1)); assertEquals("v1", cacheB.get(1)); int portServerSiteA = findServerPort(SITE_A); killSite(SITE_A); // Client connected with surviving site should find data assertEquals("v1", cacheB.get(1)); // Client connected to crashed site should failover assertEquals("v1", cacheA.get(1)); // Restart previously shut down site createHotRodSite(SITE_A, SITE_B, Optional.of(portServerSiteA)); killSite(SITE_B); // Client that had details for site A should failover back // There is no data in original site since state transfer is not enabled assertNull(cacheA.get(1)); assertNull(cacheA.put(2, "v2")); assertEquals("v2", cacheA.get(2)); } @AfterClass(alwaysRun = true) @Override protected void destroy() { HotRodClientTestingUtil.killRemoteCacheManagers(clientA, clientB); super.destroy(); } }
1,950
32.067797
83
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/admin/RemoteCacheAdminPermanentTest.java
package org.infinispan.client.hotrod.admin; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.MultiHotRodServersTest; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.internal.PrivateGlobalConfigurationBuilder; import org.infinispan.globalstate.ConfigurationStorage; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.core.admin.embeddedserver.EmbeddedServerAdminOperationHandler; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.admin.RemoteCacheAdminPermanentTest") public class RemoteCacheAdminPermanentTest extends MultiHotRodServersTest { char serverId; boolean clear = true; @Override protected void createCacheManagers() throws Throwable { serverId = 'A'; ConfigurationBuilder builder = hotRodCacheConfiguration( getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false)); createHotRodServers(2, builder); } @Override protected HotRodServer addHotRodServer(ConfigurationBuilder builder) { return addStatefulHotRodServer(builder, serverId++); } protected boolean isShared() { return false; } protected HotRodServer addStatefulHotRodServer(ConfigurationBuilder builder, char id) { GlobalConfigurationBuilder gcb = GlobalConfigurationBuilder.defaultClusteredBuilder(); gcb.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true); String stateDirectory = tmpDirectory(this.getClass().getSimpleName(), Character.toString(id)); if (clear) Util.recursiveFileRemove(stateDirectory); gcb.globalState().enable().persistentLocation(stateDirectory). configurationStorage(ConfigurationStorage.OVERLAY); if (isShared()) { String sharedDirectory = tmpDirectory(this.getClass().getSimpleName(), "COMMON"); gcb.globalState().sharedPersistentLocation(sharedDirectory); } else { gcb.globalState().sharedPersistentLocation(stateDirectory); } EmbeddedCacheManager cm = addClusterEnabledCacheManager(gcb, builder); cm.defineConfiguration("template", builder.build()); HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder(); serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler()); HotRodServer server = HotRodClientTestingUtil.startHotRodServer(cm, serverBuilder); servers.add(server); return server; } public void permanentCacheTest(Method m) throws Throwable { String cacheName = m.getName(); client(0).administration().createCache(cacheName, "template"); assertTrue(manager(0).cacheExists(cacheName)); assertTrue(manager(1).cacheExists(cacheName)); killAll(); clear = false; createCacheManagers(); assertTrue(manager(0).cacheExists(cacheName)); client(0).administration().removeCache(cacheName); killAll(); clear = false; createCacheManagers(); assertFalse(manager(0).cacheExists(cacheName)); } }
3,739
43
100
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/admin/SchemaIndexUpdateTest.java
package org.infinispan.client.hotrod.admin; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM_TYPE; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import java.util.List; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.annotation.model.Image; import org.infinispan.client.hotrod.annotation.model.Model; import org.infinispan.client.hotrod.annotation.model.ModelA; import org.infinispan.client.hotrod.annotation.model.ModelB; import org.infinispan.client.hotrod.annotation.model.ModelC; import org.infinispan.client.hotrod.annotation.model.SchemaA; import org.infinispan.client.hotrod.annotation.model.SchemaB; import org.infinispan.client.hotrod.annotation.model.SchemaC; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.query.dsl.Query; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.infinispan.server.core.admin.embeddedserver.EmbeddedServerAdminOperationHandler; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.admin.SchemaIndexUpdateTest") public class SchemaIndexUpdateTest extends SingleHotRodServerTest { private static final String CACHE_NAME = "models"; private final ProtoStreamMarshaller schemaEvolutionClientMarshaller = new ProtoStreamMarshaller(); /** * Configure server side (embedded) cache * * @return the embedded cache manager * @throws Exception */ @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder .encoding() .mediaType(APPLICATION_PROTOSTREAM_TYPE) .indexing() .enable() .storage(LOCAL_HEAP) .addIndexedEntity("model.Model"); EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createServerModeCacheManager(); cacheManager.defineConfiguration(CACHE_NAME, builder.build()); return cacheManager; } /** * Configure the server, enabling the admin operations * * @return the HotRod server */ @Override protected HotRodServer createHotRodServer() { HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder(); serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler()); return HotRodClientTestingUtil.startHotRodServer(cacheManager, serverBuilder); } /** * Configure client side (remote) cache * * @param host The used host name * @param serverPort The used server port * @return the HotRod client configuration */ @Override protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(String host, int serverPort) { org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); builder.addServer() .host(host) .port(serverPort) .addContextInitializer(SchemaA.INSTANCE) .marshaller(schemaEvolutionClientMarshaller); return builder; } @Test public void updateWithoutAndWithOtherEntities() { RemoteCache<Integer, Object> cache = remoteCacheManager.getCache(CACHE_NAME); cache.put(1, new ModelA("Fabio")); Query<Model> query = Search.getQueryFactory(cache).create("from model.Model where original is not null"); List<Model> models = query.execute().list(); assertThat(models).extracting("original").containsExactly("Fabio"); assertThat(models).hasOnlyElementsOfType(ModelA.class); updateSchemaIndex(SchemaB.INSTANCE, null); // without otherEntities cache.put(2, new ModelB("Silvia", "Silvia")); query = Search.getQueryFactory(cache).create("from model.Model where original is not null"); models = query.execute().list(); assertThat(models).extracting("original").containsExactly("Fabio", "Silvia"); assertThat(models).hasOnlyElementsOfType(ModelB.class); query = Search.getQueryFactory(cache).create("from model.Model where different is not null"); models = query.execute().list(); assertThat(models).extracting("different").containsExactly("Silvia"); assertThat(models).hasOnlyElementsOfType(ModelB.class); Query<Image> imageQuery = Search.getQueryFactory(cache).create("from model.Image where name is not null"); // model.Image is not present on the indexedEntities assertThatThrownBy(() -> imageQuery.execute().list()) .isInstanceOf(HotRodClientException.class) .hasMessageContaining("Unknown type name : model.Image"); updateSchemaIndex(SchemaC.INSTANCE, "model.Model model.Image"); cache.put(3, new ModelC("Elena", "Elena", "Elena")); query = Search.getQueryFactory(cache).create("from model.Model where original is not null"); models = query.execute().list(); assertThat(models).extracting("original").containsExactly("Fabio", "Silvia", "Elena"); assertThat(models).hasOnlyElementsOfType(ModelC.class); query = Search.getQueryFactory(cache).create("from model.Model where different is not null"); models = query.execute().list(); assertThat(models).extracting("different").containsExactly("Silvia", "Elena"); assertThat(models).hasOnlyElementsOfType(ModelC.class); query = Search.getQueryFactory(cache).create("from model.Model where divergent is not null"); models = query.execute().list(); assertThat(models).extracting("divergent").containsExactly("Elena"); assertThat(models).hasOnlyElementsOfType(ModelC.class); // now it is possible to play with model.Image message type too List<Image> images = imageQuery.execute().list(); assertThat(images).isEmpty(); cache.put(4, new Image("name")); images = imageQuery.execute().list(); assertThat(images).extracting("name").containsExactly("name"); assertThat(images).hasOnlyElementsOfType(Image.class); } private void updateSchemaIndex(GeneratedSchema schema, String newIndexedEntities) { // Register proto schema && entity marshaller on client side schema.registerSchema(schemaEvolutionClientMarshaller.getSerializationContext()); schema.registerMarshallers(schemaEvolutionClientMarshaller.getSerializationContext()); // Register proto schema on server side RemoteCache<String, String> metadataCache = remoteCacheManager .getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); metadataCache.put(schema.getProtoFileName(), schema.getProtoFile()); if (newIndexedEntities != null) { remoteCacheManager.administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .updateConfigurationAttribute(CACHE_NAME, "indexing.indexed-entities", newIndexedEntities); } // reindexCache would make this test working as well, // the difference is that with updateIndexSchema the index state (Lucene directories) is not touched, // if the schema change is not retro-compatible reindexCache is required remoteCacheManager.administration().updateIndexSchema(CACHE_NAME); } }
8,145
43.032432
146
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/admin/RemoteCacheAdminStandaloneTest.java
package org.infinispan.client.hotrod.admin; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.commons.configuration.StringConfiguration; import org.infinispan.server.core.admin.embeddedserver.EmbeddedServerAdminOperationHandler; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.admin.RemoteCacheAdminStandaloneTest") public class RemoteCacheAdminStandaloneTest extends SingleHotRodServerTest { @Override protected HotRodServer createHotRodServer() { HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder(); serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler()); return HotRodClientTestingUtil.startHotRodServer(cacheManager, serverBuilder); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN005034.*") public void testCreateClusteredCacheStandAloneServer() { String xml = String.format("<infinispan><cache-container><distributed-cache name=\"%s\"></distributed-cache></cache-container></infinispan>", "cache"); RemoteCache<?, ?> cache = remoteCacheManager.administration().createCache("cache", new StringConfiguration(xml)); assertEquals(0, cache.size()); } }
1,676
49.818182
157
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/admin/RemoteCacheCreateOnAccessTest.java
package org.infinispan.client.hotrod.admin; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import java.io.File; import java.io.Writer; import java.nio.file.Files; import java.util.Properties; import java.util.function.Supplier; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.MultiHotRodServersTest; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.internal.PrivateGlobalConfigurationBuilder; import org.infinispan.globalstate.ConfigurationStorage; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.core.admin.embeddedserver.EmbeddedServerAdminOperationHandler; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.admin.RemoteCacheCreateOnAccessTest") public class RemoteCacheCreateOnAccessTest extends MultiHotRodServersTest { char serverId; boolean clear = true; @Override protected void createCacheManagers() throws Throwable { serverId = 'A'; ConfigurationBuilder builder = hotRodCacheConfiguration( getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false)); createHotRodServers(2, builder); } @Override protected HotRodServer addHotRodServer(ConfigurationBuilder builder) { return addStatefulHotRodServer(builder, serverId++); } protected boolean isShared() { return false; } protected HotRodServer addStatefulHotRodServer(ConfigurationBuilder builder, char id) { GlobalConfigurationBuilder gcb = GlobalConfigurationBuilder.defaultClusteredBuilder(); gcb.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true); String stateDirectory = tmpDirectory(this.getClass().getSimpleName() + File.separator + id); if (clear) Util.recursiveFileRemove(stateDirectory); gcb.globalState().enable().persistentLocation(stateDirectory). configurationStorage(ConfigurationStorage.OVERLAY); if (isShared()) { String sharedDirectory = tmpDirectory(this.getClass().getSimpleName() + File.separator + "COMMON"); gcb.globalState().sharedPersistentLocation(sharedDirectory); } else { gcb.globalState().sharedPersistentLocation(stateDirectory); } EmbeddedCacheManager cm = addClusterEnabledCacheManager(gcb, builder); cm.defineConfiguration("template", builder.build()); HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder(); serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler()); HotRodServer server = HotRodClientTestingUtil.startHotRodServer(cm, serverBuilder); servers.add(server); return server; } public void createOnAccessTemplateProgrammatic() throws Throwable { String cacheName = "cache-from-template-programmatic"; org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder .addServer() .host(server(0).getHost()) .port(server(0).getPort()) .socketTimeout(3000) .remoteCache(cacheName) .templateName("template"); try (RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build())) { RemoteCache<String, String> cache = remoteCacheManager.getCache(cacheName); cache.put("a", "a"); } } public void createOnAccessTemplateProgrammaticWildcard() throws Throwable { String cacheName = "org.infinispan.cache-from-template-programmatic-wildcard"; org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder .addServer() .host(server(0).getHost()) .port(server(0).getPort()) .socketTimeout(3000) .remoteCache("org.infinispan.cache-*") .templateName("template"); try (RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build())) { RemoteCache<String, String> cache = remoteCacheManager.getCache(cacheName); cache.put("a", "a"); } } public void createOnAccessTemplateDeclarative() throws Throwable { String cacheName = "cache-from-template-declarative"; Properties properties = new Properties(); properties.put(ConfigurationProperties.SO_TIMEOUT, "3000"); properties.put(ConfigurationProperties.CACHE_PREFIX + cacheName + ConfigurationProperties.CACHE_TEMPLATE_NAME_SUFFIX, "template"); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder .addServer() .host(server(0).getHost()) .port(server(0).getPort()) .withProperties(properties); try (RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build())) { RemoteCache<String, String> cache = remoteCacheManager.getCache(cacheName); cache.put("a", "a"); } } public void createOnAccessTemplateDeclarativeWildcard() throws Throwable { String cacheName = "org.infinispan.cache-from-template-declarative"; Properties properties = new Properties(); properties.put(ConfigurationProperties.SO_TIMEOUT, "3000"); properties.put(ConfigurationProperties.CACHE_PREFIX + "[org.infinispan.cache*]" + ConfigurationProperties.CACHE_TEMPLATE_NAME_SUFFIX, "template"); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder .addServer() .host(server(0).getHost()) .port(server(0).getPort()) .withProperties(properties); try (RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build())) { RemoteCache<String, String> cache = remoteCacheManager.getCache(cacheName); cache.put("a", "a"); } } public void createOnAccessConfigurationProgrammatic() throws Throwable { String cacheName = "cache-from-config-programmatic"; String xml = String.format("<infinispan><cache-container><distributed-cache name=\"%s\"/></cache-container></infinispan>", cacheName); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder .addServer() .host(server(0).getHost()) .port(server(0).getPort()) .socketTimeout(3000) .remoteCache(cacheName) .configuration(xml); try (RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build())) { RemoteCache<String, String> cache = remoteCacheManager.getCache(cacheName); cache.put("a", "a"); } } public void createOnAccessConfigurationDeclarative() throws Throwable { String cacheName = "cache-from-config-declarative"; String xml = String.format("<infinispan><cache-container><distributed-cache name=\"%s\"/></cache-container></infinispan>", cacheName); Properties properties = new Properties(); properties.put(ConfigurationProperties.SO_TIMEOUT, "3000"); properties.put(ConfigurationProperties.CACHE_PREFIX + cacheName + ConfigurationProperties.CACHE_CONFIGURATION_SUFFIX, xml); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder .addServer() .host(server(0).getHost()) .port(server(0).getPort()) .withProperties(properties); try (RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build())) { RemoteCache<String, String> cache = remoteCacheManager.getCache(cacheName); cache.put("a", "a"); } } public void createOnAccessConfigurationURIProgrammatic() throws Throwable { String cacheName = "cache-from-config-uri-programmatic"; String xml = String.format("<infinispan><cache-container><distributed-cache name=\"%s\"/></cache-container></infinispan>", cacheName); File file = new File(String.format("target/test-classes/%s-hotrod-client.properties", cacheName)); try (Writer w = Files.newBufferedWriter(file.toPath())) { w.write(xml); } org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder .addServer() .host(server(0).getHost()) .port(server(0).getPort()) .socketTimeout(3000) .remoteCache(cacheName) .configurationURI(file.toURI()); try (RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build())) { RemoteCache<String, String> cache = remoteCacheManager.getCache(cacheName); cache.put("a", "a"); } } public void createOnAccessConfigurationURIDeclarative() throws Throwable { createOnAccessConfigurationURI("uri-with-scheme", () -> Thread.currentThread().getContextClassLoader().getResource("uri-with-scheme-hotrod-client.properties").toString()); } public void createOnAccessConfigurationSchemelessURIDeclarative() throws Throwable { createOnAccessConfigurationURI("uri-without-scheme", () -> "uri-without-scheme-hotrod-client.properties"); } private void createOnAccessConfigurationURI(String cacheName, Supplier<String> uri) throws Throwable { String xml = String.format("<infinispan><cache-container><distributed-cache name=\"%s\"/></cache-container></infinispan>", cacheName); File file = new File(String.format("target/test-classes/%s-hotrod-client.properties", cacheName)); try (Writer w = Files.newBufferedWriter(file.toPath())) { w.write(xml); } Properties properties = new Properties(); properties.put(ConfigurationProperties.SO_TIMEOUT, "3000"); properties.put(ConfigurationProperties.CACHE_PREFIX + cacheName + ConfigurationProperties.CACHE_CONFIGURATION_URI_SUFFIX, uri.get()); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder .addServer() .host(server(0).getHost()) .port(server(0).getPort()) .withProperties(properties); try (RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build())) { RemoteCache<String, String> cache = remoteCacheManager.getCache(cacheName); cache.put("a", "a"); } } public void createOnAccessConfigurationProgrammaticAfterConstruction() throws Throwable { String cacheName = "cache-from-config-declarative"; String xml = String.format("<infinispan><cache-container><distributed-cache name=\"%s\"/></cache-container></infinispan>", cacheName); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder .addServer() .host(server(0).getHost()) .port(server(0).getPort()) .socketTimeout(3000); try (RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build())) { remoteCacheManager.getConfiguration().addRemoteCache(cacheName, c -> c.configuration(xml)); RemoteCache<String, String> cache = remoteCacheManager.getCache(cacheName); cache.put("a", "a"); } } }
12,395
50.22314
177
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/admin/RemoteCacheAdminTest.java
package org.infinispan.client.hotrod.admin; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.commons.test.Exceptions.expectException; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import java.util.Date; import java.util.List; import java.util.Set; import org.infinispan.client.hotrod.DefaultTemplate; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManagerAdmin; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.query.testdomain.protobuf.TransactionPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.MultiHotRodServersTest; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.commons.configuration.BasicConfiguration; import org.infinispan.commons.configuration.StringConfiguration; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.internal.PrivateGlobalConfigurationBuilder; import org.infinispan.eviction.EvictionStrategy; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.dsl.embedded.testdomain.Transaction; import org.infinispan.query.dsl.embedded.testdomain.User; import org.infinispan.server.core.admin.embeddedserver.EmbeddedServerAdminOperationHandler; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.admin.RemoteCacheAdminTest") public class RemoteCacheAdminTest extends MultiHotRodServersTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = hotRodCacheConfiguration( getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false)); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.Transaction"); createHotRodServers(2, builder); } @Override protected HotRodServer addHotRodServer(ConfigurationBuilder builder) { GlobalConfigurationBuilder gcb = GlobalConfigurationBuilder.defaultClusteredBuilder(); gcb.defaultCacheName("default"); gcb.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true); gcb.serialization().addContextInitializer(contextInitializer()); EmbeddedCacheManager cm = addClusterEnabledCacheManager(gcb, builder); cm.defineConfiguration("template", builder.build()); cm.defineConfiguration(DefaultTemplate.DIST_ASYNC.getTemplateName(), builder.build()); HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder(); serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler()); HotRodServer server = HotRodClientTestingUtil.startHotRodServer(cm, serverBuilder); servers.add(server); return server; } @Override protected SerializationContextInitializer contextInitializer() { return TestDomainSCI.INSTANCE; } public void templateCreateRemoveTest(Method m) { String templateName = m.getName(); String xml = String.format( "<infinispan><cache-container><distributed-cache name=\"%s\"/></cache-container></infinispan>", templateName); BasicConfiguration template = new StringConfiguration(xml); client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .createTemplate(templateName, template); assertTrue(manager(0).getCacheConfigurationNames().contains(templateName)); assertTrue(manager(0).getCacheConfigurationNames().contains(templateName)); client(1).administration().removeTemplate(templateName); assertFalse(manager(0).getCacheConfigurationNames().contains(templateName)); assertFalse(manager(0).getCacheConfigurationNames().contains(templateName)); } public void cacheCreateRemoveTest(Method m) { String cacheName = m.getName(); client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).createCache(cacheName, "template"); assertTrue(manager(0).cacheExists(cacheName)); assertTrue(manager(1).cacheExists(cacheName)); client(1).administration().removeCache(cacheName); assertFalse(manager(0).cacheExists(cacheName)); assertFalse(manager(1).cacheExists(cacheName)); } public void cacheCreateMissingTemplate(Method m) throws InterruptedException { RemoteCacheManagerAdmin admin = client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE); // Creation with a non-existent template fails expectException(HotRodClientException.class, () -> admin.createCache("some_name", "some_template_name")); // Cache can still be created later with a string configuration admin.createCache("some_name", new StringConfiguration("<infinispan><cache-container>" + "<local-cache name=\"some_name\"/>" + "</cache-container></infinispan>")); RemoteCache<Object, Object> someCache = client(0).getCache("some_name"); someCache.put("key", "value"); } public void cacheCreateRemoveTestWithDefaultTemplateEnum(Method m) { String cacheName = m.getName(); client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .createCache(cacheName, DefaultTemplate.DIST_ASYNC); assertTrue(manager(0).cacheExists(cacheName)); assertTrue(manager(1).cacheExists(cacheName)); client(1).administration().removeCache(cacheName); assertFalse(manager(0).cacheExists(cacheName)); assertFalse(manager(1).cacheExists(cacheName)); } public void cacheGetOrCreateRemoveTestWithDefaultTemplateEnum(Method m) { String cacheName = m.getName(); client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .getOrCreateCache(cacheName, DefaultTemplate.DIST_ASYNC); assertTrue(manager(0).cacheExists(cacheName)); assertTrue(manager(1).cacheExists(cacheName)); client(1).administration().removeCache(cacheName); assertFalse(manager(0).cacheExists(cacheName)); assertFalse(manager(1).cacheExists(cacheName)); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN000374.*") public void nonExistentTemplateTest(Method m) { String cacheName = m.getName(); client(0).administration().createCache(cacheName, "nonExistentTemplate"); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN000507.*") public void alreadyExistingCacheTest(Method m) { String cacheName = m.getName(); client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).createCache(cacheName, "template"); client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).createCache(cacheName, "template"); } public void getOrCreateWithTemplateTest(Method m) { String cacheName = m.getName(); client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).createCache(cacheName, "template"); client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .getOrCreateCache(cacheName, "template"); } public void getOrCreateWithoutTemplateTest() { client(0).administration().getOrCreateCache("default", (String) null); } public void cacheCreateWithXMLConfigurationTest(Method m) { String cacheName = m.getName(); String xml = String.format( "<infinispan><cache-container><distributed-cache name=\"%s\"><encoding><key " + "media-type=\"text/plain\"/><value media-type=\"application/json\"/></encoding><expiration " + "interval=\"10000\" lifespan=\"10\" max-idle=\"10\"/></distributed-cache></cache-container></infinispan>", cacheName); cacheCreateWithStringConfiguration(cacheName, xml); } public void cacheCreateWithXMLFragmentConfigurationTest(Method m) { String cacheName = m.getName(); String xml = String.format( "<distributed-cache name=\"%s\"><encoding><key media-type=\"text/plain\"/><value " + "media-type=\"application/json\"/></encoding><expiration interval=\"10000\" lifespan=\"10\" " + "max-idle=\"10\"/></distributed-cache>", cacheName); cacheCreateWithStringConfiguration(cacheName, xml); } public void cacheCreateWithJSONConfigurationTest(Method m) { String cacheName = m.getName(); String json = "{\n" + " \"distributed-cache\" : {\n" + " \"encoding\" : {\n" + " \"key\" : {\n" + " \"media-type\" : \"text/plain\"\n" + " },\n" + " \"value\" : {\n" + " \"media-type\" : \"application/json\"\n" + " }\n" + " },\n" + " \"expiration\" : {\n" + " \"interval\" : \"10000\",\n" + " \"lifespan\" : \"10\",\n" + " \"max-idle\" : \"10\"\n" + " }\n" + " }\n" + "}\n"; cacheCreateWithStringConfiguration(cacheName, json); } public void cacheCreateWithYAMLConfigurationTest(Method m) { String cacheName = m.getName(); String yaml = "distributed-cache:\n" + " encoding:\n" + " key:\n"+ " media-type: text/plain\n"+ " value:\n"+ " media-type: application/json\n"+ " expiration:\n"+ " interval: 10000\n"+ " lifespan: 10\n"+ " max-idle: 10\n"; cacheCreateWithStringConfiguration(cacheName, yaml); } private void cacheCreateWithStringConfiguration(String cacheName, String xml) { client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .getOrCreateCache(cacheName, new StringConfiguration(xml)); Configuration configuration = manager(0).getCache(cacheName).getCacheConfiguration(); assertEquals(10000, configuration.expiration().wakeUpInterval()); assertEquals(10, configuration.expiration().lifespan()); assertEquals(10, configuration.expiration().maxIdle()); assertEquals(MediaType.TEXT_PLAIN, configuration.encoding().keyDataType().mediaType()); assertEquals(MediaType.APPLICATION_JSON, configuration.encoding().valueDataType().mediaType()); } public void cacheCreateWithXMLConfigurationAndGetCacheTest(Method m) { String cacheName = m.getName(); String xml = String.format( "<infinispan><cache-container><distributed-cache name=\"%s\"/></cache-container></infinispan>", cacheName); cacheCreateWithXMLConfigurationAndGetCache(cacheName, xml); } public void cacheCreateWithReducedXMLConfigurationAndGetCacheTest(Method m) { String cacheName = m.getName(); String xml = String.format("<distributed-cache name=\"%s\"/>", cacheName); cacheCreateWithXMLConfigurationAndGetCache(cacheName, xml); } private void cacheCreateWithXMLConfigurationAndGetCache(String cacheName, String xml) { client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .createCache(cacheName, new StringConfiguration(xml)); final RemoteCache<Object, Object> cache = client(0).getCache(cacheName); assertNotNull(cache); } public void cacheCreateWithEmbeddedConfigurationTest(Method m) { String cacheName = m.getName(); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.expiration().wakeUpInterval(10000).maxIdle(10).lifespan(10); client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .getOrCreateCache(cacheName, builder.build()); Configuration configuration = manager(0).getCache(cacheName).getCacheConfiguration(); assertEquals(10000, configuration.expiration().wakeUpInterval()); assertEquals(10, configuration.expiration().lifespan()); assertEquals(10, configuration.expiration().maxIdle()); } public void cacheReindexTest(Method m) { String cacheName = m.getName(); // Create the cache client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).createCache(cacheName, "template"); RemoteCache<String, Transaction> cache = client(0).getCache(cacheName); verifyQuery(cache, 0); Transaction tx = new TransactionPB(); tx.setId(1); tx.setAccountId(777); tx.setAmount(500); tx.setDate(new Date(1)); tx.setDescription("February rent"); tx.setLongDescription("February rent"); tx.setNotes("card was not present"); cache.withFlags(Flag.SKIP_INDEXING).put("tx", tx); verifyQuery(cache, 0); client(0).administration().reindexCache(cacheName); verifyQuery(cache, 1); client(0).administration().removeCache(cacheName); } public void updateIndexSchemaTest(Method m) { String cacheName = m.getName(); // Create the cache client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).createCache(cacheName, "template"); RemoteCache<String, Transaction> cache = client(0).getCache(cacheName); verifyQuery(cache, 0); Transaction tx = new TransactionPB(); tx.setId(1); tx.setAccountId(777); tx.setAmount(500); tx.setDate(new Date(1)); tx.setDescription("February rent"); tx.setLongDescription("February rent"); tx.setNotes("card was not present"); cache.put("tx", tx); verifyQuery(cache, 1); client(0).administration().updateIndexSchema(cacheName); verifyQuery(cache, 1); client(0).administration().removeCache(cacheName); } private void verifyQuery(RemoteCache<String, Transaction> cache, int count) { List<User> users = Search.getQueryFactory(cache) .<User>create("from sample_bank_account.Transaction where longDescription:'RENT'") .execute().list(); assertEquals(count, users.size()); } public void updateConfigurationAttribute(Method m) { String yaml = "distributed-cache:\n" + " memory:\n"+ " max-count: 100\n"+ " when-full: REMOVE\n"; String cacheName = m.getName(); // Create the cache client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .createCache(cacheName, new StringConfiguration(yaml)); Configuration config = manager(0).getCache(cacheName).getCacheConfiguration(); assertThat(config.memory().maxCount()).isEqualTo(100); assertThat(config.memory().whenFull()).isEqualTo(EvictionStrategy.REMOVE); client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .updateConfigurationAttribute(cacheName, "memory.max-count", "5"); assertThat(config.memory().maxCount()).isEqualTo(5); RemoteCache<String, Transaction> cache = client(0).getCache(cacheName); for (int i = 0; i < 10; i++) { Transaction tx = new TransactionPB(); tx.setId(i); tx.setAccountId(777); tx.setAmount(500); tx.setDate(new Date(1)); tx.setDescription("February rent"); tx.setLongDescription("February rent"); tx.setNotes("card was not present"); cache.put("foo_" + i, tx); } assertThat(cache).hasSize(5); } public void testGetCacheNames(Method m) { String cacheName = m.getName(); client(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).createCache(cacheName, "template"); Set<String> cacheNames = client(0).getCacheNames(); assertEquals(manager(0).getCacheNames(), cacheNames); } }
16,998
45.829201
119
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/admin/SecureRemoteCacheAdminTest.java
package org.infinispan.client.hotrod.admin; import org.infinispan.client.hotrod.DefaultTemplate; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.internal.PrivateGlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.Security; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.server.core.admin.embeddedserver.EmbeddedServerAdminOperationHandler; import org.infinispan.server.core.security.simple.SimpleSaslAuthenticator; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.admin.SecureRemoteCacheAdminTest") public class SecureRemoteCacheAdminTest extends RemoteCacheAdminTest { @Override protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(String host, int serverPort) { org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder = super.createHotRodClientConfigurationBuilder(host, serverPort); builder.security().authentication().enable().saslMechanism("CRAM-MD5").username("admin").password("password"); return builder; } @Override protected HotRodServer addHotRodServer(ConfigurationBuilder builder) { GlobalConfigurationBuilder gcb = GlobalConfigurationBuilder.defaultClusteredBuilder(); gcb.defaultCacheName("default"); gcb.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true); gcb.security().authorization().enable().groupOnlyMapping(false).principalRoleMapper(new IdentityRoleMapper()).role("admin").permission(AuthorizationPermission.ALL); gcb.serialization().addContextInitializer(contextInitializer()); ConfigurationBuilder template = new ConfigurationBuilder(); template.read(builder.build()); template.security().authorization().role("admin"); EmbeddedCacheManager cm = Security.doPrivileged(() -> { EmbeddedCacheManager cacheManager = addClusterEnabledCacheManager(gcb, builder); cacheManager.defineConfiguration("template", builder.build()); cacheManager.defineConfiguration(DefaultTemplate.DIST_ASYNC.getTemplateName(), builder.build()); return cacheManager; }); HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder(); serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler()); SimpleSaslAuthenticator ssa = new SimpleSaslAuthenticator(); ssa.addUser("admin", "realm", "password".toCharArray(), "admin"); serverBuilder.authentication() .enable() .sasl() .authenticator(ssa) .serverName("localhost") .addAllowedMech("CRAM-MD5"); HotRodServer server = Security.doPrivileged(() -> HotRodClientTestingUtil.startHotRodServer(cm, serverBuilder)); servers.add(server); return server; } }
3,294
52.145161
170
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/size/HugeProtobufMessageTest.java
package org.infinispan.client.hotrod.size; import static org.assertj.core.api.Assertions.assertThat; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.annotation.model.Essay; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "org.infinispan.client.hotrod.size.HugeProtobufMessageTest") public class HugeProtobufMessageTest extends SingleHotRodServerTest { public static final int SIZE = 68_000_000; // use something that is > 64M (67,108,864) @Override protected EmbeddedCacheManager createCacheManager() throws Exception { EmbeddedCacheManager manager = TestCacheManagerFactory.createServerModeCacheManager(); manager.defineConfiguration("homeworks", new ConfigurationBuilder().build()); return manager; } @Override protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(String host, int serverPort) { return super.createHotRodClientConfigurationBuilder(host, serverPort).socketTimeout(20_000); } @Override protected SerializationContextInitializer contextInitializer() { return Essay.EssaySchema.INSTANCE; } @Test public void testSearches() { RemoteCache<Integer, Essay> remoteCache = remoteCacheManager.getCache("homeworks"); remoteCache.put(1, new Essay("my-very-extensive-essay", makeHugeString())); Essay essay = remoteCache.get(1); assertThat(essay).isNotNull(); } private String makeHugeString() { char[] chars = new char[SIZE]; for (int i = 0; i < SIZE; i++) { char delta = (char) (i % 20); chars[i] = (char) ('a' + delta); } return new String(chars); } }
2,041
35.464286
146
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/tracing/OpenTelemetryClient.java
package org.infinispan.client.hotrod.tracing; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.api.trace.StatusCode; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; import io.opentelemetry.context.Scope; import io.opentelemetry.context.propagation.ContextPropagators; import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.trace.SdkTracerProvider; import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; import io.opentelemetry.sdk.trace.SpanProcessor; import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; import io.opentelemetry.sdk.trace.export.SpanExporter; public class OpenTelemetryClient { private final SdkTracerProvider tracerProvider; private final OpenTelemetry openTelemetry; private final Tracer tracer; public OpenTelemetryClient(SpanExporter spanExporter) { // we usually use a batch processor, // but this is a test SpanProcessor spanProcessor = SimpleSpanProcessor.create(spanExporter); SdkTracerProviderBuilder builder = SdkTracerProvider.builder() .addSpanProcessor(spanProcessor); tracerProvider = builder.build(); GlobalOpenTelemetry.resetForTest(); openTelemetry = OpenTelemetrySdk.builder() .setTracerProvider(tracerProvider) .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance())) .buildAndRegisterGlobal(); tracer = openTelemetry.getTracer("org.infinispan.hotrod.client.test", "1.0.0"); } public void shutdown() { tracerProvider.shutdown(); GlobalOpenTelemetry.resetForTest(); } public OpenTelemetry openTelemetry() { return openTelemetry; } @SuppressWarnings("unused") public void withinClientSideSpan(String spanName, Runnable operations) { Span span = tracer.spanBuilder(spanName).setSpanKind(SpanKind.CLIENT).startSpan(); // put the span into the current Context try (Scope scope = span.makeCurrent()) { operations.run(); } catch (Throwable throwable) { span.setStatus(StatusCode.ERROR, "Something bad happened!"); span.recordException(throwable); throw throwable; } finally { span.end(); // Cannot set a span after this call } } }
2,477
37.123077
95
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/tracing/TracingPropagationTest.java
package org.infinispan.client.hotrod.tracing; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.annotation.model.Author; import org.infinispan.client.hotrod.annotation.model.Poem; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.server.core.telemetry.TelemetryService; import org.infinispan.server.core.telemetry.impl.OpenTelemetryService; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; import io.opentelemetry.sdk.trace.data.SpanData; @Test(groups = "functional", testName = "org.infinispan.client.hotrod.tracing.TracingPropagationTest") public class TracingPropagationTest extends SingleHotRodServerTest { private final InMemorySpanExporter inMemorySpanExporter = InMemorySpanExporter.create(); // Configure OpenTelemetry SDK for tests private final OpenTelemetryClient oTelConfig = new OpenTelemetryClient(inMemorySpanExporter); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("poem.Poem"); EmbeddedCacheManager manager = TestCacheManagerFactory.createServerModeCacheManager(); manager.defineConfiguration("poems", builder.build()); GlobalComponentRegistry globalComponentRegistry = manager.getGlobalComponentRegistry(); globalComponentRegistry.registerComponent(new OpenTelemetryService(oTelConfig.openTelemetry()), TelemetryService.class); return manager; } @Override protected void teardown() { oTelConfig.shutdown(); super.teardown(); } @Override protected SerializationContextInitializer contextInitializer() { return Poem.PoemSchema.INSTANCE; } @Test public void smokeTest() { RemoteCache<Integer, Poem> remoteCache = remoteCacheManager.getCache("poems"); oTelConfig.withinClientSideSpan("user-client-side-span", () -> { // verify that the client thread contains the span context Map<String, String> contextMap = getContextMap(); assertThat(contextMap).isNotEmpty(); remoteCache.put(1, new Poem(new Author("Edgar Allen Poe"), "The Raven", 1845)); remoteCache.put(2, new Poem(new Author("Emily Dickinson"), "Because I could not stop for Death", 1890)); }); // Verify that the client span (user-client-side-span) and the two PUT server spans are exported correctly. // We're going now to correlate the client span with the server spans! List<SpanData> spans = inMemorySpanExporter.getFinishedSpanItems(); assertThat(spans).hasSize(3); String traceId = null; Set spanIds = new HashSet(); Map<String, Integer> parentSpanIds = new HashMap<>(); String parentSpan = null; for (SpanData span : spans) { if (traceId == null) { traceId = span.getTraceId(); } else { // check that the spans have all the same trace id assertThat(span.getTraceId()).isEqualTo(traceId); } spanIds.add(span.getSpanId()); parentSpanIds.compute(span.getParentSpanId(), (key, value) -> (value == null) ? 1 : value + 1); Integer times = parentSpanIds.get(span.getParentSpanId()); if (times == 2) { parentSpan = span.getParentSpanId(); } } // we have 3 different spans: assertThat(spanIds).hasSize(3); // two of which have the same parent span assertThat(parentSpanIds).hasSize(2); // that is the other span assertThat(spanIds).contains(parentSpan); } public static Map<String, String> getContextMap() { HashMap<String, String> result = new HashMap<>(); // Inject the request with the *current* Context, which contains our current Span. W3CTraceContextPropagator.getInstance().inject(Context.current(), result, (carrier, key, value) -> carrier.put(key, value)); return result; } }
4,775
38.8
126
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/tracing/TracingDisabledTest.java
package org.infinispan.client.hotrod.tracing; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.annotation.model.Author; import org.infinispan.client.hotrod.annotation.model.Poem; import org.infinispan.client.hotrod.test.InternalRemoteCacheManager; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.server.core.telemetry.TelemetryService; import org.infinispan.server.core.telemetry.impl.OpenTelemetryService; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; import io.opentelemetry.sdk.trace.data.SpanData; @Test(groups = "functional", testName = "org.infinispan.client.hotrod.tracing.TracingDisabledTest") public class TracingDisabledTest extends SingleHotRodServerTest { private final InMemorySpanExporter inMemorySpanExporter = InMemorySpanExporter.create(); // Configure OpenTelemetry SDK for tests private final OpenTelemetryClient oTelConfig = new OpenTelemetryClient(inMemorySpanExporter); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("poem.Poem"); EmbeddedCacheManager manager = TestCacheManagerFactory.createServerModeCacheManager(); manager.defineConfiguration("poems", builder.build()); GlobalComponentRegistry globalComponentRegistry = manager.getGlobalComponentRegistry(); globalComponentRegistry.registerComponent(new OpenTelemetryService(oTelConfig.openTelemetry()), TelemetryService.class); return manager; } @Override protected RemoteCacheManager getRemoteCacheManager() { org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder = createHotRodClientConfigurationBuilder("127.0.0.1", hotrodServer.getPort()); builder.disableTracingPropagation(); // <-- tracing context propagation is disabled client side return new InternalRemoteCacheManager(builder.build()); } @Override protected void teardown() { oTelConfig.shutdown(); super.teardown(); } @Override protected SerializationContextInitializer contextInitializer() { return Poem.PoemSchema.INSTANCE; } @Test public void smokeTest() { RemoteCache<Integer, Poem> remoteCache = remoteCacheManager.getCache("poems"); oTelConfig.withinClientSideSpan("user-client-side-span", () -> { remoteCache.put(1, new Poem(new Author("Edgar Allen Poe"), "The Raven", 1845)); remoteCache.put(2, new Poem(new Author("Emily Dickinson"), "Because I could not stop for Death", 1890)); }); // Verify that the client span (user-client-side-span) and the two PUT server spans are exported correctly. // We're going now to correlate the client span with the server spans! List<SpanData> spans = inMemorySpanExporter.getFinishedSpanItems(); assertThat(spans).hasSize(3); String traceId = null; Set spanIds = new HashSet(); Map<String, Integer> parentSpanIds = new HashMap<>(); String parentSpan = null; for (SpanData span : spans) { if (traceId == null) { traceId = span.getTraceId(); } else { // check that the spans have all different trace ids assertThat(span.getTraceId()).isNotEqualTo(traceId); } spanIds.add(span.getSpanId()); parentSpanIds.compute(span.getParentSpanId(), (key, value) -> (value == null) ? 1 : value + 1); Integer times = parentSpanIds.get(span.getParentSpanId()); if (times == 2) { parentSpan = span.getParentSpanId(); } } // we have 3 different spans: assertThat(spanIds).hasSize(3); // client spans <--> server spans are not correlated assertThat(parentSpanIds).hasSize(1); assertThat(spanIds).doesNotContain(parentSpan); } }
4,623
39.920354
156
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/PrimitiveEmbeddedRemoteInteropTest.java
package org.infinispan.client.hotrod.marshall; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.Cache; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * Tests interoperability between remote and embedded with primitive types * * @author anistor@redhat.com * @since 7.0 */ @Test(testName = "client.hotrod.marshall.PrimitiveEmbeddedRemoteInteropTest", groups = "functional") public class PrimitiveEmbeddedRemoteInteropTest extends SingleCacheManagerTest { private HotRodServer hotRodServer; private RemoteCacheManager remoteCacheManager; private RemoteCache<Object, Object> remoteCache; private Cache embeddedCache; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { org.infinispan.configuration.cache.ConfigurationBuilder builder = createConfigBuilder(); cacheManager = TestCacheManagerFactory.createServerModeCacheManager(builder); cache = cacheManager.getCache(); embeddedCache = cache.getAdvancedCache(); hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager); ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServer().host("127.0.0.1").port(hotRodServer.getPort()); remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); remoteCache = remoteCacheManager.getCache(); return cacheManager; } protected org.infinispan.configuration.cache.ConfigurationBuilder createConfigBuilder() { org.infinispan.configuration.cache.ConfigurationBuilder builder = hotRodCacheConfiguration(); builder.encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE); builder.encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE); return builder; } @AfterClass(alwaysRun = true) public void release() { killRemoteCacheManager(remoteCacheManager); remoteCacheManager = null; killServers(hotRodServer); hotRodServer = null; } public void testRemotePutAndGet() { remotePutAndGet(1, "foo"); remotePutAndGet(1, true); remotePutAndGet(1, 7); remotePutAndGet(1, 777L); remotePutAndGet(1, 0.0); remotePutAndGet(1, 1.0d); } private void remotePutAndGet(Object key, Object value) { remoteCache.clear(); remoteCache.put(key, value); Object remoteValue = remoteCache.get(key); assertEquals(value, remoteValue); // try to get the value through the embedded cache interface and check it's equals with the value we put assertEquals(1, embeddedCache.keySet().size()); Object localKey = embeddedCache.keySet().iterator().next(); assertEquals(key, localKey); Object localObject = embeddedCache.get(localKey); assertEquals(value, localObject); } public void testEmbeddedPutAndGet() { embeddedPutAndGet(1, "bar"); embeddedPutAndGet(1, true); embeddedPutAndGet(1, 7); embeddedPutAndGet(1, 777L); embeddedPutAndGet(1, 0.0); embeddedPutAndGet(1, 1.0d); } private void embeddedPutAndGet(Object key, Object value) { embeddedCache.clear(); embeddedCache.put(key, value); assertTrue(embeddedCache.keySet().contains(key)); Object localValue = embeddedCache.get(key); assertEquals(value, localValue); // try to get the value through the remote cache interface and check it's equals with the value we put assertEquals(1, remoteCache.keySet().size()); Object remoteKey = remoteCache.keySet().iterator().next(); assertEquals(key, remoteKey); Object remoteValue = remoteCache.get(remoteKey); assertEquals(value, remoteValue); } }
4,586
37.546218
110
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/ProtoStreamMarshallerWithAnnotationsTest.java
package org.infinispan.client.hotrod.marshall; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.ProtobufUtil; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoName; import org.infinispan.protostream.annotations.ProtoSchemaBuilder; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * Tests integration between HotRod client and ProtoStream marshalling library using the {@code @ProtoXyz} annotations. * * @author anistor@redhat.com * @since 7.1 */ @Test(testName = "client.hotrod.marshall.ProtoStreamMarshallerWithAnnotationsTest", groups = "functional") @CleanupAfterMethod public class ProtoStreamMarshallerWithAnnotationsTest extends SingleCacheManagerTest { private HotRodServer hotRodServer; private RemoteCacheManager remoteCacheManager; private RemoteCache<Integer, AnnotatedUser> remoteCache; @ProtoName("User") public static class AnnotatedUser { private int id; private String name; @ProtoField(number = 1, required = true) public int getId() { return id; } public void setId(int id) { this.id = id; } @ProtoField(2) public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "AnnotatedUser{id=" + id + ", name='" + name + "'}"; } } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()); cache = cacheManager.getCache().getAdvancedCache().withStorageMediaType(); hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager); ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServer().host("127.0.0.1").port(hotRodServer.getPort()); remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); remoteCache = remoteCacheManager.getCache(); //initialize client-side serialization context SerializationContext serializationContext = MarshallerUtil.getSerializationContext(remoteCacheManager); ProtoSchemaBuilder protoSchemaBuilder = new ProtoSchemaBuilder(); protoSchemaBuilder.fileName("test.proto") .addClass(AnnotatedUser.class) .build(serializationContext); return cacheManager; } @AfterClass(alwaysRun = true) public void release() { killRemoteCacheManager(remoteCacheManager); remoteCacheManager = null; killServers(hotRodServer); hotRodServer = null; } public void testPutAndGet() throws Exception { AnnotatedUser user = createUser(); remoteCache.put(1, user); // try to get the object through the local cache interface and check it's the same object we put assertEquals(1, cache.keySet().size()); byte[] key = (byte[]) cache.keySet().iterator().next(); Object localObject = cache.get(key); assertNotNull(localObject); assertTrue(localObject instanceof byte[]); Object unmarshalledObject = ProtobufUtil.fromWrappedByteArray(MarshallerUtil.getSerializationContext(remoteCacheManager), (byte[]) localObject); assertTrue(unmarshalledObject instanceof AnnotatedUser); assertUser((AnnotatedUser) unmarshalledObject); // get the object through the remote cache interface and check it's the same object we put AnnotatedUser fromRemoteCache = remoteCache.get(1); assertUser(fromRemoteCache); } private AnnotatedUser createUser() { AnnotatedUser user = new AnnotatedUser(); user.setId(33); user.setName("Tom"); return user; } private void assertUser(AnnotatedUser user) { assertNotNull(user); assertEquals(33, user.getId()); assertEquals("Tom", user.getName()); } }
4,966
35.792593
150
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/CircularReferencesMarshallTest.java
package org.infinispan.client.hotrod.marshall; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import java.util.Collections; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.query.testdomain.protobuf.company.FootballSchemaImpl; import org.infinispan.client.hotrod.query.testdomain.protobuf.company.FootballTeam; import org.infinispan.client.hotrod.query.testdomain.protobuf.company.Player; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.commons.test.annotation.TestForIssue; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.exception.ProtoStreamException; import org.testng.annotations.Test; @Test(groups = "functional", testName = "org.infinispan.client.hotrod.marshall.CircularReferencesMarshallTest") @TestForIssue(jiraKey = "ISPN-14687") public class CircularReferencesMarshallTest extends SingleHotRodServerTest { @Override protected SerializationContextInitializer contextInitializer() { return new FootballSchemaImpl(); } @Test public void testCircularity() { FootballTeam footBallTeam = new FootballTeam(); footBallTeam.setName("New-Team"); Player player = new Player("fax4ever", footBallTeam); footBallTeam.setPlayers(Collections.singletonList(player)); RemoteCache<Object, Object> remoteCache = remoteCacheManager.getCache(); assertThatThrownBy(() -> remoteCache.put("ciao", footBallTeam)).isInstanceOf(ProtoStreamException.class) .hasMessageContaining("IPROTO000008"); } }
1,623
40.641026
111
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/EmbeddedRemoteInteropQueryTest.java
package org.infinispan.client.hotrod.marshall; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.stream.IntStream; import org.infinispan.Cache; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.query.testdomain.protobuf.AccountPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.CurrencyMarshaller; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.GenderMarshaller; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.filter.AbstractKeyValueFilterConverter; import org.infinispan.filter.KeyValueFilterConverterFactory; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.AbstractSerializationContextInitializer; import org.infinispan.metadata.Metadata; import org.infinispan.protostream.SerializationContext; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.embedded.testdomain.Account; 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.TransactionHS; import org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Tests interoperability between remote query and embedded mode. * * @author anistor@redhat.com * @since 6.0 */ @Test(testName = "client.hotrod.marshall.EmbeddedRemoteInteropQueryTest", groups = "functional") @CleanupAfterMethod public class EmbeddedRemoteInteropQueryTest extends SingleCacheManagerTest { protected RemoteCache<Integer, Account> remoteCache; private HotRodServer hotRodServer; private RemoteCacheManager remoteCacheManager; private Cache<?, ?> embeddedCache; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { org.infinispan.configuration.cache.ConfigurationBuilder builder = createConfigBuilder(); GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault(); globalBuilder.serialization().addContextInitializers(new ServerSCI()); cacheManager = TestCacheManagerFactory.createServerModeCacheManager(globalBuilder, builder); cache = cacheManager.getCache(); embeddedCache = cache.getAdvancedCache(); hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager); ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServer().host("127.0.0.1").port(hotRodServer.getPort()) .addContextInitializers(TestDomainSCI.INSTANCE, NotIndexedSCI.INSTANCE); remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); remoteCache = remoteCacheManager.getCache(); return cacheManager; } protected org.infinispan.configuration.cache.ConfigurationBuilder createConfigBuilder() { org.infinispan.configuration.cache.ConfigurationBuilder builder = hotRodCacheConfiguration(); builder.encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE); builder.encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntities(UserHS.class, AccountHS.class, TransactionHS.class); return builder; } @Override protected void teardown() { killRemoteCacheManager(remoteCacheManager); remoteCacheManager = null; killServers(hotRodServer); hotRodServer = null; super.teardown(); } public void testPutAndGet() { Account account = createAccountPB(1); remoteCache.put(1, account); // try to get the object through the local cache interface and check it's the same object we put assertEquals(1, embeddedCache.keySet().size()); Object key = embeddedCache.keySet().iterator().next(); Object localObject = embeddedCache.get(key); assertAccount((Account) localObject, AccountHS.class); // get the object through the remote cache interface and check it's the same object we put Account fromRemoteCache = remoteCache.get(1); assertAccount(fromRemoteCache, AccountPB.class); } public void testPutAndGetForEmbeddedEntry() { AccountHS account = new AccountHS(); account.setId(1); account.setDescription("test description"); account.setCreationDate(new Date(42)); cache.put(1, account); // try to get the object through the remote cache interface and check it's the same object we put assertEquals(1, remoteCache.keySet().size()); Map.Entry<Integer, Account> entry = remoteCache.entrySet().iterator().next(); assertAccount(entry.getValue(), AccountPB.class); // get the object through the embedded cache interface and check it's the same object we put Account fromEmbeddedCache = (Account) embeddedCache.get(1); assertAccount(fromEmbeddedCache, AccountHS.class); } public void testRemoteQuery() { Account account = createAccountPB(1); remoteCache.put(1, account); // get account back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache); Query<Account> query = qf.create("FROM sample_bank_account.Account WHERE description LIKE '%test%'"); List<Account> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertAccount(list.get(0), AccountPB.class); } public void testRemoteQueryForEmbeddedEntry() { AccountHS account = new AccountHS(); account.setId(1); account.setDescription("test description"); account.setCreationDate(new Date(42)); cache.put(1, account); // get account back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache); Query<Account> query = qf.create("FROM sample_bank_account.Account WHERE description LIKE '%test%'"); List<Account> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertAccount(list.get(0), AccountPB.class); } public void testRemoteQueryForEmbeddedEntryOnNonIndexedField() { UserHS user = new UserHS(); user.setId(1); user.setName("test name"); user.setSurname("test surname"); user.setGender(User.Gender.MALE); user.setNotes("1234567890"); cache.put(1, user); // get user back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache); Query<User> query = qf.create("FROM sample_bank_account.User WHERE notes LIKE '%567%'"); List<User> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertNotNull(list.get(0)); assertEquals(UserPB.class, list.get(0).getClass()); assertEquals(1, list.get(0).getId()); assertEquals("1234567890", list.get(0).getNotes()); } public void testRemoteQueryForEmbeddedEntryOnNonIndexedType() { cache.put(1, new NotIndexed("testing 123")); // get user back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache); Query<NotIndexed> query = qf.create("FROM sample_bank_account.NotIndexed WHERE notIndexedField LIKE '%123%'"); List<NotIndexed> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertNotNull(list.get(0)); assertEquals("testing 123", list.get(0).notIndexedField); } public void testRemoteQueryForEmbeddedEntryOnIndexedAndNonIndexedField() { UserHS user = new UserHS(); user.setId(1); user.setName("test name"); user.setSurname("test surname"); user.setGender(User.Gender.MALE); user.setNotes("1234567890"); cache.put(1, user); // get user back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache); Query<User> query = qf.create("FROM sample_bank_account.User WHERE notes LIKE '%567%' AND surname = 'test surname'"); List<User> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertNotNull(list.get(0)); assertEquals(UserPB.class, list.get(0).getClass()); assertEquals(1, list.get(0).getId()); assertEquals("1234567890", list.get(0).getNotes()); assertEquals("test surname", list.get(0).getSurname()); } public void testRemoteQueryWithProjectionsForEmbeddedEntry() { AccountHS account = new AccountHS(); account.setId(1); account.setDescription("test description"); account.setCreationDate(new Date(42)); cache.put(1, account); // get account back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache); Query<Object[]> query = qf.create("SELECT description, id FROM sample_bank_account.Account WHERE description LIKE '%test%'"); List<Object[]> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertEquals("test description", list.get(0)[0]); assertEquals(1, list.get(0)[1]); } public void testRemoteFullTextQuery() { Transaction transaction = new TransactionHS(); transaction.setId(3); transaction.setDescription("Hotel"); transaction.setLongDescription("Expenses for Infinispan F2F meeting"); transaction.setAccountId(2); transaction.setAmount(99); transaction.setDate(new Date(42)); transaction.setDebit(true); transaction.setValid(true); cache.put(transaction.getId(), transaction); QueryFactory qf = Search.getQueryFactory(remoteCache); // Hibernate Search 6 does not support fields that are sortable and full text at the same time Query<Transaction> q = qf.create("from sample_bank_account.Transaction where longDescription='Expenses for Infinispan F2F meeting'"); List<Transaction> list = q.execute().list(); assertEquals(1, list.size()); } public void testEmbeddedLuceneQuery() { Account account = createAccountPB(1); remoteCache.put(1, account); // get account back from local cache via query and check its attributes QueryFactory queryFactory = org.infinispan.query.Search.getQueryFactory(embeddedCache); Query<Account> query = queryFactory.create(String.format("FROM %s WHERE description LIKE '%%test%%'", AccountHS.class.getName())); List<Account> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertAccount(list.get(0), AccountHS.class); } public void testEmbeddedQueryForEmbeddedEntryOnNonIndexedField() { UserHS user = new UserHS(); user.setId(1); user.setName("test name"); user.setSurname("test surname"); user.setGender(User.Gender.MALE); user.setNotes("1234567890"); cache.put(1, user); // get user back from remote cache via query and check its attributes QueryFactory qf = org.infinispan.query.Search.getQueryFactory(cache); Query<User> query = qf.create("FROM " + UserHS.class.getName() + " WHERE notes LIKE '%567%'"); List<User> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertNotNull(list.get(0)); assertEquals(UserHS.class, list.get(0).getClass()); assertEquals(1, list.get(0).getId()); assertEquals("1234567890", list.get(0).getNotes()); } public void testEmbeddedQueryForEmbeddedEntryOnNonIndexedType() { cache.put(1, new NotIndexed("testing 123")); // get user back from remote cache via query and check its attributes QueryFactory qf = org.infinispan.query.Search.getQueryFactory(cache); Query<NotIndexed> query = qf.create("FROM " + NotIndexed.class.getName() + " WHERE notIndexedField LIKE '%123%'"); List<NotIndexed> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertNotNull(list.get(0)); assertEquals("testing 123", list.get(0).notIndexedField); } public void testEmbeddedQueryForEmbeddedEntryOnIndexedAndNonIndexedField() { UserHS user = new UserHS(); user.setId(1); user.setName("test name"); user.setSurname("test surname"); user.setGender(User.Gender.MALE); user.setNotes("1234567890"); cache.put(1, user); // get user back from remote cache via query and check its attributes QueryFactory qf = org.infinispan.query.Search.getQueryFactory(cache); Query<User> query = qf.create("FROM " + UserHS.class.getName() + " WHERE notes LIKE '%567%' AND surname = 'test surname'"); List<User> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertNotNull(list.get(0)); assertEquals(UserHS.class, list.get(0).getClass()); assertEquals(1, list.get(0).getId()); assertEquals("1234567890", list.get(0).getNotes()); assertEquals("test surname", list.get(0).getSurname()); } public void testIterationForRemote() { IntStream.range(0, 10).forEach(id -> remoteCache.put(id, createAccountPB(id))); // Remote unfiltered iteration CloseableIterator<Map.Entry<Object, Object>> remoteUnfilteredIterator = remoteCache.retrieveEntries(null, null, 10); remoteUnfilteredIterator.forEachRemaining(e -> { Integer key = (Integer) e.getKey(); AccountPB value = (AccountPB) e.getValue(); assertTrue(key < 10); assertEquals((int) key, value.getId()); }); // Remote filtered iteration KeyValueFilterConverterFactory<Integer, Account, String> filterConverterFactory = () -> new AbstractKeyValueFilterConverter<Integer, Account, String>() { @Override public String filterAndConvert(Integer key, Account value, Metadata metadata) { if (key % 2 == 0) { return value.toString(); } return null; } }; hotRodServer.addKeyValueFilterConverterFactory("filterConverterFactory", filterConverterFactory); CloseableIterator<Map.Entry<Object, Object>> remoteFilteredIterator = remoteCache.retrieveEntries("filterConverterFactory", null, 10); remoteFilteredIterator.forEachRemaining(e -> { Integer key = (Integer) e.getKey(); String value = (String) e.getValue(); assertTrue(key < 10); assertEquals(createAccountHS(key).toString(), value); }); // Embedded iteration Cache<Integer, AccountHS> ourCache = (Cache<Integer, AccountHS>) embeddedCache; Iterator<Map.Entry<Integer, AccountHS>> localUnfilteredIterator = ourCache.entrySet().stream().iterator(); localUnfilteredIterator.forEachRemaining(e -> { Integer key = e.getKey(); AccountHS value = e.getValue(); assertTrue(key < 10); assertEquals((int) key, value.getId()); }); } public void testEqEmptyStringRemote() { UserHS user = new UserHS(); user.setId(1); user.setName("test name"); user.setSurname("test surname"); user.setGender(User.Gender.MALE); user.setNotes("1234567890"); cache.put(1, user); QueryFactory qf = Search.getQueryFactory(remoteCache); Query<User> q = qf.create("FROM sample_bank_account.User WHERE name = ''"); List<User> list = q.execute().list(); assertTrue(list.isEmpty()); } public void testEqSentenceRemote() { AccountHS account = new AccountHS(); account.setId(1); account.setDescription("John Doe's first bank account"); account.setCreationDate(new Date(42)); cache.put(1, account); QueryFactory qf = Search.getQueryFactory(remoteCache); Query<Account> q = qf.create("FROM sample_bank_account.Account WHERE description = \"John Doe's first bank account\""); List<Account> list = q.execute().list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getId()); } public void testEqEmptyStringEmbedded() { UserHS user = new UserHS(); user.setId(1); user.setName("test name"); user.setSurname("test surname"); user.setGender(User.Gender.MALE); user.setNotes("1234567890"); cache.put(1, user); QueryFactory qf = org.infinispan.query.Search.getQueryFactory(cache); Query<User> q = qf.create("FROM " + UserHS.class.getName() + " WHERE name = ''"); List<User> list = q.execute().list(); assertTrue(list.isEmpty()); } public void testEqSentenceEmbedded() { AccountHS account = new AccountHS(); account.setId(1); account.setDescription("John Doe's first bank account"); account.setCreationDate(new Date(42)); cache.put(1, account); QueryFactory qf = org.infinispan.query.Search.getQueryFactory(cache); Query<Account> q = qf.create("FROM " + AccountHS.class.getName() + " WHERE description = \"John Doe's first bank account\""); List<Account> list = q.execute().list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).getId()); } public void testDuplicateBooleanProjectionEmbedded() { Transaction transaction = new TransactionHS(); transaction.setId(3); transaction.setDescription("Hotel"); transaction.setAccountId(2); transaction.setAmount(45); transaction.setDate(new Date(42)); transaction.setDebit(true); transaction.setValid(true); cache.put(transaction.getId(), transaction); QueryFactory qf = org.infinispan.query.Search.getQueryFactory(cache); Query<Object[]> q = qf.create("SELECT id, isDebit, isDebit FROM " + TransactionHS.class.getName() + " WHERE description = 'Hotel'"); List<Object[]> list = q.execute().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]); } public void testDuplicateBooleanProjectionRemote() { Transaction transaction = new TransactionHS(); transaction.setId(3); transaction.setDescription("Hotel"); transaction.setAccountId(2); transaction.setAmount(45); transaction.setDate(new Date(42)); transaction.setDebit(true); transaction.setValid(true); cache.put(transaction.getId(), transaction); QueryFactory qf = Search.getQueryFactory(remoteCache); Query<Object[]> q = qf.create("SELECT id, isDebit, isDebit FROM sample_bank_account.Transaction WHERE description = 'Hotel'"); List<Object[]> list = q.execute().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]); } private AccountPB createAccountPB(int id) { AccountPB account = new AccountPB(); account.setId(id); account.setDescription("test description"); account.setCreationDate(new Date(42)); return account; } private AccountHS createAccountHS(int id) { AccountHS account = new AccountHS(); account.setId(id); account.setDescription("test description"); account.setCreationDate(new Date(42)); return account; } private void assertAccount(Account account, Class<?> cls) { assertNotNull(account); assertEquals(cls, account.getClass()); assertEquals(1, account.getId()); assertEquals("test description", account.getDescription()); assertEquals(42, account.getCreationDate().getTime()); } static class ServerSCI extends AbstractSerializationContextInitializer { ServerSCI() { super("sample_bank_account/bank.proto"); } @Override public void registerSchema(SerializationContext ctx) { super.registerSchema(ctx); NotIndexedSCI.INSTANCE.registerSchema(ctx); } @Override public void registerMarshallers(SerializationContext ctx) { ctx.registerMarshaller(new EmbeddedAccountMarshaller()); ctx.registerMarshaller(new CurrencyMarshaller()); ctx.registerMarshaller(new EmbeddedLimitsMarshaller()); ctx.registerMarshaller(new EmbeddedUserMarshaller()); ctx.registerMarshaller(new GenderMarshaller()); ctx.registerMarshaller(new EmbeddedTransactionMarshaller()); NotIndexedSCI.INSTANCE.registerMarshallers(ctx); } } }
22,246
39.970534
140
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/PrimitiveProtoStreamMarshallerTest.java
package org.infinispan.client.hotrod.marshall; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * Tests integration between HotRod client and ProtoStream marshalling library with primitive types. * * @author anistor@redhat.com * @since 7.1 */ @Test(testName = "client.hotrod.marshall.PrimitiveProtoStreamMarshallerTest", groups = "functional") public class PrimitiveProtoStreamMarshallerTest extends SingleCacheManagerTest { private HotRodServer hotRodServer; private RemoteCacheManager remoteCacheManager; private RemoteCache<Object, Object> remoteCache; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()); cache = cacheManager.getCache().getAdvancedCache().withStorageMediaType(); hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager); ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServer().host("127.0.0.1").port(hotRodServer.getPort()); remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); remoteCache = remoteCacheManager.getCache(); return cacheManager; } @AfterClass(alwaysRun = true) public void release() { killRemoteCacheManager(remoteCacheManager); remoteCacheManager = null; killServers(hotRodServer); hotRodServer = null; } public void testPutAndGet() { putAndGet(1, "bar"); putAndGet(1, true); putAndGet(1, 7); putAndGet(1, 777L); putAndGet(1, 0.0); putAndGet(1, 1.0d); } private void putAndGet(Object key, Object value) { remoteCache.clear(); remoteCache.put(key, value); assertTrue(remoteCache.keySet().contains(key)); Object remoteValue = remoteCache.get(key); assertEquals(value, remoteValue); assertEquals(1, cache.keySet().size()); Object localKey = cache.keySet().iterator().next(); assertTrue(localKey instanceof byte[]); Object localObject = cache.get(localKey); assertNotNull(localObject); assertTrue(localObject instanceof byte[]); } }
3,115
37
100
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/EmbeddedUserMarshaller.java
package org.infinispan.client.hotrod.marshall; import java.io.IOException; import java.time.Instant; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.infinispan.protostream.MessageMarshaller; import org.infinispan.query.dsl.embedded.testdomain.Address; import org.infinispan.query.dsl.embedded.testdomain.User; import org.infinispan.query.dsl.embedded.testdomain.hsearch.AddressHS; import org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS; /** * @author anistor@redhat.com * @since 7.2 */ public class EmbeddedUserMarshaller implements MessageMarshaller<UserHS> { @Override public String getTypeName() { return "sample_bank_account.User"; } @Override public Class<UserHS> getJavaClass() { return UserHS.class; } @Override public UserHS readFrom(ProtoStreamReader reader) throws IOException { int id = reader.readInt("id"); Set<Integer> accountIds = reader.readCollection("accountIds", new HashSet<>(), Integer.class); // Read them out of order. It still works but logs a warning! String surname = reader.readString("surname"); String name = reader.readString("name"); String salutation = reader.readString("salutation"); List<Address> addresses = reader.readCollection("addresses", new ArrayList<>(), AddressHS.class); Integer age = reader.readInt("age"); User.Gender gender = reader.readEnum("gender", User.Gender.class); String notes = reader.readString("notes"); Instant creationDate = reader.readInstant("creationDate"); Instant passwordExpirationDate = reader.readInstant("passwordExpirationDate"); UserHS user = new UserHS(); user.setId(id); user.setAccountIds(accountIds); user.setName(name); user.setSurname(surname); user.setSalutation(salutation); user.setAge(age); user.setGender(gender); user.setAddresses(addresses); user.setNotes(notes); user.setCreationDate(creationDate); user.setPasswordExpirationDate(passwordExpirationDate); return user; } @Override public void writeTo(ProtoStreamWriter writer, UserHS user) throws IOException { writer.writeInt("id", user.getId()); writer.writeCollection("accountIds", user.getAccountIds(), Integer.class); writer.writeString("name", user.getName()); writer.writeString("surname", user.getSurname()); writer.writeString("salutation", user.getSalutation()); writer.writeCollection("addresses", user.getAddresses(), AddressHS.class); writer.writeInt("age", user.getAge()); writer.writeEnum("gender", user.getGender()); writer.writeString("notes", user.getNotes()); writer.writeInstant("creationDate", user.getCreationDate()); writer.writeInstant("passwordExpirationDate", user.getPasswordExpirationDate()); } }
2,912
35.4125
103
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/EmbeddedAccountMarshaller.java
package org.infinispan.client.hotrod.marshall; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.infinispan.protostream.MessageMarshaller; import org.infinispan.query.dsl.embedded.testdomain.Account; import org.infinispan.query.dsl.embedded.testdomain.Limits; import org.infinispan.query.dsl.embedded.testdomain.hsearch.AccountHS; import org.infinispan.query.dsl.embedded.testdomain.hsearch.LimitsHS; /** * @author anistor@redhat.com * @since 6.0 */ public class EmbeddedAccountMarshaller implements MessageMarshaller<AccountHS> { @Override public String getTypeName() { return "sample_bank_account.Account"; } @Override public Class<AccountHS> getJavaClass() { return AccountHS.class; } @Override public AccountHS readFrom(ProtoStreamReader reader) throws IOException { int id = reader.readInt("id"); String description = reader.readString("description"); long creationDate = reader.readLong("creationDate"); Limits limits = reader.readObject("limits", LimitsHS.class); Limits hardLimits = reader.readObject("hardLimits", LimitsHS.class); List<byte[]> blurb = reader.readCollection("blurb", new ArrayList<>(), byte[].class); Account.Currency[] currencies = reader.readArray("currencies", Account.Currency.class); AccountHS account = new AccountHS(); account.setId(id); account.setDescription(description); account.setCreationDate(new Date(creationDate)); account.setLimits(limits); account.setHardLimits(hardLimits); account.setBlurb(blurb); account.setCurrencies(currencies); return account; } @Override public void writeTo(ProtoStreamWriter writer, AccountHS account) throws IOException { writer.writeInt("id", account.getId()); writer.writeString("description", account.getDescription()); writer.writeLong("creationDate", account.getCreationDate().getTime()); writer.writeObject("limits", account.getLimits(), LimitsHS.class); writer.writeObject("hardLimits", account.getHardLimits(), LimitsHS.class); writer.writeCollection("blurb", account.getBlurb(), byte[].class); writer.writeArray("currencies", account.getCurrencies(), Account.Currency.class); } }
2,319
36.419355
93
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/NotIndexedSCI.java
package org.infinispan.client.hotrod.marshall; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.query.dsl.embedded.testdomain.NotIndexed; @AutoProtoSchemaBuilder( includeClasses = NotIndexed.class, schemaPackageName = "sample_bank_account", schemaFileName = "not_indexed.proto", schemaFilePath = "/", service = false ) public interface NotIndexedSCI extends SerializationContextInitializer { SerializationContextInitializer INSTANCE = new NotIndexedSCIImpl(); }
608
32.833333
72
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/EmbeddedTransactionMarshaller.java
package org.infinispan.client.hotrod.marshall; import java.io.IOException; import java.util.Date; import org.infinispan.protostream.MessageMarshaller; import org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS; /** * @author anistor@redhat.com * @since 8.2 */ public class EmbeddedTransactionMarshaller implements MessageMarshaller<TransactionHS> { @Override public String getTypeName() { return "sample_bank_account.Transaction"; } @Override public Class<TransactionHS> getJavaClass() { return TransactionHS.class; } @Override public TransactionHS readFrom(ProtoStreamReader reader) throws IOException { int id = reader.readInt("id"); String description = reader.readString("description"); int accountId = reader.readInt("accountId"); long date = reader.readLong("date"); double amount = reader.readDouble("amount"); boolean isDebit = reader.readBoolean("isDebit"); boolean isValid = reader.readBoolean("isValid"); TransactionHS transaction = new TransactionHS(); transaction.setId(id); transaction.setDescription(description); transaction.setAccountId(accountId); transaction.setDate(new Date(date)); transaction.setAmount(amount); transaction.setDebit(isDebit); transaction.setValid(isValid); return transaction; } @Override public void writeTo(ProtoStreamWriter writer, TransactionHS transaction) throws IOException { writer.writeInt("id", transaction.getId()); writer.writeString("description", transaction.getDescription()); writer.writeInt("accountId", transaction.getAccountId()); writer.writeLong("date", transaction.getDate().getTime()); writer.writeDouble("amount", transaction.getAmount()); writer.writeBoolean("isDebit", transaction.isDebit()); writer.writeBoolean("isValid", transaction.isValid()); } }
1,929
32.859649
96
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/ClientProtoStreamMarshallerTest.java
package org.infinispan.client.hotrod.marshall; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.util.Collections; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.query.testdomain.protobuf.AddressPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.ProtobufUtil; import org.infinispan.query.dsl.embedded.testdomain.Address; import org.infinispan.query.dsl.embedded.testdomain.User; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * Tests integration between HotRod client and ProtoStream marshalling library. * * @author anistor@redhat.com * @since 6.0 */ @Test(testName = "client.hotrod.marshall.ClientProtoStreamMarshallerTest", groups = "functional") @CleanupAfterMethod public class ClientProtoStreamMarshallerTest extends SingleCacheManagerTest { private HotRodServer hotRodServer; private RemoteCacheManager remoteCacheManager; private RemoteCache<Integer, User> remoteCache; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()); cache = cacheManager.getCache().getAdvancedCache().withStorageMediaType(); hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager); ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServer().host("127.0.0.1").port(hotRodServer.getPort()).addContextInitializer(TestDomainSCI.INSTANCE); remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); remoteCache = remoteCacheManager.getCache(); return cacheManager; } @AfterClass(alwaysRun = true) public void release() { killRemoteCacheManager(remoteCacheManager); remoteCacheManager = null; killServers(hotRodServer); hotRodServer = null; } public void testPutAndGet() throws Exception { User user = createUser(); remoteCache.put(1, user); // try to get the object through the local cache interface and check it's the same object we put assertEquals(1, cache.keySet().size()); byte[] key = (byte[]) cache.keySet().iterator().next(); Object localObject = cache.get(key); assertNotNull(localObject); assertTrue(localObject instanceof byte[]); Object unmarshalledObject = ProtobufUtil.fromWrappedByteArray(MarshallerUtil.getSerializationContext(remoteCacheManager), (byte[]) localObject); assertTrue(unmarshalledObject instanceof User); assertUser((User) unmarshalledObject); // get the object through the remote cache interface and check it's the same object we put User fromRemoteCache = remoteCache.get(1); assertUser(fromRemoteCache); } private User createUser() { User user = new UserPB(); user.setId(1); user.setName("Tom"); user.setSurname("Cat"); user.setGender(User.Gender.MALE); user.setAccountIds(Collections.singleton(12)); Address address = new AddressPB(); address.setStreet("Dark Alley"); address.setPostCode("1234"); user.setAddresses(Collections.singletonList(address)); return user; } private void assertUser(User user) { assertNotNull(user); assertEquals(1, user.getId()); assertEquals("Tom", user.getName()); assertEquals("Cat", user.getSurname()); assertEquals(User.Gender.MALE, user.getGender()); assertNotNull(user.getAccountIds()); assertEquals(1, user.getAccountIds().size()); assertTrue(user.getAccountIds().contains(12)); assertNotNull(user.getAddresses()); assertEquals(1, user.getAddresses().size()); assertEquals("Dark Alley", user.getAddresses().get(0).getStreet()); assertEquals("1234", user.getAddresses().get(0).getPostCode()); } }
4,859
41.26087
150
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/NonIndexedEmbeddedRemoteQueryTest.java
package org.infinispan.client.hotrod.marshall; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import java.util.Date; import java.util.List; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.embedded.testdomain.Transaction; import org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.annotations.Test; /** * Tests interoperability between remote query and embedded mode. Do not enable indexing for query. * * @author anistor@redhat.com * @since 7.0 */ @Test(testName = "client.hotrod.marshall.NonIndexedEmbeddedRemoteQueryTest", groups = "functional") @CleanupAfterMethod public class NonIndexedEmbeddedRemoteQueryTest extends EmbeddedRemoteInteropQueryTest { @Override protected ConfigurationBuilder createConfigBuilder() { ConfigurationBuilder builder = hotRodCacheConfiguration(); builder.encoding().key().mediaType(MediaType.APPLICATION_OBJECT_TYPE); builder.encoding().value().mediaType(MediaType.APPLICATION_OBJECT_TYPE); return builder; } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "org.infinispan.objectfilter.ParsingException: ISPN028521: Full-text queries cannot be applied to property 'longDescription' in type sample_bank_account.Transaction unless the property is indexed and analyzed.") @Override public void testRemoteFullTextQuery() { Transaction transaction = new TransactionHS(); transaction.setId(3); transaction.setDescription("Hotel"); transaction.setLongDescription("Expenses for Infinispan F2F meeting"); transaction.setAccountId(2); transaction.setAmount(99); transaction.setDate(new Date(42)); transaction.setDebit(true); transaction.setValid(true); cache.put(transaction.getId(), transaction); QueryFactory qf = Search.getQueryFactory(remoteCache); Query<Transaction> q = qf.create("from sample_bank_account.Transaction where longDescription:'Expenses for Infinispan F2F meeting'"); List<Transaction> list = q.execute().list(); assertEquals(1, list.size()); } }
2,558
41.65
304
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/MarshallerPerCacheTest.java
package org.infinispan.client.hotrod.marshall; import static java.nio.charset.StandardCharsets.UTF_8; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM_TYPE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_SERIALIZED_OBJECT; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals; import java.io.IOException; import java.io.Serializable; import java.util.Objects; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.impl.MarshallerRegistry; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.io.ByteBuffer; import org.infinispan.commons.io.ByteBufferImpl; import org.infinispan.commons.marshall.AbstractMarshaller; import org.infinispan.commons.marshall.IdentityMarshaller; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.internal.PrivateGlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * @since 12.1 */ @Test(groups = "functional", testName = "client.hotrod.MarshallerPerCacheTest") public class MarshallerPerCacheTest extends SingleHotRodServerTest { private static final String CACHE_TEXT = "text"; private static final String CACHE_JAVA_SERIALIZED = "serialized"; private static final String CACHE_DEFAULT = "default"; private static final Object KEY = 1; private static final Object VALUE = new CustomValue("this is the value"); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder().nonClusteredDefault(); gcb.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(gcb, hotRodCacheConfiguration()); Configuration protobufConfig = new org.infinispan.configuration.cache.ConfigurationBuilder() .encoding().mediaType(APPLICATION_PROTOSTREAM_TYPE) .build(); Configuration defaultConfig = new org.infinispan.configuration.cache.ConfigurationBuilder().build(); cm.createCache(CACHE_TEXT, defaultConfig); cm.createCache(CACHE_JAVA_SERIALIZED, defaultConfig); cm.createCache(CACHE_DEFAULT, protobufConfig); return cm; } @AutoProtoSchemaBuilder( includeClasses = CustomValue.class, schemaFileName = "custom-value.proto", schemaFilePath = "proto/generated", schemaPackageName = "org.infinispan.test.client.MarshallerPerCacheTest" ) interface CtxInitializer extends SerializationContextInitializer { CtxInitializer INSTANCE = new CtxInitializerImpl(); } @Override protected SerializationContextInitializer contextInitializer() { return CtxInitializer.INSTANCE; } static class CustomValue implements Serializable { private String field; @ProtoFactory public CustomValue(String field) { this.field = field; } @ProtoField(1) public String getField() { return field; } public void setField(String field) { this.field = field; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomValue that = (CustomValue) o; return field.equals(that.field); } @Override public int hashCode() { return Objects.hash(field); } } static final class CustomValueMarshaller extends AbstractMarshaller { @Override protected ByteBuffer objectToBuffer(Object o, int estimatedSize) { String json; if (o instanceof CustomValue) { CustomValue customValue = (CustomValue) o; json = Json.object().set("field", customValue.getField()).toString(); } else { json = Json.make(o).asString(); } return ByteBufferImpl.create(json.getBytes(UTF_8)); } @Override public Object objectFromByteBuffer(byte[] buf, int offset, int length) throws IOException, ClassNotFoundException { Json json = Json.read(new String(buf, UTF_8)); if (json.has("field")) { return new CustomValue(json.at("field").asString()); } return json.asString(); } @Override public boolean isMarshallable(Object o) { return o instanceof CustomValue || o instanceof String; } @Override public MediaType mediaType() { return APPLICATION_JSON; } } @Override protected ConfigurationBuilder createHotRodClientConfigurationBuilder(String host, int serverPort) { ConfigurationBuilder builder = super.createHotRodClientConfigurationBuilder(host, serverPort); builder.security().addJavaSerialAllowList(".*CustomValue.*"); // Configure RemoteCaches with different marshallers builder.remoteCache(CACHE_DEFAULT).marshaller(ProtoStreamMarshaller.class); builder.remoteCache(CACHE_TEXT).marshaller(new CustomValueMarshaller()); builder.remoteCache(CACHE_JAVA_SERIALIZED).marshaller(JavaSerializationMarshaller.class); return builder; } @Test public void testMarshallerPerCache() throws IOException, InterruptedException { MarshallerRegistry marshallerRegistry = remoteCacheManager.getMarshallerRegistry(); assertMarshallerUsed(CACHE_DEFAULT, marshallerRegistry.getMarshaller(APPLICATION_PROTOSTREAM)); assertMarshallerUsed(CACHE_TEXT, new CustomValueMarshaller()); assertMarshallerUsed(CACHE_JAVA_SERIALIZED, marshallerRegistry.getMarshaller(APPLICATION_SERIALIZED_OBJECT)); } @Test public void testOverrideMarshallerAtRuntime() throws Exception { // RemoteCache 'CACHE_JAVA_SERIALIZED' is configured to use the java marshaller RemoteCache<String, Object> cache = remoteCacheManager.getCache(CACHE_JAVA_SERIALIZED); cache.put("KEY", VALUE); // Override the value marshaller at runtime RemoteCache<String, byte[]> rawValueCache = cache.withDataFormat(DataFormat.builder().valueMarshaller(IdentityMarshaller.INSTANCE).build()); // Make sure the key marshaller stays the same as configured in the cache, but the value marshaller is replaced byte[] rawValue = rawValueCache.get("KEY"); assertArrayEquals(new JavaSerializationMarshaller().objectToByteBuffer(VALUE), rawValue); } private void assertMarshallerUsed(String cacheName, Marshaller expectedMarshaller) throws InterruptedException, IOException { // Read and write to the remote cache RemoteCache<Object, Object> remoteCache = remoteCacheManager.getCache(cacheName); remoteCache.put(KEY, VALUE); assertEquals(VALUE, remoteCache.get(KEY)); // Read data from the embedded cache as it is stored Cache<byte[], byte[]> cache = cacheManager.getCache(remoteCache.getName()); AdvancedCache<byte[], byte[]> asStored = cache.getAdvancedCache().withStorageMediaType(); // Assert that data was written using the 'expectedMarshaller' byte[] keyMarshalled = expectedMarshaller.objectToByteBuffer(KEY); byte[] valueMarshalled = expectedMarshaller.objectToByteBuffer(VALUE); assertArrayEquals(valueMarshalled, asStored.get(keyMarshalled)); } }
8,600
41.791045
146
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/AllowListMarshallingTest.java
package org.infinispan.client.hotrod.marshall; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_SERIALIZED_OBJECT; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import java.io.Serializable; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.InternalRemoteCacheManager; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.data.Person; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(testName = "client.hotrod.marshall.AllowListMarshallingTest", groups = {"functional", "smoke"} ) public class AllowListMarshallingTest extends SingleHotRodServerTest { @Override protected RemoteCacheManager getRemoteCacheManager() { ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); builder.addJavaSerialAllowList(".*Person.*").marshaller(JavaSerializationMarshaller.class); builder.addServer().host("127.0.0.1").port(hotrodServer.getPort()); return new InternalRemoteCacheManager(builder.build()); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.createCacheManager(contextInitializer(), hotRodCacheConfiguration(APPLICATION_SERIALIZED_OBJECT)); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN004034:.*") public void testUnsafeClassNotAllowed() { remoteCacheManager.getCache().put("unsafe", new UnsafeClass()); remoteCacheManager.getCache().get("unsafe"); } public void testSafeClassAllowed() { remoteCacheManager.getCache().put("safe", new Person()); remoteCacheManager.getCache().get("safe"); } private static final class UnsafeClass implements Serializable { } }
2,248
42.25
135
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/EmbeddedLimitsMarshaller.java
package org.infinispan.client.hotrod.marshall; import java.io.IOException; import org.infinispan.protostream.MessageMarshaller; import org.infinispan.query.dsl.embedded.testdomain.hsearch.LimitsHS; /** * @author anistor@redhat.com * @since 9.4.1 */ public class EmbeddedLimitsMarshaller implements MessageMarshaller<LimitsHS> { @Override public String getTypeName() { return "sample_bank_account.Account.Limits"; } @Override public Class<LimitsHS> getJavaClass() { return LimitsHS.class; } @Override public LimitsHS readFrom(ProtoStreamReader reader) throws IOException { double maxDailyLimit = reader.readDouble("maxDailyLimit"); double maxTransactionLimit = reader.readDouble("maxTransactionLimit"); String[] payees = reader.readArray("payees", String.class); LimitsHS limits = new LimitsHS(); limits.setMaxDailyLimit(maxDailyLimit); limits.setMaxTransactionLimit(maxTransactionLimit); limits.setPayees(payees); return limits; } @Override public void writeTo(ProtoStreamWriter writer, LimitsHS limits) throws IOException { writer.writeDouble("maxDailyLimit", limits.getMaxDailyLimit()); writer.writeDouble("maxTransactionLimit", limits.getMaxTransactionLimit()); writer.writeArray("payees", limits.getPayees(), String.class); } }
1,357
29.863636
86
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/protostream/builder/ProtoBufBuilderTest.java
package org.infinispan.client.hotrod.marshall.protostream.builder; import static org.assertj.core.api.Assertions.assertThat; import org.infinispan.Cache; import org.infinispan.api.protostream.builder.ProtoBuf; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.commons.test.annotation.TestForIssue; import org.infinispan.protostream.impl.ResourceUtils; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.testng.annotations.Test; @Test(groups = "functional", testName = "org.infinispan.client.hotrod.marshall.protostream.builder.ProtoBufBuilderTest") @TestForIssue(jiraKey = "ISPN-14724") public class ProtoBufBuilderTest extends SingleHotRodServerTest { @Test private void testGeneratedSchema() { String generatedSchema = ProtoBuf.builder() .packageName("org.infinispan") .message("author") // protobuf message is usually lowercase .indexed() .required("name", 1, "string") .basic() .sortable(true) .projectable(true) .optional("age", 2, "int32") .keyword() .sortable(true) .aggregable(true) .message("book") .indexed() .required("title", 1, "string") .basic() .projectable(true) .optional("yearOfPublication", 2, "int32") .keyword() .normalizer("lowercase") .optional("description", 3, "string") .text() .analyzer("english") .searchAnalyzer("whitespace") .required("author", 4, "author") .embedded() .build(); Cache<String, String> metadataCache = cacheManager.getCache( ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); metadataCache.put("ciao.proto", generatedSchema); String filesWithErrors = metadataCache.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX); assertThat(filesWithErrors).isNull(); String expectedSchema = ResourceUtils.getResourceAsString(getClass(), "/proto/ciao.proto"); assertThat(generatedSchema).isEqualTo(expectedSchema); } }
2,343
38.728814
120
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/protostream/validation/ProtobufValidationTest.java
package org.infinispan.client.hotrod.marshall.protostream.validation; import static org.assertj.core.api.Assertions.assertThat; import org.infinispan.Cache; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.commons.test.annotation.TestForIssue; import org.infinispan.protostream.impl.ResourceUtils; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @Test(groups = "functional", testName = "org.infinispan.client.hotrod.marshall.protostream.validation.ProtobufValidationTest") @TestForIssue(jiraKey = "ISPN-14816") public class ProtobufValidationTest extends SingleHotRodServerTest { private static final String SCHEMA_NAME = "my-schema.proto"; public static final String SCHEMA_ERROR_KEY = SCHEMA_NAME + ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX; private Cache<String, String> metadataCache; private String goodSchema; private String wrongSchema; @BeforeClass public void beforeAll() { metadataCache = cacheManager.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); goodSchema = ResourceUtils.getResourceAsString(getClass(), "/proto/ciao.proto"); wrongSchema = ResourceUtils.getResourceAsString(getClass(), "/proto/ciao-wrong.proto"); } @AfterMethod public void afterEach() { metadataCache.clear(); } @Test public void testGoodSchema() { metadataCache.put(SCHEMA_NAME, goodSchema); String filesWithErrors = metadataCache.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX); assertThat(filesWithErrors).isNull(); } @Test public void testWrongSchema() { metadataCache.put(SCHEMA_NAME, wrongSchema); String filesWithErrors = metadataCache.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX); assertThat(filesWithErrors).isEqualTo(SCHEMA_NAME); String errorMessage = metadataCache.get(SCHEMA_ERROR_KEY); assertThat(errorMessage).isNotBlank(); } @Test public void testUpdateWithWrongSchema() { metadataCache.put(SCHEMA_NAME, goodSchema); String filesWithErrors = metadataCache.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX); assertThat(filesWithErrors).isNull(); metadataCache.put(SCHEMA_NAME, wrongSchema); filesWithErrors = metadataCache.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX); assertThat(filesWithErrors).isEqualTo(SCHEMA_NAME); String errorMessage = metadataCache.get(SCHEMA_ERROR_KEY); assertThat(errorMessage).isNotBlank(); } }
2,674
37.214286
126
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryDslConditionsTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers; 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.sum; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.io.IOException; import java.util.List; import org.infinispan.Cache; import org.infinispan.client.hotrod.ProtocolVersion; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.impl.query.RemoteQueryFactory; import org.infinispan.client.hotrod.marshall.NotIndexedSCI; import org.infinispan.client.hotrod.query.testdomain.protobuf.ModelFactoryPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.SortOrder; import org.infinispan.query.dsl.embedded.QueryDslConditionsTest; import org.infinispan.query.dsl.embedded.testdomain.Account; import org.infinispan.query.dsl.embedded.testdomain.ModelFactory; import org.infinispan.search.mapper.mapping.SearchMapping; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.TestingUtil; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * Test for query conditions (filtering). Exercises the whole query DSL on the sample domain model. * Uses Protobuf marshalling and Protobuf doc annotations for configuring indexing. * * @author anistor@redhat.com * @since 6.0 */ @Test(groups = "functional", testName = "client.hotrod.query.RemoteQueryDslConditionsTest") public class RemoteQueryDslConditionsTest extends QueryDslConditionsTest { protected HotRodServer hotRodServer; protected RemoteCacheManager remoteCacheManager; protected RemoteCache<Object, Object> remoteCache; protected Cache<Object, Object> cache; protected ProtocolVersion getProtocolVersion() { return ProtocolVersion.DEFAULT_PROTOCOL_VERSION; } @Override protected QueryFactory getQueryFactory() { return Search.getQueryFactory(remoteCache); } @Override protected ModelFactory getModelFactory() { return ModelFactoryPB.INSTANCE; } /** * Both populating the cache and querying are done via remote cache. */ @Override protected RemoteCache<Object, Object> getCacheForQuery() { return remoteCache; } protected Cache<Object, Object> getEmbeddedCache() { return cache; } @Override protected void createCacheManagers() throws Throwable { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().clusteredDefault(); globalBuilder.serialization().addContextInitializers(TestDomainSCI.INSTANCE, NotIndexedSCI.INSTANCE); createClusteredCaches(1, globalBuilder, getConfigurationBuilder(), true); cache = manager(0).getCache(); hotRodServer = HotRodClientTestingUtil.startHotRodServer(manager(0)); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServer().host("127.0.0.1").port(hotRodServer.getPort()) .addContextInitializers(TestDomainSCI.INSTANCE, NotIndexedSCI.INSTANCE); clientBuilder.version(getProtocolVersion()); remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); remoteCache = remoteCacheManager.getCache(); } protected String loadSchema() throws IOException { return Util.getResourceAsString("/sample_bank_account/bank.proto", getClass().getClassLoader()); } protected ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder builder = hotRodCacheConfiguration(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.User") .addIndexedEntity("sample_bank_account.Account") .addIndexedEntity("sample_bank_account.Transaction"); return builder; } @AfterClass(alwaysRun = true) public void release() { killRemoteCacheManager(remoteCacheManager); remoteCacheManager = null; killServers(hotRodServer); hotRodServer = null; } @Override public void testIndexPresence() { SearchMapping searchMapping = TestingUtil.extractComponent(cache, SearchMapping.class); // we have indexing for remote query! assertNotNull(searchMapping.indexedEntity("sample_bank_account.User")); assertNotNull(searchMapping.indexedEntity("sample_bank_account.Account")); assertNotNull(searchMapping.indexedEntity("sample_bank_account.Transaction")); // we have some indexes for this cache assertEquals(3, searchMapping.allIndexedEntities().size()); } @Override public void testQueryFactoryType() { assertEquals(RemoteQueryFactory.class, getQueryFactory().getClass()); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN028503:.*") @Override public void testInvalidEmbeddedAttributeQuery() { // the original exception gets wrapped in HotRodClientException super.testInvalidEmbeddedAttributeQuery(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "org.infinispan.objectfilter.ParsingException: ISPN014027: The property path 'addresses.postCode' cannot be projected because it is multi-valued") @Override public void testRejectProjectionOfRepeatedProperty() { // the original exception gets wrapped in HotRodClientException super.testRejectProjectionOfRepeatedProperty(); } /** * This test is overridden because dates need special handling for protobuf (being actually emulated as long * timestamps). */ @Override public void testSampleDomainQuery9() throws Exception { QueryFactory qf = getQueryFactory(); // all the transactions that happened in January 2013, projected by date field only Query<Object[]> q = qf.from(getModelFactory().getTransactionImplClass()) .select("date") .having("date").between(makeDate("2013-01-01"), makeDate("2013-01-31")) .build(); List<Object[]> list = q.execute().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++) { Long d = (Long) list.get(i)[0]; assertTrue(d.compareTo(makeDate("2013-01-31").getTime()) <= 0); assertTrue(d.compareTo(makeDate("2013-01-01").getTime()) >= 0); } } public void testDefaultValue() { QueryFactory qf = getQueryFactory(); Query<Account> q = qf.from(getModelFactory().getAccountImplClass()).orderBy("description", SortOrder.ASC).build(); List<Account> list = q.execute().list(); assertEquals(3, list.size()); assertEquals("Checking account", list.get(0).getDescription()); } @Override @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "org.infinispan.objectfilter.ParsingException: ISPN014026: The expression 'surname' must be part of an aggregate function or it should be included in the GROUP BY clause") public void testGroupBy3() { // the original exception gets wrapped in HotRodClientException super.testGroupBy3(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "org.infinispan.objectfilter.ParsingException: ISPN014021: Queries containing grouping and aggregation functions must use projections.") @Override public void testGroupBy5() { // the original exception gets wrapped in HotRodClientException super.testGroupBy5(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: Aggregation SUM cannot be applied to property of type java.lang.String") public void testGroupBy6() { // the original exception gets wrapped in HotRodClientException super.testGroupBy6(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "org.infinispan.objectfilter.ParsingException: ISPN028515: Cannot have aggregate functions in the WHERE clause : SUM.") public void testGroupBy7() { // the original exception gets wrapped in HotRodClientException super.testGroupBy7(); } /** * This test is overridden because dates need special handling for protobuf (being actually emulated as long * timestamps). */ @Override public void testDateGrouping1() throws Exception { QueryFactory qf = getQueryFactory(); Query<Object[]> 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.execute().list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(makeDate("2013-02-27").getTime(), list.get(0)[0]); } /** * This test is overridden because dates need special handling for protobuf (being actually emulated as long * timestamps). */ @Override public void testDateGrouping2() throws Exception { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getTransactionImplClass()) .select(count("date"), min("date")) .having("description").eq("Hotel") .groupBy("id") .build(); List<Object[]> list = q.execute().list(); assertEquals(1, list.size()); assertEquals(2, list.get(0).length); assertEquals(1L, list.get(0)[0]); assertEquals(makeDate("2013-02-27").getTime(), list.get(0)[1]); } /** * This test is overridden because dates need special handling for protobuf (being actually emulated as long * timestamps). */ @Override public void testDateGrouping3() throws Exception { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getTransactionImplClass()) .select(min("date"), count("date")) .having("description").eq("Hotel") .groupBy("id") .build(); List<Object[]> list = q.execute().list(); assertEquals(1, list.size()); assertEquals(2, list.get(0).length); assertEquals(makeDate("2013-02-27").getTime(), list.get(0)[0]); assertEquals(1L, list.get(0)[1]); } /** * This test is overridden because dates need special handling for protobuf (being actually emulated as long * timestamps). */ @Override 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.execute().list(); assertEquals(1, list.size()); assertEquals(3, list.get(0).length); assertEquals(3, list.get(0)[0]); assertEquals(makeDate("2013-02-27").getTime(), list.get(0)[1]); assertEquals(makeDate("2013-02-27").getTime(), list.get(0)[2]); } @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "ISPN014825: Query parameter 'param2' was not set") @Override public void testMissingParamWithParameterMap() { // exception message code is different because it is generated by a different logger super.testMissingParamWithParameterMap(); } @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "ISPN014825: Query parameter 'param2' was not set") @Override public void testMissingParam() { // exception message code is different because it is generated by a different logger super.testMissingParam(); } /** * This test is overridden because dates need special handling for protobuf (being actually emulated as long * timestamps). */ @Override public void testComplexQuery() throws Exception { QueryFactory qf = getQueryFactory(); Query<Object[]> 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.execute().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(Long.class, list.get(0)[3].getClass()); assertEquals(makeDate("2013-01-01").getTime(), list.get(0)[3]); assertEquals(2, list.get(0)[4]); } /** * This test is overridden because dates need special handling for protobuf (being actually emulated as long * timestamps). */ @Override public void testDateFilteringWithGroupBy() throws Exception { QueryFactory qf = getQueryFactory(); Query<Object[]> 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.execute().list(); assertEquals(1, list.size()); assertEquals(1, list.get(0).length); assertEquals(Long.class, list.get(0)[0].getClass()); assertEquals(makeDate("2013-02-27").getTime(), list.get(0)[0]); } /** * This test is overridden because dates need special handling for protobuf (being actually emulated as long * timestamps). */ @Override public void testAggregateDate() throws Exception { QueryFactory qf = getQueryFactory(); Query<Object[]> q = qf.from(getModelFactory().getTransactionImplClass()) .select(count("date"), min("date")) .having("description").eq("Hotel") .groupBy("id") .build(); List<Object[]> list = q.execute().list(); assertEquals(1, list.size()); assertEquals(2, list.get(0).length); assertEquals(1L, list.get(0)[0]); assertEquals(Long.class, list.get(0)[1].getClass()); assertEquals(makeDate("2013-02-27").getTime(), list.get(0)[1]); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "org.infinispan.objectfilter.ParsingException: ISPN014023: Using the multi-valued property path 'addresses.street' in the GROUP BY clause is not currently supported") @Override public void testGroupByMustNotAcceptRepeatedProperty() { // the original exception gets wrapped in HotRodClientException super.testGroupByMustNotAcceptRepeatedProperty(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "org.infinispan.objectfilter.ParsingException: ISPN014024: The property path 'addresses.street' cannot be used in the ORDER BY clause because it is multi-valued") @Override public void testOrderByMustNotAcceptRepeatedProperty() { // the original exception gets wrapped in HotRodClientException super.testOrderByMustNotAcceptRepeatedProperty(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "org.infinispan.objectfilter.ParsingException: ISPN028515: Cannot have aggregate functions in the WHERE clause : MIN.") @Override public void testRejectAggregationsInWhereClause() { // the original exception gets wrapped in HotRodClientException super.testRejectAggregationsInWhereClause(); } }
17,222
41.421182
264
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryWithProtostreamAnnotationsTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.io.IOException; import java.util.List; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.marshall.MarshallerUtil; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.FileDescriptorSource; import org.infinispan.protostream.MessageMarshaller; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.annotations.ProtoDoc; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoName; import org.infinispan.protostream.annotations.ProtoSchemaBuilder; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Tests for remote queries over HotRod using protostream annotations on a local cache using indexing in RAM. * * @author Adrian Nistor */ @Test(testName = "client.hotrod.query.RemoteQueryWithProtostreamAnnotationsTest", groups = "functional") public class RemoteQueryWithProtostreamAnnotationsTest extends SingleHotRodServerTest { @ProtoDoc("@Indexed") @ProtoName("Memo") public static class Memo { private int id; private String text; private Author author; public Memo(int id, String text) { this.id = id; this.text = text; } public Memo() { } @ProtoDoc("@Field(index = Index.NO, store = Store.NO)") @ProtoField(number = 10, required = true) public int getId() { return id; } public void setId(int id) { this.id = id; } @ProtoDoc("@Field(store = Store.YES)") @ProtoField(20) public String getText() { return text; } public void setText(String text) { this.text = text; } @ProtoDoc("@Field(store = Store.YES)") @ProtoField(30) public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } @Override public String toString() { return "Memo{id=" + id + ", text='" + text + '\'' + ", author=" + author + '}'; } } public static class Author { private int id; private String name; public Author(int id, String name) { this.id = id; this.name = name; } public Author() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Author{id=" + id + ", name='" + name + "'}"; } } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { org.infinispan.configuration.cache.ConfigurationBuilder builder = new org.infinispan.configuration.cache.ConfigurationBuilder(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("Memo"); EmbeddedCacheManager manager = TestCacheManagerFactory.createServerModeCacheManager(); manager.defineConfiguration("test", builder.build()); return manager; } @Override protected RemoteCacheManager getRemoteCacheManager() { org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServer().host("127.0.0.1").port(hotrodServer.getPort()); RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); try { registerProtobufSchema(remoteCacheManager); } catch (Exception e) { throw new RuntimeException(e); } return remoteCacheManager; } protected void registerProtobufSchema(RemoteCacheManager remoteCacheManager) throws Exception { //initialize client-side serialization context String authorSchemaFile = "/* @Indexed */\n" + "message Author {\n" + " required int32 id = 1;\n" + " /* @Field(store = Store.YES) */\n" + " required string name = 2;\n" + "}"; SerializationContext serializationContext = MarshallerUtil.getSerializationContext(remoteCacheManager); serializationContext.registerProtoFiles(FileDescriptorSource.fromString("author.proto", authorSchemaFile)); serializationContext.registerMarshaller(new MessageMarshaller<Author>() { @Override public Author readFrom(ProtoStreamReader reader) throws IOException { int id = reader.readInt("id"); String name = reader.readString("name"); Author author = new Author(); author.setId(id); author.setName(name); return author; } @Override public void writeTo(ProtoStreamWriter writer, Author author) throws IOException { writer.writeInt("id", author.getId()); writer.writeString("name", author.getName()); } @Override public Class<Author> getJavaClass() { return Author.class; } @Override public String getTypeName() { return "Author"; } }); ProtoSchemaBuilder protoSchemaBuilder = new ProtoSchemaBuilder(); String memoSchemaFile = protoSchemaBuilder.fileName("memo.proto") .addClass(Memo.class) .build(serializationContext); //initialize server-side serialization context RemoteCache<String, String> metadataCache = remoteCacheManager.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); metadataCache.put("author.proto", authorSchemaFile); metadataCache.put("memo.proto", memoSchemaFile); RemoteQueryTestUtils.checkSchemaErrors(metadataCache); } public void testAttributeQuery() { RemoteCache<Integer, Memo> remoteCache = remoteCacheManager.getCache("test"); remoteCache.put(1, createMemo1()); remoteCache.put(2, createMemo2()); // get memo1 back from remote cache and check its attributes Memo fromCache = remoteCache.get(1); assertMemo1(fromCache); // get memo1 back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache); Query<Memo> query = qf.from(Memo.class) .having("text").like("%ipsum%") .build(); List<Memo> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertEquals(Memo.class, list.get(0).getClass()); assertMemo1(list.get(0)); // get memo2 back from remote cache via query and check its attributes query = qf.from(Memo.class) .having("author.name").eq("Adrian") .build(); list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertEquals(Memo.class, list.get(0).getClass()); assertMemo2(list.get(0)); } private Memo createMemo1() { Memo memo = new Memo(1, "Lorem ipsum"); memo.setAuthor(new Author(1, "Tom")); return memo; } private Memo createMemo2() { Memo memo = new Memo(2, "Sed ut perspiciatis unde omnis iste natus error"); memo.setAuthor(new Author(2, "Adrian")); return memo; } private void assertMemo1(Memo memo) { assertNotNull(memo); assertEquals(1, memo.getId()); assertEquals("Lorem ipsum", memo.getText()); assertEquals(1, memo.getAuthor().getId()); } private void assertMemo2(Memo memo) { assertNotNull(memo); assertEquals(2, memo.getId()); assertEquals("Sed ut perspiciatis unde omnis iste natus error", memo.getText()); assertEquals(2, memo.getAuthor().getId()); } }
8,507
31.34981
142
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteNonIndexedQueryStringTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Test for query language in remote mode. * * @author anistor@redhat.com * @since 9.0 */ @Test(groups = "functional", testName = "client.hotrod.query.RemoteNonIndexedQueryStringTest") public class RemoteNonIndexedQueryStringTest extends RemoteQueryStringTest { protected ConfigurationBuilder getConfigurationBuilder() { return hotRodCacheConfiguration(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextTerm() { super.testFullTextTerm(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextTermRightOperandAnalyzed() { super.testFullTextTermRightOperandAnalyzed(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextTermBoost() { super.testFullTextTermBoost(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextPhrase() { super.testFullTextPhrase(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextWithAggregation() { super.testFullTextWithAggregation(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextTermBoostAndSorting() { super.testFullTextTermBoostAndSorting(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextTermOccur() { super.testFullTextTermOccur(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextTermDoesntOccur() { super.testFullTextTermDoesntOccur(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextRangeWildcard() { super.testFullTextRangeWildcard(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextRange() { super.testFullTextRange(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextPrefix() { super.testFullTextPrefix(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextWildcard() { super.testFullTextWildcard(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextWildcardFuzzyNotAllowed() { super.testFullTextWildcardFuzzyNotAllowed(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextFuzzy() { super.testFullTextFuzzy(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextFuzzyDefaultEdits() { super.testFullTextFuzzyDefaultEdits(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextFuzzySpecifiedEdits() { super.testFullTextFuzzySpecifiedEdits(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextRegexp() { super.testFullTextRegexp(); } @Override public void testExactMatchOnAnalyzedFieldNotAllowed() { // Not applicable to non-indexed caches } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "org.infinispan.objectfilter.ParsingException: ISPN028521: Full-text queries cannot be applied to property 'description' in type sample_bank_account.Transaction unless the property is indexed and analyzed.") @Override public void testFullTextTermOnNonAnalyzedFieldNotAllowed() { super.testFullTextTermOnNonAnalyzedFieldNotAllowed(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextRegexp2() { super.testFullTextRegexp2(); } @Override public void testCustomFieldAnalyzer() { // Not applicable to non-indexed caches } }
6,628
44.40411
300
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryDslConditionsAllFieldsStoredTest.java
package org.infinispan.client.hotrod.query; import java.io.IOException; import org.testng.annotations.Test; /** * Force all 'bank.proto' schema fields the were explicitly defined in initial schema as 'Stored.NO' to be stored. This * should not impact any test. * * @author anistor@redhat.com */ @Test(groups = "functional", testName = "client.hotrod.query.RemoteQueryDslConditionsAllFieldsStoredTest") public class RemoteQueryDslConditionsAllFieldsStoredTest extends RemoteQueryDslConditionsTest { @Override protected String loadSchema() throws IOException { String schema = super.loadSchema(); return schema.replace("Store.NO", "Store.YES"); } }
677
29.818182
119
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/LargeTermTest.java
/* * Hibernate Search, full-text search for your domain model * * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.infinispan.client.hotrod.query; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.query.testdomain.protobuf.KeywordEntity; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.query.LargeTermTest") public class LargeTermTest extends SingleHotRodServerTest { public static final String DESCRIPTION = "foo bar% baz"; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("KeywordEntity"); EmbeddedCacheManager manager = TestCacheManagerFactory.createServerModeCacheManager(); manager.defineConfiguration("keyword", builder.build()); return manager; } @Override protected SerializationContextInitializer contextInitializer() { return KeywordEntity.KeywordSchema.INSTANCE; } @Test public void test() { RemoteCache<Integer, KeywordEntity> remoteCache = remoteCacheManager.getCache("keyword"); assertThatThrownBy(() -> remoteCache.put(1, new KeywordEntity(createLargeDescription(3000)))) .isInstanceOf(HotRodClientException.class) .hasMessageContaining("bytes can be at most 32766"); // the server continue to work KeywordEntity entity = new KeywordEntity(createLargeDescription(1)); remoteCache.put(1, entity); QueryFactory queryFactory = Search.getQueryFactory(remoteCache); assertEquals(1, queryFactory.create("from KeywordEntity where keyword : 'foo bar0 baz'").execute().count().value()); } public String createLargeDescription(int times) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < times; i++) { String desc = DESCRIPTION.replace("%", i + ""); builder.append(desc); if (i < times - 1) { builder.append(" "); } } return builder.toString(); } }
2,945
38.28
122
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryRepeatedMappingTest.java
package org.infinispan.client.hotrod.query; import static java.nio.charset.StandardCharsets.UTF_8; import static org.infinispan.commons.api.CacheContainerAdmin.AdminFlag.VOLATILE; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM_TYPE; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.commons.configuration.StringConfiguration; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.query.dsl.Query; import org.infinispan.server.core.admin.embeddedserver.EmbeddedServerAdminOperationHandler; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.testng.annotations.Test; /** * Tests protobuf mapping with nested indexed and non-indexed messages * * @since 12.1 */ @Test(testName = "client.hotrod.query.RemoteQueryRepeatedMappingTest", groups = "functional") public class RemoteQueryRepeatedMappingTest extends SingleHotRodServerTest { private static final String CACHE_NAME = RemoteQueryRepeatedMappingTest.class.getName(); private static final String SCHEMA_FILE = "indexed-repeated.proto"; @Override protected HotRodServer createHotRodServer() { HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder(); serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler()); return HotRodClientTestingUtil.startHotRodServer(cacheManager, serverBuilder); } @Override protected RemoteCacheManager getRemoteCacheManager() { return super.getRemoteCacheManager(); } @Test public void testCreateAndQuery() throws Exception { registerProtoBuf(); RemoteCache<Object, Object> cache = remoteCacheManager.administration().withFlags(VOLATILE) .createCache(CACHE_NAME, createCacheXMLConfig()); DataFormat dataFormat = DataFormat.builder().keyType(APPLICATION_JSON).valueType(APPLICATION_JSON).build(); RemoteCache<byte[], byte[]> jsonCache = cache.withDataFormat(dataFormat); jsonCache.put(keyAsJson(), valueAsJson()); Query<Object> querySlowChildren = Search.getQueryFactory(cache).create("SELECT COUNT(*) FROM Parent p WHERE p.slowChildren.id = 0"); Query<Object> queryFastChildren = Search.getQueryFactory(cache).create("SELECT COUNT(*) FROM Parent p WHERE p.fastChildren.id = 10"); Query<Object> queryFieldChildren = Search.getQueryFactory(cache).create("SELECT COUNT(*) FROM Parent p WHERE p.fieldLessChildren.id = 0"); Query<Object> queryNotIndexedWithFieldChildren = Search.getQueryFactory(cache).create("SELECT COUNT(*) FROM Parent p WHERE p.notIndexedWithFieldChild.id = 37"); assertEquals(1, querySlowChildren.execute().count().value()); assertEquals(1, queryFastChildren.execute().count().value()); assertEquals(1, queryFieldChildren.execute().count().value()); assertEquals(1, queryNotIndexedWithFieldChildren.execute().count().value()); } private byte[] keyAsJson() { return Json.object().set("_type", "int32").set("_value", "1").toString().getBytes(UTF_8); } private byte[] valueAsJson() { Json parent = Json.object() .set("_type", "Parent") .set("id", 1) .set("name", "Kim") .set("slowChildren", Json.array(Json.object().set("id", "0"))) .set("fastChildren", Json.array(Json.object().set("id", "10"))) .set("fieldLessChildren", Json.array(Json.object().set("id", "0"))) .set("notIndexedWithFieldChild", Json.array(Json.object().set("id", "37"))); return parent.toString().getBytes(UTF_8); } private void registerProtoBuf() throws Exception { RemoteCache<String, String> protoCache = remoteCacheManager.getCache(PROTOBUF_METADATA_CACHE_NAME); String protobuf = Util.getResourceAsString(SCHEMA_FILE, getClass().getClassLoader()); protoCache.put(SCHEMA_FILE, protobuf); } private StringConfiguration createCacheXMLConfig() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.encoding().mediaType(APPLICATION_PROTOSTREAM_TYPE); builder.indexing().enable().storage(LOCAL_HEAP).addIndexedEntities("Parent"); String config = builder.build().toStringConfiguration(CACHE_NAME); return new StringConfiguration(config); } }
5,094
47.990385
166
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteOffHeapQueryDslConditionsTest.java
package org.infinispan.client.hotrod.query; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.testng.annotations.Test; /** * @author anistor@redhat.com */ @Test(groups = "functional", testName = "client.hotrod.query.RemoteOffHeapQueryDslConditionsTest") public class RemoteOffHeapQueryDslConditionsTest extends RemoteQueryDslConditionsTest { @Override protected ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder builder = super.getConfigurationBuilder(); builder.memory().storageType(StorageType.OFF_HEAP); return builder; } }
659
32
98
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/HotRodQueryTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers; 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.Collections; import java.util.List; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.query.testdomain.protobuf.AddressPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.internal.PrivateGlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.embedded.testdomain.Address; import org.infinispan.query.dsl.embedded.testdomain.User; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test query via Hot Rod on a LOCAL cache. * * @author anistor@redhat.com * @since 6.0 */ @Test(testName = "client.hotrod.query.HotRodQueryTest", groups = {"functional", "smoke"}) public class HotRodQueryTest extends SingleCacheManagerTest { private static final String TEST_CACHE_NAME = "userCache"; private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); protected HotRodServer hotRodServer; protected RemoteCacheManager remoteCacheManager; protected RemoteCache<Integer, User> remoteCache; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder().nonClusteredDefault(); gcb.jmx().enabled(true) .domain(getClass().getSimpleName()) .mBeanServerLookup(mBeanServerLookup); gcb.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true); gcb.serialization().addContextInitializer(TestDomainSCI.INSTANCE); configure(gcb); ConfigurationBuilder builder = getConfigurationBuilder(); cacheManager = TestCacheManagerFactory.createCacheManager(gcb, new ConfigurationBuilder()); cacheManager.defineConfiguration(TEST_CACHE_NAME, builder.build()); cache = cacheManager.getCache(TEST_CACHE_NAME); hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServer().host("127.0.0.1").port(hotRodServer.getPort()).addContextInitializer(TestDomainSCI.INSTANCE); remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); remoteCache = remoteCacheManager.getCache(TEST_CACHE_NAME); return cacheManager; } protected void configure(GlobalConfigurationBuilder builder) { // no-op } protected ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.User"); return builder; } @AfterClass(alwaysRun = true) public void release() { killRemoteCacheManager(remoteCacheManager); remoteCacheManager = null; killServers(hotRodServer); hotRodServer = null; } @BeforeClass(alwaysRun = true) protected void populateCache() { User user1 = new UserPB(); user1.setId(1); user1.setName("Tom"); user1.setSurname("Cat"); user1.setGender(User.Gender.MALE); user1.setAccountIds(Collections.singleton(12)); Address address1 = new AddressPB(); address1.setStreet("Dark Alley"); address1.setPostCode("1234"); user1.setAddresses(Collections.singletonList(address1)); remoteCache.put(1, user1); User user2 = new UserPB(); user2.setId(2); user2.setName("Adrian"); user2.setSurname("Nistor"); user2.setGender(User.Gender.MALE); Address address2 = new AddressPB(); address2.setStreet("Old Street"); address2.setPostCode("XYZ"); user2.setAddresses(Collections.singletonList(address2)); remoteCache.put(2, user2); } @Override protected void clearContent() { //Don't clear, this is destroying the index } public void testAttributeQuery() { // get user back from remote cache and check its attributes User fromCache = remoteCache.get(1); assertNotNull(fromCache); assertUser1(fromCache); // get user back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache); Query<User> query = qf.create("FROM sample_bank_account.User u WHERE u.name = 'Tom'"); List<User> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertEquals(UserPB.class, list.get(0).getClass()); assertUser1(list.get(0)); } public void testEmbeddedAttributeQuery() { // get user back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache); Query<User> query = qf.create("FROM sample_bank_account.User u WHERE u.addresses.postCode = '1234'"); List<User> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertEquals(UserPB.class, list.get(0).getClass()); assertUser1(list.get(0)); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN028503: Property addresses can not be selected from type sample_bank_account.User since it is an embedded entity.") public void testInvalidEmbeddedAttributeQuery() { QueryFactory qf = Search.getQueryFactory(remoteCache); Query<Object[]> q = qf.create("SELECT addresses FROM sample_bank_account.User"); q.execute(); // exception expected } public void testProjections() { // get user back from remote cache and check its attributes User fromCache = remoteCache.get(1); assertUser1(fromCache); // get user back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache); Query<Object[]> query = qf.create("SELECT name, surname FROM sample_bank_account.User WHERE name = 'Tom'"); List<Object[]> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertEquals(Object[].class, list.get(0).getClass()); assertEquals("Tom", list.get(0)[0]); assertEquals("Cat", list.get(0)[1]); } private void assertUser1(User user) { assertNotNull(user); assertEquals(1, user.getId()); assertEquals("Tom", user.getName()); assertEquals("Cat", user.getSurname()); assertEquals(User.Gender.MALE, user.getGender()); assertNotNull(user.getAccountIds()); assertEquals(1, user.getAccountIds().size()); assertTrue(user.getAccountIds().contains(12)); assertNotNull(user.getAddresses()); assertEquals(1, user.getAddresses().size()); assertEquals("Dark Alley", user.getAddresses().get(0).getStreet()); assertEquals("1234", user.getAddresses().get(0).getPostCode()); } }
8,229
40.356784
215
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/MultipleIndexedCacheTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.Assert.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.Collections; import java.util.Date; import org.infinispan.Cache; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.query.testdomain.protobuf.AccountPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.MultiHotRodServersTest; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.Indexer; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.Test; /** * Tests for multiple indexed caches in the server. */ @Test(testName = "client.hotrod.query.MultipleIndexedCacheTest", groups = "functional") public class MultipleIndexedCacheTest extends MultiHotRodServersTest { private static final String USER_CACHE = "users"; private static final String ACCOUNT_CACHE = "accounts"; private static final int NODES = 3; private static final int NUM_ENTRIES = 50; private RemoteCache<Integer, UserPB> userCache; private RemoteCache<Integer, AccountPB> accountCache; public Configuration buildIndexedConfig() { ConfigurationBuilder builder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false)); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.User") .addIndexedEntity("sample_bank_account.Account"); return builder.build(); } public Configuration getNonIndexLockConfig() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false).build(); } public Configuration getNonIndexDataConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false).build(); } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder defaultConfiguration = new ConfigurationBuilder(); createHotRodServers(NODES, defaultConfiguration); cacheManagers.forEach(cm -> { cm.defineConfiguration(USER_CACHE, buildIndexedConfig()); cm.defineConfiguration(ACCOUNT_CACHE, buildIndexedConfig()); cm.getCache(USER_CACHE); cm.getCache(ACCOUNT_CACHE); }); waitForClusterToForm(USER_CACHE, ACCOUNT_CACHE); userCache = client(0).getCache(USER_CACHE); accountCache = client(0).getCache(ACCOUNT_CACHE); for (int i = 0; i < NUM_ENTRIES; i++) { AccountPB account = new AccountPB(); account.setId(i); account.setDescription("account" + i); account.setCreationDate(new Date()); accountCache.put(account.getId(), account); UserPB user = new UserPB(); user.setId(i); user.setName("name" + i); user.setSurname("surname" + i); user.setAccountIds(Collections.singleton(i)); userCache.put(user.getId(), user); } } @Override protected SerializationContextInitializer contextInitializer() { return TestDomainSCI.INSTANCE; } @Test public void testMassIndexing() { assertEquals(query("sample_bank_account.Account", accountCache, "description", "'account1'"), 1); assertEquals(query("sample_bank_account.User", userCache, "name", "'name1'"), 1); reindex(ACCOUNT_CACHE); assertEquals(query("sample_bank_account.Account", accountCache, "description", "'account1'"), 1); assertEquals(query("sample_bank_account.User", userCache, "name", "'name1'"), 1); reindex(USER_CACHE); assertEquals(query("sample_bank_account.Account", accountCache, "description", "'account1'"), 1); assertEquals(query("sample_bank_account.User", userCache, "name", "'name1'"), 1); } @Test public void testLocalQueries() { Query<?> matchAll = Search.getQueryFactory(userCache).create("FROM sample_bank_account.User"); long totalUsers = matchAll.execute().count().value(); assertEquals(totalUsers, NUM_ENTRIES); long partialCount = matchAll.local(true).execute().count().value(); assertTrue(partialCount > 0 && partialCount < NUM_ENTRIES); } private void reindex(String cacheName) { Cache<?, ?> cache = cacheManagers.get(0).getCache(cacheName); Indexer indexer = org.infinispan.query.Search.getIndexer(cache); CompletionStages.join(indexer.run()); } private <T> long query(String entity, RemoteCache<?, ?> cache, String fieldName, String fieldValue) { QueryFactory qf = Search.getQueryFactory(cache); Query<T> q = qf.create("FROM " + entity + " WHERE " + fieldName + " = " + fieldValue); return q.execute().count().value(); } }
5,319
38.117647
122
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteNonIndexedQueryDslConditionsTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Test for query conditions (filtering) without an index. Exercises the whole query DSL on the sample domain model. * * @author anistor@redhat.com * @since 7.0 */ @Test(groups = "functional", testName = "client.hotrod.query.RemoteNonIndexedQueryDslConditionsTest") public class RemoteNonIndexedQueryDslConditionsTest extends RemoteQueryDslConditionsTest { @Override protected ConfigurationBuilder getConfigurationBuilder() { return hotRodCacheConfiguration(); } @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Indexing was not enabled on cache.*") @Override public void testIndexPresence() { org.infinispan.query.Search.getIndexer(getEmbeddedCache()); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextTerm() { super.testFullTextTerm(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "java.lang.IllegalStateException: The cache must be indexed in order to use full-text queries.") @Override public void testFullTextPhrase() { super.testFullTextPhrase(); } }
1,610
38.292683
189
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/EvictionProtobufTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.StorageType.HEAP; import static org.infinispan.eviction.EvictionStrategy.REMOVE; import static org.testng.Assert.assertEquals; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.test.MultiHotRodServersTest; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.IndexStorage; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoDoc; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.server.hotrod.HotRodServer; import org.testng.annotations.Test; /** * @since 12.0 */ @Test(groups = "functional", testName = "client.hotrod.query.EvictionProtobufTest") public class EvictionProtobufTest extends MultiHotRodServersTest { private static final int NUM_SERVERS = 2; private static final String CACHE_NAME = "test"; @Override protected void createCacheManagers() throws Throwable { createHotRodServers(NUM_SERVERS, new ConfigurationBuilder()); ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); builder.encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); builder.expiration().wakeUpInterval(60_000); builder.memory().storage(HEAP).maxSize("1000000000").whenFull(REMOVE); builder.indexing().enable().storage(IndexStorage.LOCAL_HEAP).addIndexedEntities("sample.Book"); for (HotRodServer server : servers) { server.getCacheManager().defineConfiguration(CACHE_NAME, builder.build()); server.getCacheManager().getCache(CACHE_NAME); } } @Override protected SerializationContextInitializer contextInitializer() { return TestSCI.INSTANCE; } @Test public void testCacheInteraction() { RemoteCacheManager client = client(0); RemoteCache<String, Book> cache = client.getCache(CACHE_NAME); cache.put("100", new Book("Persepolis Rising", "James Corey", 2017)); assertEquals(cache.size(), 1); cache.put("100", new Book("Nemesis Games", "James Corey", 2015)); assertEquals(cache.size(), 1); cache.remove("100"); assertEquals(cache.size(), 0); } @AutoProtoSchemaBuilder( includeClasses = Book.class, schemaFileName = "test.EvictionProtobufTest.proto", schemaFilePath = "proto/generated", schemaPackageName = "sample" ) interface TestSCI extends SerializationContextInitializer { EvictionProtobufTest.TestSCI INSTANCE = new TestSCIImpl(); } @ProtoDoc("@Indexed") public static class Book { @ProtoDoc("@Field(index=Index.YES, analyze = Analyze.YES, store = Store.NO)") @ProtoField(number = 1) final String title; @ProtoDoc("@Field(index=Index.YES, analyze = Analyze.YES, store = Store.NO)") @ProtoField(number = 2) final String author; @ProtoDoc("@Field(index=Index.YES, analyze = Analyze.YES, store = Store.NO)") @ProtoField(number = 3, defaultValue = "0") final int publicationYear; @ProtoFactory public Book(String title, String author, int publicationYear) { this.title = title; this.author = author; this.publicationYear = publicationYear; } } }
3,675
35.39604
101
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/ReplicationIndexTransactionalTest.java
package org.infinispan.client.hotrod.query; import org.testng.annotations.Test; /** * Test indexing during state transfer with a transactional cache. */ @Test(groups = "functional", testName = "client.hotrod.query.ReplicationIndexTransactionalTest") public class ReplicationIndexTransactionalTest extends ReplicationIndexTest { @Override protected boolean isTransactional() { return true; } }
413
24.875
96
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryTestUtils.java
package org.infinispan.client.hotrod.query; import static org.testng.AssertJUnit.fail; import org.infinispan.commons.api.BasicCache; import org.infinispan.commons.logging.LogFactory; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.infinispan.query.remote.impl.logging.Log; /** * @author anistor@redhat.com * @since 9.3 */ public final class RemoteQueryTestUtils { private static final Log log = LogFactory.getLog(RemoteQueryTestUtils.class, Log.class); /** * Logs the Protobuf schema errors (if any) and fails the test if there are schema errors. */ public static void checkSchemaErrors(BasicCache<String, String> metadataCache) { if (metadataCache.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX)) { // The existence of this key indicates there are errors in some files String files = metadataCache.get(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX); for (String fname : files.split("\n")) { String errorKey = fname + ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX; String errorMessage = metadataCache.get(errorKey); log.errorf("Found errors in Protobuf schema file: %s\n%s\n", fname, errorMessage); } fail("There are errors in the following Protobuf schema files:\n" + files); } } }
1,370
38.171429
94
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/MultipleIndexFieldAnnotationsTest.java
package org.infinispan.client.hotrod.query; import static org.assertj.core.api.Assertions.assertThat; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.query.testdomain.protobuf.Color; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.IndexStorage; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.query.MultipleIndexFieldAnnotationsTest") public class MultipleIndexFieldAnnotationsTest extends SingleHotRodServerTest { // 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 = new ConfigurationBuilder(); builder.indexing().enable() .storage(IndexStorage.LOCAL_HEAP) .addIndexedEntity("Color"); EmbeddedCacheManager manager = TestCacheManagerFactory.createServerModeCacheManager(); manager.defineConfiguration("colors", builder.build()); return manager; } @Override protected SerializationContextInitializer contextInitializer() { return Color.ColorSchema.INSTANCE; } @Test public void testDifferentIndexProperties() { RemoteCache<Integer, Color> remoteCache = remoteCacheManager.getCache("colors"); Color color1 = new Color(); color1.setName("red"); color1.setDescription(RED_DESCRIPTION); remoteCache.put(1, color1); Color color2 = new Color(); color2.setName("green"); color2.setDescription(GREEN_DESCRIPTION); remoteCache.put(2, color2); Color color3 = new Color(); color3.setName("blue"); color3.setDescription(BLUE_DESCRIPTION); remoteCache.put(3, color3); QueryFactory queryFactory = Search.getQueryFactory(remoteCache); Query<Color> query = queryFactory.create("from Color where name = 'red'"); QueryResult<Color> result = query.execute(); assertThat(result.count().value()).isEqualTo(1L); assertThat(result.list()).extracting("name").contains("red"); } }
2,991
41.140845
191
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/HotRodQueryIspnDirectoryTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import java.util.List; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.marshall.UTF8StringMarshaller; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryResult; import org.testng.annotations.Test; /** * Test remote queries against Infinispan Directory provider. * * @author anistor@redhat.com * @since 6.0 */ @Test(testName = "client.hotrod.query.HotRodQueryIspnDirectoryTest", groups = "functional") public class HotRodQueryIspnDirectoryTest extends HotRodQueryTest { public void testReadAsJSON() { DataFormat acceptJSON = DataFormat.builder().valueType(APPLICATION_JSON).valueMarshaller(new UTF8StringMarshaller()).build(); RemoteCache<Integer, String> jsonCache = remoteCache.withDataFormat(acceptJSON); Json user1 = Json.read(jsonCache.get(1)); assertEquals("Tom", user1.at("name").asString()); assertEquals("Cat", user1.at("surname").asString()); Query<String> query = Search.getQueryFactory(jsonCache).create("FROM sample_bank_account.User WHERE name = :name"); query.maxResults(10).startOffset(0).setParameter("name", "Tom"); QueryResult<String> result = query.execute(); List<String> results = result.list(); assertEquals(1, query.getResultSize()); assertFalse(query.hasProjections()); Json jsonNode = Json.read(results.iterator().next()); assertEquals("Tom", jsonNode.at("name").asString()); assertEquals("Cat", jsonNode.at("surname").asString()); query = Search.getQueryFactory(jsonCache).create("FROM sample_bank_account.User WHERE name = \"Tom\""); results = query.execute().list(); assertEquals(1, results.size()); } }
2,091
37.036364
131
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/HotRodQueryFileSystemTest.java
package org.infinispan.client.hotrod.query; 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.testng.annotations.Test; /** * Tests verifying the functionality of Remote queries for HotRod using FileSystem as a directory provider. * * @author Anna Manukyan * @author anistor@redhat.com */ @Test(testName = "client.hotrod.query.HotRodQueryFileSystemTest", groups = "functional") public class HotRodQueryFileSystemTest extends HotRodQueryIspnDirectoryTest { private final String indexDirectory = CommonsTestingUtil.tmpDirectory(getClass()); @Override protected ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder builder = super.getConfigurationBuilder(); builder.indexing().storage(IndexStorage.FILESYSTEM).path(indexDirectory); return builder; } @Override protected void setup() throws Exception { Util.recursiveFileRemove(indexDirectory); boolean created = new File(indexDirectory).mkdirs(); assertTrue(created); super.setup(); } @Override protected void teardown() { try { //first stop cache managers, then clear the index super.teardown(); } finally { //delete the index otherwise it will mess up the index for next tests Util.recursiveFileRemove(indexDirectory); } } }
1,576
30.54
107
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryNonQueryableCacheTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.embedded.testdomain.User; import org.infinispan.test.TestDataSCI; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Tests for error reporting when trying to query caches that are not queryable, i.e., not storing protobuf * or java objects * * @since 11.0 */ @Test(testName = "client.hotrod.query.RemoteQueryNonQueryableCacheTest", groups = "functional") public class RemoteQueryNonQueryableCacheTest extends SingleHotRodServerTest { private static final String DEFAULT_CACHE = "default"; private static final String INDEXED_CACHE = "indexed"; private static final String PROTOBUF_CACHE = "protobuf"; private static final String POJO_CACHE = "object"; private static final String JSON_CACHE = "json"; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { EmbeddedCacheManager cm = TestCacheManagerFactory.createServerModeCacheManager(TestDomainSCI.INSTANCE, new ConfigurationBuilder()); cm.defineConfiguration(DEFAULT_CACHE, new ConfigurationBuilder().build()); cm.defineConfiguration(INDEXED_CACHE, createIndexedCache()); cm.defineConfiguration(PROTOBUF_CACHE, createCache(MediaType.APPLICATION_PROTOSTREAM_TYPE)); cm.defineConfiguration(POJO_CACHE, createCache(MediaType.APPLICATION_OBJECT_TYPE)); cm.defineConfiguration(JSON_CACHE, createCache(MediaType.APPLICATION_JSON_TYPE)); return cm; } @Override protected SerializationContextInitializer contextInitializer() { return TestDataSCI.INSTANCE; } private Configuration createCache(String mediaType) { return new ConfigurationBuilder().encoding().mediaType(mediaType).build(); } private Configuration createIndexedCache() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.User") .addIndexedEntity("sample_bank_account.Account") .addIndexedEntity("sample_bank_account.Transaction"); return builder.build(); } @Test public void testQueryable() { executeQuery(DEFAULT_CACHE); executeQuery(INDEXED_CACHE); executeQuery(PROTOBUF_CACHE); executeQuery(POJO_CACHE); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN028015.*") public void assertErrorForCacheWithoutNonQueryableEncoding() { executeQuery(JSON_CACHE); } private void executeQuery(String cacheName) { RemoteCache<String, User> remoteCache = remoteCacheManager.getCache(cacheName); Query<User> q = Search.getQueryFactory(remoteCache).create("FROM sample_bank_account.User"); q.execute(); } }
3,577
40.604651
137
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryStringTest.java
package org.infinispan.client.hotrod.query; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import java.time.Instant; import java.util.List; import org.infinispan.Cache; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.marshall.NotIndexedSCI; import org.infinispan.client.hotrod.query.testdomain.protobuf.AnalyzerTestEntity; import org.infinispan.client.hotrod.query.testdomain.protobuf.ModelFactoryPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.AnalyzerTestEntityMarshaller; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.marshall.AbstractSerializationContextInitializer; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.query.dsl.embedded.QueryStringTest; import org.infinispan.query.dsl.embedded.testdomain.ModelFactory; 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.server.hotrod.HotRodServer; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test for query language in remote mode. * * @author anistor@redhat.com * @since 9.0 */ @Test(groups = "functional", testName = "client.hotrod.query.RemoteQueryStringTest") public class RemoteQueryStringTest extends QueryStringTest { private static final SerializationContextInitializer CUSTOM_ANALYZER_SCI = new AbstractSerializationContextInitializer("custom_analyzer.proto") { @Override public String getProtoFile() { return "package sample_bank_account;\n" + "/* @Indexed \n" + " @Analyzer(definition = \"standard-with-stop\") */" + "message AnalyzerTestEntity {\n" + "\t/* @Field(store = Store.YES, analyze = Analyze.YES, analyzer = @Analyzer(definition = \"stemmer\")) */\n" + "\toptional string f1 = 1;\n" + "\t/* @Field(store = Store.YES, analyze = Analyze.NO, indexNullAs = \"-1\") */\n" + "\toptional int32 f2 = 2;\n" + "}\n"; } @Override public void registerMarshallers(SerializationContext serCtx) { serCtx.registerMarshaller(new AnalyzerTestEntityMarshaller()); } }; protected HotRodServer hotRodServer; protected RemoteCacheManager remoteCacheManager; protected RemoteCache<Object, Object> remoteCache; protected Cache<Object, Object> cache; @BeforeClass @Override protected void populateCache() throws Exception { super.populateCache(); getCacheForWrite().put("analyzed1", new AnalyzerTestEntity("tested 123", 3)); getCacheForWrite().put("analyzed2", new AnalyzerTestEntity("testing 1234", 3)); getCacheForWrite().put("analyzed3", new AnalyzerTestEntity("xyz", null)); } @Override protected QueryFactory getQueryFactory() { return Search.getQueryFactory(remoteCache); } @Override protected ModelFactory getModelFactory() { return ModelFactoryPB.INSTANCE; } /** * Both populating the cache and querying are done via remote cache. */ @Override protected RemoteCache<Object, Object> getCacheForQuery() { return remoteCache; } protected Cache<Object, Object> getEmbeddedCache() { return cache; } protected int getNodesCount() { return 1; } @Override protected void createCacheManagers() throws Throwable { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().clusteredDefault(); globalBuilder.serialization().addContextInitializers(TestDomainSCI.INSTANCE, NotIndexedSCI.INSTANCE, CUSTOM_ANALYZER_SCI); createClusteredCaches(getNodesCount(), globalBuilder, getConfigurationBuilder(), true); cache = manager(0).getCache(); hotRodServer = HotRodClientTestingUtil.startHotRodServer(manager(0)); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServer().host("127.0.0.1").port(hotRodServer.getPort()) .addContextInitializers(TestDomainSCI.INSTANCE, NotIndexedSCI.INSTANCE, CUSTOM_ANALYZER_SCI); remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); remoteCache = remoteCacheManager.getCache(); } protected ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder builder = hotRodCacheConfiguration(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.User") .addIndexedEntity("sample_bank_account.Account") .addIndexedEntity("sample_bank_account.Transaction") .addIndexedEntity("sample_bank_account.AnalyzerTestEntity"); return builder; } @AfterClass(alwaysRun = true) public void release() { killRemoteCacheManager(remoteCacheManager); remoteCacheManager = null; killServers(hotRodServer); hotRodServer = null; } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "org.infinispan.objectfilter.ParsingException: ISPN014036: Prefix, wildcard or regexp queries cannot be fuzzy.*") @Override public void testFullTextWildcardFuzzyNotAllowed() { super.testFullTextWildcardFuzzyNotAllowed(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "org.infinispan.objectfilter.ParsingException: ISPN028526: Invalid query.*") @Override public void testFullTextRegexpFuzzyNotAllowed() { super.testFullTextRegexpFuzzyNotAllowed(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "org.infinispan.objectfilter.ParsingException: ISPN028522: .*property is analyzed.*") @Override public void testExactMatchOnAnalyzedFieldNotAllowed() { // exception is wrapped in HotRodClientException super.testExactMatchOnAnalyzedFieldNotAllowed(); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = "org.infinispan.objectfilter.ParsingException: ISPN028521: .*unless the property is indexed and analyzed.*") @Override public void testFullTextTermOnNonAnalyzedFieldNotAllowed() { // exception is wrapped in HotRodClientException super.testFullTextTermOnNonAnalyzedFieldNotAllowed(); } /** * This test is overridden because instants need special handling for protobuf (being actually emulated as long * timestamps). */ @Override public void testInstant1() { Query<User> q = createQueryFromString("from " + getModelFactory().getUserTypeName() + " u where u.creationDate = " + Instant.parse("2011-12-03T10:15:30Z").toEpochMilli()); List<User> list = q.execute().list(); assertEquals(3, list.size()); } /** * This test is overridden because instants need special handling for protobuf (being actually emulated as long * timestamps). */ @Override public void testInstant2() { Query<User> q = createQueryFromString("from " + getModelFactory().getUserTypeName() + " u where u.passwordExpirationDate = " + Instant.parse("2011-12-03T10:15:30Z").toEpochMilli()); List<User> list = q.execute().list(); assertEquals(3, list.size()); } public void testCustomFieldAnalyzer() { Query<AnalyzerTestEntity> q = createQueryFromString("from sample_bank_account.AnalyzerTestEntity where f1:'test'"); List<AnalyzerTestEntity> list = q.execute().list(); assertEquals(2, list.size()); } @Override public void testEqNonIndexedType() { Query<NotIndexed> q = createQueryFromString("from sample_bank_account.NotIndexed where notIndexedField = 'testing 123'"); List<NotIndexed> list = q.execute().list(); assertEquals(1, list.size()); assertEquals("testing 123", list.get(0).notIndexedField); } @Override public void testDeleteByQueryOnNonIndexedType() { getCacheForWrite().put("notIndexedToBeDeleted", new NotIndexed("testing delete")); Query<NotIndexed> select = createQueryFromString("FROM sample_bank_account.NotIndexed WHERE notIndexedField = 'testing delete'"); QueryResult<NotIndexed> result = select.execute(); assertThat(result.count().value()).isOne(); assertThat(result.count().isExact()).isTrue(); Query<Transaction> delete = createQueryFromString("DELETE FROM sample_bank_account.NotIndexed WHERE notIndexedField = 'testing delete'"); assertEquals(1, delete.executeStatement()); result = select.execute(); assertThat(result.count().value()).isZero(); assertThat(result.count().isExact()).isTrue(); } @Override @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN028526: Invalid query.*") public void testDeleteWithProjections() { super.testDeleteWithProjections(); } @Override @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN028526: Invalid query.*") public void testDeleteWithOrderBy() { super.testDeleteWithOrderBy(); } @Override @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN028526: Invalid query.*") public void testDeleteWithGroupBy() { super.testDeleteWithGroupBy(); } @Override @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN014057: DELETE statements cannot use paging \\(firstResult/maxResults\\)") public void testDeleteWithPaging() { super.testDeleteWithPaging(); } }
10,823
41.447059
206
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/IndexNoIndexedTest.java
package org.infinispan.client.hotrod.query; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Collections; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.query.testdomain.protobuf.Reviewer; import org.infinispan.client.hotrod.query.testdomain.protobuf.Revision; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.IndexStorage; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.query.IndexNoIndexedTest") public class IndexNoIndexedTest extends SingleHotRodServerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() .storage(IndexStorage.LOCAL_HEAP) .addIndexedEntity("Reviewer") .addIndexedEntity("Revision"); EmbeddedCacheManager manager = TestCacheManagerFactory.createServerModeCacheManager(); manager.defineConfiguration("revisions", builder.build()); return manager; } @Override protected SerializationContextInitializer contextInitializer() { return Reviewer.ReviewerSchema.INSTANCE; } @Test public void testIndexedEntityWithNoIndexedFields() { RemoteCache<Integer, Revision> remoteCache = remoteCacheManager.getCache("revisions"); Revision revision = new Revision("ccc", "ddd"); revision.setReviewers(Collections.singletonList(new Reviewer("aaa", "bbb"))); assertThat(revision).isNotNull(); assertThatThrownBy(() -> remoteCache.put(1, revision)).isInstanceOf(HotRodClientException.class) .hasMessageContaining("The configured indexed-entity type 'Reviewer' must be indexed"); } }
2,196
39.685185
102
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/MultiHotRodServerIspnDirQueryTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.testng.annotations.Test; /** * Verifying the functionality of queries using a local infinispan directory provider. * * @author Anna Manukyan */ @Test(testName = "client.hotrod.query.MultiHotRodServerIspnDirQueryTest", groups = "functional") public class MultiHotRodServerIspnDirQueryTest extends MultiHotRodServerQueryTest { protected static final String TEST_CACHE = "queryableCache"; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder defaultConfiguration = new ConfigurationBuilder(); createHotRodServers(3, defaultConfiguration); ConfigurationBuilder builder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false)); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.User"); for (EmbeddedCacheManager cm : cacheManagers) { cm.defineConfiguration(TEST_CACHE, builder.build()); cm.getCache(TEST_CACHE); } waitForClusterToForm(); remoteCache0 = client(0).getCache(TEST_CACHE); remoteCache1 = client(1).getCache(TEST_CACHE); } }
1,544
35.785714
122
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryStringBroadcastTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Tests for local indexes in the Hot Rod client. * * @since 9.2 */ @Test(groups = "functional", testName = "client.hotrod.query.RemoteQueryStringBroadcastTest") public class RemoteQueryStringBroadcastTest extends RemoteQueryStringTest { @Override protected ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder cfgBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); cfgBuilder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.User") .addIndexedEntity("sample_bank_account.Transaction") .addIndexedEntity("sample_bank_account.AnalyzerTestEntity"); return cfgBuilder; } @Override protected int getNodesCount() { return 3; } }
1,056
31.030303
93
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryProtostreamAnnotationsDisableIndexingTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import java.util.List; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.marshall.MarshallerUtil; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoSchemaBuilder; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests for remote queries over HotRod using protostream annotations on a local cache using indexing in RAM. Indexing * is not enabled for the searched entity. Non-indexed querying should still work. * * @author anistor@redhat.com * @since 9.4 */ @Test(groups = "functional", testName = "client.hotrod.query.RemoteQueryProtostreamAnnotationsDisableIndexingTest") public class RemoteQueryProtostreamAnnotationsDisableIndexingTest extends SingleHotRodServerTest { public static class Memo { @ProtoField(number = 10, required = true) public int id; @ProtoField(20) public String text; @ProtoField(30) public Author author; public Memo(int id, String text) { this.id = id; this.text = text; } public Memo() { } @Override public String toString() { return "Memo{id=" + id + ", text='" + text + '\'' + ", author=" + author + '}'; } } public static class Author { @ProtoField(number = 1, required = true) public int id; @ProtoField(2) public String name; public Author(int id, String name) { this.id = id; this.name = name; } public Author() { } @Override public String toString() { return "Author{id=" + id + ", name='" + name + "'}"; } } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { org.infinispan.configuration.cache.ConfigurationBuilder builder = new org.infinispan.configuration.cache.ConfigurationBuilder(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.User"); return TestCacheManagerFactory.createServerModeCacheManager(TestDomainSCI.INSTANCE, builder); } @Override protected RemoteCacheManager getRemoteCacheManager() { org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServer().host("127.0.0.1").port(hotrodServer.getPort()); return new RemoteCacheManager(clientBuilder.build()); } @BeforeClass protected void registerProtobufSchema() throws Exception { //initialize client-side serialization context SerializationContext serializationContext = MarshallerUtil.getSerializationContext(remoteCacheManager); ProtoSchemaBuilder protoSchemaBuilder = new ProtoSchemaBuilder(); String protoSchemaFile = protoSchemaBuilder.fileName("memo.proto") .addClass(Memo.class) .addClass(Author.class) .build(serializationContext); //initialize server-side serialization context RemoteCache<String, String> metadataCache = remoteCacheManager.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); metadataCache.put("memo.proto", protoSchemaFile); assertFalse(metadataCache.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX)); } public void testAttributeQuery() { RemoteCache<Integer, Memo> remoteCache = remoteCacheManager.getCache(); remoteCache.put(1, createMemo1()); remoteCache.put(2, createMemo2()); // get memo1 back from remote cache and check its attributes Memo fromCache = remoteCache.get(1); assertMemo1(fromCache); // get memo1 back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache); Query<Memo> query = qf.from(Memo.class) .having("text").like("%ipsum%") .build(); List<Memo> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertEquals(Memo.class, list.get(0).getClass()); assertMemo1(list.get(0)); // get memo2 back from remote cache via query and check its attributes query = qf.from(Memo.class) .having("author.name").eq("Adrian") .build(); list = query.list(); assertNotNull(list); assertEquals(1, list.size()); assertEquals(Memo.class, list.get(0).getClass()); assertMemo2(list.get(0)); } private Memo createMemo1() { Memo memo = new Memo(1, "Lorem ipsum"); memo.author = new Author(1, "Tom"); return memo; } private Memo createMemo2() { Memo memo = new Memo(2, "Sed ut perspiciatis unde omnis iste natus error"); memo.author = new Author(2, "Adrian"); return memo; } private void assertMemo1(Memo memo) { assertNotNull(memo); assertEquals(1, memo.id); assertEquals("Lorem ipsum", memo.text); assertEquals(1, memo.author.id); } private void assertMemo2(Memo memo) { assertNotNull(memo); assertEquals(2, memo.id); assertEquals("Sed ut perspiciatis unde omnis iste natus error", memo.text); assertEquals(2, memo.author.id); } }
6,196
34.210227
142
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryDisableIndexingTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.util.List; import org.infinispan.Cache; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.marshall.NotIndexedSCI; import org.infinispan.client.hotrod.query.testdomain.protobuf.ModelFactoryPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.embedded.AbstractQueryDslTest; import org.infinispan.query.dsl.embedded.testdomain.ModelFactory; import org.infinispan.query.dsl.embedded.testdomain.NotIndexed; import org.infinispan.search.mapper.mapping.SearchMapping; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.TestingUtil; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test query for message types that are not annotated with {@code @Indexed}. Non-indexed querying must always work. * * @author anistor@redhat.com * @since 9.3 */ @Test(groups = "functional", testName = "client.hotrod.query.RemoteQueryDisableIndexingTest") public class RemoteQueryDisableIndexingTest extends AbstractQueryDslTest { protected HotRodServer hotRodServer; protected RemoteCacheManager remoteCacheManager; protected RemoteCache<Object, Object> remoteCache; protected Cache<Object, Object> cache; @BeforeClass protected void populateCache() { getCacheForWrite().put("notIndexed1", new NotIndexed("testing 123")); getCacheForWrite().put("notIndexed2", new NotIndexed("xyz")); } @Override protected QueryFactory getQueryFactory() { return Search.getQueryFactory(remoteCache); } @Override protected ModelFactory getModelFactory() { return ModelFactoryPB.INSTANCE; } @Override protected RemoteCache<Object, Object> getCacheForQuery() { return remoteCache; } protected Cache<Object, Object> getEmbeddedCache() { return cache; } protected int getNodesCount() { return 1; } @Override protected void createCacheManagers() throws Throwable { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().clusteredDefault(); globalBuilder.serialization().addContextInitializers(TestDomainSCI.INSTANCE, NotIndexedSCI.INSTANCE); createClusteredCaches(getNodesCount(), globalBuilder, getConfigurationBuilder(), true); cache = manager(0).getCache(); hotRodServer = HotRodClientTestingUtil.startHotRodServer(manager(0)); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServer().host("127.0.0.1").port(hotRodServer.getPort()) .addContextInitializers(TestDomainSCI.INSTANCE, NotIndexedSCI.INSTANCE); remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); remoteCache = remoteCacheManager.getCache(); } protected ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder builder = hotRodCacheConfiguration(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.User") .addIndexedEntity("sample_bank_account.Account") .addIndexedEntity("sample_bank_account.Transaction"); return builder; } @AfterClass(alwaysRun = true) public void release() { killRemoteCacheManager(remoteCacheManager); remoteCacheManager = null; killServers(hotRodServer); hotRodServer = null; } public void testEmptyIndexIsPresent() { SearchMapping searchMapping = TestingUtil.extractComponent(cache, SearchMapping.class); // we have indexing for remote query! assertNotNull(searchMapping.indexedEntity("sample_bank_account.User")); assertNotNull(searchMapping.indexedEntity("sample_bank_account.Account")); assertNotNull(searchMapping.indexedEntity("sample_bank_account.Transaction")); // we have some indexes for this cache assertEquals(3, searchMapping.allIndexedEntities().size()); } public void testEqNonIndexedType() { Query<NotIndexed> q = getQueryFactory().create("from sample_bank_account.NotIndexed where notIndexedField = 'testing 123'"); List<NotIndexed> list = q.execute().list(); assertEquals(1, list.size()); assertEquals("testing 123", list.get(0).notIndexedField); } }
5,291
39.090909
142
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/TwoCachesSharedIndexTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.Assert.assertEquals; import java.util.Date; import java.util.List; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.query.testdomain.protobuf.AccountPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.MultiHotRodServersTest; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.embedded.testdomain.Account; import org.infinispan.query.dsl.embedded.testdomain.User; import org.testng.annotations.Test; /** * Tests remote query using two caches and a shared index * * @author gustavonalle * @since 9.0 */ @Test(testName = "client.hotrod.query.TwoCachesSharedIndexTest", groups = "functional") public class TwoCachesSharedIndexTest extends MultiHotRodServersTest { private static final String USER_CACHE = "users"; private static final String ACCOUNT_CACHE = "accounts"; public Configuration buildIndexedConfig() { ConfigurationBuilder builder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false)); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.User") .addIndexedEntity("sample_bank_account.Account"); return builder.build(); } public Configuration getNonIndexLockConfig() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false).build(); } public Configuration getNonIndexDataConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false).build(); } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder defaultConfiguration = new ConfigurationBuilder(); createHotRodServers(2, defaultConfiguration); cacheManagers.forEach(cm -> { cm.defineConfiguration(USER_CACHE, buildIndexedConfig()); cm.defineConfiguration(ACCOUNT_CACHE, buildIndexedConfig()); cm.getCache(USER_CACHE); cm.getCache(ACCOUNT_CACHE); }); waitForClusterToForm(USER_CACHE, ACCOUNT_CACHE); } @Override protected SerializationContextInitializer contextInitializer() { return TestDomainSCI.INSTANCE; } @Test public void testWithUserCache() { RemoteCache<Integer, UserPB> userCache = client(0).getCache(USER_CACHE); userCache.put(1, getUserPB()); Query<User> query = Search.getQueryFactory(userCache).create("FROM sample_bank_account.User WHERE name = 'John'"); List<User> users = query.execute().list(); assertEquals("John", users.iterator().next().getName()); } @Test public void testWithAccountCache() { RemoteCache<Integer, AccountPB> accountCache = client(0).getCache(ACCOUNT_CACHE); accountCache.put(1, getAccountPB()); Query<Account> query = Search.getQueryFactory(accountCache).create("FROM sample_bank_account.Account WHERE description = 'account1'"); List<Account> accounts = query.execute().list(); assertEquals(accounts.iterator().next().getDescription(), "account1"); } private AccountPB getAccountPB() { AccountPB accountPB = new AccountPB(); accountPB.setId(1); accountPB.setDescription("account1"); accountPB.setCreationDate(new Date()); return accountPB; } private UserPB getUserPB() { UserPB userPB = new UserPB(); userPB.setName("John"); userPB.setSurname("Doe"); return userPB; } }
4,072
35.366071
140
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryDslConditionsTunedTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.FILESYSTEM; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.search.mapper.mapping.SearchMapping; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; /** * Verifying that the tuned query configuration also works for Remote Queries. * * @author Anna Manukyan * @author anistor@redhat.com * @since 6.0 */ @Test(testName = "client.hotrod.query.RemoteQueryDslConditionsTunedTest", groups = "functional") public class RemoteQueryDslConditionsTunedTest extends RemoteQueryDslConditionsFilesystemTest { private static final int NUM_SHARDS = 6; @Override protected ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() .storage(FILESYSTEM).path(indexDirectory) .addIndexedEntity("sample_bank_account.User") .addIndexedEntity("sample_bank_account.Account") .addIndexedEntity("sample_bank_account.Transaction") .writer().ramBufferSize(220) .merge().factor(30).maxSize(4096); return builder; } @Override public void testIndexPresence() { SearchMapping searchMapping = TestingUtil.extractComponent(cache, SearchMapping.class); // we have indexing for remote query! assertNotNull(searchMapping.indexedEntity("sample_bank_account.User")); assertNotNull(searchMapping.indexedEntity("sample_bank_account.Account")); assertNotNull(searchMapping.indexedEntity("sample_bank_account.Transaction")); // we have some indexes for this cache assertEquals(3, searchMapping.allIndexedEntities().size()); } }
1,902
36.313725
96
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/TransactionalIndexingTest.java
package org.infinispan.client.hotrod.query; import org.testng.annotations.Test; /** * @since 9.4 */ @Test(testName = "client.hotrod.query.TransactionalIndexingTest", groups = "functional") public class TransactionalIndexingTest extends MultiHotRodServerQueryTest { @Override protected boolean useTransactions() { return true; } }
350
20.9375
88
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/QueryLimitTest.java
package org.infinispan.client.hotrod.query; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.query.testdomain.protobuf.KeywordEntity; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.QueryResult; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.query.QueryLimitTest") public class QueryLimitTest extends SingleHotRodServerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("KeywordEntity"); EmbeddedCacheManager manager = TestCacheManagerFactory.createServerModeCacheManager(); manager.defineConfiguration("keyword", builder.build()); return manager; } @Override protected SerializationContextInitializer contextInitializer() { return KeywordEntity.KeywordSchema.INSTANCE; } @Test public void testNextPageWithNoMaxResults() { RemoteCache<Integer, KeywordEntity> remoteCache = remoteCacheManager.getCache("keyword"); for (int i=0; i<20; i++) { remoteCache.put(i, new KeywordEntity(i + "")); } QueryFactory queryFactory = Search.getQueryFactory(remoteCache); Query<KeywordEntity> query = queryFactory.create("from KeywordEntity"); query.startOffset(10); query.maxResults(-1); QueryResult<KeywordEntity> result = query.execute(); assertThat(result.count().value()).isEqualTo(20); assertThat(result.list()).hasSize(10); } }
2,174
37.839286
95
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/IndexNormalizerTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.query.testdomain.protobuf.Book; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.query.IndexNormalizerTest") public class IndexNormalizerTest extends SingleHotRodServerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("Book"); EmbeddedCacheManager manager = TestCacheManagerFactory.createServerModeCacheManager(); manager.defineConfiguration("books", builder.build()); return manager; } @Override protected SerializationContextInitializer contextInitializer() { return Book.BookSchema.INSTANCE; } @Test public void testLowercaseNormalizer() { RemoteCache<Integer, Book> remoteCache = remoteCacheManager.getCache("books"); remoteCache.put(1, new Book("LIBERTY")); QueryFactory queryFactory = Search.getQueryFactory(remoteCache); assertEquals(1, queryFactory.create("from Book where title : 'li*ty'").execute().count().value()); } }
1,805
37.425532
104
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryJmxTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; 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.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import javax.management.Attribute; import javax.management.JMX; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.query.testdomain.protobuf.AddressPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.commons.jmx.MBeanServerLookup; import org.infinispan.commons.jmx.TestMBeanServerLookup; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.internal.PrivateGlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.embedded.testdomain.Address; import org.infinispan.query.dsl.embedded.testdomain.User; import org.infinispan.query.remote.client.ProtobufMetadataManagerMBean; import org.infinispan.query.remote.impl.indexing.ProtobufValueWrapper; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * Testing the functionality of JMX operations for the Remote Queries. * * @author Anna Manukyan * @author anistor@redhat.com * @since 6.0 */ // TODO HSEARCH-3129 Restore support for statistics @Test(testName = "client.hotrod.query.RemoteQueryJmxTest", groups = "functional", enabled = false) public class RemoteQueryJmxTest extends SingleCacheManagerTest { private static final String TEST_CACHE_NAME = "userCache"; private static final String JMX_DOMAIN = RemoteQueryJmxTest.class.getSimpleName(); private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create(); private final MBeanServer mBeanServer = mBeanServerLookup.getMBeanServer(); private HotRodServer hotRodServer; private RemoteCacheManager remoteCacheManager; private RemoteCache<Integer, User> remoteCache; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder().nonClusteredDefault(); gcb.jmx().enabled(true) .domain(JMX_DOMAIN) .mBeanServerLookup(mBeanServerLookup); gcb.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true); cacheManager = TestCacheManagerFactory.createCacheManager(gcb, null); hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager); ProtobufMetadataManagerMBean protobufMetadataManagerMBean = JMX.newMBeanProxy(mBeanServer, getProtobufMetadataManagerObjectName(), ProtobufMetadataManagerMBean.class); String protofile = Util.getResourceAsString("/sample_bank_account/bank.proto", getClass().getClassLoader()); protobufMetadataManagerMBean.registerProtofile("sample_bank_account/bank.proto", protofile); assertEquals(protofile, protobufMetadataManagerMBean.getProtofile("sample_bank_account/bank.proto")); assertNull(protobufMetadataManagerMBean.getFilesWithErrors()); assertTrue(Arrays.asList(protobufMetadataManagerMBean.getProtofileNames()).contains("sample_bank_account/bank.proto")); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.User"); cacheManager.defineConfiguration(TEST_CACHE_NAME, builder.build()); cache = cacheManager.getCache(TEST_CACHE_NAME); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServer().host("127.0.0.1").port(hotRodServer.getPort()).addContextInitializer(TestDomainSCI.INSTANCE); remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); remoteCache = remoteCacheManager.getCache(TEST_CACHE_NAME); return cacheManager; } @AfterClass(alwaysRun = true) public void release() { killRemoteCacheManager(remoteCacheManager); remoteCacheManager = null; killServers(hotRodServer); hotRodServer = null; } public void testIndexAndQuery() throws Exception { ObjectName name = getQueryStatsObjectName(TEST_CACHE_NAME); assertTrue(mBeanServer.isRegistered(name)); assertFalse((Boolean) mBeanServer.getAttribute(name, "StatisticsEnabled")); mBeanServer.setAttribute(name, new Attribute("StatisticsEnabled", true)); assertTrue((Boolean) mBeanServer.getAttribute(name, "StatisticsEnabled")); remoteCache.put(1, createUser(1)); remoteCache.put(2, createUser(2)); // get user back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache); Query<User> query = qf.create("FROM sample_bank_account.User u WHERE u.addresses.postCode = '1231'"); List<User> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertEquals(UserPB.class, list.get(0).getClass()); assertEquals("Tom1", list.get(0).getName()); assertEquals(2, mBeanServer.invoke(name, "getNumberOfIndexedEntities", new Object[]{ProtobufValueWrapper.class.getName()}, new String[]{String.class.getName()})); Set<String> classNames = (Set<String>) mBeanServer.getAttribute(name, "IndexedClassNames"); assertEquals(1, classNames.size()); assertTrue("The set should contain the ProtobufValueWrapper class name.", classNames.contains(ProtobufValueWrapper.class.getName())); assertTrue("The query execution total time should be > 0.", (Long) mBeanServer.getAttribute(name, "SearchQueryTotalTime") > 0); assertEquals((long) 1, mBeanServer.getAttribute(name, "SearchQueryExecutionCount")); } private User createUser(int id) { User user = new UserPB(); user.setId(id); user.setName("Tom" + id); user.setSurname("Cat" + id); user.setGender(User.Gender.MALE); user.setAccountIds(Collections.singleton(12)); Address address = new AddressPB(); address.setStreet("Dark Alley"); address.setPostCode("123" + id); user.setAddresses(Collections.singletonList(address)); return user; } private ObjectName getQueryStatsObjectName(String cacheName) throws MalformedObjectNameException { String cacheManagerName = cacheManager.getCacheManagerConfiguration().cacheManagerName(); return new ObjectName(JMX_DOMAIN + ":type=Query,manager=" + ObjectName.quote(cacheManagerName) + ",cache=" + ObjectName.quote(cacheName) + ",component=Statistics"); } private ObjectName getProtobufMetadataManagerObjectName() throws MalformedObjectNameException { String cacheManagerName = cacheManager.getCacheManagerConfiguration().cacheManagerName(); return new ObjectName(JMX_DOMAIN + ":type=RemoteQuery,name=" + ObjectName.quote(cacheManagerName) + ",component=" + ProtobufMetadataManagerMBean.OBJECT_NAME); } }
8,209
47.294118
173
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryDslConditionsFilesystemTest.java
package org.infinispan.client.hotrod.query; 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.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * Verifying the functionality of Remote Queries for filesystem directory provider. * * @author Anna Manukyan * @author anistor@redhat.com * @since 6.0 */ @Test(testName = "client.hotrod.query.RemoteQueryDslConditionsFilesystemTest", groups = "functional") public class RemoteQueryDslConditionsFilesystemTest extends RemoteQueryDslConditionsTest { protected final String indexDirectory = CommonsTestingUtil.tmpDirectory(getClass()); @Override protected void createCacheManagers() throws Throwable { Util.recursiveFileRemove(indexDirectory); boolean created = new File(indexDirectory).mkdirs(); assertTrue(created); super.createCacheManagers(); } @Override protected ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder builder = super.getConfigurationBuilder(); builder.indexing().storage(IndexStorage.FILESYSTEM).path(indexDirectory); return builder; } @AfterClass(alwaysRun = true) @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,696
30.425926
101
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryStringBroadcastHAIndexTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Tests for query Broadcasting when using DIST caches with Index.ALL * * @since 10.1 */ @Test(groups = "functional", testName = "client.hotrod.query.RemoteQueryStringBroadcastHAIndexTest") public class RemoteQueryStringBroadcastHAIndexTest extends RemoteQueryStringBroadcastTest { @Override protected ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder cfgBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); cfgBuilder.indexing().enable().storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.User") .addIndexedEntity("sample_bank_account.Account") .addIndexedEntity("sample_bank_account.Transaction") .addIndexedEntity("sample_bank_account.AnalyzerTestEntity"); return cfgBuilder; } }
1,078
37.535714
100
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/MultiServerStoreQueryTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import java.util.Objects; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.marshall.MarshallerUtil; import org.infinispan.client.hotrod.test.MultiHotRodServersTest; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.annotations.ProtoDoc; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoSchemaBuilder; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.testng.annotations.Test; /** * Reproducer for https://issues.jboss.org/browse/ISPN-9068 */ @Test(testName = "client.hotrod.query.MultiServerStoreQueryTest", groups = "functional") public class MultiServerStoreQueryTest extends MultiHotRodServersTest { private static final int NODES = 2; private static final boolean USE_PERSISTENCE = true; private static final String USER_CACHE = "news"; private RemoteCache<Object, Object> userCache; private long evictionSize = -1; @Override protected String parameters() { return "[" + storageType + ":" + evictionSize + "]"; } @Override protected String[] parameterNames() { return concat(super.parameterNames(), "STORAGE-TYPE", "EVICTION_SIZE"); } @Override protected Object[] parameterValues() { return concat(super.parameterValues(), storageType, evictionSize); } public Object[] factory() { return new Object[]{ new MultiServerStoreQueryTest().storageType(StorageType.OFF_HEAP), new MultiServerStoreQueryTest().storageType(StorageType.BINARY), new MultiServerStoreQueryTest().storageType(StorageType.OBJECT), new MultiServerStoreQueryTest().storageType(StorageType.OFF_HEAP).evictionSize(1), new MultiServerStoreQueryTest().storageType(StorageType.BINARY).evictionSize(1), new MultiServerStoreQueryTest().storageType(StorageType.OBJECT).evictionSize(1), }; } public MultiServerStoreQueryTest storageType(StorageType storageType) { this.storageType = storageType; return this; } MultiServerStoreQueryTest evictionSize(long size) { evictionSize = size; return this; } public Configuration getLockCacheConfig() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false).build(); } public Configuration getLuceneCacheConfig(String storeName) { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); if (USE_PERSISTENCE) { builder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class).preload(true).storeName(storeName); } return builder.build(); } public Configuration buildIndexedConfig(String storeName) { ConfigurationBuilder builder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false)); builder.indexing().enable() .storage(LOCAL_HEAP) .writer().commitInterval(500).ramBufferSize(256) .merge().factor(30).maxSize(1024) .addIndexedEntity("News"); builder.memory().storageType(storageType); if (evictionSize > 0) { builder.memory().size(evictionSize); } if (USE_PERSISTENCE) builder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class).preload(true).storeName(storeName); return builder.build(); } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder defaultConfiguration = new ConfigurationBuilder(); createHotRodServers(NODES, defaultConfiguration); RemoteCacheManager remoteCacheManager = client(0); //initialize client-side serialization context SerializationContext serializationContext = MarshallerUtil.getSerializationContext(remoteCacheManager); ProtoSchemaBuilder protoSchemaBuilder = new ProtoSchemaBuilder(); String protoFile = protoSchemaBuilder.fileName("news.proto") .addClass(News.class) .addClass(NewsKey.class) .build(serializationContext); //initialize server-side serialization context RemoteCache<String, String> metadataCache = remoteCacheManager.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); metadataCache.put("news.proto", protoFile); assertFalse(metadataCache.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX)); for (int i = 0; i < cacheManagers.size(); i++) { EmbeddedCacheManager cm = cacheManagers.get(i); cm.defineConfiguration(USER_CACHE, buildIndexedConfig("News-" + i)); cm.getCache(USER_CACHE); } waitForClusterToForm(USER_CACHE); userCache = remoteCacheManager.getCache(USER_CACHE); } public void testIndexing() { News news = new News(); news.setId("testnews"); news.setTimestamp(0); userCache.put(news.getId(), news); Object testNews = userCache.get("testnews"); assertEquals(news, testNews); } public void testNonPrimitiveKey() { NewsKey newsKey1 = new NewsKey(); newsKey1.setArticle("articleKey1"); NewsKey newsKey2 = new NewsKey(); newsKey2.setArticle("articleKey2"); News news1 = new News(); news1.setId("test-news-1"); news1.setTimestamp(0); News news2 = new News(); news2.setId("test-news-2"); news2.setTimestamp(0); userCache.put(newsKey1, news1); userCache.put(newsKey2, news2); assertEquals(news1, userCache.get(newsKey1)); assertEquals(news2, userCache.get(newsKey2)); } } class NewsKey { private String article; NewsKey() { } @ProtoField(number = 1, required = true) public void setArticle(String article) { this.article = article; } public String getArticle() { return article; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NewsKey newsKey = (NewsKey) o; return Objects.equals(article, newsKey.article); } @Override public int hashCode() { return Objects.hash(article); } } @ProtoDoc("@Indexed") class News { private String id; private long timestamp; public News() { } public String getId() { return id; } @ProtoField(number = 1, required = true) public void setId(String id) { this.id = id; } @ProtoDoc("@Field(index=Index.YES, analyze = Analyze.NO, store = Store.NO)") @ProtoDoc("@SortableField") @ProtoField(number = 2, required = true) public long getTimestamp() { return timestamp; } public void setTimestamp(long time) { this.timestamp = time; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } News news = (News) o; return timestamp == news.timestamp && Objects.equals(id, news.id); } @Override public int hashCode() { return Objects.hash(id, timestamp); } }
7,898
30.979757
141
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryDslConditionsIspnDirTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.marshall.NotIndexedSCI; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.testng.annotations.Test; /** * Verifying the functionality of remote queries for infinispan directory.type. * * @author Anna Manukyan * @author anistor@redhat.com * @since 6.0 */ @Test(testName = "client.hotrod.query.RemoteQueryDslConditionsIspnDirTest", groups = "functional") public class RemoteQueryDslConditionsIspnDirTest extends RemoteQueryDslConditionsTest { private static final String TEST_CACHE_NAME = "testCache"; @Override protected void createCacheManagers() throws Throwable { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().clusteredDefault(); globalBuilder.serialization().addContextInitializers(TestDomainSCI.INSTANCE, NotIndexedSCI.INSTANCE); createClusteredCaches(1, globalBuilder, new ConfigurationBuilder(), true); ConfigurationBuilder cfg = getConfigurationBuilder(); manager(0).defineConfiguration(TEST_CACHE_NAME, cfg.build()); cache = manager(0).getCache(TEST_CACHE_NAME); hotRodServer = HotRodClientTestingUtil.startHotRodServer(manager(0)); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServer().host("127.0.0.1").port(hotRodServer.getPort()).addContextInitializers(TestDomainSCI.INSTANCE, NotIndexedSCI.INSTANCE); remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); remoteCache = remoteCacheManager.getCache(TEST_CACHE_NAME); } @Override protected ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder builder = super.getConfigurationBuilder(); builder.indexing().storage(LOCAL_HEAP); return builder; } }
2,256
44.14
150
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/ReplicationIndexTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.CacheMode.REPL_SYNC; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.marshall.MarshallerUtil; import org.infinispan.client.hotrod.test.FixedServerBalancing; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.InternalRemoteCacheManager; import org.infinispan.client.hotrod.test.MultiHotRodServersTest; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.annotations.ProtoDoc; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoSchemaBuilder; import org.infinispan.server.hotrod.HotRodServer; import org.testng.annotations.Test; /** * Test indexing during state transfer. */ @Test(groups = "functional", testName = "client.hotrod.query.ReplicationIndexTest") public class ReplicationIndexTest extends MultiHotRodServersTest { public static final String CACHE_NAME = "test-cache"; public static final String PROTO_FILE = "file.proto"; public static final int ENTRIES = 2; private final AtomicInteger serverCount = new AtomicInteger(0); protected void addNode() throws IOException { int index = serverCount.incrementAndGet(); // Add a new Hot Rod server addHotRodServer(getDefaultClusteredCacheConfig(REPL_SYNC)); EmbeddedCacheManager cacheManager = manager(index - 1); // Create a client that goes exclusively to the Hot Rod server RemoteCacheManager remoteCacheManager = createClient(index - 1); clients.add(remoteCacheManager); // Create client and server Serialization Contexts SerializationContext serCtx = MarshallerUtil.getSerializationContext(remoteCacheManager); ProtoSchemaBuilder protoSchemaBuilder = new ProtoSchemaBuilder(); String protoFile = protoSchemaBuilder.fileName(PROTO_FILE).addClass(Entity.class).build(serCtx); RemoteCache<String, String> metadataCache = remoteCacheManager.getCache(PROTOBUF_METADATA_CACHE_NAME); metadataCache.put(PROTO_FILE, protoFile); assertFalse(metadataCache.containsKey(ERRORS_KEY_SUFFIX)); // Add the test caches org.infinispan.configuration.cache.ConfigurationBuilder builder = getDefaultClusteredCacheConfig(REPL_SYNC, isTransactional()); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("Entity"); cacheManager.defineConfiguration(CACHE_NAME, builder.build()); } private void killLastNode() { int index = serverCount.decrementAndGet(); clients.remove(index).close(); killServer(index); } protected boolean isTransactional() { return false; } protected RemoteCacheManager createClient(int i) { HotRodServer server = server(i); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); clientBuilder.addServer() .host(server.getHost()) .port(server.getPort()) .marshaller(new ProtoStreamMarshaller()) .balancingStrategy(() -> new FixedServerBalancing(server)); return new InternalRemoteCacheManager(clientBuilder.build()); } @Override protected void createCacheManagers() throws Throwable { addNode(); } @ProtoDoc("@Indexed") static class Entity { private String name; public Entity() { } static Entity create(String name) { Entity entity = new Entity(); entity.setName(name); return entity; } @ProtoDoc("@Field(index=Index.YES, analyze = Analyze.YES, store = Store.NO)") @ProtoField(number = 1, required = true) public String getName() { return name; } public void setName(String name) { this.name = name; } } private long queryCount(String query, RemoteCache<?, ?> remoteCache) { return Search.getQueryFactory(remoteCache).create(query).execute().count().value(); } @Test public void testIndexingDuringStateTransfer() throws IOException { RemoteCache<Object, Object> remoteCache = clients.get(0).getCache(CACHE_NAME); for (int i = 0; i < ENTRIES; i++) { remoteCache.put(i, Entity.create("name" + i)); } assertIndexed(remoteCache); addNode(); try { waitForClusterToForm(CACHE_NAME); RemoteCache<Object, Object> secondRemoteCache = clients.get(1).getCache(CACHE_NAME); assertIndexed(secondRemoteCache); } finally { killLastNode(); } } private void assertIndexed(RemoteCache<?, ?> remoteCache) { assertEquals(ENTRIES, remoteCache.size()); assertEquals(ENTRIES, queryCount("FROM Entity", remoteCache)); assertEquals(1, queryCount("FROM Entity where name:'name1'", remoteCache)); } }
5,654
36.203947
142
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/IndexedCacheNonIndexedEntityTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers; import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.newRemoteConfigurationBuilder; import static org.infinispan.commons.api.CacheContainerAdmin.AdminFlag.VOLATILE; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME; import static org.testng.AssertJUnit.assertFalse; import java.io.IOException; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.marshall.MarshallerUtil; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.commons.configuration.StringConfiguration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.annotations.ProtoDoc; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoName; import org.infinispan.protostream.annotations.ProtoSchemaBuilder; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.infinispan.server.core.admin.embeddedserver.EmbeddedServerAdminOperationHandler; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * @since 12.0 */ @Test(testName = "client.hotrod.query.IndexedCacheNonIndexedEntityTest", groups = "functional") public class IndexedCacheNonIndexedEntityTest extends SingleCacheManagerTest { private static final String CACHE_NAME = "IndexedCacheNonIndexedEntitiesTest"; protected HotRodServer hotRodServer; protected RemoteCacheManager remoteCacheManager; @ProtoName("Entity") static class Entity { private final String name; @ProtoFactory public Entity(String name) { this.name = name; } @ProtoField(1) public String getName() { return name; } } @ProtoDoc("@Indexed") @ProtoName("EvilTwin") static class EvilTwin { @ProtoDoc("@Field(index=Index.YES, analyze=Analyze.NO)") @ProtoField(1) public String name; } private String createProtoFile() throws IOException { SerializationContext serializationContext = MarshallerUtil.getSerializationContext(remoteCacheManager); ProtoSchemaBuilder protoSchemaBuilder = new ProtoSchemaBuilder(); return protoSchemaBuilder.fileName("file.proto") .addClass(Entity.class) .addClass(EvilTwin.class) .build(serializationContext); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { cacheManager = TestCacheManagerFactory.createCacheManager(new ConfigurationBuilder()); HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder(); serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler()); hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager, serverBuilder); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = newRemoteConfigurationBuilder(); clientBuilder.addServer().host("127.0.0.1").port(hotRodServer.getPort()); remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); RemoteCache<String, String> metadataCache = remoteCacheManager.getCache(PROTOBUF_METADATA_CACHE_NAME); metadataCache.put("file.proto", createProtoFile()); assertFalse(metadataCache.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX)); return cacheManager; } @AfterClass(alwaysRun = true) public void release() { killRemoteCacheManager(remoteCacheManager); killServers(hotRodServer); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*The configured indexed-entity type 'Entity' must be indexed.*") public void shouldPreventNonIndexedEntities() { String config = "<infinispan>" + " <cache-container>" + " <local-cache name=\"" + CACHE_NAME + "\">\n" + " <encoding media-type=\"application/x-protostream\"/>\n" + " <indexing storage=\"local-heap\">\n" + " <indexed-entities>\n" + " <indexed-entity>Entity</indexed-entity>\n" + " <indexed-entity>EvilTwin</indexed-entity>\n" + " </indexed-entities>\n" + " </indexing>" + " </local-cache>" + " </cache-container>" + "</infinispan>"; remoteCacheManager.administration().withFlags(VOLATILE).createCache(CACHE_NAME, new StringConfiguration(config)); // The SearchMapping is started lazily for protobuf caches, so the exception only happens after first usage RemoteCache<Object, Object> cache = remoteCacheManager.getCache(CACHE_NAME); cache.put("1", new Entity("name")); } }
5,680
43.732283
159
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/ReindexCacheTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.infinispan.test.fwk.TestCacheManagerFactory.createServerModeCacheManager; import static org.testng.Assert.assertEquals; import org.infinispan.Cache; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.Indexer; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.embedded.testdomain.User; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * Tests for the MassIndexer when using storing protobuf */ @Test(testName = "client.hotrod.query.ReindexCacheTest", groups = "functional") public class ReindexCacheTest extends SingleHotRodServerTest { private static final String USER_CACHE = "users"; private static final int NUM_ENTRIES = 50; private StorageType storageType; @Factory public Object[] factory() { return new Object[]{ new ReindexCacheTest().storageType(StorageType.OBJECT), new ReindexCacheTest().storageType(StorageType.OFF_HEAP) }; } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { cacheManager = createServerModeCacheManager(contextInitializer(), hotRodCacheConfiguration()); cacheManager.defineConfiguration(USER_CACHE, hotRodCacheConfiguration(buildIndexedConfig()).build()); return cacheManager; } @Override protected String parameters() { return "storageType-" + storageType; } private ReindexCacheTest storageType(StorageType storageType) { this.storageType = storageType; return this; } public ConfigurationBuilder buildIndexedConfig() { ConfigurationBuilder builder = hotRodCacheConfiguration(new ConfigurationBuilder()); builder.memory().storageType(storageType) .indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.User"); return builder; } @Override protected SerializationContextInitializer contextInitializer() { return TestDomainSCI.INSTANCE; } @Test public void testMassIndexing() { RemoteCache<Integer, UserPB> userCache = remoteCacheManager.getCache(USER_CACHE); for (int i = 0; i < NUM_ENTRIES; i++) { UserPB user = new UserPB(); user.setId(i); user.setName("name" + i); user.setSurname("surname" + i); userCache.put(user.getId(), user); } assertEquals(query(userCache), NUM_ENTRIES); wipeIndexes(); assertIndexEmpty(); reindex(); assertEquals(query(userCache), NUM_ENTRIES); } private void wipeIndexes() { Cache<?, ?> cache = cacheManager.getCache(USER_CACHE); Indexer indexer = org.infinispan.query.Search.getIndexer(cache); CompletionStages.join(indexer.remove()); } private void assertIndexEmpty() { assertEquals(query(remoteCacheManager.getCache(USER_CACHE)), 0); } private void reindex() { Cache<?, ?> cache = cacheManager.getCache(USER_CACHE); Indexer indexer = org.infinispan.query.Search.getIndexer(cache); CompletionStages.join(indexer.run()); } private long query(RemoteCache<?, ?> cache) { QueryFactory qf = Search.getQueryFactory(cache); Query<User> q = qf.create("FROM sample_bank_account.User"); return q.execute().count().value(); } }
4,146
33.558333
107
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/HotRodNonIndexedQueryTest.java
package org.infinispan.client.hotrod.query; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author anistor@redhat.com * @since 7.0 */ @Test(testName = "client.hotrod.query.HotRodNonIndexedQueryTest", groups = "functional") public class HotRodNonIndexedQueryTest extends HotRodQueryTest { @Override protected ConfigurationBuilder getConfigurationBuilder() { return new ConfigurationBuilder(); } }
476
25.5
88
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteOffHeapNonIndexedQueryDslConditionsTest.java
package org.infinispan.client.hotrod.query; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.testng.annotations.Test; /** * @author anistor@redhat.com */ @Test(groups = "functional", testName = "client.hotrod.query.RemoteOffHeapNonIndexedQueryDslConditionsTest") public class RemoteOffHeapNonIndexedQueryDslConditionsTest extends RemoteNonIndexedQueryDslConditionsTest { @Override protected ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder builder = super.getConfigurationBuilder(); builder.memory().storageType(StorageType.OFF_HEAP); return builder; } }
689
33.5
108
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/MultiHotRodServerIspnDirReplQueryTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.testng.annotations.Test; /** * Verifies the functionality of the Queries in case of REPL infinispan directory.type for clustered Hotrod servers. * * @author Anna Manukyan */ @Test(testName = "client.hotrod.query.MultiHotRodServerIspnDirReplQueryTest", groups = "functional") public class MultiHotRodServerIspnDirReplQueryTest extends MultiHotRodServerIspnDirQueryTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder defaultConfiguration = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); createHotRodServers(3, defaultConfiguration); ConfigurationBuilder builder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false)); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.User"); for (EmbeddedCacheManager cm : cacheManagers) { cm.defineConfiguration(TEST_CACHE, builder.build()); cm.getCache(TEST_CACHE); } waitForClusterToForm(); remoteCache0 = client(0).getCache(TEST_CACHE); remoteCache1 = client(1).getCache(TEST_CACHE); } }
1,556
37.925
122
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryDslConditionsNoFieldsStoredTest.java
package org.infinispan.client.hotrod.query; import java.io.IOException; import org.testng.annotations.Test; /** * Force all 'bank.proto' schema fields the were explicitly defined in initial schema as 'Stored.YES' to be not stored. * This should not impact any test. * * @author anistor@redhat.com */ @Test(groups = "functional", testName = "client.hotrod.query.RemoteQueryDslConditionsNoFieldsStoredTest") public class RemoteQueryDslConditionsNoFieldsStoredTest extends RemoteQueryDslConditionsTest { @Override protected String loadSchema() throws IOException { String schema = super.loadSchema(); return schema.replace("Store.YES", "Store.NO"); } }
680
29.954545
119
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/HotRodNonIndexedSingleFileStoreQueryTest.java
package org.infinispan.client.hotrod.query; 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.testng.annotations.Test; /** * @author anistor@redhat.com * @since 7.0 */ @Test(testName = "client.hotrod.query.HotRodNonIndexedSingleFileStoreQueryTest", groups = "functional") public class HotRodNonIndexedSingleFileStoreQueryTest extends HotRodNonIndexedQueryTest { private final String tmpDirectory = CommonsTestingUtil.tmpDirectory(getClass()); @Override protected void setup() throws Exception { Util.recursiveFileRemove(tmpDirectory); super.setup(); } @Override protected void teardown() { try { super.teardown(); } finally { Util.recursiveFileRemove(tmpDirectory); } } @Override protected void configure(GlobalConfigurationBuilder builder) { builder.globalState().persistentLocation(tmpDirectory); } @Override protected ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.persistence() .addStore(SingleFileStoreConfigurationBuilder.class) .location(tmpDirectory); // ensure the data container contains minimal data so the store will need to be accessed to get the rest builder.locking().concurrencyLevel(1).memory().size(1); return builder; } }
1,639
31.156863
110
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/MultiHotRodServerQueryTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.util.Collections; import java.util.List; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.hotrod.query.testdomain.protobuf.AddressPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB; import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI; import org.infinispan.client.hotrod.test.MultiHotRodServersTest; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.dsl.embedded.testdomain.Address; import org.infinispan.query.dsl.embedded.testdomain.User; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Tests query over Hot Rod in a three node cluster. * * @author anistor@redhat.com * @since 6.0 */ @Test(testName = "client.hotrod.query.MultiHotRodServerQueryTest", groups = "functional") public class MultiHotRodServerQueryTest extends MultiHotRodServersTest { protected RemoteCache<Integer, User> remoteCache0; protected RemoteCache<Integer, User> remoteCache1; protected boolean useTransactions() { return false; } @Override protected void modifyGlobalConfiguration(GlobalConfigurationBuilder builder) { super.modifyGlobalConfiguration(builder); } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, useTransactions())); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("sample_bank_account.User"); createHotRodServers(3, builder); waitForClusterToForm(); remoteCache0 = client(0).getCache(); remoteCache1 = client(1).getCache(); } @Override protected SerializationContextInitializer contextInitializer() { return TestDomainSCI.INSTANCE; } @BeforeClass(alwaysRun = true) protected void populateCache() { User user1 = new UserPB(); user1.setId(1); user1.setName("Tom"); user1.setSurname("Cat"); user1.setGender(User.Gender.MALE); user1.setAge(5); user1.setAccountIds(Collections.singleton(12)); Address address1 = new AddressPB(); address1.setStreet("Dark Alley"); address1.setPostCode("1234"); user1.setAddresses(Collections.singletonList(address1)); remoteCache0.put(1, user1); assertNotNull(remoteCache0.get(1)); assertNotNull(remoteCache1.get(1)); User user2 = new UserPB(); user2.setId(2); user2.setName("Adrian"); user2.setSurname("Nistor"); user2.setGender(User.Gender.MALE); user2.setAge(22); Address address2 = new AddressPB(); address2.setStreet("Old Street"); address2.setPostCode("XYZ"); user2.setAddresses(Collections.singletonList(address2)); remoteCache1.put(2, user2); assertNotNull(remoteCache0.get(2)); assertNotNull(remoteCache1.get(2)); // this value should be ignored gracefully client(0).getCache().put("dummy", "a primitive value cannot be queried"); } public void testAttributeQuery() { // get user back from remote cache and check its attributes User fromCache = remoteCache0.get(1); assertNotNull(fromCache); assertUser1(fromCache); // get user back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache1); Query<User> query = qf.create("FROM sample_bank_account.User WHERE name = 'Tom'"); List<User> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertEquals(UserPB.class, list.get(0).getClass()); assertUser1(list.get(0)); } public void testGroupByQuery() { // get user back from remote cache and check its attributes User fromCache = remoteCache0.get(1); assertNotNull(fromCache); assertUser1(fromCache); // get user back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache0); Query<Object[]> query = qf.create("SELECT name, COUNT(age) FROM sample_bank_account.User WHERE age >= 5 GROUP BY name ORDER BY name ASC"); List<Object[]> list = query.execute().list(); assertNotNull(list); assertEquals(2, list.size()); assertEquals(Object[].class, list.get(0).getClass()); assertEquals(Object[].class, list.get(1).getClass()); assertEquals("Adrian", list.get(0)[0]); assertEquals("Tom", list.get(1)[0]); } public void testEmbeddedAttributeQuery() { // get user back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache1); Query<User> query = qf.create("FROM sample_bank_account.User u WHERE u.addresses.postCode = '1234'"); List<User> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertEquals(UserPB.class, list.get(0).getClass()); assertUser1(list.get(0)); } @Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN028503: Property addresses can not be selected from type sample_bank_account.User since it is an embedded entity.") public void testInvalidEmbeddedAttributeQuery() { QueryFactory qf = Search.getQueryFactory(remoteCache1); Query<Object[]> q = qf.create("SELECT addresses FROM sample_bank_account.User"); q.execute(); // exception expected } public void testProjections() { // get user back from remote cache and check its attributes User fromCache = remoteCache0.get(1); assertUser1(fromCache); // get user back from remote cache via query and check its attributes QueryFactory qf = Search.getQueryFactory(remoteCache1); Query<Object[]> query = qf.create("SELECT name, surname FROM sample_bank_account.User WHERE name = 'Tom'"); List<Object[]> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertEquals(Object[].class, list.get(0).getClass()); assertEquals("Tom", list.get(0)[0]); assertEquals("Cat", list.get(0)[1]); } private void assertUser1(User user) { assertNotNull(user); assertEquals(1, user.getId()); assertEquals("Tom", user.getName()); assertEquals("Cat", user.getSurname()); assertEquals(User.Gender.MALE, user.getGender()); assertNotNull(user.getAccountIds()); assertEquals(1, user.getAccountIds().size()); assertTrue(user.getAccountIds().contains(12)); assertNotNull(user.getAddresses()); assertEquals(1, user.getAddresses().size()); assertEquals("Dark Alley", user.getAddresses().get(0).getStreet()); assertEquals("1234", user.getAddresses().get(0).getPostCode()); } }
7,628
38.734375
215
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/RemoteQueryDslConditionsOldClient.java
package org.infinispan.client.hotrod.query; import org.infinispan.client.hotrod.ProtocolVersion; import org.testng.annotations.Test; @Test(groups = "functional", testName = "client.hotrod.query.RemoteQueryDslConditionsOldClient") public class RemoteQueryDslConditionsOldClient extends RemoteQueryDslConditionsTest { @Override protected ProtocolVersion getProtocolVersion() { return ProtocolVersion.PROTOCOL_VERSION_27; } }
442
28.533333
96
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/MultiHotRodServerNonIndexedQueryTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Tests query without indexing over Hot Rod in a three node cluster. * * @author anistor@redhat.com * @since 7.2 */ @Test(testName = "client.hotrod.query.MultiHotRodServerNonIndexedQueryTest", groups = "functional") public class MultiHotRodServerNonIndexedQueryTest extends MultiHotRodServerQueryTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false)); createHotRodServers(3, builder); waitForClusterToForm(); remoteCache0 = client(0).getCache(); remoteCache1 = client(1).getCache(); } }
964
32.275862
122
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/BuiltInAnalyzersTest.java
package org.infinispan.client.hotrod.query; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.Cache; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.marshall.MarshallerUtil; import org.infinispan.client.hotrod.query.testdomain.protobuf.TestEntity; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.client.hotrod.test.InternalRemoteCacheManager; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.commons.util.Util; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.FileDescriptorSource; import org.infinispan.protostream.SerializationContext; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test build-in analyzers * * @since 9.3.2 */ @Test(groups = "functional", testName = "client.hotrod.query.BuiltInAnalyzersTest") public class BuiltInAnalyzersTest extends SingleHotRodServerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { org.infinispan.configuration.cache.ConfigurationBuilder builder = new org.infinispan.configuration.cache.ConfigurationBuilder(); builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("TestEntity"); EmbeddedCacheManager manager = TestCacheManagerFactory.createServerModeCacheManager(); Cache<String, String> metadataCache = manager.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); String protoFile = Util.getResourceAsString("/analyzers.proto", getClass().getClassLoader()); metadataCache.put("analyzers.proto", protoFile); RemoteQueryTestUtils.checkSchemaErrors(metadataCache); manager.defineConfiguration("test", builder.build()); return manager; } @BeforeClass protected void registerProtobufSchema() throws Exception { String protoFile = Util.getResourceAsString("/analyzers.proto", getClass().getClassLoader()); SerializationContext serCtx = MarshallerUtil.getSerializationContext(remoteCacheManager); serCtx.registerProtoFiles(FileDescriptorSource.fromString("analyzers.proto", protoFile)); serCtx.registerMarshaller(new TestEntity.TestEntityMarshaller()); } @Override protected RemoteCacheManager getRemoteCacheManager() { ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); builder.addServer().host("127.0.0.1").port(hotrodServer.getPort()); return new InternalRemoteCacheManager(builder.build()); } @Test public void testKeywordAnalyzer() { RemoteCache<Integer, TestEntity> remoteCache = remoteCacheManager.getCache("test"); TestEntity child = new TestEntity("name", "name", "name", "name-with-dashes", "name", "name", null); TestEntity parent = new TestEntity("name", "name", "name", "name-with-dashes", "name", "name", child); remoteCache.put(1, parent); QueryFactory queryFactory = Search.getQueryFactory(remoteCache); assertEquals(1, queryFactory.create("From TestEntity where name4:'name-with-dashes'").execute().count().value()); assertEquals(1, queryFactory.create("From TestEntity p where p.child.name4:'name-with-dashes'").execute().count().value()); } @Test public void testShippedAnalyzers() { RemoteCache<Integer, TestEntity> remoteCache = remoteCacheManager.getCache("test"); TestEntity testEntity = new TestEntity("Sarah-Jane Lee", "John McDougall", "James Connor", "Oswald Lee", "Jason Hawkings", "Gyorgy Constantinides"); remoteCache.put(1, testEntity); QueryFactory queryFactory = Search.getQueryFactory(remoteCache); assertEquals(1, queryFactory.create("From TestEntity where name1:'jane'").execute().count().value()); assertEquals(1, queryFactory.create("From TestEntity where name2:'McDougall'").execute().count().value()); assertEquals(1, queryFactory.create("From TestEntity where name3:'Connor'").execute().count().value()); assertEquals(1, queryFactory.create("From TestEntity where name4:'Oswald Lee'").execute().count().value()); assertEquals(1, queryFactory.create("From TestEntity where name5:'hawk'").execute().count().value()); assertEquals(1, queryFactory.create("From TestEntity where name6:'constan'").execute().count().value()); assertEquals(0, queryFactory.create("From TestEntity where name1:'sara'").execute().count().value()); assertEquals(0, queryFactory.create("From TestEntity where name2:'John McDougal'").execute().count().value()); assertEquals(0, queryFactory.create("From TestEntity where name3:'James-Connor'").execute().count().value()); assertEquals(0, queryFactory.create("From TestEntity where name4:'Oswald lee'").execute().count().value()); assertEquals(0, queryFactory.create("From TestEntity where name5:'json'").execute().count().value()); assertEquals(0, queryFactory.create("From TestEntity where name6:'Georje'").execute().count().value()); } }
5,544
50.342593
134
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/projection/MetaProjectionTest.java
package org.infinispan.client.hotrod.query.projection; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import java.util.List; import org.infinispan.client.hotrod.MetadataValue; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.test.SingleHotRodServerTest; import org.infinispan.commons.test.annotation.TestForIssue; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.model.Developer; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "org.infinispan.client.hotrod.query.projection.MetaProjectionTest") @TestForIssue(jiraKey = "ISPN-14478") public class MetaProjectionTest extends SingleHotRodServerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder config = new ConfigurationBuilder(); config.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity("io.dev.Developer"); return TestCacheManagerFactory.createServerModeCacheManager(config); } @Override protected SerializationContextInitializer contextInitializer() { return Developer.DeveloperSchema.INSTANCE; } @Test public void testVersionProjection() { RemoteCache<String, Developer> remoteCache = remoteCacheManager.getCache(); remoteCache.put("open-contributor", new Developer("iamopen", "iamopen@redmail.io", "Hibernate developer", 2000)); remoteCache.put("open-contributor", new Developer("iamopen", "iamopen@redmail.io", "Infinispan developer", 2000)); remoteCache.put("another-contributor", new Developer("mycodeisopen", "mycodeisopen@redmail.io", "Infinispan engineer", 799)); MetadataValue<Developer> metadata = remoteCache.getWithMetadata("open-contributor"); assertThat(metadata.getVersion()).isEqualTo(2L); metadata = remoteCache.getWithMetadata("another-contributor"); assertThat(metadata.getVersion()).isEqualTo(3L); // version is global to the cache - not to the entry QueryFactory queryFactory = Search.getQueryFactory(remoteCache); Query<Object[]> query = queryFactory.create( "select d.nick, version(d), d.email, d.biography, d.contributions from io.dev.Developer d where d.biography : 'Infinispan' order by d.email"); List<Object[]> list = query.execute().list(); assertThat(list).hasSize(2); assertThat(list.get(0)).containsExactly("iamopen", 2L, "iamopen@redmail.io", "Infinispan developer", 2000); assertThat(list.get(1)).containsExactly("mycodeisopen", 3L, "mycodeisopen@redmail.io", "Infinispan engineer", 799); query = queryFactory.create( "select d, version(d) from io.dev.Developer d where d.biography : 'Infinispan' order by d.email"); list = query.execute().list(); assertThat(list).hasSize(2); assertThat(list.get(0)[0]).isNotNull().isInstanceOf(Developer.class); assertThat(list.get(0)[1]).isEqualTo(2L); assertThat(list.get(1)[0]).isNotNull().isInstanceOf(Developer.class); assertThat(list.get(1)[1]).isEqualTo(3L); } }
3,529
44.844156
154
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/TestEntity.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import java.io.IOException; import org.infinispan.protostream.MessageMarshaller; public class TestEntity { private final String name1; private final String name2; private final String name3; private final String name4; private final String name5; private final String name6; private final TestEntity child; public TestEntity(String name1, String name2, String name3, String name4, String name5, String name6, TestEntity child) { this.name1 = name1; this.name2 = name2; this.name3 = name3; this.name4 = name4; this.name5 = name5; this.name6 = name6; this.child = child; } public TestEntity(String name1, String name2, String name3, String name4, String name5, String name6) { this(name1, name2, name3, name4, name5, name6, null); } public static class TestEntityMarshaller implements MessageMarshaller<TestEntity> { @Override public TestEntity readFrom(ProtoStreamReader reader) throws IOException { String name1 = reader.readString("name1"); String name2 = reader.readString("name2"); String name3 = reader.readString("name3"); String name4 = reader.readString("name4"); String name5 = reader.readString("name5"); String name6 = reader.readString("name6"); TestEntity child = reader.readObject("child", TestEntity.class); return new TestEntity(name1, name2, name3, name4, name5, name6, child); } @Override public void writeTo(ProtoStreamWriter writer, TestEntity testEntity) throws IOException { writer.writeString("name1", testEntity.name1); writer.writeString("name2", testEntity.name2); writer.writeString("name3", testEntity.name3); writer.writeString("name4", testEntity.name4); writer.writeString("name5", testEntity.name5); writer.writeString("name6", testEntity.name6); writer.writeObject("child", testEntity.child, TestEntity.class); } @Override public Class<TestEntity> getJavaClass() { return TestEntity.class; } @Override public String getTypeName() { return "TestEntity"; } } }
2,279
32.529412
124
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/AccountPB.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; 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.query.dsl.embedded.testdomain.Account; import org.infinispan.query.dsl.embedded.testdomain.Limits; /** * @author anistor@redhat.com * @since 7.0 */ public class AccountPB implements Account { private int id; private String description; private Date creationDate; private Limits limits; private Limits hardLimits; // not indexed private List<byte[]> blurb = new ArrayList<>(); private Currency[] currencies = new Currency[0]; public AccountPB() { // hardLimits is a required field, so we make our life easy by providing defaults here hardLimits = new LimitsPB(); hardLimits.setMaxTransactionLimit(5000.0); hardLimits.setMaxDailyLimit(10000.0); } @Override public int getId() { return id; } @Override public void setId(int id) { this.id = id; } @Override public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = description; } @Override public Date getCreationDate() { return creationDate; } @Override public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } @Override public Limits getLimits() { return limits; } @Override public void setLimits(Limits limits) { this.limits = limits; } @Override public Limits getHardLimits() { return hardLimits; } @Override public void setHardLimits(Limits hardLimits) { this.hardLimits = 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 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; AccountPB account = (AccountPB) 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 "AccountPB{" + "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) + '}'; } }
3,991
23.341463
119
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/Revision.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import java.util.ArrayList; import java.util.List; import org.infinispan.protostream.annotations.ProtoDoc; import org.infinispan.protostream.annotations.ProtoField; @ProtoDoc("@org.hibernate.search.annotations.Indexed") public class Revision { private String messageId; private String message; private List<Reviewer> reviewers; public Revision() { } public Revision(String messageId, String message) { this.messageId = messageId; this.message = message; } @ProtoField(number = 1, required = true) @ProtoDoc("@org.hibernate.search.annotations.Field(index=Index.YES, store=Store.NO, analyze=Analyze.NO)") public String getKey() { return messageId; } public void setKey(String key) { this.messageId = key; } @ProtoField(number = 2, required = true) @ProtoDoc("@org.hibernate.search.annotations.Field(index=Index.NO, store=Store.NO, analyze=Analyze.NO)") public String getMessage() { return message; } public void setMessage(String text) { this.message = text; } @ProtoField(number = 3, collectionImplementation = ArrayList.class) @ProtoDoc("@org.hibernate.search.annotations.Field(index=Index.NO, store=Store.NO, analyze=Analyze.NO)") public List<Reviewer> getReviewers() { if (reviewers == null) { reviewers = new ArrayList<>(); } return reviewers; } public void setReviewers(List<Reviewer> reviewers) { this.reviewers = reviewers; } }
1,554
26.280702
108
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/CalculusIndexed.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import java.math.BigDecimal; import java.math.BigInteger; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Decimal; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Keyword; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.types.java.CommonTypes; @Indexed public class CalculusIndexed { private String name; private BigInteger purchases; private BigDecimal prospect; private BigDecimal decimal; @ProtoFactory public CalculusIndexed(String name, BigInteger purchases, BigDecimal prospect, BigDecimal decimal) { this.name = name; this.purchases = purchases; this.prospect = prospect; this.decimal = decimal; } @Keyword @ProtoField(value = 1) public String getName() { return name; } @Basic @ProtoField(value = 2) public BigInteger getPurchases() { return purchases; } @Basic // the scale is 0 by default @ProtoField(value = 3) public BigDecimal getProspect() { return prospect; } @Decimal // the scale is 2 by default @ProtoField(value = 4) public BigDecimal getDecimal() { return decimal; } @AutoProtoSchemaBuilder(includeClasses = CalculusIndexed.class, dependsOn = CommonTypes.class, schemaFilePath = "/protostream", schemaFileName = "calculus-indexed.proto", schemaPackageName = "lab.indexed") public interface CalculusIndexedSchema extends GeneratedSchema { } }
1,816
26.953846
103
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/Programmer.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; @Indexed public class Programmer { private String nick; private Integer contributions; @ProtoFactory public Programmer(String nick, Integer contributions) { this.nick = nick; this.contributions = contributions; } @Basic @ProtoField(value = 1) public String getNick() { return nick; } @Basic // not sortable! @ProtoField(value = 2) public Integer getContributions() { return contributions; } @AutoProtoSchemaBuilder(includeClasses = { Programmer.class }, schemaFileName = "pro.proto", schemaFilePath = "proto", schemaPackageName = "io.pro") public interface ProgrammerSchema extends GeneratedSchema { } }
1,106
26.675
95
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/LimitsPB.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import java.util.Arrays; import java.util.Objects; import org.infinispan.query.dsl.embedded.testdomain.Limits; /** * @author anistor@redhat.com * @since 9.4.1 */ public class LimitsPB implements Limits { private Double maxDailyLimit; private Double maxTransactionLimit; private String[] payees = new String[0]; @Override public Double getMaxDailyLimit() { return maxDailyLimit; } @Override public void setMaxDailyLimit(Double maxDailyLimit) { this.maxDailyLimit = maxDailyLimit; } @Override public Double getMaxTransactionLimit() { return maxTransactionLimit; } @Override public void setMaxTransactionLimit(Double maxTransactionLimit) { this.maxTransactionLimit = maxTransactionLimit; } @Override 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; LimitsPB limits = (LimitsPB) 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 "LimitsPB{" + "maxDailyLimit=" + maxDailyLimit + ", maxTransactionLimit=" + maxTransactionLimit + ", payees=" + Arrays.toString(payees) + '}'; } }
1,776
23.013514
87
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/ModelFactoryPB.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; 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 ModelFactoryPB implements ModelFactory { public static final ModelFactory INSTANCE = new ModelFactoryPB(); private ModelFactoryPB() { } @Override public Account makeAccount() { return new AccountPB(); } @Override public Limits makeLimits() { return new LimitsPB(); } @Override public Class<?> getAccountImplClass() { return AccountPB.class; } @Override public String getAccountTypeName() { return "sample_bank_account.Account"; } @Override public User makeUser() { return new UserPB(); } @Override public Class<UserPB> getUserImplClass() { return UserPB.class; } @Override public String getUserTypeName() { return "sample_bank_account.User"; } @Override public Address makeAddress() { return new AddressPB(); } @Override public Class<AddressPB> getAddressImplClass() { return AddressPB.class; } @Override public String getAddressTypeName() { return "sample_bank_account.User.Address"; } @Override public Transaction makeTransaction() { return new TransactionPB(); } @Override public Class<?> getTransactionImplClass() { return TransactionPB.class; } @Override public String getTransactionTypeName() { return "sample_bank_account.Transaction"; } }
1,868
20.732558
68
java
null
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/query/testdomain/protobuf/Product.java
package org.infinispan.client.hotrod.query.testdomain.protobuf; import java.math.BigInteger; import java.time.Instant; import org.infinispan.api.annotations.indexing.Basic; import org.infinispan.api.annotations.indexing.Indexed; import org.infinispan.api.annotations.indexing.Keyword; import org.infinispan.api.annotations.indexing.Text; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.types.java.math.BigIntegerAdapter; @Indexed public class Product { private String name; private Long code; private Double price; private String description; private BigInteger purchases; private Instant moment; @ProtoFactory public Product(String name, Long code, Double price, String description, BigInteger purchases, Instant moment) { this.name = name; this.code = code; this.price = price; this.description = description; this.purchases = purchases; this.moment = moment; } @ProtoField(value = 1) @Keyword(normalizer = "lowercase") public String getName() { return name; } @ProtoField(value = 2) @Basic public Long getCode() { return code; } @ProtoField(value = 3) @Basic public Double getPrice() { return price; } @ProtoField(value = 4) @Text public String getDescription() { return description; } @ProtoField(value = 5) public BigInteger getPurchases() { return purchases; } @ProtoField(value = 6) public Instant getMoment() { return moment; } @AutoProtoSchemaBuilder(includeClasses = {Product.class, BigIntegerAdapter.class}, schemaFilePath = "/protostream", schemaFileName = "product-store.proto", schemaPackageName = "store.product") public interface ProductSchema extends GeneratedSchema { ProductSchema INSTANCE = new ProductSchemaImpl(); } }
2,075
25.961039
115
java