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/server/tests/src/test/java/org/infinispan/server/security/AuthenticationMultiEndpointIT.java
package org.infinispan.server.security; import static org.infinispan.server.test.core.Common.assertStatus; import static org.infinispan.server.test.core.Common.sync; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.Protocol; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.server.test.core.Common; import org.infinispan.server.test.core.category.Security; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ParameterContext; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.aggregator.AggregateWith; import org.junit.jupiter.params.aggregator.ArgumentsAccessor; import org.junit.jupiter.params.aggregator.ArgumentsAggregationException; import org.junit.jupiter.params.aggregator.ArgumentsAggregator; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; import org.wildfly.security.http.HttpConstants; import org.wildfly.security.sasl.util.SaslMechanismInformation; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.0 **/ @Category(Security.class) public class AuthenticationMultiEndpointIT { @RegisterExtension public static InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/AuthenticationServerMultipleEndpoints.xml") .addListener(new SecurityRealmServerListener("alternate")) .build(); static class ArgsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { List<Arguments> args = new ArrayList<>(); // We test against different realms. for (String realm : Arrays.asList("default", "alternate")) { String userPrefix = "alternate".equals(realm) ? "alternate_" : ""; // We test against different ports with different configurations for (int p = 11222; p < 11227; p++) { Integer port = Integer.valueOf(p); final boolean isAnonymous; final boolean isAdmin; final boolean isPlain; final boolean isAlternateRealmHotRod; final boolean isAlternateRealmHTTP; switch (p) { case 11222: isAnonymous = false; isAdmin = true; isPlain = true; isAlternateRealmHotRod = false; isAlternateRealmHTTP = false; break; case 11223: isAnonymous = true; isAdmin = false; isPlain = false; isAlternateRealmHotRod = false; isAlternateRealmHTTP = false; break; case 11224: isAnonymous = false; isAdmin = false; isPlain = true; isAlternateRealmHotRod = true; isAlternateRealmHTTP = true; break; case 11225: isAnonymous = false; isAdmin = true; isPlain = false; isAlternateRealmHotRod = true; isAlternateRealmHTTP = false; break; case 11226: isAnonymous = false; isAdmin = true; isPlain = false; isAlternateRealmHotRod = false; isAlternateRealmHTTP = false; break; default: throw new IllegalArgumentException(); } // We test with different Hot Rod mechs Common.SASL_MECHS.forEach(m -> args.add(Arguments.of("Hot Rod", m, realm, userPrefix, port, isAnonymous, isAdmin, isPlain, isAlternateRealmHotRod)) ); Common.HTTP_MECHS.forEach(m -> args.add(Arguments.of(Protocol.HTTP_11.name(), m, realm, userPrefix, port, isAnonymous, isAdmin, isPlain, isAlternateRealmHTTP)) ); } } return args.stream(); } } @ParameterizedTest(name = "protocol={0}, mech={1}, realm={2}, userPrefix={3}, port={4}, anon={5}, admin={6}, plain={7}") @ArgumentsSource(AuthenticationMultiEndpointIT.ArgsProvider.class) public void testProtocol(@AggregateWith(EndpointAggregator.class) Endpoint endpoint) { endpoint.test(); } static class EndpointAggregator implements ArgumentsAggregator { @Override public Object aggregateArguments(ArgumentsAccessor accessor, ParameterContext context) throws ArgumentsAggregationException { return new AuthenticationMultiEndpointIT.Endpoint( accessor.getString(0), accessor.getString(1), accessor.getString(2), accessor.getString(3), accessor.getInteger(4), accessor.getBoolean(5), accessor.getBoolean(6), accessor.getBoolean(7), accessor.getBoolean(8) ); } } static class Endpoint { private final String protocol; private final String mechanism; private final String realm; private final String userPrefix; private final int port; private final boolean isAnonymous; private final boolean isAdmin; private final boolean isPlain; private final boolean isAlternateRealm; private final boolean useAuth; private final boolean isMechanismClearText; public Endpoint(String protocol, String mechanism, String realm, String userPrefix, int port, boolean isAnonymous, boolean isAdmin, boolean isPlain, boolean isAlternateRealm) { this.protocol = protocol; this.mechanism = mechanism; this.realm = realm; this.userPrefix = userPrefix; this.port = port; this.isAnonymous = isAnonymous; this.isAdmin = isAdmin; this.isPlain = isPlain; this.isAlternateRealm = isAlternateRealm; this.useAuth = !mechanism.isEmpty(); this.isMechanismClearText = SaslMechanismInformation.Names.PLAIN.equals(mechanism) || HttpConstants.BASIC_NAME.equals(mechanism); } public void test() { if (protocol.equals("Hot Rod")) { testHotRod(); } else { testRest(); } } private void testHotRod() { ConfigurationBuilder builder = new ConfigurationBuilder(); if (useAuth) { builder.security().authentication() .saslMechanism(mechanism) .realm(realm) .username(userPrefix + "all_user") .password("all"); } try { RemoteCache<String, String> cache = SERVERS.hotrod().withClientConfiguration(builder).withPort(port).withCacheMode(CacheMode.DIST_SYNC).create(); validateSuccess(); cache.put("k1", "v1"); assertEquals(1, cache.size()); assertEquals("v1", cache.get("k1")); } catch (HotRodClientException e) { validateException(e); } } private void testRest() { Protocol proto = Protocol.valueOf(protocol); RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder().followRedirects(false); if (useAuth) { builder .protocol(proto) .security().authentication() .mechanism(mechanism) .realm(realm) .username(userPrefix + "all_user") .password("all"); } try { RestClient client = SERVERS.rest().withClientConfiguration(builder).withPort(port).create(); validateSuccess(); try (RestResponse response = sync(client.cache(SERVERS.getMethodName()).post("k1", "v1"))) { assertEquals(204, response.getStatus()); assertEquals(proto, response.getProtocol()); } try (RestResponse response = sync(client.cache(SERVERS.getMethodName()).get("k1"))) { assertEquals(200, response.getStatus()); assertEquals(proto, response.getProtocol()); assertEquals("v1", response.getBody()); } assertStatus(isAdmin ? 307 : 404, client.raw().get("/")); assertStatus(isAdmin ? 200 : 404, client.server().info()); } catch (SecurityException e) { validateException(e); } } private void validateSuccess() { if (isAnonymous && useAuth) { throw new IllegalStateException("Authenticated client should not be allowed to connect to anonymous server"); } if (!isAnonymous && !useAuth) { throw new IllegalStateException("Unauthenticated client should not be allowed to connect to authenticated server"); } } private void validateException(RuntimeException e) { if (useAuth && isAnonymous) return; if (!useAuth && !isAnonymous) return; if (isAlternateRealm && "default".equals(realm)) return; if (!isAlternateRealm && !"default".equals(realm)) return; if (isPlain && !isMechanismClearText) return; if (!isPlain && isMechanismClearText) return; throw e; } } }
10,474
40.078431
182
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/security/AuthenticationTLSBouncyCastleIT.java
package org.infinispan.server.security; import static org.junit.jupiter.api.Assertions.assertEquals; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.server.test.core.Common; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.core.category.Security; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 14.0 **/ @Category(Security.class) public class AuthenticationTLSBouncyCastleIT { @RegisterExtension public static InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/AuthenticationServerTLSBouncyCastleTest.xml") .runMode(ServerRunMode.CONTAINER) .numServers(1) .mavenArtifacts("org.bouncycastle:bcprov-jdk15on:1.70") .build(); @ParameterizedTest @ArgumentsSource(Common.SaslMechsArgumentProvider.class) public void testReadWrite(String mechanism) { ConfigurationBuilder builder = new ConfigurationBuilder(); SERVERS.getServerDriver().applyTrustStore(builder, "ca.bcfks", "BCFKS", "BC"); if (!mechanism.isEmpty()) { builder.security().authentication() .saslMechanism(mechanism) .serverName("infinispan") .realm("default") .username("all_user") .password("all"); } try { RemoteCache<String, String> cache = SERVERS.hotrod().withClientConfiguration(builder).withCacheMode(CacheMode.DIST_SYNC).create(); cache.put("k1", "v1"); assertEquals(1, cache.size()); assertEquals("v1", cache.get("k1")); } catch (HotRodClientException e) { // Rethrow if unexpected if (!mechanism.isEmpty()) throw e; } } }
2,344
38.745763
139
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/security/AbstractAuthenticationKeyCloak.java
package org.infinispan.server.security; import static org.infinispan.server.test.core.Common.assertStatus; import static org.infinispan.server.test.core.Common.assertStatusAndBodyEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 13.0 **/ public abstract class AbstractAuthenticationKeyCloak { public static final String INFINISPAN_REALM = "infinispan"; public static final String INFINISPAN_CLIENT_ID = "infinispan-client"; public static final String INFINISPAN_CLIENT_SECRET = "8a43581d-62d7-47dc-9aa4-cd3af24b6083"; protected final InfinispanServerExtension ext; public AbstractAuthenticationKeyCloak(InfinispanServerExtension ext) { this.ext = ext; } @Test public void testHotRodReadWrite() { String token = getToken(); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.security().authentication() .saslMechanism("OAUTHBEARER") .serverName(INFINISPAN_REALM) .realm("default") .token(token); RemoteCache<String, String> cache = ext.hotrod().withClientConfiguration(builder).withCacheMode(CacheMode.DIST_SYNC).create(); cache.put("k1", "v1"); assertEquals(1, cache.size()); assertEquals("v1", cache.get("k1")); } @Test public void testRestReadWrite() { String token = getToken(); RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.security().authentication() .mechanism("BEARER_TOKEN") .username(token); RestClient client = ext.rest().withClientConfiguration(builder).create(); assertStatus(204, client.cache(ext.getMethodName()).post("k1", "v1")); assertStatusAndBodyEquals(200, "v1", client.cache(ext.getMethodName()).get("k1")); } protected abstract String getToken(); }
2,329
36.580645
132
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/security/authentication/AuthenticationIT.java
package org.infinispan.server.security.authentication; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.core.category.Security; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.infinispan.server.test.junit5.InfinispanSuite; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @Suite @SelectClasses({HotRodAuthentication.class, RestAuthentication.class, MemcachedAuthentication.class, RespAuthentication.class}) @Category(Security.class) public class AuthenticationIT extends InfinispanSuite { @RegisterExtension public static final InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/AuthenticationServerTest.xml") .runMode(ServerRunMode.CONTAINER) .numServers(2) .build(); }
1,155
38.862069
127
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/security/authentication/HotRodAuthentication.java
package org.infinispan.server.security.authentication; import static org.junit.jupiter.api.Assertions.assertEquals; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.server.test.core.Common; import org.infinispan.server.test.core.category.Security; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @Category(Security.class) public class HotRodAuthentication { @RegisterExtension public static InfinispanServerExtension SERVERS = AuthenticationIT.SERVERS; @ParameterizedTest @ArgumentsSource(Common.SaslMechsArgumentProvider.class) public void testHotRodReadWrite(String mechanism) { ConfigurationBuilder builder = new ConfigurationBuilder(); if (!mechanism.isEmpty()) { builder.security().authentication() .saslMechanism(mechanism) .serverName("infinispan") .realm("default") .username("all_user") .password("all"); } try { RemoteCache<String, String> cache = SERVERS.hotrod().withClientConfiguration(builder).withCacheMode(CacheMode.DIST_SYNC).create(); cache.put("k1", "v1"); assertEquals(1, cache.size()); assertEquals("v1", cache.get("k1")); } catch (HotRodClientException e) { // Rethrow if unexpected if (!mechanism.isEmpty()) throw e; } } }
1,882
35.211538
139
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/security/authentication/MemcachedAuthentication.java
package org.infinispan.server.security.authentication; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.security.Provider; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.security.BasicCallbackHandler; import org.infinispan.commons.util.Util; import org.infinispan.server.test.core.Common; import org.infinispan.server.test.core.category.Security; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; import net.spy.memcached.ConnectionFactoryBuilder; import net.spy.memcached.MemcachedClient; import net.spy.memcached.auth.AuthDescriptor; import net.spy.memcached.internal.OperationFuture; /** * @since 15.0 **/ @Category(Security.class) public class MemcachedAuthentication { @RegisterExtension public static InfinispanServerExtension SERVERS = AuthenticationIT.SERVERS; private static final Provider[] SECURITY_PROVIDERS; static { // Register only the providers that matter to us List<Provider> providers = new ArrayList<>(); for (String name : Arrays.asList( "org.wildfly.security.sasl.plain.WildFlyElytronSaslPlainProvider", "org.wildfly.security.sasl.digest.WildFlyElytronSaslDigestProvider", "org.wildfly.security.sasl.external.WildFlyElytronSaslExternalProvider", "org.wildfly.security.sasl.oauth2.WildFlyElytronSaslOAuth2Provider", "org.wildfly.security.sasl.scram.WildFlyElytronSaslScramProvider", "org.wildfly.security.sasl.gssapi.WildFlyElytronSaslGssapiProvider", "org.wildfly.security.sasl.gs2.WildFlyElytronSaslGs2Provider" )) { Provider provider = Util.getInstance(name, RemoteCacheManager.class.getClassLoader()); providers.add(provider); } SECURITY_PROVIDERS = providers.toArray(new Provider[0]); } @ParameterizedTest @ArgumentsSource(Common.SaslMechsArgumentProvider.class) public void testMemcachedReadWrite(String mechanism) throws ExecutionException, InterruptedException, TimeoutException { ConnectionFactoryBuilder builder = new ConnectionFactoryBuilder(); builder.setProtocol(mechanism.isEmpty() ? ConnectionFactoryBuilder.Protocol.TEXT : ConnectionFactoryBuilder.Protocol.BINARY); builder.setAuthDescriptor(new AuthDescriptor(new String[]{mechanism}, new BasicCallbackHandler("all_user", "default", "all".toCharArray()), null, null, SECURITY_PROVIDERS)); MemcachedClient client = SERVERS.memcached().withClientConfiguration(builder).get(); OperationFuture<Boolean> f = client.set("k" + mechanism, 0, "v"); assertTrue(f.get(10, TimeUnit.SECONDS)); assertEquals(client.get("k" + mechanism), "v"); } }
3,212
43.625
179
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/security/authentication/RestAuthentication.java
package org.infinispan.server.security.authentication; import static java.nio.charset.StandardCharsets.UTF_8; import static org.infinispan.commons.util.Util.toHexString; import static org.infinispan.server.test.core.Common.HTTP_MECHS; import static org.infinispan.server.test.core.Common.HTTP_PROTOCOLS; import static org.infinispan.server.test.core.Common.assertStatus; import static org.infinispan.server.test.core.Common.sync; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.wildfly.security.mechanism._private.ElytronMessages.httpDigest; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.stream.Stream; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.Protocol; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.test.Exceptions; import org.infinispan.server.test.core.Common; import org.infinispan.server.test.core.InfinispanServerDriver; import org.infinispan.server.test.core.category.Security; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; import org.wildfly.security.mechanism.digest.DigestUtil; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @Category(Security.class) public class RestAuthentication { @RegisterExtension public static InfinispanServerExtension SERVERS = AuthenticationIT.SERVERS; static class ArgsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) throws Exception { List<Arguments> args = new ArrayList<>(HTTP_MECHS.size() * Common.HTTP_PROTOCOLS.size()); for (Protocol protocol : HTTP_PROTOCOLS) { for (String mech : HTTP_MECHS) { args.add(Arguments.of(protocol, mech)); } } return args.stream(); } } @ParameterizedTest(name = "{1}({0})") @ArgumentsSource(ArgsProvider.class) public void testStaticResourcesAnonymously(Protocol protocol, String mechanism) throws Exception { InfinispanServerDriver serverDriver = SERVERS.getServerDriver(); InetSocketAddress serverAddress = serverDriver.getServerSocket(0, 11222); RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder().followRedirects(false); builder.addServer().host(serverAddress.getHostString()).port(serverAddress.getPort()); try (RestClient restClient = RestClient.forConfiguration(builder.build())) { assertStatus(307, restClient.raw().get("/")); // The root resource redirects to the console } } @ParameterizedTest(name = "{1}({0})") @ArgumentsSource(ArgsProvider.class) public void testMalformedDigestHeader(Protocol protocol, String mechanism) throws Exception { assumeTrue(mechanism.startsWith("DIGEST")); InfinispanServerDriver serverDriver = SERVERS.getServerDriver(); InetSocketAddress serverAddress = serverDriver.getServerSocket(0, 11222); RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder().followRedirects(false); builder.addServer().host(serverAddress.getHostString()).port(serverAddress.getPort()); try (RestClient restClient = RestClient.forConfiguration(builder.build()); RestResponse response = sync(restClient.raw().get("/rest/v2/caches"))) { assertEquals(401, response.getStatus()); String auth = response.headers().get("Www-Authenticate").stream().filter(h -> h.startsWith("Digest")).findFirst().get(); HashMap<String, byte[]> parameters = DigestUtil.parseResponse(auth.substring(7).getBytes(UTF_8), UTF_8, false, httpDigest); final String realm = new String(parameters.get("realm"), UTF_8); final String nonce = new String(parameters.get("nonce"), UTF_8); final String opaque = new String(parameters.get("opaque"), UTF_8); final String algorithm = new String(parameters.get("algorithm"), UTF_8); final String charset = StandardCharsets.ISO_8859_1.name(); final MessageDigest digester = MessageDigest.getInstance(algorithm); final String nc = "00000001"; final String cnonce = "00000000"; final String username = "h4ck0rz"; final String password = "letmein"; final String uri = "/backdoor"; final String s1 = username + ':' + realm + ':' + password; final String s2 = "GET:" + uri; final String hasha1 = toHexString(digester.digest(s1.getBytes(charset))); final String h2 = toHexString(digester.digest(s2.getBytes(charset))); final String digestValue = hasha1 + ':' + nonce + ':' + nc + ':' + cnonce + ":auth:" + h2; final String digest = toHexString(digester.digest(digestValue.getBytes(StandardCharsets.US_ASCII))); String authz = String.format("Digest username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\", qop=auth, nc=%s, cnonce=%s, algorithm=%s, opaque=\"%s\"", username, realm, nonce, uri, digest, nc, cnonce, algorithm, opaque); assertStatus(400, restClient.raw().get("/rest/v2/caches", Collections.singletonMap("Authorization", authz))); } } @ParameterizedTest(name = "{1}({0})") @ArgumentsSource(ArgsProvider.class) public void testRestReadWrite(Protocol protocol, String mechanism) { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (!mechanism.isEmpty()) { builder .protocol(protocol) .security().authentication() .mechanism(mechanism) .realm("default") .username("all_user") .password("all"); } if (mechanism.isEmpty()) { Exceptions.expectException(SecurityException.class, () -> SERVERS.rest().withClientConfiguration(builder).create()); } else { RestClient client = SERVERS.rest().withClientConfiguration(builder).create(); try (RestResponse response = sync(client.cache(SERVERS.getMethodName()).post("k1", "v1"))) { assertEquals(204, response.getStatus()); assertEquals(protocol, response.getProtocol()); } try (RestResponse response = sync(client.cache(SERVERS.getMethodName()).get("k1"))) { assertEquals(200, response.getStatus()); assertEquals(protocol, response.getProtocol()); assertEquals("v1", response.getBody()); } } } }
7,203
48.682759
246
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/security/authentication/RespAuthentication.java
package org.infinispan.server.security.authentication; import static org.junit.jupiter.api.Assertions.assertEquals; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import org.infinispan.commons.test.Exceptions; import org.infinispan.server.test.core.category.Security; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.RegisterExtension; import io.lettuce.core.KeyValue; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisCommandExecutionException; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; import io.lettuce.core.codec.StringCodec; import io.lettuce.core.output.ListOfMapsOutput; import io.lettuce.core.protocol.CommandArgs; import io.lettuce.core.protocol.CommandType; /** * @since 14.0 **/ @Category(Security.class) public class RespAuthentication { @RegisterExtension public static InfinispanServerExtension SERVERS = AuthenticationIT.SERVERS; @Test public void testRestReadWrite() { InetSocketAddress serverSocket = SERVERS.getServerDriver().getServerSocket(0, 11222); RedisClient client = RedisClient.create(String.format("redis://all_user:all@%s:%d", serverSocket.getHostString(), serverSocket.getPort())); try (StatefulRedisConnection<String, String> redisConnection = client.connect()) { RedisCommands<String, String> redis = redisConnection.sync(); redis.set("k1", "v1"); redis.set("k3", "v3"); redis.set("k4", "v4"); List<KeyValue<String, String>> expected = new ArrayList<>(4); expected.add(KeyValue.just("k1", "v1")); expected.add(KeyValue.empty("k2")); expected.add(KeyValue.just("k3", "v3")); expected.add(KeyValue.just("k4", "v4")); List<KeyValue<String, String>> results = redis.mget("k1", "k2", "k3", "k4"); assertEquals(expected, results); } finally { client.shutdown(); } } @Test public void testRespCommandDocs() { InetSocketAddress serverSocket = SERVERS.getServerDriver().getServerSocket(0, 11222); RedisClient client = RedisClient.create(String.format("redis://all_user:all@%s:%d", serverSocket.getHostString(), serverSocket.getPort())); try (StatefulRedisConnection<String, String> redisConnection = client.connect()) { RedisCommands<String, String> redis = redisConnection.sync(); Exceptions.expectException(RedisCommandExecutionException.class, () -> redis.dispatch(CommandType.COMMAND, new ListOfMapsOutput<>(StringCodec.UTF8), new CommandArgs<>(StringCodec.UTF8).add("DOCS"))); } finally { client.shutdown(); } } }
2,856
38.680556
145
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/security/authorization/AuthorizationPropertiesIT.java
package org.infinispan.server.security.authorization; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.server.test.core.Common.assertStatus; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import org.infinispan.client.rest.RestClient; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.api.TestUser; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.infinispan.server.test.junit5.InfinispanSuite; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ @Suite @SelectClasses({AuthorizationPropertiesIT.HotRod.class, AuthorizationPropertiesIT.Resp.class, AuthorizationPropertiesIT.Rest.class}) public class AuthorizationPropertiesIT extends InfinispanSuite { @RegisterExtension public static InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/AuthorizationPropertiesTest.xml") .runMode(ServerRunMode.CONTAINER) .mavenArtifacts(ClusteredIT.mavenArtifacts()) .artifacts(ClusteredIT.artifacts()) .build(); static class HotRod extends HotRodAuthorizationTest { @RegisterExtension static InfinispanServerExtension SERVERS = AuthorizationPropertiesIT.SERVERS; public HotRod() { super(SERVERS); } } static class Resp extends RESPAuthorizationTest { @RegisterExtension static InfinispanServerExtension SERVERS = AuthorizationPropertiesIT.SERVERS; public Resp() { super(SERVERS); } } static class Rest extends RESTAuthorizationTest { @RegisterExtension static InfinispanServerExtension SERVERS = AuthorizationPropertiesIT.SERVERS; public Rest() { super(SERVERS); } @Test public void testListPrincipals() { RestClient client = ext.rest().withClientConfiguration(restBuilders.get(TestUser.ADMIN)).get(); Json realmPrincipals = Json.read(assertStatus(OK, client.raw().get("/rest/v2/security/principals"))); List<Json> principals = realmPrincipals.asJsonMap().get("default:properties").asJsonList(); assertEquals(principals.size(), 21); } } }
2,667
36.055556
132
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/security/authorization/HotRodAuthorizationTest.java
package org.infinispan.server.security.authorization; import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP; import static org.infinispan.server.test.core.TestSystemPropertyNames.HOTROD_CLIENT_SASL_MECHANISM; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; 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.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.test.skip.SkipJunit; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.jboss.marshalling.commons.GenericJBossMarshaller; import org.infinispan.protostream.sampledomain.User; import org.infinispan.protostream.sampledomain.marshallers.MarshallerRegistration; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.infinispan.server.functional.hotrod.HotRodCacheQueries; import org.infinispan.server.test.api.TestUser; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; abstract class HotRodAuthorizationTest { public static final String BANK_PROTO = "bank.proto"; public static final String UNAUTHORIZED_EXCEPTION = "(?s).*ISPN000287.*"; protected final Map<TestUser, ConfigurationBuilder> hotRodBuilders; protected final InfinispanServerExtension ext; protected final Function<TestUser, String> serverPrincipal; protected final Map<String, String> bulkData; public HotRodAuthorizationTest(InfinispanServerExtension ext) { this (ext, TestUser::getUser, user -> { ConfigurationBuilder hotRodBuilder = new ConfigurationBuilder(); hotRodBuilder.security().authentication() .saslMechanism(System.getProperty(HOTROD_CLIENT_SASL_MECHANISM, "SCRAM-SHA-1")) .serverName("infinispan") .realm("default") .username(user.getUser()) .password(user.getPassword()); return hotRodBuilder; }); } public HotRodAuthorizationTest(InfinispanServerExtension ext, Function<TestUser, String> serverPrincipal, Function<TestUser, ConfigurationBuilder> hotRodBuilder) { this.ext = ext; this.serverPrincipal = serverPrincipal; this.hotRodBuilders = Stream.of(TestUser.values()).collect(Collectors.toMap(user -> user, hotRodBuilder)); this.bulkData = IntStream.range(0, 10) .boxed() .collect(Collectors.toMap(i -> "k"+i, i -> "v"+i)); } @Test public void testHotRodAdminAndDeployerCanDoEverything() { for (TestUser user : EnumSet.of(TestUser.ADMIN, TestUser.DEPLOYER)) { RemoteCache<String, String> cache = ext.hotrod().withClientConfiguration(hotRodBuilders.get(user)).withCacheMode(CacheMode.DIST_SYNC).create(); cache.put("k", "v"); assertEquals("v", cache.get("k")); cache.putAll(bulkData); assertEquals(11, cache.size()); cache.getRemoteCacheManager().administration().removeCache(cache.getName()); } } @Test public void testHotRodNonAdminsMustNotCreateCache() { for (TestUser user : EnumSet.of(TestUser.APPLICATION, TestUser.OBSERVER, TestUser.MONITOR)) { Exceptions.expectException(HotRodClientException.class, UNAUTHORIZED_EXCEPTION, () -> ext.hotrod().withClientConfiguration(hotRodBuilders.get(user)).withCacheMode(CacheMode.DIST_SYNC).create() ); } } @Test public void testHotRodWriterCannotReadImplicit() { testHotRodWriterCannotRead(); } @Test public void testHotRodWriterCannotReadExplicit() { testHotRodWriterCannotRead("admin", "observer", "deployer", "application", "writer", "reader", "monitor"); } @Test public void testHotRodBulkOperationsImplicit() { testHotRodBulkOperations(); } @Test public void testHotRodBulkOperationsExplicit() { testHotRodBulkOperations("admin", "observer", "deployer", "application", "writer", "reader"); } private void testHotRodBulkOperations(String... explicitRoles) { hotRodCreateAuthzCache(explicitRoles).putAll(bulkData); RemoteCache<String, String> readerCache = ext.hotrod().withClientConfiguration(hotRodBuilders.get(TestUser.READER)).get(); Exceptions.expectException(HotRodClientException.class, UNAUTHORIZED_EXCEPTION, () -> readerCache.getAll(bulkData.keySet()) ); //make sure iterator() is invoked (ISPN-12716) Exceptions.expectException(HotRodClientException.class, UNAUTHORIZED_EXCEPTION, () -> new ArrayList<>(readerCache.keySet()) ); Exceptions.expectException(HotRodClientException.class, UNAUTHORIZED_EXCEPTION, () -> new ArrayList<>(readerCache.values()) ); Exceptions.expectException(HotRodClientException.class, UNAUTHORIZED_EXCEPTION, () -> new ArrayList<>(readerCache.entrySet()) ); RemoteCache<String, String> supervisorCache = ext.hotrod().withClientConfiguration(hotRodBuilders.get(TestUser.DEPLOYER)).get(); supervisorCache.getAll(bulkData.keySet()); //make sure iterator() is invoked (ISPN-12716) assertFalse(new HashSet<>(supervisorCache.keySet()).isEmpty()); assertFalse(new HashSet<>(supervisorCache.values()).isEmpty()); assertFalse(new HashSet<>(supervisorCache.entrySet()).isEmpty()); } @Test public void testHotRodReaderCannotWriteImplicit() { testHotRodObserverCannotWrite(); } @Test public void testHotRodReaderCannotWriteExplicit() { testHotRodObserverCannotWrite(); } private void testHotRodObserverCannotWrite(String... explicitRoles) { hotRodCreateAuthzCache(explicitRoles); RemoteCache<String, String> readerCache = ext.hotrod().withClientConfiguration(hotRodBuilders.get(TestUser.OBSERVER)).get(); Exceptions.expectException(HotRodClientException.class, UNAUTHORIZED_EXCEPTION, () -> readerCache.put("k1", "v1") ); for (TestUser user : EnumSet.of(TestUser.DEPLOYER, TestUser.APPLICATION, TestUser.WRITER)) { RemoteCache<String, String> userCache = ext.hotrod().withClientConfiguration(hotRodBuilders.get(user)).get(); userCache.put(user.name(), user.name()); } } @Test public void testScriptUpload() { SkipJunit.skipCondition(() -> ext.getServerDriver().getConfiguration().runMode() != ServerRunMode.CONTAINER); for (TestUser user : EnumSet.of(TestUser.ADMIN, TestUser.DEPLOYER)) { RemoteCacheManager remoteCacheManager = ext.hotrod().withClientConfiguration(hotRodBuilders.get(user)).createRemoteCacheManager(); ext.addScript(remoteCacheManager, "scripts/test.js"); } for (TestUser user : EnumSet.of(TestUser.MONITOR, TestUser.APPLICATION, TestUser.OBSERVER, TestUser.WRITER)) { RemoteCacheManager remoteCacheManager = ext.hotrod().withClientConfiguration(hotRodBuilders.get(user)).createRemoteCacheManager(); Exceptions.expectException(HotRodClientException.class, UNAUTHORIZED_EXCEPTION, () -> ext.addScript(remoteCacheManager, "scripts/test.js") ); } } @Test public void testAdminCanRemoveCacheWithoutRole() { RemoteCache<String, String> adminCache = hotRodCreateAuthzCache("application"); RemoteCache<String, String> appCache = ext.hotrod().withClientConfiguration(hotRodBuilders.get(TestUser.APPLICATION)).get(); appCache.put("k1", "v1"); adminCache.getRemoteCacheManager().administration().removeCache(adminCache.getName()); } @Test public void testExecScripts() { SkipJunit.skipCondition(() -> ext.getServerDriver().getConfiguration().runMode() != ServerRunMode.CONTAINER); RemoteCache cache = ext.hotrod().withClientConfiguration(hotRodBuilders.get(TestUser.ADMIN)).create(); String scriptName = ext.addScript(cache.getRemoteCacheManager(), "scripts/test.js"); Map params = new HashMap<>(); params.put("key", "k"); params.put("value", "v"); for (TestUser user : EnumSet.of(TestUser.ADMIN, TestUser.APPLICATION, TestUser.DEPLOYER)) { RemoteCache cacheExec = ext.hotrod().withClientConfiguration(hotRodBuilders.get(user)).get(); cacheExec.execute(scriptName, params); } for (TestUser user : EnumSet.of(TestUser.MONITOR, TestUser.OBSERVER, TestUser.WRITER)) { RemoteCache cacheExec = ext.hotrod().withClientConfiguration(hotRodBuilders.get(user)).get(); Exceptions.expectException(HotRodClientException.class, UNAUTHORIZED_EXCEPTION, () -> { cacheExec.execute(scriptName, params); } ); } } @Test public void testServerTaskWithParameters() { ext.assumeContainerMode(); ext.hotrod().withClientConfiguration(hotRodBuilders.get(TestUser.ADMIN)).create(); for (TestUser user : EnumSet.of(TestUser.ADMIN, TestUser.APPLICATION, TestUser.DEPLOYER)) { RemoteCache<String, String> cache = ext.hotrod().withClientConfiguration(hotRodBuilders.get(user)).get(); ArrayList<String> messages = cache.execute("hello", Collections.singletonMap("greetee", new ArrayList<>(Arrays.asList("nurse", "kitty")))); assertEquals(2, messages.size()); assertEquals("Hello nurse", messages.get(0)); assertEquals("Hello kitty", messages.get(1)); String message = cache.execute("hello", Collections.emptyMap()); assertEquals("Hello " + serverPrincipal.apply(user), message); } for (TestUser user : EnumSet.of(TestUser.MONITOR, TestUser.OBSERVER, TestUser.WRITER)) { RemoteCache<String, String> cache = ext.hotrod().withClientConfiguration(hotRodBuilders.get(user)).get(); Exceptions.expectException(HotRodClientException.class, UNAUTHORIZED_EXCEPTION, () -> cache.execute("hello", Collections.singletonMap("greetee", new ArrayList<>(Arrays.asList("nurse", "kitty")))) ); } } @Test public void testCacheUpdateConfigurationAttribute() { org.infinispan.configuration.cache.ConfigurationBuilder builder = new org.infinispan.configuration.cache.ConfigurationBuilder(); builder.memory().maxCount(100); ext.hotrod().withClientConfiguration(hotRodBuilders.get(TestUser.ADMIN)).withServerConfiguration(builder).create(); for (TestUser user : EnumSet.of(TestUser.ADMIN, TestUser.DEPLOYER)) { RemoteCache<String, String> cache = ext.hotrod().withClientConfiguration(hotRodBuilders.get(user)).get(); cache.getRemoteCacheManager().administration().updateConfigurationAttribute(cache.getName(), "memory.max-count", "1000"); } for (TestUser user : EnumSet.complementOf(EnumSet.of(TestUser.ADMIN, TestUser.DEPLOYER, TestUser.ANONYMOUS))) { RemoteCache<String, String> cache = ext.hotrod().withClientConfiguration(hotRodBuilders.get(user)).get(); Exceptions.expectException(HotRodClientException.class, UNAUTHORIZED_EXCEPTION, () -> cache.getRemoteCacheManager().administration().updateConfigurationAttribute(cache.getName(), "memory.max-count", "500") ); } } @Test public void testDistributedServerTaskWithParameters() { ext.assumeContainerMode(); ext.hotrod().withClientConfiguration(hotRodBuilders.get(TestUser.ADMIN)).create(); for (TestUser user : EnumSet.of(TestUser.ADMIN, TestUser.APPLICATION, TestUser.DEPLOYER)) { // We must utilise the GenericJBossMarshaller due to ISPN-8814 RemoteCache<String, String> cache = ext.hotrod().withMarshaller(GenericJBossMarshaller.class).withClientConfiguration(hotRodBuilders.get(user)).get(); List<String> greetings = cache.execute("dist-hello", Collections.singletonMap("greetee", "my friend")); assertEquals(2, greetings.size()); for (String greeting : greetings) { assertTrue(greeting.matches("Hello my friend .*")); } greetings = cache.execute("dist-hello", Collections.emptyMap()); assertEquals(2, greetings.size()); for (String greeting : greetings) { assertTrue(greeting.startsWith("Hello " + serverPrincipal.apply(user) + " from "), greeting); } } } @Test public void testAdminAndDeployerCanManageSchema() { String schema = Exceptions.unchecked(() -> Util.getResourceAsString("/sample_bank_account/bank.proto", this.getClass().getClassLoader())); for (TestUser user : EnumSet.of(TestUser.ADMIN, TestUser.DEPLOYER)) { RemoteCacheManager remoteCacheManager = ext.hotrod().withClientConfiguration(hotRodBuilders.get(user)).createRemoteCacheManager(); RemoteCache<String, String> metadataCache = remoteCacheManager.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); metadataCache.put(BANK_PROTO, schema); metadataCache.remove(BANK_PROTO); } } @Test public void testNonCreatorsSchema() { String schema = Exceptions.unchecked(() -> Util.getResourceAsString("/sample_bank_account/bank.proto", this.getClass().getClassLoader())); for (TestUser user : EnumSet.of(TestUser.APPLICATION, TestUser.OBSERVER, TestUser.WRITER)) { RemoteCacheManager remoteCacheManager = ext.hotrod().withClientConfiguration(hotRodBuilders.get(user)).createRemoteCacheManager(); RemoteCache<String, String> metadataCache = remoteCacheManager.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); Exceptions.expectException(HotRodClientException.class, UNAUTHORIZED_EXCEPTION, () -> metadataCache.put(BANK_PROTO, schema)); } } @Test public void testBulkReadUsersCanQuery() { org.infinispan.configuration.cache.ConfigurationBuilder builder = prepareIndexedCache(); for (TestUser user : EnumSet.of(TestUser.ADMIN, TestUser.DEPLOYER, TestUser.APPLICATION, TestUser.OBSERVER)) { RemoteCache<Integer, User> userCache = ext.hotrod().withClientConfiguration(clientConfigurationWithProtostreamMarshaller(user)).withServerConfiguration(builder).get(); User fromCache = userCache.get(1); HotRodCacheQueries.assertUser1(fromCache); QueryFactory qf = Search.getQueryFactory(userCache); 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(User.class, list.get(0).getClass()); HotRodCacheQueries.assertUser1(list.get(0)); } } @Test public void testNonBulkReadUsersCannotQuery() { org.infinispan.configuration.cache.ConfigurationBuilder builder = prepareIndexedCache(); for (TestUser user : EnumSet.of(TestUser.READER, TestUser.WRITER)) { RemoteCache<Integer, User> userCache = ext.hotrod().withClientConfiguration(clientConfigurationWithProtostreamMarshaller(user)).withServerConfiguration(builder).get(); QueryFactory qf = Search.getQueryFactory(userCache); Query<User> query = qf.create("FROM sample_bank_account.User WHERE name = 'Tom'"); Exceptions.expectException(HotRodClientException.class, UNAUTHORIZED_EXCEPTION, () -> query.execute().list()); } } @Test public void testHotRodCacheNames() { hotRodCreateAuthzCache("admin", "observer", "deployer"); String name = ext.getMethodName(); for (TestUser type : EnumSet.of(TestUser.ADMIN, TestUser.OBSERVER, TestUser.DEPLOYER)) { Set<String> caches = ext.hotrod().withClientConfiguration(hotRodBuilders.get(type)).get().getRemoteCacheContainer().getCacheNames(); assertTrue(caches.contains(name), caches.toString()); } // Types with no access. EnumSet<TestUser> types = EnumSet.complementOf(EnumSet.of(TestUser.ADMIN, TestUser.OBSERVER, TestUser.DEPLOYER, TestUser.ANONYMOUS)); // APPLICATION, MONITOR, READER, WRITER System.out.println(types); for (TestUser type : types) { Set<String> caches = ext.hotrod().withClientConfiguration(hotRodBuilders.get(type)).get().getRemoteCacheContainer().getCacheNames(); assertFalse(caches.contains(name), caches.toString()); } } private org.infinispan.configuration.cache.ConfigurationBuilder prepareIndexedCache() { String schema = Exceptions.unchecked(() -> Util.getResourceAsString("/sample_bank_account/bank.proto", this.getClass().getClassLoader())); RemoteCacheManager remoteCacheManager = ext.hotrod().withClientConfiguration(hotRodBuilders.get(TestUser.ADMIN)).createRemoteCacheManager(); RemoteCache<String, String> metadataCache = remoteCacheManager.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); metadataCache.put(BANK_PROTO, schema); org.infinispan.configuration.cache.ConfigurationBuilder builder = new org.infinispan.configuration.cache.ConfigurationBuilder(); builder .clustering().cacheMode(CacheMode.DIST_SYNC).stateTransfer().awaitInitialTransfer(true) .security().authorization().enable() .indexing().enable().storage(LOCAL_HEAP).addIndexedEntity("sample_bank_account.User"); RemoteCache<Integer, User> adminCache = ext.hotrod().withClientConfiguration(clientConfigurationWithProtostreamMarshaller(TestUser.ADMIN)).withServerConfiguration(builder).create(); adminCache.put(1, HotRodCacheQueries.createUser1()); adminCache.put(2, HotRodCacheQueries.createUser2()); return builder; } private ConfigurationBuilder clientConfigurationWithProtostreamMarshaller(TestUser user) { ConfigurationBuilder client = new ConfigurationBuilder().read(hotRodBuilders.get(user).build(), Combine.DEFAULT); client.servers().clear(); ProtoStreamMarshaller marshaller = new ProtoStreamMarshaller(); client.marshaller(marshaller); Exceptions.unchecked(() -> MarshallerRegistration.registerMarshallers(marshaller.getSerializationContext())); return client; } private void testHotRodWriterCannotRead(String... explicitRoles) { hotRodCreateAuthzCache(explicitRoles); RemoteCache<String, String> writerCache = ext.hotrod().withClientConfiguration(hotRodBuilders.get(TestUser.WRITER)).get(); writerCache.put("k1", "v1"); Exceptions.expectException(HotRodClientException.class, UNAUTHORIZED_EXCEPTION, () -> writerCache.get("k1") ); for (TestUser user : EnumSet.complementOf(EnumSet.of(TestUser.WRITER, TestUser.MONITOR, TestUser.ANONYMOUS))) { RemoteCache<String, String> userCache = ext.hotrod().withClientConfiguration(hotRodBuilders.get(user)).get(); assertEquals("v1", userCache.get("k1")); } } private <K, V> RemoteCache<K, V> hotRodCreateAuthzCache(String... explicitRoles) { org.infinispan.configuration.cache.ConfigurationBuilder builder = new org.infinispan.configuration.cache.ConfigurationBuilder(); AuthorizationConfigurationBuilder authorizationConfigurationBuilder = builder.clustering().cacheMode(CacheMode.DIST_SYNC).security().authorization().enable(); if (explicitRoles != null) { for (String role : explicitRoles) { authorizationConfigurationBuilder.role(role); } } return ext.hotrod().withClientConfiguration(hotRodBuilders.get(TestUser.ADMIN)).withServerConfiguration(builder).create(); } }
20,583
50.331671
187
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/security/authorization/AuthorizationLDAPIT.java
package org.infinispan.server.security.authorization; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.core.LdapServerListener; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.core.category.Security; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.infinispan.server.test.junit5.InfinispanSuite; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @Suite @SelectClasses({AuthorizationLDAPIT.HotRod.class, AuthorizationLDAPIT.Resp.class, AuthorizationLDAPIT.Rest.class}) @Category(Security.class) public class AuthorizationLDAPIT extends InfinispanSuite { @RegisterExtension public static InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/AuthorizationLDAPTest.xml") .runMode(ServerRunMode.CONTAINER) .mavenArtifacts(ClusteredIT.mavenArtifacts()) .artifacts(ClusteredIT.artifacts()) .addListener(new LdapServerListener()) .build(); static class HotRod extends HotRodAuthorizationTest { @RegisterExtension static InfinispanServerExtension SERVERS = AuthorizationLDAPIT.SERVERS; public HotRod() { super(SERVERS); } } static class Rest extends RESTAuthorizationTest { @RegisterExtension static InfinispanServerExtension SERVERS = AuthorizationLDAPIT.SERVERS; public Rest() { super(SERVERS); } } static class Resp extends RESPAuthorizationTest { @RegisterExtension static InfinispanServerExtension SERVERS = AuthorizationLDAPIT.SERVERS; public Resp() { super(SERVERS); } } }
2,042
33.627119
114
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/security/authorization/RESPAuthorizationTest.java
package org.infinispan.server.security.authorization; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.fail; import java.net.InetSocketAddress; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.infinispan.server.test.api.RespTestClientDriver; import org.infinispan.server.test.api.TestUser; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisCommandExecutionException; import io.lettuce.core.RedisConnectionException; import io.lettuce.core.RedisURI; import io.lettuce.core.api.sync.BaseRedisCommands; import io.lettuce.core.api.sync.RedisCommands; import io.lettuce.core.api.sync.RedisServerCommands; import io.lettuce.core.cluster.api.sync.RedisClusterCommands; import io.lettuce.core.resource.DefaultClientResources; abstract class RESPAuthorizationTest { protected final InfinispanServerExtension ext; protected final boolean cert; protected final Function<TestUser, String> serverPrincipal; protected final Map<TestUser, RespTestClientDriver.LettuceConfiguration> respBuilders; public RESPAuthorizationTest(InfinispanServerExtension ext) { this(ext, false, TestUser::getUser, user -> { InetSocketAddress serverSocket = ext.getServerDriver().getServerSocket(0, 11222); ClientOptions clientOptions = ClientOptions.builder() .autoReconnect(false) .build(); RedisURI.Builder uriBuilder = RedisURI.builder() .withHost(serverSocket.getHostString()) .withPort(serverSocket.getPort()); if (user != TestUser.ANONYMOUS) { uriBuilder = uriBuilder.withAuthentication(user.getUser(), user.getPassword()); } return new RespTestClientDriver.LettuceConfiguration(DefaultClientResources.builder(), clientOptions, uriBuilder.build()); }); } public RESPAuthorizationTest(InfinispanServerExtension ext, boolean cert, Function<TestUser, String> serverPrincipal, Function<TestUser, RespTestClientDriver.LettuceConfiguration> respBuilder) { this.ext = ext; this.cert = cert; this.serverPrincipal = serverPrincipal; this.respBuilders = Stream.of(TestUser.values()).collect(Collectors.toMap(user -> user, respBuilder)); } @Test public void testSetGetDelete() { RedisCommands<String, String> redis = createConnection(TestUser.ADMIN); redis.set("k1", "v1"); String v = redis.get("k1"); assertThat(v).isEqualTo("v1"); redis.del("k1"); assertThat(redis.get("k1")).isNull(); assertThat(redis.get("something")).isNull(); } @Test public void testAllUsersConnectingAndOperating() { for (TestUser user: TestUser.values()) { try (RedisClient client = createClient(user)) { if (user == TestUser.ANONYMOUS) { assertAnonymous(client, BaseRedisCommands::ping); continue; } RedisCommands<String, String> conn = createConnection(client); assertThat(conn.ping()).isEqualTo("PONG"); } } } @Test public void testRPUSH() { RedisCommands<String, String> redis = createConnection(TestUser.ADMIN); long result = redis.rpush("people", "tristan"); assertThat(result).isEqualTo(1); result = redis.rpush("people", "william"); assertThat(result).isEqualTo(2); result = redis.rpush("people", "william", "jose", "pedro"); assertThat(result).isEqualTo(5); // Set a String Command redis.set("leads", "tristan"); // Push on an existing key that contains a String, not a Collection! assertThatThrownBy(() -> { redis.rpush("leads", "william"); }).isInstanceOf(RedisCommandExecutionException.class) .hasMessageContaining("ERRWRONGTYPE"); } @Test public void testInfoCommand() { for (TestUser user: TestUser.values()) { try (RedisClient client = createClient(user)) { if (user == TestUser.ANONYMOUS) { assertAnonymous(client, RedisServerCommands::info); continue; } RedisCommands<String, String> conn = createConnection(client); assertThat(conn.info()).isNotEmpty(); } } } @Test public void testClusterSHARDS() { for (TestUser user: TestUser.values()) { try (RedisClient client = createClient(user)) { if (user == TestUser.ANONYMOUS) { assertAnonymous(client, RedisServerCommands::info); continue; } RedisCommands<String, String> conn = createConnection(client); List<Object> shards = conn.clusterShards(); assertThat(shards) .isNotEmpty() .size().isEqualTo(2); } } } @Test public void testHMSETCommand() { RedisCommands<String, String> redis = createConnection(TestUser.ADMIN); Map<String, String> map = Map.of("key1", "value1", "key2", "value2", "key3", "value3"); assertThat(redis.hmset("HMSET", map)).isEqualTo("OK"); assertThat(redis.hget("HMSET", "key1")).isEqualTo("value1"); assertThat(redis.hget("HMSET", "unknown")).isNull(); assertThat(redis.set("plain", "string")).isEqualTo("OK"); assertThatThrownBy(() -> redis.hmset("plain", Map.of("k1", "v1"))) .isInstanceOf(RedisCommandExecutionException.class) .hasMessageContaining("ERRWRONGTYPE"); } @Test public void testClusterNodes() { for (TestUser user: TestUser.values()) { try (RedisClient client = createClient(user)) { if (user == TestUser.ANONYMOUS) { assertAnonymous(client, RedisClusterCommands::clusterNodes); continue; } RedisCommands<String, String> conn = createConnection(client); String nodes = conn.clusterNodes(); assertThat(nodes).isNotNull().isNotEmpty(); assertThat(nodes.split("\n")) .isNotEmpty() .hasSize(2); } } } private void assertAnonymous(RedisClient client, Consumer<RedisCommands<String, String>> consumer) { // When using certificates, an anonymous user can not connect. if (cert) { assertThatThrownBy(client::connect).isExactlyInstanceOf(RedisConnectionException.class); return; } // If using USERNAME + PASSWORD, redis accepts anonymous connections. // But following requests will fail, as user needs to be authenticated. RedisCommands<String, String> conn = createConnection(client); assertThatThrownBy(() -> consumer.accept(conn)).isExactlyInstanceOf(RedisCommandExecutionException.class); } private RedisClient createClient(TestUser user) { RespTestClientDriver.LettuceConfiguration config = respBuilders.get(user); if (config == null) { fail(this.getClass().getSimpleName() + " does not define configuration for user " + user); } return ext.resp().withConfiguration(config).get(); } private RedisCommands<String, String> createConnection(TestUser user) { RespTestClientDriver.LettuceConfiguration config = respBuilders.get(user); if (config == null) { fail(this.getClass().getSimpleName() + " does not define configuration for user " + user); } return ext.resp() .withConfiguration(config) .getConnection() .sync(); } private RedisCommands<String, String> createConnection(RedisClient client) { return ext.resp() .connect(client) .sync(); } }
8,047
35.089686
197
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/security/authorization/AuthorizationCertIT.java
package org.infinispan.server.security.authorization; import static org.infinispan.server.test.core.AbstractInfinispanServerDriver.KEY_PASSWORD; import java.net.InetSocketAddress; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.api.RespTestClientDriver; import org.infinispan.server.test.api.TestUser; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.core.category.Security; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.infinispan.server.test.junit5.InfinispanSuite; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisURI; import io.lettuce.core.SslOptions; import io.lettuce.core.SslVerifyMode; import io.lettuce.core.resource.DefaultClientResources; /** * @author Ryan Emerson * @since 13.0 */ @Suite @SelectClasses({AuthorizationCertIT.HotRod.class, AuthorizationCertIT.Resp.class, AuthorizationCertIT.Rest.class}) @Category(Security.class) public class AuthorizationCertIT extends InfinispanSuite { @RegisterExtension public static InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/AuthorizationCertTest.xml") .runMode(ServerRunMode.CONTAINER) .mavenArtifacts(ClusteredIT.mavenArtifacts()) .artifacts(ClusteredIT.artifacts()) .build(); static class HotRod extends HotRodAuthorizationTest { @RegisterExtension static InfinispanServerExtension SERVERS = AuthorizationCertIT.SERVERS; public HotRod() { super(SERVERS, AuthorizationCertIT::expectedServerPrincipalName, user -> { ConfigurationBuilder hotRodBuilder = new ConfigurationBuilder(); SERVERS.getServerDriver().applyTrustStore(hotRodBuilder, "ca.pfx"); if (user == TestUser.ANONYMOUS) { SERVERS.getServerDriver().applyKeyStore(hotRodBuilder, "server.pfx"); } else { SERVERS.getServerDriver().applyKeyStore(hotRodBuilder, user.getUser() + ".pfx"); } hotRodBuilder.security() .authentication() .saslMechanism("EXTERNAL") .serverName("infinispan") .realm("default"); return hotRodBuilder; }); } } static class Rest extends RESTAuthorizationTest { @RegisterExtension static InfinispanServerExtension SERVERS = AuthorizationCertIT.SERVERS; public Rest() { super(SERVERS, AuthorizationCertIT::expectedServerPrincipalName, user -> { RestClientConfigurationBuilder restBuilder = new RestClientConfigurationBuilder(); SERVERS.getServerDriver().applyTrustStore(restBuilder, "ca.pfx"); if (user == TestUser.ANONYMOUS) { SERVERS.getServerDriver().applyKeyStore(restBuilder, "server.pfx"); } else { SERVERS.getServerDriver().applyKeyStore(restBuilder, user.getUser() + ".pfx"); } restBuilder.security().authentication().ssl() .sniHostName("infinispan") .hostnameVerifier((hostname, session) -> true).connectionTimeout(120_000).socketTimeout(120_000); return restBuilder; }); } } static class Resp extends RESPAuthorizationTest { @RegisterExtension static InfinispanServerExtension SERVERS = AuthorizationCertIT.SERVERS; public Resp() { super(SERVERS, true, AuthorizationCertIT::expectedServerPrincipalName, user -> { DefaultClientResources.Builder builder = DefaultClientResources.builder(); SslOptions.Builder sslBuilder = SslOptions.builder() .jdkSslProvider() .truststore(SERVERS.getServerDriver().getCertificateFile("ca.pfx"), KEY_PASSWORD); RedisURI uri; InetSocketAddress serverSocket = SERVERS.getServerDriver().getServerSocket(0, 11222); if (user == TestUser.ANONYMOUS) { sslBuilder.keystore(SERVERS.getServerDriver().getCertificateFile("server.pfx"), KEY_PASSWORD.toCharArray()) .keyStoreType("pkcs12"); uri = RedisURI.create(serverSocket.getHostString(), serverSocket.getPort()); } else { sslBuilder.keystore(SERVERS.getServerDriver().getCertificateFile(user.getUser() + ".pfx"), KEY_PASSWORD.toCharArray()) .keyStoreType("pkcs12"); uri = RedisURI.builder() .withSsl(true) .withHost(serverSocket.getHostString()) .withPort(serverSocket.getPort()) .withVerifyPeer(SslVerifyMode.NONE) .build(); } ClientOptions options = ClientOptions.builder() .sslOptions(sslBuilder.build()) .autoReconnect(false) // Otherwise, Lettuce keeps retrying. .build(); return new RespTestClientDriver.LettuceConfiguration(builder, options, uri); }); } } private static String expectedServerPrincipalName(TestUser user) { return String.format("CN=%s,OU=Infinispan,O=JBoss,L=Red Hat", user.getUser()); } }
5,724
42.70229
133
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/security/authorization/RESTAuthorizationTest.java
package org.infinispan.server.security.authorization; import static org.infinispan.client.rest.RestResponse.ACCEPTED; import static org.infinispan.client.rest.RestResponse.CREATED; import static org.infinispan.client.rest.RestResponse.FORBIDDEN; import static org.infinispan.client.rest.RestResponse.NOT_FOUND; import static org.infinispan.client.rest.RestResponse.NOT_MODIFIED; import static org.infinispan.client.rest.RestResponse.NO_CONTENT; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.client.rest.RestResponse.TEMPORARY_REDIRECT; import static org.infinispan.server.test.core.Common.assertStatus; import static org.infinispan.server.test.core.Common.assertStatusAndBodyEquals; import static org.infinispan.server.test.core.Common.awaitStatus; import static org.infinispan.server.test.core.Common.sync; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestCacheManagerClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestClusterClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.RestSecurityClient; import org.infinispan.client.rest.RestServerClient; import org.infinispan.client.rest.configuration.RestClientConfiguration; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.client.rest.impl.okhttp.StringRestEntityOkHttp; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.XSiteStateTransferMode; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.infinispan.rest.resources.WeakSSEListener; import org.infinispan.server.test.api.TestUser; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.util.concurrent.CompletionStages; import org.junit.jupiter.api.Test; abstract class RESTAuthorizationTest { public static final String BANK_PROTO = "bank.proto"; protected final InfinispanServerExtension ext; protected final Function<TestUser, String> serverPrincipal; protected final Map<TestUser, RestClientConfigurationBuilder> restBuilders; public RESTAuthorizationTest(InfinispanServerExtension ext) { this(ext, TestUser::getUser, user -> { RestClientConfigurationBuilder restBuilder = new RestClientConfigurationBuilder(); restBuilder.security().authentication() .mechanism("AUTO") .username(user.getUser()) .password(user.getPassword()); return restBuilder; }); } public RESTAuthorizationTest(InfinispanServerExtension ext, Function<TestUser, String> serverPrincipal, Function<TestUser, RestClientConfigurationBuilder> restBuilder) { this.ext = ext; this.serverPrincipal = serverPrincipal; this.restBuilders = Stream.of(TestUser.values()).collect(Collectors.toMap(user -> user, restBuilder)); } @Test public void testRestAdminCanDoEverything() { RestCacheClient adminCache = ext.rest().withClientConfiguration(restBuilders.get(TestUser.ADMIN)) .withCacheMode(CacheMode.DIST_SYNC).create().cache(ext.getMethodName()); assertStatus(NO_CONTENT, adminCache.put("k", "v")); assertStatusAndBodyEquals(OK, "v", adminCache.get("k")); assertStatus(OK, adminCache.distribution()); } @Test public void testRestLocalCacheDistribution() { restCreateAuthzLocalCache("admin", "observer", "deployer", "application", "writer", "reader", "monitor"); actualTestCacheDistribution(); } @Test public void testRestCacheDistribution() { restCreateAuthzCache("admin", "observer", "deployer", "application", "writer", "reader", "monitor"); actualTestCacheDistribution(); } private void actualTestCacheDistribution() { for (TestUser type : EnumSet.of(TestUser.ADMIN, TestUser.MONITOR)) { RestCacheClient cache = ext.rest().withClientConfiguration(restBuilders.get(type)).get() .cache(ext.getMethodName()); assertStatus(OK, cache.distribution()); } // Types with no access. for (TestUser type : EnumSet.complementOf(EnumSet.of(TestUser.ANONYMOUS, TestUser.ADMIN, TestUser.MONITOR))) { RestCacheClient cache = ext.rest().withClientConfiguration(restBuilders.get(type)).get().cache(ext.getMethodName()); assertStatus(FORBIDDEN, cache.distribution()); } } @Test public void testRestKeyDistribution() { restCreateAuthzCache("admin", "observer", "deployer", "application", "writer", "reader", "monitor"); RestCacheClient adminCache = ext.rest().withClientConfiguration(restBuilders.get(TestUser.ADMIN)) .get().cache(ext.getMethodName()); assertStatus(NO_CONTENT, adminCache.put("existentKey", "v")); for (TestUser type : EnumSet.of(TestUser.ADMIN, TestUser.MONITOR)) { RestCacheClient cache = ext.rest().withClientConfiguration(restBuilders.get(type)).get() .cache(ext.getMethodName()); assertStatus(OK, cache.distribution("somekey")); assertStatus(OK, cache.distribution("existentKey")); } // Types with no access. for (TestUser type : EnumSet.complementOf(EnumSet.of(TestUser.ANONYMOUS, TestUser.ADMIN, TestUser.MONITOR))) { RestCacheClient cache = ext.rest().withClientConfiguration(restBuilders.get(type)).get() .cache(ext.getMethodName()); assertStatus(FORBIDDEN, cache.distribution("somekey")); assertStatus(FORBIDDEN, cache.distribution("existentKey")); } } @Test public void testStats() { restCreateAuthzCache("admin", "observer", "deployer", "application", "writer", "reader", "monitor"); for (TestUser type : EnumSet.of(TestUser.ADMIN, TestUser.MONITOR)) { RestCacheClient cache = ext.rest().withClientConfiguration(restBuilders.get(type)).get() .cache(ext.getMethodName()); assertStatus(OK, cache.stats()); } // Types with no access. for (TestUser type : EnumSet.complementOf(EnumSet.of(TestUser.ANONYMOUS, TestUser.ADMIN, TestUser.MONITOR))) { RestCacheClient cache = ext.rest().withClientConfiguration(restBuilders.get(type)).get() .cache(ext.getMethodName()); assertStatus(FORBIDDEN, cache.stats()); } } @Test public void testStatsReset() { restCreateAuthzCache("admin", "observer", "deployer", "application", "writer", "reader", "monitor"); for (TestUser type : EnumSet.of(TestUser.ADMIN)) { RestCacheClient cache = ext.rest().withClientConfiguration(restBuilders.get(type)).get() .cache(ext.getMethodName()); assertStatus(NO_CONTENT, cache.statsReset()); } // Types with no access. for (TestUser type : EnumSet.complementOf(EnumSet.of(TestUser.ANONYMOUS, TestUser.ADMIN))) { RestCacheClient cache = ext.rest().withClientConfiguration(restBuilders.get(type)).get() .cache(ext.getMethodName()); assertStatus(FORBIDDEN, cache.statsReset()); } } @Test public void testRestNonAdminsMustNotCreateCache() { for (TestUser user : EnumSet.of(TestUser.APPLICATION, TestUser.OBSERVER, TestUser.MONITOR)) { Exceptions.expectException(SecurityException.class, "(?s).*403.*", () -> ext.rest().withClientConfiguration(restBuilders.get(user)).withCacheMode(CacheMode.DIST_SYNC).create() ); } } @Test public void testRestWriterCannotReadImplicit() { testRestWriterCannotRead(); } @Test public void testRestWriterCannotReadExplicit() { testRestWriterCannotRead("admin", "observer", "deployer", "application", "writer", "reader"); } private void testRestWriterCannotRead(String... explicitRoles) { restCreateAuthzCache(explicitRoles); RestCacheClient writerCache = ext.rest().withClientConfiguration(restBuilders.get(TestUser.WRITER)).get() .cache(ext.getMethodName()); assertStatus(NO_CONTENT, writerCache.put("k1", "v1")); assertStatus(FORBIDDEN, writerCache.get("k1")); for (TestUser user : EnumSet.of(TestUser.OBSERVER, TestUser.DEPLOYER)) { RestCacheClient userCache = ext.rest().withClientConfiguration(restBuilders.get(user)).get() .cache(ext.getMethodName()); assertStatusAndBodyEquals(OK, "v1", userCache.get("k1")); } } @Test public void testRestReaderCannotWriteImplicit() { testRestReaderCannotWrite(); } @Test public void testRestReaderCannotWriteExplicit() { testRestReaderCannotWrite("admin", "observer", "deployer", "application", "writer", "reader"); } private void testRestReaderCannotWrite(String... explicitRoles) { restCreateAuthzCache(explicitRoles); RestCacheClient readerCache = ext.rest().withClientConfiguration(restBuilders.get(TestUser.OBSERVER)).get() .cache(ext.getMethodName()); assertStatus(FORBIDDEN, readerCache.put("k1", "v1")); for (TestUser user : EnumSet.of(TestUser.APPLICATION, TestUser.DEPLOYER)) { RestCacheClient userCache = ext.rest().withClientConfiguration(restBuilders.get(user)).get() .cache(ext.getMethodName()); assertStatus(NO_CONTENT, userCache.put(user.name(), user.name())); } } @Test public void testAnonymousHealthPredefinedCache() { RestClient client = ext.rest().withClientConfiguration(restBuilders.get(TestUser.ANONYMOUS)).get(); assertStatusAndBodyEquals(OK, "HEALTHY", client.cacheManager("default").healthStatus()); } @Test public void testRestNonAdminsMustNotShutdownServer() { for (TestUser user : TestUser.NON_ADMINS) { assertStatus(FORBIDDEN, ext.rest().withClientConfiguration(restBuilders.get(user)).get().server().stop()); } } @Test public void testRestNonAdminsMustNotShutdownCluster() { for (TestUser user : TestUser.NON_ADMINS) { assertStatus(FORBIDDEN, ext.rest().withClientConfiguration(restBuilders.get(user)).get().cluster().stop()); } } @Test public void testRestNonAdminsMustNotModifyCacheIgnores() { for (TestUser user : TestUser.NON_ADMINS) { RestClient client = ext.rest().withClientConfiguration(restBuilders.get(user)).get(); assertStatus(FORBIDDEN, client.server().ignoreCache("default", "predefined")); assertStatus(FORBIDDEN, client.server().unIgnoreCache("default", "predefined")); } } @Test public void testRestAdminsShouldBeAbleToModifyLoggers() { RestClient client = ext.rest().withClientConfiguration(restBuilders.get(TestUser.ADMIN)).get(); assertStatus(NO_CONTENT, client.server().logging().setLogger("org.infinispan.TEST_LOGGER", "ERROR", "STDOUT")); assertStatus(NO_CONTENT, client.server().logging().removeLogger("org.infinispan.TEST_LOGGER")); } @Test public void testRestNonAdminsMustNotModifyLoggers() { for (TestUser user : TestUser.NON_ADMINS) { assertStatus(FORBIDDEN, ext.rest().withClientConfiguration(restBuilders.get(user)).get().server().logging().setLogger("org.infinispan.TEST_LOGGER", "ERROR", "STDOUT")); assertStatus(FORBIDDEN, ext.rest().withClientConfiguration(restBuilders.get(user)).get().server().logging().removeLogger("org.infinispan.TEST_LOGGER")); } } @Test public void testRestAdminsShouldBeAbleToAdminServer() { RestClientConfigurationBuilder adminConfig = restBuilders.get(TestUser.ADMIN); RestClient client = ext.rest().withClientConfiguration(adminConfig).get(); assertStatus(NO_CONTENT, client.server().connectorStop("endpoint-alternate-1")); assertStatus(NO_CONTENT, client.server().connectorStart("endpoint-alternate-1")); assertStatus(NO_CONTENT, client.server().connectorIpFilterSet("endpoint-alternate-1", Collections.emptyList())); assertStatus(NO_CONTENT, client.server().connectorIpFiltersClear("endpoint-alternate-1")); assertStatus(OK, client.server().memory()); assertStatus(OK, client.server().env()); assertStatus(OK, client.server().configuration()); String connections = assertStatus(OK, client.server().listConnections(true)); Json json = Json.read(connections); assertTrue(json.isArray()); } @Test public void testRestNonAdminsMustNotAdminServer() { for (TestUser user : TestUser.NON_ADMINS) { RestClientConfigurationBuilder userConfig = restBuilders.get(user); RestClient client = ext.rest().withClientConfiguration(userConfig).get(); assertStatus(FORBIDDEN, client.server().report()); assertStatus(FORBIDDEN, client.server().connectorStop("endpoint-default")); assertStatus(FORBIDDEN, client.server().connectorStart("endpoint-default")); assertStatus(FORBIDDEN, client.server().connectorIpFilterSet("endpoint-default", Collections.emptyList())); assertStatus(FORBIDDEN, client.server().connectorIpFiltersClear("endpoint-default")); assertStatus(FORBIDDEN, client.server().memory()); assertStatus(FORBIDDEN, client.server().env()); assertStatus(FORBIDDEN, client.server().configuration()); } } @Test public void testAdminsAccessToPerformXSiteOps() { assertXSiteOps(TestUser.ADMIN, OK, NO_CONTENT, NOT_MODIFIED); } @Test public void testRestNonAdminsMustNotAccessPerformXSiteOps() { for (TestUser user : TestUser.NON_ADMINS) { assertXSiteOps(user, FORBIDDEN, FORBIDDEN, FORBIDDEN); } } private void assertXSiteOps(TestUser user, int status, int noContentStatus, int notModifiedStatus) { RestClientConfigurationBuilder userConfig = restBuilders.get(user); RestClient client = ext.rest().withClientConfiguration(userConfig).get(); RestCacheClient xsiteCache = client.cache("xsite"); assertStatus(status, xsiteCache.takeSiteOffline("NYC")); assertStatus(status, xsiteCache.bringSiteOnline("NYC")); assertStatus(status, xsiteCache.cancelPushState("NYC")); assertStatus(status, xsiteCache.cancelReceiveState("NYC")); assertStatus(status, xsiteCache.clearPushStateStatus()); assertStatus(status, xsiteCache.pushSiteState("NYC")); assertStatus(status, xsiteCache.pushStateStatus()); assertStatus(status, xsiteCache.xsiteBackups()); assertStatus(status, xsiteCache.backupStatus("NYC")); assertStatus(status, xsiteCache.getXSiteTakeOfflineConfig("NYC")); assertStatus(noContentStatus, xsiteCache.updateXSiteTakeOfflineConfig("NYC", 10, 1000)); assertStatus(status, xsiteCache.xSiteStateTransferMode("NYC")); assertStatus(notModifiedStatus, xsiteCache.xSiteStateTransferMode("NYC", XSiteStateTransferMode.MANUAL)); RestCacheManagerClient xsiteCacheManager = client.cacheManager("default"); assertStatus(status, xsiteCacheManager.bringBackupOnline("NYC")); assertStatus(status, xsiteCacheManager.takeOffline("NYC")); assertStatus(status, xsiteCacheManager.backupStatuses()); } @Test public void testRestNonAdminsMustNotPerformSearchActions() { String schema = Exceptions.unchecked(() -> Util.getResourceAsString("/sample_bank_account/bank.proto", this.getClass().getClassLoader())); assertStatus(OK, ext.rest().withClientConfiguration(restBuilders.get(TestUser.ADMIN)).get().schemas().put(BANK_PROTO, schema)); org.infinispan.configuration.cache.ConfigurationBuilder builder = new org.infinispan.configuration.cache.ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); builder.indexing().enable().addIndexedEntity("sample_bank_account.User").statistics().enable(); RestClient restClient = ext.rest().withClientConfiguration(restBuilders.get(TestUser.ADMIN)) .withServerConfiguration(builder).create(); String indexedCache = ext.getMethodName(); RestCacheClient cache = restClient.cache(indexedCache); for (TestUser user : TestUser.NON_ADMINS) { searchActions(user, indexedCache, FORBIDDEN, FORBIDDEN); } searchActions(TestUser.ADMIN, indexedCache, OK, NO_CONTENT); } private void searchActions(TestUser user, String indexedCache, int status, int noContentStatus) { RestClient client = ext.rest().withClientConfiguration(restBuilders.get(user)).get(); assertStatus(status, client.cache(indexedCache).clearSearchStats()); assertStatus(noContentStatus, client.cache(indexedCache).reindex()); assertStatus(noContentStatus, client.cache(indexedCache).clearIndex()); } @Test public void testRestClusterDistributionPermission() { EnumSet<TestUser> allowed = EnumSet.of(TestUser.ADMIN, TestUser.MONITOR); for (TestUser user : allowed) { RestClusterClient client = ext.rest().withClientConfiguration(restBuilders.get(user)).get().cluster(); assertStatus(OK, client.distribution()); } for (TestUser user : EnumSet.complementOf(EnumSet.of(TestUser.ANONYMOUS, allowed.toArray(new TestUser[0])))) { RestClusterClient client = ext.rest().withClientConfiguration(restBuilders.get(user)).get().cluster(); assertStatus(FORBIDDEN, client.distribution()); } } @Test public void testRestServerNodeReport() { ext.assumeContainerMode(); RestClusterClient restClient = ext.rest().withClientConfiguration(restBuilders.get(TestUser.ADMIN)).get().cluster(); CompletionStage<RestResponse> distribution = restClient.distribution(); RestResponse distributionResponse = CompletionStages.join(distribution); assertEquals(OK, distributionResponse.getStatus()); Json json = Json.read(distributionResponse.getBody()); List<String> nodes = json.asJsonList().stream().map(j -> j.at("node_name").asString()).collect(Collectors.toList()); RestServerClient client = ext.rest().withClientConfiguration(restBuilders.get(TestUser.ADMIN)).get().server(); for (String name : nodes) { RestResponse response = CompletionStages.join(client.report(name)); assertEquals(OK, response.getStatus()); assertEquals("application/gzip", response.getHeader("content-type")); assertTrue(response.getHeader("Content-Disposition").startsWith("attachment;")); } RestResponse response = CompletionStages.join(client.report("not-a-node-name")); assertEquals(NOT_FOUND, response.getStatus()); for (TestUser user : EnumSet.complementOf(EnumSet.of(TestUser.ANONYMOUS, TestUser.ADMIN))) { RestServerClient otherClient = ext.rest().withClientConfiguration(restBuilders.get(user)).get().server(); assertStatus(FORBIDDEN, otherClient.report(ext.getMethodName())); } } @Test public void testRestAdminsMustAccessBackupsAndRestores() { String BACKUP_NAME = "backup"; RestClusterClient client = ext.rest().withClientConfiguration(restBuilders.get(TestUser.ADMIN)).get().cluster(); assertStatus(ACCEPTED, client.createBackup(BACKUP_NAME)); File zip = awaitStatus(() -> client.getBackup(BACKUP_NAME, false), ACCEPTED, OK, response -> { String fileName = response.getHeader("Content-Disposition").split("=")[1]; File backupZip = new File(ext.getServerDriver().getRootDir(), fileName); try (InputStream is = response.getBodyAsStream()) { Files.copy(is, backupZip.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new RuntimeException(e); } return backupZip; }); assertStatus(NO_CONTENT, client.deleteBackup(BACKUP_NAME)); assertStatus(OK, client.getBackupNames()); assertStatus(ACCEPTED, client.restore(BACKUP_NAME, zip)); assertStatus(OK, client.getRestoreNames()); awaitStatus(() -> client.getRestore(BACKUP_NAME), ACCEPTED, CREATED); assertStatus(NO_CONTENT, client.deleteRestore(BACKUP_NAME)); } @Test public void testRestNonAdminsMustNotAccessBackupsAndRestores() { for (TestUser user : TestUser.NON_ADMINS) { RestClusterClient client = ext.rest().withClientConfiguration(restBuilders.get(user)).get().cluster(); assertStatus(FORBIDDEN, client.createBackup("backup")); assertStatus(FORBIDDEN, client.getBackup("backup", true)); assertStatus(FORBIDDEN, client.getBackupNames()); assertStatus(FORBIDDEN, client.deleteBackup("backup")); assertStatus(FORBIDDEN, client.restore("restore", "somewhere")); assertStatus(FORBIDDEN, client.getRestoreNames()); assertStatus(FORBIDDEN, client.getRestore("restore")); assertStatus(FORBIDDEN, client.deleteRestore("restore")); } } @Test public void testRestListenSSEAuthorizations() throws Exception { RestClient adminClient = ext.rest().withClientConfiguration(restBuilders.get(TestUser.ADMIN)).get(); WeakSSEListener sseListener = new WeakSSEListener(); // admin must be able to listen events. try (Closeable ignored = adminClient.raw().listen("/rest/v2/container?action=listen", Collections.emptyMap(), sseListener)) { assertTrue(sseListener.await(10, TimeUnit.SECONDS)); } // non-admins must receive 403 status code. for (TestUser nonAdmin : TestUser.NON_ADMINS) { CountDownLatch latch = new CountDownLatch(1); RestClient client = ext.rest().withClientConfiguration(restBuilders.get(nonAdmin)).get(); WeakSSEListener listener = new WeakSSEListener() { @Override public void onError(Throwable t, RestResponse response) { if (response.getStatus() == FORBIDDEN) { latch.countDown(); } } }; try (Closeable ignored = client.raw().listen("/rest/v2/container?action=listen", Collections.emptyMap(), listener)) { assertTrue(latch.await(10, TimeUnit.SECONDS)); } } } @Test public void testConsoleLogin() { for (TestUser user : TestUser.ALL) { RestClientConfiguration cfg = restBuilders.get(user).build(); boolean followRedirects = !cfg.security().authentication().mechanism().equals("SPNEGO"); RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder().read(cfg, Combine.DEFAULT).clearServers().followRedirects(followRedirects); InetSocketAddress serverAddress = ext.getServerDriver().getServerSocket(0, 11222); builder.addServer().host(serverAddress.getHostName()).port(serverAddress.getPort()); RestClient client = ext.rest().withClientConfiguration(builder).get(); assertStatus(followRedirects ? OK : TEMPORARY_REDIRECT, client.raw().get("/rest/v2/login")); Json acl = Json.read(assertStatus(OK, client.raw().get("/rest/v2/security/user/acl"))); Json subject = acl.asJsonMap().get("subject"); Map<String, Object> principal = subject.asJsonList().get(0).asMap(); assertEquals(serverPrincipal.apply(user), principal.get("name")); } } @Test public void testRestCacheNames() { restCreateAuthzCache("admin", "observer", "deployer"); String name = ext.getMethodName(); for (TestUser type : EnumSet.of(TestUser.ADMIN, TestUser.OBSERVER, TestUser.DEPLOYER)) { try (RestResponse caches = CompletionStages.join(ext.rest().withClientConfiguration(restBuilders.get(type)).get().cacheManager("default").caches())) { assertEquals(OK, caches.getStatus()); Json json = Json.read(caches.getBody()); Set<String> names = json.asJsonList().stream().map(Json::asJsonMap).map(j -> j.get("name").asString()).collect(Collectors.toSet()); assertTrue(names.contains(name), names.toString()); } } // Types with no access. for (TestUser type : EnumSet.complementOf(EnumSet.of(TestUser.ADMIN, TestUser.OBSERVER, TestUser.DEPLOYER, TestUser.ANONYMOUS))) { try (RestResponse caches = CompletionStages.join(ext.rest().withClientConfiguration(restBuilders.get(type)).get().cacheManager("default").caches())) { assertEquals(OK, caches.getStatus()); Json json = Json.read(caches.getBody()); Set<String> names = json.asJsonList().stream().map(Json::asJsonMap).map(j -> j.get("name").asString()).collect(Collectors.toSet()); assertFalse(names.contains(name), names.toString()); } } } @Test public void testBulkReadUsersCanQuery() { createIndexedCache(); for (TestUser user : EnumSet.of(TestUser.ADMIN, TestUser.DEPLOYER, TestUser.APPLICATION, TestUser.OBSERVER)) { RestCacheClient userCache = ext.rest().withClientConfiguration(restBuilders.get(user)).get().cache(ext.getMethodName()); assertStatus(OK, userCache.query("FROM sample_bank_account.User WHERE name = 'Tom'")); assertStatus(OK, userCache.searchStats()); assertStatus(OK, userCache.indexStats()); assertStatus(OK, userCache.queryStats()); } } @Test public void testNonBulkReadUsersCannotQuery() { createIndexedCache(); for (TestUser user : EnumSet.of(TestUser.READER, TestUser.WRITER, TestUser.MONITOR)) { RestCacheClient userCache = ext.rest().withClientConfiguration(restBuilders.get(user)).get().cache(ext.getMethodName()); assertStatus(FORBIDDEN, userCache.query("FROM sample_bank_account.User WHERE name = 'Tom'")); assertStatus(OK, userCache.searchStats()); assertStatus(OK, userCache.indexStats()); assertStatus(OK, userCache.queryStats()); } } @Test public void testFlushACL() { for (TestUser user : EnumSet.of(TestUser.ADMIN)) { RestClient client = ext.rest().withClientConfiguration(restBuilders.get(user)).get(); assertStatus(NO_CONTENT, client.security().flushCache()); } for (TestUser user : EnumSet.complementOf(EnumSet.of(TestUser.ADMIN, TestUser.ANONYMOUS))) { RestClient client = ext.rest().withClientConfiguration(restBuilders.get(user)).get(); assertStatus(FORBIDDEN, client.security().flushCache()); } } @Test public void testRoleManipulation() { for (TestUser user : EnumSet.of(TestUser.ADMIN)) { RestSecurityClient security = ext.rest().withClientConfiguration(restBuilders.get(user)).get().security(); assertStatus(OK, security.listPrincipals()); assertStatus(NO_CONTENT, security.createRole("myrole", List.of("ALL_READ", "ALL_WRITE"))); Json json = Json.read(assertStatus(OK, security.describeRole("myrole"))); assertEquals("myrole", json.at("name").asString()); List<Json> permissions = json.at("permissions").asJsonList(); assertEquals(2, permissions.size()); assertTrue(permissions.stream().map(Json::asString).collect(Collectors.toSet()).containsAll(List.of("ALL_READ", "ALL_WRITE")), permissions.toString()); // The code below only works when using the cluster mapper try(RestResponse response = sync(security.grant("myuser", List.of("myrole")))) { if (response.getStatus() == NO_CONTENT) { assertStatusAndBodyEquals(OK, "[\"myrole\"]", security.listRoles("myuser")); assertStatus(NO_CONTENT, security.deny("myuser", List.of("myrole"))); } } } for (TestUser user : EnumSet.complementOf(EnumSet.of(TestUser.ADMIN, TestUser.ANONYMOUS))) { RestSecurityClient security = ext.rest().withClientConfiguration(restBuilders.get(user)).get().security(); assertStatus(FORBIDDEN, security.listPrincipals()); assertStatus(FORBIDDEN, security.createRole("myrole", List.of("ALL_READ", "ALL_WRITE"))); assertStatus(FORBIDDEN, security.describeRole("myrole")); assertStatus(FORBIDDEN, security.grant("myuser", List.of("myrole"))); assertStatus(FORBIDDEN, security.listRoles("myuser")); assertStatus(FORBIDDEN, security.deny("myuser", List.of("myrole"))); } } private void createIndexedCache() { String schema = Exceptions.unchecked(() -> Util.getResourceAsString("/sample_bank_account/bank.proto", this.getClass().getClassLoader())); RestClient adminClient = ext.rest().withClientConfiguration(restBuilders.get(TestUser.ADMIN)).get(); RestCacheClient protobufCache = adminClient.cache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); assertStatus(NO_CONTENT, protobufCache.put(BANK_PROTO, schema)); String cacheName = ext.getMethodName(); String cacheConfig = "{\"distributed-cache\":{\"statistics\":true,\"encoding\":{\"media-type\":\"application/x-protostream\"},\"indexing\":{\"enabled\":true,\"storage\":\"local-heap\",\"indexed-entities\":[\"sample_bank_account.User\"]},\"security\":{\"authorization\":{}}}}"; assertStatus(OK, adminClient.cache(cacheName) .createWithConfiguration(new StringRestEntityOkHttp(MediaType.APPLICATION_JSON, cacheConfig)) ); } private RestClient restCreateAuthzCache(String... explicitRoles) { return restCreateAuthzCache(CacheMode.DIST_SYNC, explicitRoles); } private RestClient restCreateAuthzLocalCache(String... explicitRoles) { return restCreateAuthzCache(CacheMode.LOCAL, explicitRoles); } private RestClient restCreateAuthzCache(CacheMode mode, String... explicitRoles) { org.infinispan.configuration.cache.ConfigurationBuilder builder = new org.infinispan.configuration.cache.ConfigurationBuilder(); AuthorizationConfigurationBuilder authorizationConfigurationBuilder = builder.clustering().cacheMode(mode).security().authorization().enable(); if (explicitRoles != null) { for (String role : explicitRoles) { authorizationConfigurationBuilder.role(role); } } return ext.rest().withClientConfiguration(restBuilders.get(TestUser.ADMIN)).withServerConfiguration(builder).create(); } }
31,253
49.086538
282
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/security/authorization/AuthorizationKerberosIT.java
package org.infinispan.server.security.authorization; import java.net.InetSocketAddress; import javax.security.auth.Subject; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.security.VoidCallbackHandler; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.server.test.api.TestUser; import org.infinispan.server.test.core.Common; import org.infinispan.server.test.core.LdapServerListener; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.core.category.Security; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.infinispan.server.test.junit5.InfinispanSuite; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.1 **/ @Suite @SelectClasses({AuthorizationKerberosIT.HotRod.class, AuthorizationKerberosIT.Rest.class}) @Category(Security.class) public class AuthorizationKerberosIT extends InfinispanSuite { @RegisterExtension public static InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/AuthorizationKerberosTest.xml") .numServers(1) .property("java.security.krb5.conf", "${infinispan.server.config.path}/krb5.conf") .addListener(new LdapServerListener(true)) .runMode(ServerRunMode.EMBEDDED) .build(); static class HotRod extends HotRodAuthorizationTest { @RegisterExtension static InfinispanServerExtension SERVERS = AuthorizationKerberosIT.SERVERS; public HotRod() { super(SERVERS, AuthorizationKerberosIT::expectedServerPrincipalName, user -> { ConfigurationBuilder hotRodBuilder = new ConfigurationBuilder(); if (user != TestUser.ANONYMOUS) { Subject subject = Common.createSubject(user.getUser(), "INFINISPAN.ORG", user.getPassword().toCharArray()); hotRodBuilder.security().authentication() .saslMechanism("GSSAPI") .serverName("datagrid") .realm("default") .callbackHandler(new VoidCallbackHandler()) .clientSubject(subject); } return hotRodBuilder; }); } } static class Rest extends RESTAuthorizationTest { @RegisterExtension static InfinispanServerExtension SERVERS = AuthorizationKerberosIT.SERVERS; public Rest() { super(SERVERS, AuthorizationKerberosIT::expectedServerPrincipalName, user -> { RestClientConfigurationBuilder restBuilder = new RestClientConfigurationBuilder(); if (user != TestUser.ANONYMOUS) { Subject subject = Common.createSubject(user.getUser(), "INFINISPAN.ORG", user.getPassword().toCharArray()); restBuilder.security().authentication() .mechanism("SPNEGO") .clientSubject(subject); // Kerberos is strict about the hostname, so we do this by hand InetSocketAddress serverAddress = SERVERS.getServerDriver().getServerSocket(0, 11222); restBuilder.addServer().host(serverAddress.getHostName()).port(serverAddress.getPort()); } return restBuilder; }); } } private static String expectedServerPrincipalName(TestUser user) { return String.format("%s@INFINISPAN.ORG", user.getUser()); } }
3,792
42.597701
122
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/container/InfinispanContainerTest.java
package org.infinispan.server.container; import static org.junit.jupiter.api.Assertions.assertEquals; import org.infinispan.client.hotrod.DefaultTemplate; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.server.test.core.InfinispanContainer; import org.junit.jupiter.api.Test; public class InfinispanContainerTest { @Test public void testContainer() { try (InfinispanContainer container = new InfinispanContainer()) { container.start(); try (RemoteCacheManager cacheManager = container.getRemoteCacheManager()) { RemoteCache<Object, Object> testCache = cacheManager.administration().getOrCreateCache("test", DefaultTemplate.DIST_SYNC); testCache.put("key", "value"); assertEquals("value", testCache.get("key")); } } } }
885
35.916667
134
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/test/core/LdapServerListener.java
package org.infinispan.server.test.core; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.test.ThreadLeakChecker; import org.infinispan.server.test.core.ldap.AbstractLdapServer; import org.infinispan.server.test.core.ldap.ApacheLdapServer; import org.infinispan.server.test.core.ldap.RemoteLdapServer; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.1 **/ public class LdapServerListener implements InfinispanServerListener { public static final String LDAP_SERVER = System.getProperty(TestSystemPropertyNames.LDAP_SERVER, "apache"); private static final String DEFAULT_LDIF = "ldif/infinispan.ldif"; private static final String KERBEROS_LDIF = "ldif/infinispan-kerberos.ldif"; private final AbstractLdapServer ldapServer; public LdapServerListener() { this(false); } public LdapServerListener(boolean withKdc) { if ("apache".equals(LDAP_SERVER)) { ldapServer = new ApacheLdapServer(withKdc, withKdc ? KERBEROS_LDIF : DEFAULT_LDIF); // when using the remote ldap server, you should overwrite the content of the ldif files before running the test } else if ("remote".equals(LDAP_SERVER)) { ldapServer = new RemoteLdapServer(withKdc ? KERBEROS_LDIF : DEFAULT_LDIF); } else { throw new IllegalStateException("Unsupported LDAP Server: " + LDAP_SERVER); } } @Override public void before(InfinispanServerDriver driver) { Exceptions.unchecked(() -> { ldapServer.start(driver.getCertificateFile("server.pfx").getAbsolutePath(), driver.getConfDir()); }); } @Override public void after(InfinispanServerDriver driver) { try { ldapServer.stop(); } catch (Exception e) { // Ignore } // LdapServer creates an ExecutorFilter with an "unmanaged" executor and doesn't stop the executor itself ThreadLeakChecker.ignoreThreadsContaining("pool-.*thread-"); // ThreadLeakChecker.ignoreThreadsContaining("^Thread-\\d+$"); } }
2,054
35.696429
118
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/test/core/KeyCloakServerExtension.java
package org.infinispan.server.test.core; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.logging.LogFactory; import org.infinispan.test.TestingUtil; import org.junit.jupiter.api.extension.AfterAllCallback; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.testcontainers.containers.FixedHostPortGenericContainer; import org.testcontainers.containers.wait.strategy.Wait; import org.testcontainers.utility.MountableFile; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class KeyCloakServerExtension implements AfterAllCallback, BeforeAllCallback { public static final String KEYCLOAK_IMAGE = System.getProperty(TestSystemPropertyNames.KEYCLOAK_IMAGE, "quay.io/keycloak/keycloak:10.0.1"); private final String realmJsonFile; private FixedHostPortGenericContainer<?> container; private final List<Consumer<KeyCloakServerExtension>> beforeListeners = new ArrayList<>(); private final File keycloakDirectory; public KeyCloakServerExtension(String realmJsonFile) { this.realmJsonFile = realmJsonFile; this.keycloakDirectory = new File(tmpDirectory("keycloak")); } @Override public void beforeAll(ExtensionContext context) { Class<?> testClass = context.getRequiredTestClass(); keycloakDirectory.mkdirs(); beforeListeners.forEach(l -> l.accept(this)); File keycloakImport = new File(keycloakDirectory, "keycloak.json"); try (InputStream is = getClass().getClassLoader().getResourceAsStream(realmJsonFile); OutputStream os = new FileOutputStream(keycloakImport)) { TestingUtil.copy(is, os); } catch (IOException e) { throw new RuntimeException(e); } final Map<String, String> environment = new HashMap<>(); environment.put("DB_VENDOR", "h2"); environment.put(System.getProperty(TestSystemPropertyNames.KEYCLOAK_USER, "KEYCLOAK_USER"), "keycloak"); environment.put(System.getProperty(TestSystemPropertyNames.KEYCLOAK_PASSWORD, "KEYCLOAK_PASSWORD"), "keycloak"); environment.put("KEYCLOAK_IMPORT", keycloakImport.getAbsolutePath()); environment.put("JAVA_OPTS_APPEND", "-Dkeycloak.migration.action=import -Dkeycloak.migration.provider=singleFile -Dkeycloak.migration.file="+keycloakImport.getAbsolutePath()); container = new FixedHostPortGenericContainer<>(KEYCLOAK_IMAGE); container .withFixedExposedPort(14567, 8080) .withFixedExposedPort(14568, 8443) .withEnv(environment) .withCopyFileToContainer(MountableFile.forHostPath(keycloakImport.getAbsolutePath()), keycloakImport.getPath()) .withFileSystemBind(keycloakDirectory.getPath(), "/etc/x509/https") //.waitingFor(Wait.forHttp("/").forPort(14567)) .waitingFor(Wait.forLogMessage(".*WFLYSRV0051.*",1)) .withLogConsumer(new JBossLoggingConsumer(LogFactory.getLog(testClass))); container.start(); } public String getAccessTokenForCredentials(String realm, String client, String secret, String username, String password, Path trustStore, String trustStorePassword) { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); int port; if (trustStore != null) { builder.security().ssl().trustStoreFileName(trustStore.toString()).trustStorePassword(trustStorePassword.toCharArray()).hostnameVerifier((hostname, session) -> true); port = 8443; } else { port = 8080; } builder.addServer().host(container.getContainerIpAddress()).port(container.getMappedPort(port)).connectionTimeout(5000).socketTimeout(5000); try (RestClient c = RestClient.forConfiguration(builder.build())) { String url = String.format("/auth/realms/%s/protocol/openid-connect/token", realm); Map<String, List<String>> form = new HashMap<>(); form.put("client_id", Collections.singletonList(client)); form.put("client_secret", Collections.singletonList(secret)); form.put("username", Collections.singletonList(username)); form.put("password", Collections.singletonList(password)); form.put("grant_type", Collections.singletonList("password")); RestResponse response = c.raw().postForm(url, Collections.singletonMap("Content-Type", "application/x-www-form-urlencoded"), form).toCompletableFuture().get(5, TimeUnit.SECONDS); Map<String, Json> map = Json.read(response.getBody()).asJsonMap(); return map.get("access_token").asString(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void afterAll(ExtensionContext context) { container.close(); } public KeyCloakServerExtension addBeforeListener(Consumer<KeyCloakServerExtension> listener) { beforeListeners.add(listener); return this; } public File getKeycloakDirectory() { return keycloakDirectory; } }
5,681
45.958678
187
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/test/core/Krb5ConfPropertyExtension.java
package org.infinispan.server.test.core; import java.nio.file.Paths; import org.junit.jupiter.api.extension.AfterAllCallback; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.ExtensionContext; public class Krb5ConfPropertyExtension implements AfterAllCallback, BeforeAllCallback { private static String oldKrb5Conf; @Override public void afterAll(ExtensionContext context) { oldKrb5Conf = System.setProperty("java.security.krb5.conf", Paths.get("src/test/resources/configuration/krb5.conf").toString()); } @Override public void beforeAll(ExtensionContext context) { if (oldKrb5Conf != null) { System.setProperty("java.security.krb5.conf", oldKrb5Conf); } } }
760
30.708333
134
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/test/core/Common.java
package org.infinispan.server.test.core; import static javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag.REQUIRED; 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.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.security.auth.Subject; import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginContext; import org.apache.logging.log4j.core.util.StringBuilderWriter; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHash; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.marshall.MarshallerUtil; import org.infinispan.client.hotrod.security.BasicCallbackHandler; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.Protocol; import org.infinispan.commons.configuration.io.ConfigurationWriter; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.protostream.sampledomain.marshallers.MarshallerRegistration; import org.infinispan.query.remote.client.ProtobufMetadataManagerConstants; import org.infinispan.server.persistence.PersistenceIT; import org.infinispan.server.test.api.HotRodTestClientDriver; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.test.TestingUtil; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.wildfly.security.http.HttpConstants; import org.wildfly.security.sasl.util.SaslMechanismInformation; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class Common { private static final boolean IS_IBM = System.getProperty("java.vendor").contains("IBM"); public static final Collection<String> SASL_MECHS = List.of( "", SaslMechanismInformation.Names.PLAIN, SaslMechanismInformation.Names.DIGEST_MD5, SaslMechanismInformation.Names.DIGEST_SHA_512, SaslMechanismInformation.Names.DIGEST_SHA_384, SaslMechanismInformation.Names.DIGEST_SHA_256, SaslMechanismInformation.Names.DIGEST_SHA, SaslMechanismInformation.Names.SCRAM_SHA_512, SaslMechanismInformation.Names.SCRAM_SHA_384, SaslMechanismInformation.Names.SCRAM_SHA_256, SaslMechanismInformation.Names.SCRAM_SHA_1 ); public static final Collection<Arguments> SASL_MECH_ARGUMENTS = SASL_MECHS.stream() .map(Arguments::of) .collect(Collectors.toList()); public static final Collection<String> SASL_KERBEROS = List.of( "", SaslMechanismInformation.Names.GSSAPI, SaslMechanismInformation.Names.GS2_KRB5 ); public static final Collection<String> HTTP_MECHS = List.of( "", HttpConstants.BASIC_NAME, HttpConstants.DIGEST_NAME ); public static final Collection<String> HTTP_KERBEROS_MECHS = List.of( "", HttpConstants.SPNEGO_NAME ); public static final Collection<Protocol> HTTP_PROTOCOLS = Arrays.asList(Protocol.values()); public static final String[] NASHORN_DEPS = new String[]{ "org.openjdk.nashorn:nashorn-core:15.4", "org.ow2.asm:asm:9.5", "org.ow2.asm:asm-analysis:9.5", "org.ow2.asm:asm-commons:9.5", "org.ow2.asm:asm-tree:9.5", "org.ow2.asm:asm-util:9.5" }; public static class SaslMechsArgumentProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { return SASL_MECH_ARGUMENTS.stream(); } } public static class DatabaseProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) throws Exception { return Arrays.stream(PersistenceIT.DATABASE_LISTENER.getDatabaseTypes()) .map(PersistenceIT.DATABASE_LISTENER::getDatabase) .map(Arguments::of); } } public static <T> T awaitStatus(Supplier<CompletionStage<RestResponse>> request, int pendingStatus, int completeStatus, Function<RestResponse, T> f) { int MAX_RETRIES = 100; for (int i = 0; i < MAX_RETRIES; i++) { try (RestResponse response = sync(request.get())) { if (response.getStatus() == pendingStatus) { TestingUtil.sleepThread(100); } else if (response.getStatus() == completeStatus) { return f.apply(response); } else { fail(String.format("Request returned unexpected status %d instead of %d or %d", response.getStatus(), pendingStatus, completeStatus)); } } } fail(String.format("Request did not complete with status %d after %d retries", completeStatus, MAX_RETRIES)); return null; // Never executed } public static void awaitStatus(Supplier<CompletionStage<RestResponse>> request, int pendingStatus, int completeStatus) { awaitStatus(request, pendingStatus, completeStatus, r -> null); } public static RestResponse awaitResponse(Supplier<CompletionStage<RestResponse>> request, int pendingStatus, int completeStatus) { int MAX_RETRIES = 100; for (int i = 0; i < MAX_RETRIES; i++) { RestResponse response = sync(request.get()); if (response.getStatus() == pendingStatus) { response.close(); TestingUtil.sleepThread(100); } else if (response.getStatus() == completeStatus) { return response; } else { response.close(); fail(String.format("Request returned unexpected status %d instead of %d or %d", response.getStatus(), pendingStatus, completeStatus)); } } fail(String.format("Request did not complete with status %d after %d retries", completeStatus, MAX_RETRIES)); return null; // Never executed } public static <T> T sync(CompletionStage<T> stage) { return sync(stage, 10, TimeUnit.SECONDS); } public static <T> T sync(CompletionStage<T> stage, long timeout, TimeUnit timeUnit) { return Exceptions.unchecked(() -> stage.toCompletableFuture().get(timeout, timeUnit)); } public static String assertStatus(int status, CompletionStage<RestResponse> request) { try (RestResponse response = sync(request)) { String body = response.getBody(); assertEquals(status, response.getStatus(), body); return body; } } public static void assertStatusAndBodyEquals(int status, String body, CompletionStage<RestResponse> response) { assertEquals(body, assertStatus(status, response)); } public static void assertStatusAndBodyContains(int status, String body, CompletionStage<RestResponse> response) { String responseBody = assertStatus(status, response); assertTrue(responseBody.contains(body), responseBody); } public static void assertResponse(int status, CompletionStage<RestResponse> request, Consumer<RestResponse> consumer) { try (RestResponse response = sync(request)) { assertEquals(status, response.getStatus()); consumer.accept(response); } } public static Subject createSubject(String principal, String realm, char[] password) { return Exceptions.unchecked(() -> { LoginContext context = new LoginContext("KDC", null, new BasicCallbackHandler(principal, realm, password), createJaasConfiguration(false)); context.login(); return context.getSubject(); }); } private static Configuration createJaasConfiguration(boolean server) { return new Configuration() { @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { if (!"KDC".equals(name)) { throw new IllegalArgumentException(String.format("Unexpected name '%s'", name)); } AppConfigurationEntry[] entries = new AppConfigurationEntry[1]; Map<String, Object> options = new HashMap<>(); //options.put("debug", "true"); options.put("refreshKrb5Config", "true"); if (IS_IBM) { options.put("noAddress", "true"); options.put("credsType", server ? "acceptor" : "initiator"); entries[0] = new AppConfigurationEntry("com.ibm.security.auth.module.Krb5LoginModule", REQUIRED, options); } else { options.put("storeKey", "true"); options.put("isInitiator", server ? "false" : "true"); entries[0] = new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule", REQUIRED, options); } return entries; } }; } public static String cacheConfigToJson(String name, org.infinispan.configuration.cache.Configuration configuration) { StringBuilderWriter sw = new StringBuilderWriter(); try (ConfigurationWriter w = ConfigurationWriter.to(sw).withType(APPLICATION_JSON).prettyPrint(false).build()) { new ParserRegistry().serialize(w, name, configuration); } return sw.toString(); } public static <K, V> RemoteCache<K, V> createQueryableCache(InfinispanServerExtension server, boolean indexed, String protoFile, String entityName) { ConfigurationBuilder config = new ConfigurationBuilder(); config.marshaller(new ProtoStreamMarshaller()); HotRodTestClientDriver hotRodTestClientDriver = server.hotrod().withClientConfiguration(config); RemoteCacheManager remoteCacheManager = hotRodTestClientDriver.createRemoteCacheManager(); RemoteCache<String, String> metadataCache = remoteCacheManager.getCache(ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME); String schema = Exceptions.unchecked(() -> Util.getResourceAsString(protoFile, server.getClass().getClassLoader())); metadataCache.putIfAbsent(protoFile, schema); assertFalse(metadataCache.containsKey(ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX)); assertNotNull(metadataCache.get(protoFile)); Exceptions.unchecked(() -> MarshallerRegistration.registerMarshallers(MarshallerUtil.getSerializationContext(remoteCacheManager))); org.infinispan.configuration.cache.ConfigurationBuilder builder = new org.infinispan.configuration.cache.ConfigurationBuilder(); builder.encoding().mediaType(APPLICATION_PROTOSTREAM_TYPE); builder.clustering().cacheMode(CacheMode.DIST_SYNC).stateTransfer().awaitInitialTransfer(true); if (indexed) { builder.indexing().enable() .storage(LOCAL_HEAP) .addIndexedEntity(entityName); } return hotRodTestClientDriver.withServerConfiguration(builder).create(); } public static void assertAnyEquals(Object expected, Object actual) { if (expected instanceof byte[] && actual instanceof byte[]) assertArrayEquals((byte[]) expected, (byte[]) actual); else assertEquals(expected, actual); } public static Integer getIntKeyForServer(RemoteCache<Integer, ?> cache, int server) { ChannelFactory cf = cache.getRemoteCacheManager().getChannelFactory(); byte[] name = RemoteCacheManager.cacheNameBytes(cache.getName()); InetSocketAddress serverAddress = cf.getServers(name).stream().skip(server).findFirst().get(); DataFormat df = cache.getDataFormat(); ConsistentHash ch = cf.getConsistentHash(name); Random r = new Random(); for(int i = 0; i < 1000; i++) { int aInt = r.nextInt(); SocketAddress keyAddress = ch.getServer(df.keyToBytes(aInt)); if (keyAddress.equals(serverAddress)) { return aInt; } } throw new IllegalStateException("Could not find any key owned by " + serverAddress); } }
13,378
43.448505
153
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/test/core/ldap/RemoteLdapServer.java
package org.infinispan.server.test.core.ldap; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.List; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapEntryAlreadyExistsException; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.ldif.LdifEntry; import org.apache.directory.api.ldap.model.ldif.LdifReader; import org.apache.directory.ldap.client.api.LdapNetworkConnection; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testcontainers.shaded.com.google.common.io.Files; public class RemoteLdapServer extends AbstractLdapServer { private final String initLDIF; public RemoteLdapServer(String initLDIF) { this.initLDIF = initLDIF; } private static final Log log = LogFactory.getLog(RemoteLdapServer.class); @Override public void start(String keystoreFile, File confDir) throws URISyntaxException, LdapException, IOException { URI ldapUri = new URI(System.getProperty(TEST_LDAP_URL)); LdapNetworkConnection connection = new LdapNetworkConnection(ldapUri.getHost(), ldapUri.getPort()); connection.setTimeOut(60); connection.bind(System.getProperty(TEST_LDAP_PRINCIPAL), System.getProperty(TEST_LDAP_CREDENTIAL)); // for each ldap server, there is a ldif file. you should replace infinispan.ldif content String fullPathFile = getClass().getClassLoader().getResource(initLDIF).getFile(); String fileContent = Files.toString(new File(fullPathFile), Charset.defaultCharset()); LdifReader ldifReader = new LdifReader(); List<LdifEntry> entries = ldifReader.parseLdif(fileContent); for (LdifEntry ldifEntry : entries) { try { Entry entry = ldifEntry.getEntry(); connection.add(entry); } catch (LdapEntryAlreadyExistsException e) { // for now, remove entry or edit is not supported log.debug(ldifEntry.getDn().toString(), e); } } } @Override public void stop() { // it is remote } }
2,246
37.741379
111
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/test/core/ldap/ApacheLdapServer.java
package org.infinispan.server.test.core.ldap; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.security.auth.kerberos.KerberosPrincipal; import org.apache.directory.api.ldap.model.entry.DefaultEntry; import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; import org.apache.directory.api.ldap.model.ldif.LdifEntry; import org.apache.directory.api.ldap.model.ldif.LdifReader; import org.apache.directory.api.ldap.model.schema.SchemaManager; import org.apache.directory.server.annotations.CreateLdapServer; import org.apache.directory.server.annotations.CreateTransport; import org.apache.directory.server.core.annotations.AnnotationUtils; import org.apache.directory.server.core.annotations.ContextEntry; import org.apache.directory.server.core.annotations.CreateDS; import org.apache.directory.server.core.annotations.CreateIndex; import org.apache.directory.server.core.annotations.CreatePartition; import org.apache.directory.server.core.api.DirectoryService; import org.apache.directory.server.core.factory.DSAnnotationProcessor; import org.apache.directory.server.core.kerberos.KeyDerivationInterceptor; import org.apache.directory.server.factory.ServerAnnotationProcessor; import org.apache.directory.server.kerberos.KerberosConfig; import org.apache.directory.server.kerberos.kdc.KdcServer; import org.apache.directory.server.kerberos.shared.crypto.encryption.KerberosKeyFactory; import org.apache.directory.server.kerberos.shared.keytab.Keytab; import org.apache.directory.server.kerberos.shared.keytab.KeytabEntry; import org.apache.directory.server.ldap.LdapServer; import org.apache.directory.server.protocol.shared.transport.TcpTransport; import org.apache.directory.server.protocol.shared.transport.Transport; import org.apache.directory.server.protocol.shared.transport.UdpTransport; import org.apache.directory.shared.kerberos.KerberosTime; import org.apache.directory.shared.kerberos.codec.types.EncryptionType; import org.apache.directory.shared.kerberos.components.EncryptionKey; import org.infinispan.commons.util.Util; import org.infinispan.server.test.core.AbstractInfinispanServerDriver; public class ApacheLdapServer extends AbstractLdapServer { private static final String LDAP_HOST = "0.0.0.0"; public static final int KDC_PORT = 6088; public static final int LDAP_PORT = 10389; public static final int LDAPS_PORT = 10636; public static final String DOMAIN = "dc=infinispan,dc=org"; public static final String REALM = "INFINISPAN.ORG"; private DirectoryService directoryService; private LdapServer ldapServer; private KdcServer kdcServer; private final boolean withKdc; private final String initLDIF; public ApacheLdapServer(boolean withKdc, String initLDIF) { this.withKdc = withKdc; this.initLDIF = initLDIF; } @CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP", port = LDAP_PORT, address = LDAP_HOST)}) public void createLdap(String keystoreFile, String initLDIF) throws Exception { final SchemaManager schemaManager = directoryService.getSchemaManager(); try (InputStream is = getClass().getClassLoader().getResourceAsStream(initLDIF)) { for (LdifEntry ldifEntry : new LdifReader(is)) { directoryService.getAdminSession().add(new DefaultEntry(schemaManager, ldifEntry.getEntry())); } } final CreateLdapServer createLdapServer = (CreateLdapServer) AnnotationUtils.getInstance(CreateLdapServer.class); ldapServer = ServerAnnotationProcessor.instantiateLdapServer(createLdapServer, directoryService); ldapServer.setKeystoreFile(keystoreFile); ldapServer.setCertificatePassword(AbstractInfinispanServerDriver.KEY_PASSWORD); Transport ldaps = new TcpTransport(LDAPS_PORT); ldaps.enableSSL(true); ldapServer.addTransports(ldaps); } @CreateDS( name = "InfinispanDS", partitions = { @CreatePartition( name = "infinispan", suffix = DOMAIN, contextEntry = @ContextEntry( entryLdif = "dn: " + DOMAIN + "\n" + "dc: infinispan\n" + "objectClass: top\n" + "objectClass: domain\n\n"), indexes = { @CreateIndex(attribute = "objectClass"), @CreateIndex(attribute = "dc"), @CreateIndex(attribute = "ou"), @CreateIndex(attribute = "uid"), } ) } ) public void createDs() throws Exception { directoryService = DSAnnotationProcessor.getDirectoryService(); directoryService.getChangeLog().setEnabled(false); directoryService.addLast(new KeyDerivationInterceptor()); } @Override public void start(String keystoreFile, File confDir) throws Exception { if (withKdc) { generateKeyTab(new File(confDir, "hotrod.keytab"), "hotrod/datagrid@INFINISPAN.ORG", "hotrodPassword"); generateKeyTab(new File(confDir, "http.keytab"), "HTTP/localhost@INFINISPAN.ORG", "httpPassword"); } createDs(); createLdap(keystoreFile, initLDIF); ldapServer.start(); if (withKdc) { startKdc(); } } @Override public void stop() throws Exception { try { if (kdcServer != null) { kdcServer.stop(); kdcServer = null; } ldapServer.stop(); directoryService.shutdown(); } finally { Util.recursiveFileRemove(directoryService.getInstanceLayout().getInstanceDirectory()); } } private void startKdc() throws IOException, LdapInvalidDnException { createKdc(); kdcServer.start(); } private void createKdc() { KdcServer kdcServer = new KdcServer(); kdcServer.setServiceName("TestKDCServer"); kdcServer.setSearchBaseDn(DOMAIN); KerberosConfig config = kdcServer.getConfig(); config.setServicePrincipal("krbtgt/INFINISPAN.ORG@" + REALM); config.setPrimaryRealm(REALM); config.setMaximumTicketLifetime(60_000 * 1440); config.setMaximumRenewableLifetime(60_000 * 10_080); config.setPaEncTimestampRequired(false); UdpTransport udp = new UdpTransport("0.0.0.0", KDC_PORT); kdcServer.addTransports(udp); kdcServer.setDirectoryService(directoryService); this.kdcServer = kdcServer; } public static String generateKeyTab(File keyTabFile, String... credentials) { List<KeytabEntry> entries = new ArrayList<>(); KerberosTime ktm = new KerberosTime(); for (int i = 0; i < credentials.length; ) { String principal = credentials[i++]; String password = credentials[i++]; for (Map.Entry<EncryptionType, EncryptionKey> keyEntry : KerberosKeyFactory.getKerberosKeys(principal, password) .entrySet()) { EncryptionKey key = keyEntry.getValue(); entries.add(new KeytabEntry(principal, KerberosPrincipal.KRB_NT_PRINCIPAL, ktm, (byte) key.getKeyVersion(), key)); } } Keytab keyTab = Keytab.getInstance(); keyTab.setEntries(entries); try { keyTab.write(keyTabFile); return keyTabFile.getAbsolutePath(); } catch (IOException e) { throw new IllegalStateException("Cannot create keytab: " + keyTabFile, e); } } }
7,689
39.904255
126
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/test/core/ldap/AbstractLdapServer.java
package org.infinispan.server.test.core.ldap; import java.io.File; public abstract class AbstractLdapServer { public static final String TEST_LDAP_URL = "org.infinispan.test.ldap.url"; public static final String TEST_LDAP_PRINCIPAL = "org.infinispan.test.ldap.principal"; public static final String TEST_LDAP_CREDENTIAL = "org.infinispan.test.ldap.credential"; public abstract void start(String keystoreFile, File confDir) throws Exception; public abstract void stop() throws Exception; }
509
33
91
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/test/core/category/Persistence.java
package org.infinispan.server.test.core.category; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class Persistence { }
162
17.111111
57
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/test/core/category/Security.java
package org.infinispan.server.test.core.category; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class Security { }
159
16.777778
57
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/test/core/category/Resilience.java
package org.infinispan.server.test.core.category; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class Resilience { }
161
17
57
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/resilience/ResilienceMaxRetryIT.java
package org.infinispan.server.resilience; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.exceptions.TransportException; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.core.category.Resilience; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.jupiter.api.Test; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.RegisterExtension; /** * Test that a client can reset to the initial server list * even when it is configured with max_retries=0 and the current server topology * contains more than one server. */ @Category(Resilience.class) public class ResilienceMaxRetryIT { @RegisterExtension public static InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/ClusteredServerTest.xml") .runMode(ServerRunMode.EMBEDDED) .numServers(3) .build(); @Test public void testMaxRetries0() { // Start the client with initial_server_list=server0 and max_retries=0 RemoteCache<Integer, String> cache = SERVERS.hotrod() .withClientConfiguration(new ConfigurationBuilder().maxRetries(0).connectionTimeout(500)) .withCacheMode(CacheMode.REPL_SYNC) .create(0); // Perform an operation so the client receives a topology update with server0, server1, and server2 cache.get(ThreadLocalRandom.current().nextInt()); // Stop server0 InetSocketAddress serverAddress0 = SERVERS.getServerDriver().getServerSocket(0, SERVERS.getTestServer().getDefaultPortNumber()); InetSocketAddress serverAddress1 = SERVERS.getServerDriver().getServerSocket(1, SERVERS.getTestServer().getDefaultPortNumber()); InetSocketAddress serverAddress2 = SERVERS.getServerDriver().getServerSocket(2, SERVERS.getTestServer().getDefaultPortNumber()); SERVERS.getServerDriver().stop(0); // Execute cache operations so the client connects to server1 or server2 and receives a topology update // The client keeps trying to connect to failed servers for each new operation, // so the number of operations we need depends on which server owns each key byte[] cacheNameBytes = cache.getName().getBytes(); for (int i = 0; i < 10; i++) { try { cache.get(ThreadLocalRandom.current().nextInt()); break; } catch (TransportException e) { // Assert that the failed server is the one that we killed assertTrue(e.getMessage().contains(serverAddress0.toString()), serverAddress0 + " not found in " + e.getMessage()); } } // Check that the stopped server was properly removed from the list Collection<InetSocketAddress> currentServers = cache.getRemoteCacheManager().getChannelFactory().getServers(cacheNameBytes); assertEquals(new HashSet<>(asList(serverAddress1, serverAddress2)), new HashSet<>(resolveAddresses(currentServers))); // Stop server1 and server2, start server0 SERVERS.getServerDriver().stop(1); SERVERS.getServerDriver().stop(2); SERVERS.getServerDriver().restart(0); // Execute cache operations until the client resets to the initial server list (server0) // The reset happens when all current servers (server1 and server2) are marked failed // But the client keeps trying to connect to failed servers for each new operation, // so the number of operations we need depends on which server owns each key for (int i = 0; i < 10; i++) { try { cache.get(ThreadLocalRandom.current().nextInt()); break; } catch (TransportException e) { // Expected to fail to connect to server1 or server2, not server0 assertTrue(e.getMessage().contains(serverAddress1.toString()) || e.getMessage().contains(serverAddress2.toString()), e.getMessage()); } } // Check that the client switched to the initial server list currentServers = cache.getRemoteCacheManager().getChannelFactory().getServers(cacheNameBytes); assertEquals(singletonList(serverAddress0), resolveAddresses(currentServers)); // Do another operation, it should succeed cache.get(ThreadLocalRandom.current().nextInt()); } /** * ChannelFactory keeps the addresses unresolved, so we must convert the addresses to unresolved if we want them to match */ private Collection<InetSocketAddress> resolveAddresses(Collection<InetSocketAddress> serverAddresses) { List<InetSocketAddress> list = new ArrayList<>(serverAddresses.size()); for (InetSocketAddress serverAddress : serverAddresses) { list.add(new InetSocketAddress(serverAddress.getHostString(), serverAddress.getPort())); } return list; } }
5,491
46.756522
145
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/resilience/StatefulSetRollingUpgradeIT.java
package org.infinispan.server.resilience; import static org.infinispan.server.test.core.Common.assertStatus; import java.util.stream.IntStream; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.impl.okhttp.StringRestEntityOkHttp; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.test.categories.Unstable; import org.infinispan.server.test.core.InfinispanServerDriver; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.core.TestClient; import org.infinispan.server.test.core.TestServer; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.experimental.categories.Category; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import io.netty.handler.codec.http.HttpResponseStatus; /** * Start cluster (0..numServers) redeploy after upgrade. Rolling upgrades always occur in the order numServers...0 and * the node with index numServers - 1 does not restart until node numServers has completed successfully. * * @author Ryan Emerson * @since 11.0 */ @Category(Unstable.class) public class StatefulSetRollingUpgradeIT { private static final int NUM_ROLLING_UPGRADES = 4; private static final String CACHE_MANAGER = "default"; @ParameterizedTest @ValueSource(ints = {2, 3, 4, 5}) public void testStatefulSetRollingUpgrade(int numServers) { TestServer server = new TestServer( InfinispanServerExtensionBuilder.config("configuration/ClusteredServerTest.xml") .numServers(numServers) .runMode(ServerRunMode.CONTAINER) .parallelStartup(false) .createServerTestConfiguration() ); String testName = StatefulSetRollingUpgradeIT.class.getSimpleName(); server.initServerDriver(); server.getDriver().prepare(testName); server.getDriver().start(testName); TestClient client = new TestClient(server); try { client.initResources(); client.setMethodName(testName + "-" + numServers); IntStream.range(0, numServers).forEach(i -> assertLiveness(client, i)); InfinispanServerDriver serverDriver = server.getDriver(); // ISPN-13997 Ensure that Memory max-size is represented in original format in caches.xml String cacheConfig = "<replicated-cache name=\"cache01\"><memory storage=\"OFF_HEAP\" max-size=\"200MB\"/><transaction transaction-manager-lookup=\"org.infinispan.transaction.lookup.GenericTransactionManagerLookup\"/></replicated-cache>"; StringRestEntityOkHttp body = new StringRestEntityOkHttp(MediaType.APPLICATION_XML, cacheConfig); assertStatus(HttpResponseStatus.OK.code(), client.rest().get().cache("cache01").createWithConfiguration(body)); for (int i = 0; i < NUM_ROLLING_UPGRADES; i++) { for (int j = numServers - 1; j > -1; j--) { serverDriver.stop(j); serverDriver.restart(j); assertLiveness(client, j); } } } finally { client.clearResources(); server.stopServerDriver(testName); } } private void assertLiveness(TestClient client, int server) { RestClient rest = client.rest().get(server); assertStatus(HttpResponseStatus.OK.code(), rest.cacheManager(CACHE_MANAGER).healthStatus()); } }
3,456
42.2125
247
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/resilience/ResilienceIT.java
package org.infinispan.server.resilience; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.test.Eventually; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.core.category.Resilience; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.jupiter.api.Test; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.RegisterExtension; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @Category(Resilience.class) public class ResilienceIT { @RegisterExtension public static InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/ClusteredServerTest.xml") .runMode(ServerRunMode.CONTAINER) .build(); @Test public void testUnresponsiveNode() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.socketTimeout(1000).connectionTimeout(1000).maxRetries(10).connectionPool().maxActive(1); RemoteCache<String, String> cache = SERVERS.hotrod().withClientConfiguration(builder).withCacheMode(CacheMode.REPL_SYNC).create(); cache.put("k1", "v1"); assertEquals("v1", cache.get("k1")); SERVERS.getServerDriver().pause(0); Eventually.eventually("Cluster should have 1 node", () -> { cache.get("k1"); return cache.getCacheTopologyInfo().getSegmentsPerServer().size() == 1; }, 30, 1, TimeUnit.SECONDS); SERVERS.getServerDriver().resume(0); Eventually.eventually("Cluster should have 2 nodes", () -> { cache.get("k1"); return cache.getCacheTopologyInfo().getSegmentsPerServer().size() == 2; }, 30, 1, TimeUnit.SECONDS); } }
2,126
39.132075
136
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/resilience/GracefulShutdownRestartIT.java
package org.infinispan.server.resilience; import static org.infinispan.server.test.core.Common.sync; import static org.infinispan.server.test.core.TestSystemPropertyNames.INFINISPAN_TEST_SERVER_CONTAINER_VOLUME_REQUIRED; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.client.rest.configuration.RestClientConfigurationProperties; import org.infinispan.commons.test.Eventually; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.server.test.core.ContainerInfinispanServerDriver; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @since 10.0 */ public class GracefulShutdownRestartIT { @RegisterExtension public static final InfinispanServerExtension SERVER = InfinispanServerExtensionBuilder.config("configuration/ClusteredServerTest.xml") .numServers(2) .runMode(ServerRunMode.CONTAINER) .property(INFINISPAN_TEST_SERVER_CONTAINER_VOLUME_REQUIRED, "true") .build(); @Test public void testGracefulShutdownRestart() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC).persistence().addSingleFileStore().segmented(false); RemoteCache<Object, Object> hotRod = SERVER.hotrod().withServerConfiguration(builder).create(); for (int i = 0; i < 100; i++) { hotRod.put(String.format("k%03d", i), String.format("v%03d", i)); } RestClientConfigurationBuilder restClientBuilder = new RestClientConfigurationBuilder() .socketTimeout(RestClientConfigurationProperties.DEFAULT_SO_TIMEOUT * 60) .connectionTimeout(RestClientConfigurationProperties.DEFAULT_CONNECT_TIMEOUT * 60); RestClient rest = SERVER.rest().withClientConfiguration(restClientBuilder).get(); sync(rest.cluster().stop(), 5, TimeUnit.MINUTES).close(); ContainerInfinispanServerDriver serverDriver = (ContainerInfinispanServerDriver) SERVER.getServerDriver(); Eventually.eventually( "Cluster did not shutdown within timeout", () -> (!serverDriver.isRunning(0) && !serverDriver.isRunning(1)), serverDriver.getTimeout(), 1, TimeUnit.SECONDS); serverDriver.restartCluster(); for (int i = 0; i < 100; i++) { assertEquals(String.format("v%03d", i), hotRod.get(String.format("k%03d", i))); } } }
3,017
46.15625
119
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/persistence/CustomStoreOperationsIT.java
package org.infinispan.server.persistence; import static org.junit.jupiter.api.Assertions.assertEquals; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.CustomStoreConfigurationBuilder; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.core.category.Persistence; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.Test; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.RegisterExtension; @Category(Persistence.class) public class CustomStoreOperationsIT { @RegisterExtension public static InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/CustomStoreTest.xml") .numServers(1) .artifacts(artifacts()) .runMode(ServerRunMode.CONTAINER) .build(); private static JavaArchive[] artifacts() { JavaArchive customStoreJar = ShrinkWrap.create(JavaArchive.class, "custom-store.jar"); customStoreJar.addClass(CustomNonBlockingStore.class); return new JavaArchive[] {customStoreJar}; } @Test public void testDefineCustomStoreAndUtilize() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.clustering().cacheMode(CacheMode.DIST_SYNC); configurationBuilder.encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); configurationBuilder.persistence() .addStore(CustomStoreConfigurationBuilder.class) .segmented(false) .customStoreClass(CustomNonBlockingStore.class); RemoteCache<String, String> cache = SERVERS.hotrod().withServerConfiguration(configurationBuilder).create(); assertEquals("Hello World", cache.get("World")); } }
2,200
41.326923
114
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/persistence/PersistenceIT.java
package org.infinispan.server.persistence; import static org.infinispan.server.test.core.TestSystemPropertyNames.INFINISPAN_TEST_SERVER_CONTAINER_VOLUME_REQUIRED; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import org.infinispan.commons.test.Exceptions; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.core.TestSystemPropertyNames; import org.infinispan.server.test.core.persistence.DatabaseServerListener; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.infinispan.server.test.junit5.InfinispanSuite; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; /** * @author Gustavo Lira &lt;glira@redhat.com&gt; * @since 10.0 **/ @Suite @SelectClasses({ PooledConnectionOperations.class, ManagedConnectionOperations.class, JdbcStringBasedCacheStorePassivation.class, AsyncJdbcStringBasedCacheStore.class }) public class PersistenceIT extends InfinispanSuite { private static final String DATABASE_LIBS = System.getProperty(TestSystemPropertyNames.INFINISPAN_TEST_CONTAINER_DATABASE_LIBS); private static final String EXTERNAL_JDBC_DRIVER = System.getProperty(TestSystemPropertyNames.INFINISPAN_TEST_CONTAINER_DATABASE_EXTERNAL_DRIVERS); private static final String JDBC_DRIVER_FROM_FILE = System.getProperty(TestSystemPropertyNames.INFINISPAN_TEST_CONTAINER_DATABASE_DRIVERS_FILE, "target/test-classes/database/jdbc-drivers.txt"); public static final DatabaseServerListener DATABASE_LISTENER = new DatabaseServerListener("h2", "mysql", "postgres"); @RegisterExtension public static InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config(System.getProperty(PersistenceIT.class.getName(), "configuration/PersistenceTest.xml")) .numServers(1) .runMode(ServerRunMode.CONTAINER) .mavenArtifacts(getJdbcDrivers()) .artifacts(getJavaArchive()) .addListener(DATABASE_LISTENER) .property(INFINISPAN_TEST_SERVER_CONTAINER_VOLUME_REQUIRED, "true") .build(); private static String[] getJdbcDrivers() { Map<String, String> jdbcDrivers = Exceptions.unchecked(() -> Files.lines(Paths.get(JDBC_DRIVER_FROM_FILE)) .collect(Collectors.toMap(PersistenceIT::getArtifactId, Function.identity()))); // default jdbc drivers can also be set through system properties // jdbc drivers can be updated or added if(DATABASE_LIBS != null) { Arrays.stream(DATABASE_LIBS.split(",")).forEach(it -> jdbcDrivers.put(getArtifactId(it), it)); } return jdbcDrivers.values().toArray(new String[0]); } private static String getArtifactId(String gav) { return gav.split(":")[1]; } //Some jdbc drivers are not available through maven (like sybase), in this case we can pass the jdbc driver location private static JavaArchive[] getJavaArchive() { List<JavaArchive> externalJdbcDriver = new ArrayList<>(); if(EXTERNAL_JDBC_DRIVER != null) { Arrays.stream(EXTERNAL_JDBC_DRIVER.split(",")) .map(File::new) .forEach( it -> externalJdbcDriver.add(ShrinkWrap.createFromZipFile(JavaArchive.class, it))); } return externalJdbcDriver.toArray(new JavaArchive[0]); } }
3,947
43.863636
196
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/persistence/PooledConnectionOperations.java
package org.infinispan.server.persistence; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.server.test.core.Common; import org.infinispan.server.test.core.category.Persistence; import org.infinispan.server.test.core.persistence.Database; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; /** * @author Gustavo Lira &lt;glira@redhat.com&gt; * @since 10.0 **/ @Category(Persistence.class) public class PooledConnectionOperations { @RegisterExtension public static InfinispanServerExtension SERVERS = PersistenceIT.SERVERS; @ParameterizedTest @ArgumentsSource(Common.DatabaseProvider.class) public void testTwoCachesSameCacheStore(Database database) { JdbcConfigurationUtil jdbcUtil = new JdbcConfigurationUtil(CacheMode.DIST_SYNC, database, false, false); RemoteCache<String, String> cache1 = SERVERS.hotrod().withServerConfiguration(jdbcUtil.getConfigurationBuilder()).withQualifier("1").create(); RemoteCache<String, String> cache2 = SERVERS.hotrod().withServerConfiguration(jdbcUtil.getConfigurationBuilder()).withQualifier("2").create(); cache1.put("k1", "v1"); String firstK1 = cache1.get("k1"); assertEquals("v1", firstK1); assertNull(cache2.get("k1")); cache2.put("k2", "v2"); assertEquals("v2", cache2.get("k2")); assertNull(cache1.get("k2")); assertCleanCacheAndStore(cache1); assertCleanCacheAndStore(cache2); } @ParameterizedTest @ArgumentsSource(Common.DatabaseProvider.class) public void testPutGetRemove(Database database) { JdbcConfigurationUtil jdbcUtil = new JdbcConfigurationUtil(CacheMode.DIST_SYNC, database, false, false); RemoteCache<String, String> cache = SERVERS.hotrod().withServerConfiguration(jdbcUtil.getConfigurationBuilder()).create(); cache.put("k1", "v1"); cache.put("k2", "v2"); assertNotNull(cache.get("k1")); assertNotNull(cache.get("k2")); cache.stop(); cache.start(); assertNotNull(cache.get("k1")); assertNotNull(cache.get("k2")); assertEquals("v1", cache.get("k1")); assertEquals("v2", cache.get("k2")); cache.remove("k1"); assertNull(cache.get("k1")); assertCleanCacheAndStore(cache); } @ParameterizedTest @ArgumentsSource(Common.DatabaseProvider.class) public void testPreload(Database database) throws Exception { JdbcConfigurationUtil jdbcUtil = new JdbcConfigurationUtil(CacheMode.REPL_SYNC, database, false, true) .setLockingConfigurations(); RemoteCache<String, String> cache = SERVERS.hotrod().withServerConfiguration(jdbcUtil.getConfigurationBuilder()).create(); cache.put("k1", "v1"); cache.put("k2", "v2"); SERVERS.getServerDriver().stop(0); SERVERS.getServerDriver().restart(0); // test preload==true, entries should be immediately in the cache after restart assertEquals(2, cache.withFlags(Flag.SKIP_CACHE_LOAD).size()); assertEquals("v1", cache.get("k1")); assertEquals("v2", cache.get("k2")); cache.clear(); } @ParameterizedTest @ArgumentsSource(Common.DatabaseProvider.class) public void testSoftRestartWithPassivation(Database database) throws Exception { JdbcConfigurationUtil jdbcUtil = new JdbcConfigurationUtil(CacheMode.REPL_SYNC, database, true, false) .setEviction() .setLockingConfigurations(); RemoteCache<String, String> cache = SERVERS.hotrod().withServerConfiguration(jdbcUtil.getConfigurationBuilder()).create(); cache.put("k1", "v1"); cache.put("k2", "v2"); cache.put("k3", "v3"); //now k3 is evicted and stored in store assertEquals(2, cache.withFlags(Flag.SKIP_CACHE_LOAD).size()); SERVERS.getServerDriver().stop(0); SERVERS.getServerDriver().restart(0); //soft stop should store all entries from cache to store // test preload==false assertEquals(0, cache.withFlags(Flag.SKIP_CACHE_LOAD).size()); // test purge==false, entries should remain in the database after restart assertEquals(3, cache.size()); assertEquals("v1", cache.get("k1")); assertCleanCacheAndStore(cache); } protected void assertCleanCacheAndStore(RemoteCache cache) { cache.clear(); assertEquals(0, cache.size()); } }
4,843
38.382114
148
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/persistence/ManagedConnectionOperations.java
package org.infinispan.server.persistence; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import java.util.Properties; import org.infinispan.cli.commands.CLI; import org.infinispan.cli.impl.AeshDelegatingShell; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.persistence.jdbc.configuration.JdbcStringBasedStoreConfigurationBuilder; import org.infinispan.server.test.core.AeshTestConnection; import org.infinispan.server.test.core.Common; import org.infinispan.server.test.core.category.Persistence; import org.infinispan.server.test.core.persistence.Database; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; @Category(Persistence.class) public class ManagedConnectionOperations { @RegisterExtension public static InfinispanServerExtension SERVERS = PersistenceIT.SERVERS; private org.infinispan.configuration.cache.ConfigurationBuilder createConfigurationBuilder(Database database) { org.infinispan.configuration.cache.ConfigurationBuilder builder = new org.infinispan.configuration.cache.ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); builder.persistence().addStore(JdbcStringBasedStoreConfigurationBuilder.class) .table() .dropOnExit(true) .tableNamePrefix("TBL") .idColumnName("ID").idColumnType(database.getIdColumType()) .dataColumnName("DATA").dataColumnType(database.getDataColumnType()) .timestampColumnName("TS").timestampColumnType(database.getTimeStampColumnType()) .segmentColumnName("S").segmentColumnType(database.getSegmentColumnType()) .dataSource().jndiUrl("jdbc/" + database.getType()); return builder; } @ParameterizedTest @ArgumentsSource(Common.DatabaseProvider.class) public void testTwoCachesSameCacheStore(Database database) { RemoteCache<String, String> cache1 = SERVERS.hotrod().withServerConfiguration(createConfigurationBuilder(database)).withQualifier("1").create(); RemoteCache<String, String> cache2 = SERVERS.hotrod().withServerConfiguration(createConfigurationBuilder(database)).withQualifier("2").create(); cache1.put("k1", "v1"); String firstK1 = cache1.get("k1"); assertEquals("v1", firstK1); assertNull(cache2.get("k1")); cache2.put("k2", "v2"); assertEquals("v2", cache2.get("k2")); assertNull(cache1.get("k2")); assertCleanCacheAndStore(cache1); assertCleanCacheAndStore(cache2); } @ParameterizedTest @ArgumentsSource(Common.DatabaseProvider.class) public void testPutGetRemove(Database database) { RemoteCache<String, String> cache = SERVERS.hotrod().withServerConfiguration(createConfigurationBuilder(database)).create(); cache.put("k1", "v1"); cache.put("k2", "v2"); assertNotNull(cache.get("k1")); assertNotNull(cache.get("k2")); cache.stop(); cache.start(); assertNotNull(cache.get("k1")); assertNotNull(cache.get("k2")); assertEquals("v1", cache.get("k1")); assertEquals("v2", cache.get("k2")); cache.remove("k1"); assertNull(cache.get("k1")); } protected void assertCleanCacheAndStore(RemoteCache cache) { cache.clear(); assertEquals(0, cache.size()); } @ParameterizedTest @ArgumentsSource(Common.DatabaseProvider.class) public void testDataSourceCLI(Database database) { try (AeshTestConnection terminal = new AeshTestConnection()) { CLI.main(new AeshDelegatingShell(terminal), new String[]{}, new Properties()); terminal.send("connect " + SERVERS.getServerDriver().getServerAddress(0).getHostAddress() + ":11222"); terminal.assertContains("//containers/default]>"); terminal.clear(); terminal.send("server datasource ls"); terminal.assertContains(database.getType()); terminal.clear(); terminal.send("server datasource test " + database.getType()); terminal.assertContains("ISPN012502: Connection to data source '" + database.getType()+ "' successful"); } } }
4,524
42.509615
150
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/persistence/JdbcConfigurationUtil.java
package org.infinispan.server.persistence; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.jdbc.common.configuration.PooledConnectionFactoryConfigurationBuilder; import org.infinispan.persistence.jdbc.configuration.JdbcStringBasedStoreConfigurationBuilder; import org.infinispan.server.test.core.persistence.Database; import org.infinispan.util.concurrent.IsolationLevel; public class JdbcConfigurationUtil { private PooledConnectionFactoryConfigurationBuilder persistenceConfiguration; private final ConfigurationBuilder configurationBuilder; private final CacheMode cacheMode; public JdbcConfigurationUtil(CacheMode cacheMode, Database database, boolean passivation, boolean preload) { configurationBuilder = new ConfigurationBuilder(); this.cacheMode = cacheMode; createPersistenceConfiguration(database, passivation, preload); } private JdbcConfigurationUtil createPersistenceConfiguration(Database database, boolean passivation, boolean preload) { persistenceConfiguration = configurationBuilder.clustering().cacheMode(cacheMode).hash().numOwners(1) .persistence() .passivation(passivation) .addStore(JdbcStringBasedStoreConfigurationBuilder.class) .shared(false) .preload(preload) .fetchPersistentState(true) .table() .dropOnExit(false) .createOnStart(true) .tableNamePrefix("tbl") .idColumnName("id").idColumnType(database.getIdColumType()) .dataColumnName("data").dataColumnType(database.getDataColumnType()) .timestampColumnName("ts").timestampColumnType(database.getTimeStampColumnType()) .segmentColumnName("s").segmentColumnType(database.getSegmentColumnType()) .connectionPool() .connectionUrl(database.jdbcUrl()) .username(database.username()) .password(database.password()) .driverClass(database.driverClassName()); return this; } public JdbcConfigurationUtil setLockingConfigurations() { configurationBuilder.locking().isolationLevel(IsolationLevel.READ_COMMITTED).lockAcquisitionTimeout(20000).concurrencyLevel(500).useLockStriping(false); return this; } public JdbcConfigurationUtil setEviction() { configurationBuilder.memory().maxCount(2); return this; } public PooledConnectionFactoryConfigurationBuilder getPersistenceConfiguration() { return this.persistenceConfiguration; } public ConfigurationBuilder getConfigurationBuilder() { return configurationBuilder; } }
2,852
42.892308
160
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/persistence/JdbcStringBasedCacheStorePassivation.java
package org.infinispan.server.persistence; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.commons.test.Eventually; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.server.test.core.Common; import org.infinispan.server.test.core.category.Persistence; import org.infinispan.server.test.core.persistence.Database; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; /** * Tests String-based jdbc cache store under the following circumstances: * <p> * passivation == false --all cache entries should always be also in the cache store * preload == true --after server restart, all entries should appear in the cache immediately * purge == false --all entries should remain in the cache store after server * restart * <p> * Other attributes like singleton, shared, fetch-state do not make sense in single node cluster. * */ @Category(Persistence.class) public class JdbcStringBasedCacheStorePassivation { @RegisterExtension public static InfinispanServerExtension SERVERS = PersistenceIT.SERVERS; @ParameterizedTest @ArgumentsSource(Common.DatabaseProvider.class) public void testFailover(Database database) throws Exception { JdbcConfigurationUtil jdbcUtil = new JdbcConfigurationUtil(CacheMode.REPL_SYNC, database, false, true) .setLockingConfigurations(); RemoteCache<String, String> cache = SERVERS.hotrod().withServerConfiguration(jdbcUtil.getConfigurationBuilder()).create(); try(TableManipulation table = new TableManipulation(cache.getName(), jdbcUtil.getPersistenceConfiguration())) { cache.put("k1", "v1"); cache.put("k2", "v2"); // test passivation==false, database should contain all entries which are in the cache assertNotNull(table.getValueByKey("k1")); assertNotNull(table.getValueByKey("k2")); SERVERS.getServerDriver().stop(0); SERVERS.getServerDriver().restart(0); assertNotNull(table.getValueByKey("k1")); assertNotNull(table.getValueByKey("k2")); assertNull(cache.withFlags(Flag.SKIP_CACHE_LOAD).get("k3")); assertEquals("v1", cache.get("k1")); assertEquals("v2", cache.get("k2")); //when the entry is removed from the cache, it should be also removed from the cache store (the store //and the cache are the same sets of keys) cache.remove("k1"); assertNull(table.getValueByKey("k1")); cache.clear(); } } @ParameterizedTest @ArgumentsSource(Common.DatabaseProvider.class) public void testPreload(Database database) throws Exception { JdbcConfigurationUtil jdbcUtil = new JdbcConfigurationUtil(CacheMode.REPL_SYNC, database, false, true) .setLockingConfigurations(); RemoteCache<String, String> cache = SERVERS.hotrod().withServerConfiguration(jdbcUtil.getConfigurationBuilder()).create(); try(TableManipulation table = new TableManipulation(cache.getName(), jdbcUtil.getPersistenceConfiguration())) { cache.clear(); cache.put("k1", "v1"); cache.put("k2", "v2"); assertNotNull(table.getValueByKey("k1")); assertNotNull(table.getValueByKey("k2")); SERVERS.getServerDriver().stop(0); SERVERS.getServerDriver().restart(0); // test preload==true, entries should be immediately in the cache after restart assertEquals(2, cache.size()); // test purge==false, entries should remain in the database after restart assertNotNull(table.getValueByKey("k1")); assertNotNull(table.getValueByKey("k2")); } } /* * This should verify that DefaultTwoWayKey2StringMapper on server side can work with ByteArrayKey which * is always produced by HotRod client regardless of type of key being stored in a cache. */ @ParameterizedTest @ArgumentsSource(Common.DatabaseProvider.class) public void testDefaultTwoWayKey2StringMapper(Database database) throws Exception { JdbcConfigurationUtil jdbcUtil = new JdbcConfigurationUtil(CacheMode.REPL_SYNC, database, false, true) .setLockingConfigurations(); RemoteCache<Object, Object> cache = SERVERS.hotrod().withServerConfiguration(jdbcUtil.getConfigurationBuilder()).create(); try(TableManipulation table = new TableManipulation(cache.getName(), jdbcUtil.getPersistenceConfiguration())) { Double doubleKey = 10.0; Double doubleValue = 20.0; assertEquals(0, cache.size()); assertEquals(0, table.countAllRows()); cache.put(doubleKey, doubleValue); // test passivation==false, database should contain all entries which are in the cache assertEquals(1, table.countAllRows()); assertEquals(doubleValue, cache.get(doubleKey)); } } @ParameterizedTest @ArgumentsSource(Common.DatabaseProvider.class) public void testSoftRestartWithPassivation(Database database) throws Exception { JdbcConfigurationUtil jdbcUtil = new JdbcConfigurationUtil(CacheMode.REPL_SYNC, database, true, false) .setEviction() .setLockingConfigurations(); RemoteCache<String, String> cache = SERVERS.hotrod().withServerConfiguration(jdbcUtil.getConfigurationBuilder()).create(); try(TableManipulation table = new TableManipulation(cache.getName(), jdbcUtil.getPersistenceConfiguration())) { cache.put("k1", "v1"); cache.put("k2", "v2"); //not yet in store (eviction.max-entries=2, LRU) assertNull(table.getValueByKey("k1")); assertNull(table.getValueByKey("k2")); cache.put("k3", "v3"); //now some key is evicted and stored in store assertEquals(2, getNumberOfEntriesInMemory(cache)); //the passivation is asynchronous Eventually.eventuallyEquals(1, table::countAllRows); SERVERS.getServerDriver().stop(0); SERVERS.getServerDriver().restart(0); //soft stop should store all entries from cache to store // test preload==false assertEquals(0, getNumberOfEntriesInMemory(cache)); // test purge==false, entries should remain in the database after restart assertEquals(3, table.countAllRows()); assertEquals("v1", cache.get("k1")); } } /** * This test differs from the preceding expecting 1 entry in the DB * after fail-over instead of 3 when doing soft * restart. */ @ParameterizedTest @ArgumentsSource(Common.DatabaseProvider.class) public void testFailoverWithPassivation(Database database) throws Exception { JdbcConfigurationUtil jdbcUtil = new JdbcConfigurationUtil(CacheMode.REPL_SYNC, database, true, false) .setEviction() .setLockingConfigurations(); RemoteCache<String, String> cache = SERVERS.hotrod().withServerConfiguration(jdbcUtil.getConfigurationBuilder()).create(); try(TableManipulation table = new TableManipulation(cache.getName(), jdbcUtil.getPersistenceConfiguration())) { cache.put("k1", "v1"); cache.put("k2", "v2"); assertNull(table.getValueByKey("k1")); assertNull(table.getValueByKey("k2")); cache.put("k3", "v3"); assertEquals(2, getNumberOfEntriesInMemory(cache)); Eventually.eventuallyEquals(1, table::countAllRows); SERVERS.getServerDriver().kill(0); SERVERS.getServerDriver().restart(0); assertEquals(0, getNumberOfEntriesInMemory(cache)); assertEquals(1, table.countAllRows()); assertEquals("v1", cache.get("k1")); } } private int getNumberOfEntriesInMemory(RemoteCache<?, ?> cache) { return cache.withFlags(Flag.SKIP_CACHE_LOAD).size(); } }
8,507
47.617143
130
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/persistence/AsyncJdbcStringBasedCacheStore.java
package org.infinispan.server.persistence; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.server.test.core.Common; import org.infinispan.server.test.core.category.Persistence; import org.infinispan.server.test.core.persistence.Database; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; @Category(Persistence.class) public class AsyncJdbcStringBasedCacheStore { @RegisterExtension public static InfinispanServerExtension SERVERS = PersistenceIT.SERVERS; @ParameterizedTest @ArgumentsSource(Common.DatabaseProvider.class) public void testPutRemove(Database database) throws Exception { int numEntries = 10; String keyPrefix = "testPutRemove-k-"; String valuePrefix = "testPutRemove-k-"; JdbcConfigurationUtil jdbcUtil = new JdbcConfigurationUtil(CacheMode.REPL_SYNC, database, false, true) .setLockingConfigurations(); RemoteCache<String, String> cache = SERVERS.hotrod().withServerConfiguration(jdbcUtil.getConfigurationBuilder()).create(); try(TableManipulation table = new TableManipulation(cache.getName(), jdbcUtil.getPersistenceConfiguration())) { // test PUT operation for (int i = 0; i < numEntries; i++) { cache.putAsync(keyPrefix+i, valuePrefix+i).toCompletableFuture().get(); } assertCountRow(table.countAllRows(), numEntries); for (int i = 0; i < numEntries; i++) { String key = keyPrefix + i; String keyFromDatabase = table.getValueByKey(key); assertNotNull("Key " + key + " was not found in DB" , keyFromDatabase); } //test REMOVE operation for (int i = 0; i < numEntries; i++) { cache.removeAsync(keyPrefix + i).toCompletableFuture().get(); } assertCountRow(table.countAllRows(), 0); } } public void assertCountRow(int result, int numberExpected) { assertEquals(numberExpected, result); } }
2,463
40.762712
130
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/persistence/CustomNonBlockingStore.java
package org.infinispan.server.persistence; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT; import java.util.EnumSet; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import org.infinispan.AdvancedCache; import org.infinispan.encoding.DataConversion; import org.infinispan.persistence.spi.InitializationContext; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.MarshallableEntryFactory; import org.infinispan.persistence.spi.NonBlockingStore; import org.infinispan.commons.util.concurrent.CompletableFutures; public class CustomNonBlockingStore implements NonBlockingStore<String, String> { private MarshallableEntryFactory<String, String> marshallableEntryFactory; private DataConversion keyDataConversion; private DataConversion valueDataConversion; @Override public CompletionStage<Void> start(InitializationContext ctx) { marshallableEntryFactory = ctx.getMarshallableEntryFactory(); AdvancedCache<String, String> object = ctx.getCache().getAdvancedCache().withMediaType(APPLICATION_OBJECT, APPLICATION_OBJECT); keyDataConversion = object.getKeyDataConversion(); valueDataConversion = object.getValueDataConversion(); return CompletableFutures.completedNull(); } @Override public CompletionStage<Void> stop() { return CompletableFutures.completedNull(); } @Override public Set<Characteristic> characteristics() { return EnumSet.of(Characteristic.READ_ONLY); } @Override public CompletionStage<MarshallableEntry<String, String>> load(int segment, Object storageKey) { Object objectKey = keyDataConversion.fromStorage(storageKey); String value = "Hello " + objectKey; Object storageValue = valueDataConversion.toStorage(value); return CompletableFuture.completedFuture(marshallableEntryFactory.create(storageKey, storageValue)); } @Override public CompletionStage<Void> write(int segment, MarshallableEntry<? extends String, ? extends String> entry) { throw new UnsupportedOperationException("This store doesn't support write!"); } @Override public CompletionStage<Boolean> delete(int segment, Object key) { throw new UnsupportedOperationException("This store doesn't support delete!"); } @Override public CompletionStage<Void> clear() { throw new UnsupportedOperationException("This store doesn't support clear!"); } }
2,533
37.984615
133
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/persistence/TableManipulation.java
package org.infinispan.server.persistence; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Enumeration; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.persistence.jdbc.common.DatabaseType; import org.infinispan.persistence.jdbc.common.JdbcUtil; import org.infinispan.persistence.jdbc.common.configuration.PooledConnectionFactoryConfiguration; import org.infinispan.persistence.jdbc.common.configuration.PooledConnectionFactoryConfigurationBuilder; import org.infinispan.persistence.jdbc.common.connectionfactory.ConnectionFactory; import org.infinispan.persistence.jdbc.common.impl.connectionfactory.PooledConnectionFactory; import org.infinispan.persistence.keymappers.DefaultTwoWayKey2StringMapper; import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread; public class TableManipulation implements AutoCloseable { private ConnectionFactory connectionFactory; private Connection connection; public PooledConnectionFactoryConfiguration poolConfiguration; private final String countRowsSql; private final String selectIdRowSqlWithLike; private static final String ID_COLUMN_NAME = "id"; private static final String DEFAULT_IDENTIFIER_QUOTE_STRING = "\""; private static final String TABLE_NAME_PREFIX = "tbl"; private String tableName; public TableManipulation(String cacheName, PooledConnectionFactoryConfigurationBuilder builder) { this.poolConfiguration = builder.create(); this.tableName = String.format("%s%s_%s%s", DEFAULT_IDENTIFIER_QUOTE_STRING, TABLE_NAME_PREFIX, cacheName, DEFAULT_IDENTIFIER_QUOTE_STRING); if (isMysql()) { this.tableName = this.tableName.replaceAll("\"", ""); } this.countRowsSql = "SELECT COUNT(*) FROM " + tableName; this.selectIdRowSqlWithLike = String.format("SELECT %s FROM %s WHERE %s LIKE ?", ID_COLUMN_NAME, tableName, ID_COLUMN_NAME); } private ConnectionFactory getConnectionFactory() { connectionFactory = ConnectionFactory.getConnectionFactory(PooledConnectionFactory.class); connectionFactory.start(poolConfiguration, connectionFactory.getClass().getClassLoader()); return connectionFactory; } private Connection getConnection() { if (connection == null) { connection = getConnectionFactory().getConnection(); } return connection; } public String getValueByKey(String key) throws Exception { Connection connection = getConnection(); PreparedStatement ps = null; ResultSet rs = null; try { ps = connection.prepareStatement(selectIdRowSqlWithLike); ps.setString(1, "%" + getEncodedKey(key) + "%"); rs = ps.executeQuery(); if (rs.next()) { return rs.getString("ID"); } return null; } finally { JdbcUtil.safeClose(ps); JdbcUtil.safeClose(rs); } } public int countAllRows() { connection = getConnection(); try (PreparedStatement ps = connection.prepareStatement(countRowsSql); ResultSet rs = ps.executeQuery()) { if (rs.next()) { return rs.getInt(1); } else { throw new IllegalStateException(countRowsSql + " returned no rows"); } } catch (SQLException e) { throw new RuntimeException(e); } } public String getEncodedKey(String key) throws Exception { ProtoStreamMarshaller protoStreamMarshaller = new ProtoStreamMarshaller(); byte[] marshalled = protoStreamMarshaller.objectToByteBuffer(key); DefaultTwoWayKey2StringMapper mapper = new DefaultTwoWayKey2StringMapper(); return mapper.getStringMapping(new WrappedByteArray(marshalled)); } private void deregisterDrivers() { Enumeration<Driver> drivers = DriverManager.getDrivers(); Driver driver; while (drivers.hasMoreElements()) { try { driver = drivers.nextElement(); if (driver instanceof com.mysql.cj.jdbc.Driver) { AbandonedConnectionCleanupThread.checkedShutdown(); } DriverManager.deregisterDriver(driver); } catch (SQLException ex) { ex.printStackTrace(); } } } private boolean isMysql() { try { connection = getConnection(); String dbProduct = connection.getMetaData().getDatabaseProductName(); DatabaseType databaseType = DatabaseType.guessDialect(dbProduct); if (databaseType == DatabaseType.MYSQL) { return true; } } catch (SQLException e) { throw new RuntimeException(e); } return false; } @Override public void close() { if (connection != null) { JdbcUtil.safeClose(connection); connectionFactory.stop(); connectionFactory.releaseConnection(connection); } deregisterDrivers(); } }
5,109
36.29927
146
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/HotRodCompCacheOperationsIT.java
package org.infinispan.server.functional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Collection; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.configuration.TransactionMode; import org.infinispan.client.hotrod.multimap.MultimapCacheManager; import org.infinispan.client.hotrod.multimap.RemoteMultimapCache; import org.infinispan.client.hotrod.multimap.RemoteMultimapCacheManagerFactory; import org.infinispan.client.hotrod.transaction.lookup.RemoteTransactionManagerLookup; import org.infinispan.commons.configuration.StringConfiguration; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.SyncStrongCounter; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.core.TestSystemPropertyNames; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import jakarta.transaction.TransactionManager; /** * @since 15.0 **/ public class HotRodCompCacheOperationsIT { private static final String TX_CACHE_CONFIG = "<distributed-cache name=\"%s\">\n" + " <encoding media-type=\"application/x-protostream\"/>\n" + " <transaction mode=\"NON_XA\"/>\n" + "</distributed-cache>"; private static final String MULTIMAP_CACHE_CONFIG = "<distributed-cache name=\"%s\">\n" + " <encoding media-type=\"application/x-protostream\"/>\n" + "</distributed-cache>"; @RegisterExtension public static final InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/ClusteredServerIspn13Test.xml") .numServers(2) .property(TestSystemPropertyNames.INFINISPAN_TEST_SERVER_BASE_IMAGE_NAME, "quay.io/infinispan/server:13.0") .runMode(ServerRunMode.CONTAINER) .build(); @Test public void testHotRodOperations() { RemoteCache<String, String> cache = SERVERS.hotrod().create(); cache.put("k1", "v1"); assertEquals(1, cache.size()); assertEquals("v1", cache.get("k1")); cache.remove("k1"); assertEquals(0, cache.size()); } @Test public void testCounter() { String counterName = SERVERS.getMethodName(); CounterManager counterManager = SERVERS.getCounterManager(); assertNull(counterManager.getConfiguration(counterName)); assertTrue(counterManager.defineCounter(counterName, CounterConfiguration.builder(CounterType.BOUNDED_STRONG).build())); SyncStrongCounter strongCounter = counterManager.getStrongCounter(counterName).sync(); assertEquals(0, strongCounter.getValue()); assertEquals(10, strongCounter.addAndGet(10)); } @Test public void testTransaction() throws Exception { ConfigurationBuilder config = new ConfigurationBuilder(); config.remoteCache(SERVERS.getMethodName()) .transactionMode(TransactionMode.NON_XA) .transactionManagerLookup(RemoteTransactionManagerLookup.getInstance()); String xml = String.format(TX_CACHE_CONFIG, SERVERS.getMethodName()); RemoteCache<String, String> cache = SERVERS.hotrod() .withClientConfiguration(config) .withServerConfiguration(new StringConfiguration(xml)) .create(); TransactionManager tm = cache.getTransactionManager(); tm.begin(); cache.put("k", "v"); assertEquals("v", cache.get("k")); tm.commit(); assertEquals("v", cache.get("k")); } @Test public void testMultiMap() { ConfigurationBuilder config = new ConfigurationBuilder(); config.remoteCache(SERVERS.getMethodName()); String xml = String.format(MULTIMAP_CACHE_CONFIG, SERVERS.getMethodName()); RemoteCacheManager rcm = SERVERS.hotrod() .withClientConfiguration(config) .withServerConfiguration(new StringConfiguration(xml)) .create().getRemoteCacheManager(); MultimapCacheManager<String, String> multimapCacheManager = RemoteMultimapCacheManagerFactory.from(rcm); RemoteMultimapCache<String, String> people = multimapCacheManager.get(SERVERS.getMethodName()); people.put("coders", "Will"); people.put("coders", "Auri"); people.put("coders", "Pedro"); Collection<String> coders = people.get("coders").join(); assertTrue(coders.contains("Will")); assertTrue(coders.contains("Auri")); assertTrue(coders.contains("Pedro")); } @Test public void testMultiMapWithDuplicates() { ConfigurationBuilder config = new ConfigurationBuilder(); config.remoteCache(SERVERS.getMethodName()); String xml = String.format(MULTIMAP_CACHE_CONFIG, SERVERS.getMethodName()); RemoteCacheManager rcm = SERVERS.hotrod() .withClientConfiguration(config) .withServerConfiguration(new StringConfiguration(xml)) .create().getRemoteCacheManager(); MultimapCacheManager<String, String> multimapCacheManager = RemoteMultimapCacheManagerFactory.from(rcm); RemoteMultimapCache<String, String> people = multimapCacheManager.get(SERVERS.getMethodName(), true); people.put("coders", "Will"); people.put("coders", "Will"); people.put("coders", "Auri"); people.put("coders", "Pedro"); Collection<String> coders = people.get("coders").join(); assertTrue(coders.contains("Will")); assertTrue(coders.contains("Auri")); assertTrue(coders.contains("Pedro")); } }
6,079
39.805369
126
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/RequestTracingIT.java
package org.infinispan.server.functional; import static org.infinispan.server.test.core.Containers.ipAddress; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.test.Eventually; import org.infinispan.server.test.core.InfinispanServerDriver; import org.infinispan.server.test.core.InfinispanServerListener; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.core.TestSystemPropertyNames; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.testcontainers.containers.GenericContainer; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Test OpenTelemetry tracing integration with the Jaeger client * * @since 10.0 */ public class RequestTracingIT { public static final int JAEGER_QUERY_PORT = 16686; public static final String JAEGER_IMAGE = System.getProperty(TestSystemPropertyNames.JAEGER_IMAGE, "quay.io/jaegertracing/all-in-one:1.35.2"); public static final String SERVICE_NAME = RequestTracingIT.class.getName(); public static final int NUM_KEYS = 10; private static final GenericContainer JAEGER = new GenericContainer(JAEGER_IMAGE) .withEnv("COLLECTOR_OTLP_ENABLED", "true"); @RegisterExtension public static final InfinispanServerExtension SERVER = InfinispanServerExtensionBuilder.config("configuration/ClusteredServerTest.xml") .runMode(ServerRunMode.CONTAINER) .numServers(1) .property("infinispan.tracing.enabled", "true") .property("otel.traces.exporter", "otlp") .property("otel.service.name", SERVICE_NAME) .addListener(new InfinispanServerListener() { @Override public void before(InfinispanServerDriver driver) { JAEGER.start(); String endpoint = String.format("http://%s:%s", ipAddress(JAEGER), "4317"); driver.getConfiguration().properties() .setProperty("otel.exporter.otlp.endpoint", endpoint); } @Override public void after(InfinispanServerDriver driver) { JAEGER.stop(); } }) .build(); @Test public void testRequestIsTraced() { RemoteCache<Object, Object> remoteCache = SERVER.hotrod().create(); for (int i = 0; i < NUM_KEYS; i++) { remoteCache.put("key" + i, "value"); } OkHttpClient httpClient = new OkHttpClient(); String queryUrl = String.format("http://%s:%s/api/traces?service=%s", ipAddress(JAEGER), JAEGER_QUERY_PORT, SERVICE_NAME); Eventually.eventually(() -> { try (Response response = httpClient.newCall(new Request.Builder().url(queryUrl).build()).execute()) { if (response.body() == null) return false; Json json = Json.read(response.body().string()); return json.has("data") && !json.at("data").asList().isEmpty(); } }); } }
3,451
39.611765
145
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/StartupFailureIT.java
package org.infinispan.server.functional; import static org.junit.jupiter.api.Assertions.assertFalse; import java.net.ServerSocket; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.AfterAllCallback; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.RegisterExtension; /** * @author Dan Berindei * @since 14 **/ @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ExtendWith(StartupFailureIT.Extension.class) public class StartupFailureIT { @RegisterExtension public static final InfinispanServerExtension SERVER = InfinispanServerExtensionBuilder.config("configuration/ClusteredServerTest.xml") .numServers(1) .runMode(ServerRunMode.EMBEDDED) .build(); @Test public void testAddressAlreadyBound() { assertFalse(SERVER.getServerDriver().isRunning(0)); } static class Extension implements AfterAllCallback, BeforeAllCallback { ServerSocket socket; @Override public void beforeAll(ExtensionContext context) throws Exception { socket = new ServerSocket(11222); } @Override public void afterAll(ExtensionContext context) throws Exception { if (socket != null) socket.close(); } } }
1,660
29.759259
89
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/ClusteredIT.java
package org.infinispan.server.functional; import org.infinispan.notifications.cachelistener.filter.CacheEventConverterFactory; import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverterFactory; import org.infinispan.notifications.cachelistener.filter.CacheEventFilterFactory; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.server.functional.extensions.DistributedHelloServerTask; import org.infinispan.server.functional.extensions.HelloServerTask; import org.infinispan.server.functional.extensions.IsolatedTask; import org.infinispan.server.functional.extensions.Person; import org.infinispan.server.functional.extensions.PojoMarshalling; import org.infinispan.server.functional.extensions.ScriptingTasks; import org.infinispan.server.functional.extensions.ServerTasks; import org.infinispan.server.functional.extensions.SharedTask; import org.infinispan.server.functional.extensions.entities.Entities; import org.infinispan.server.functional.extensions.entities.EntitiesImpl; import org.infinispan.server.functional.extensions.filters.DynamicCacheEventFilterFactory; import org.infinispan.server.functional.extensions.filters.DynamicConverterFactory; import org.infinispan.server.functional.extensions.filters.FilterConverterFactory; import org.infinispan.server.functional.extensions.filters.RawStaticCacheEventFilterFactory; import org.infinispan.server.functional.extensions.filters.RawStaticConverterFactory; import org.infinispan.server.functional.extensions.filters.SimpleConverterFactory; import org.infinispan.server.functional.extensions.filters.StaticCacheEventFilterFactory; import org.infinispan.server.functional.extensions.filters.StaticConverterFactory; import org.infinispan.server.functional.hotrod.HotRodAdmin; import org.infinispan.server.functional.hotrod.HotRodCacheContinuousQueries; import org.infinispan.server.functional.hotrod.HotRodCacheEvents; import org.infinispan.server.functional.hotrod.HotRodCacheOperations; import org.infinispan.server.functional.hotrod.HotRodCacheQueries; import org.infinispan.server.functional.hotrod.HotRodCounterOperations; import org.infinispan.server.functional.hotrod.HotRodListenerWithDslFilter; import org.infinispan.server.functional.hotrod.HotRodMultiMapOperations; import org.infinispan.server.functional.hotrod.HotRodTransactionalCacheOperations; import org.infinispan.server.functional.hotrod.IgnoreCaches; import org.infinispan.server.functional.memcached.MemcachedOperations; import org.infinispan.server.functional.rest.RestLoggingResource; import org.infinispan.server.functional.rest.RestMetricsResource; import org.infinispan.server.functional.rest.RestOperations; import org.infinispan.server.functional.rest.RestRouter; import org.infinispan.server.functional.rest.RestServerResource; import org.infinispan.server.test.core.Common; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.infinispan.server.test.junit5.InfinispanSuite; import org.infinispan.tasks.ServerTask; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @Suite @SelectClasses({ // This needs to be first as it collects all metrics and all the tests below add a lot which due to inefficiencies // in small rye can be very very slow! RestMetricsResource.class, HotRodCacheOperations.class, RestOperations.class, RestRouter.class, RestServerResource.class, MemcachedOperations.class, HotRodAdmin.class, HotRodCounterOperations.class, HotRodMultiMapOperations.class, HotRodTransactionalCacheOperations.class, HotRodCacheEvents.class, HotRodCacheQueries.class, HotRodCacheContinuousQueries.class, HotRodListenerWithDslFilter.class, IgnoreCaches.class, RestLoggingResource.class, ScriptingTasks.class, ServerTasks.class, PojoMarshalling.class }) public class ClusteredIT extends InfinispanSuite { @RegisterExtension public static final InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/ClusteredServerTest.xml") .numServers(2) .runMode(ServerRunMode.CONTAINER) .mavenArtifacts(mavenArtifacts()) .artifacts(artifacts()) .property("infinispan.query.lucene.max-boolean-clauses", "1025") .build(); public static String[] mavenArtifacts() { return Common.NASHORN_DEPS; } public static JavaArchive[] artifacts() { JavaArchive hello = ShrinkWrap.create(JavaArchive.class, "hello-server-task.jar") .addClass(HelloServerTask.class) .addAsServiceProvider(ServerTask.class, HelloServerTask.class); JavaArchive distHello = ShrinkWrap.create(JavaArchive.class, "distributed-hello-server-task.jar") .addPackage(DistributedHelloServerTask.class.getPackage()) .addAsServiceProvider(ServerTask.class, DistributedHelloServerTask.class); JavaArchive isolated = ShrinkWrap.create(JavaArchive.class, "isolated-server-task.jar") .addPackage(IsolatedTask.class.getPackage()) .addAsServiceProvider(ServerTask.class, IsolatedTask.class); JavaArchive shared = ShrinkWrap.create(JavaArchive.class, "shared-server-task.jar") .addPackage(SharedTask.class.getPackage()) .addAsServiceProvider(ServerTask.class, SharedTask.class); JavaArchive pojo = ShrinkWrap.create(JavaArchive.class, "pojo.jar") .addClass(Person.class); JavaArchive filterFactories = ShrinkWrap.create(JavaArchive.class, "filter-factories.jar") .addPackage(DynamicCacheEventFilterFactory.class.getPackage()) .addPackage(Entities.class.getPackage()) .addAsServiceProvider(CacheEventFilterFactory.class, DynamicCacheEventFilterFactory.class, RawStaticCacheEventFilterFactory.class, StaticCacheEventFilterFactory.class) .addAsServiceProvider(CacheEventConverterFactory.class, DynamicConverterFactory.class, RawStaticConverterFactory.class, SimpleConverterFactory.class, StaticConverterFactory.class) .addAsServiceProvider(CacheEventFilterConverterFactory.class, FilterConverterFactory.class) .addAsServiceProvider(SerializationContextInitializer.class, EntitiesImpl.class); return new JavaArchive[]{hello, distHello, isolated, shared, pojo, filterFactories}; } }
7,003
50.5
120
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/XSiteIT.java
package org.infinispan.server.functional; import static org.infinispan.server.test.core.InfinispanServerTestConfiguration.LON; import static org.infinispan.server.test.core.InfinispanServerTestConfiguration.NYC; import org.infinispan.server.cli.XSiteCliOperations; import org.infinispan.server.functional.hotrod.XSiteHotRodCacheOperations; import org.infinispan.server.functional.rest.XSiteRestCacheOperations; import org.infinispan.server.functional.rest.XSiteRestMetricsOperations; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.infinispan.server.test.junit5.InfinispanSuite; import org.infinispan.server.test.junit5.InfinispanXSiteServerExtension; import org.infinispan.server.test.junit5.InfinispanXSiteServerExtensionBuilder; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; /** * Cross-Site suite * * @author Pedro Ruivo * @author Gustavo Lira * @since 11.0 */ @Suite @SelectClasses({ XSiteRestMetricsOperations.class, XSiteHotRodCacheOperations.class, XSiteRestCacheOperations.class, XSiteCliOperations.class }) public class XSiteIT extends InfinispanSuite { public static final int NUM_SERVERS = 3; public static final String LON_CACHE_CONFIG = "<replicated-cache name=\"%s\">" + " <backups>" + " <backup site=\"NYC\" strategy=\"ASYNC\"/>" + " </backups>" + "</replicated-cache>"; public static final String NYC_CACHE_CONFIG = "<replicated-cache name=\"%s\">" + " <backups>" + " <backup site=\"LON\" strategy=\"ASYNC\"/>" + " </backups>" + "</replicated-cache>"; public static final String LON_CACHE_CUSTOM_NAME_CONFIG = "<replicated-cache name=\"lon-cache-%s\">" + " <backups>" + " <backup site=\"NYC\" strategy=\"ASYNC\"/>" + " </backups>" + " <backup-for remote-cache=\"nyc-cache-%s\" remote-site=\"NYC\" />" + "</replicated-cache>"; public static final String NYC_CACHE_CUSTOM_NAME_CONFIG = "<replicated-cache name=\"nyc-cache-%s\">" + " <backups>" + " <backup site=\"LON\" strategy=\"ASYNC\"/>" + " </backups>" + " <backup-for remote-cache=\"lon-cache-%s\" remote-site=\"LON\" />" + "</replicated-cache>"; public static final int NR_KEYS = 30; public static final int MAX_COUNT_KEYS = 10; public static final String LON_CACHE_OFF_HEAP = "<distributed-cache name=\"%s\" owners=\"2\" mode=\"ASYNC\" remote-timeout=\"25000\" statistics=\"true\">" + " <backups>" + " <backup site=\"" + NYC + "\" strategy=\"ASYNC\" timeout=\"30000\">" + " <take-offline after-failures=\"-1\" min-wait=\"60000\"/>" + " </backup>" + " </backups>" + " <memory storage=\"OFF_HEAP\" max-count=\"" + MAX_COUNT_KEYS + "\" when-full=\"REMOVE\"/>" + " <persistence passivation=\"true\">" + " <file-store shared=\"false\" preload=\"true\" purge=\"false\" />" + " </persistence>" + "</distributed-cache>"; static InfinispanServerExtensionBuilder lonServerRule = InfinispanServerExtensionBuilder .config("configuration/XSiteServerTest.xml") .runMode(ServerRunMode.CONTAINER) .numServers(NUM_SERVERS); static InfinispanServerExtensionBuilder nycServerRule = InfinispanServerExtensionBuilder .config("configuration/XSiteServerTest.xml") .runMode(ServerRunMode.CONTAINER) .numServers(NUM_SERVERS); @RegisterExtension public static final InfinispanXSiteServerExtension SERVERS = new InfinispanXSiteServerExtensionBuilder() .addSite(LON, lonServerRule) .addSite(NYC, nycServerRule) .build(); }
4,236
42.234694
117
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/AnchoredKeysIT.java
package org.infinispan.server.functional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.commons.configuration.BasicConfiguration; import org.infinispan.commons.configuration.StringConfiguration; import org.infinispan.commons.util.Version; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @author Ryan Emerson * @since 11.0 */ public class AnchoredKeysIT { @RegisterExtension public static final InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/AnchoredKeys.xml") .numServers(2) .runMode(ServerRunMode.EMBEDDED) .featuresEnabled("anchored-keys") .build(); @Test public void testAnchoredKeysCache() { RemoteCacheManager rcm = SERVERS.hotrod().createRemoteCacheManager(); test(rcm.getCache("default")); } @Test public void testCreateAnchoredKeysCache() { BasicConfiguration config = new StringConfiguration("<infinispan><cache-container><replicated-cache name=\"anchored2\">\n" + "<locking concurrency-level=\"100\" acquire-timeout=\"1000\"/>\n" + "<anchored-keys xmlns=\"urn:infinispan:config:anchored-keys:" + Version.getMajorMinor() + "\" enabled=\"true\"/>\n" + "</replicated-cache></cache-container></infinispan>"); RemoteCacheManager rcm = SERVERS.hotrod().createRemoteCacheManager(); rcm.administration().createCache("anchored2", config); test(rcm.getCache("anchored2")); } private void test(RemoteCache<String, String> cache) { assertNotNull(cache); cache.put("k1", "v1"); assertEquals("v1", cache.get("k1")); assertEquals(1, cache.size()); } }
2,186
38.763636
144
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/BackupManagerIT.java
package org.infinispan.server.functional; import static org.infinispan.client.rest.RestResponse.ACCEPTED; import static org.infinispan.client.rest.RestResponse.CONFLICT; import static org.infinispan.client.rest.RestResponse.CREATED; import static org.infinispan.client.rest.RestResponse.NOT_FOUND; import static org.infinispan.client.rest.RestResponse.NO_CONTENT; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.infinispan.server.core.BackupManager.Resources.Type.CACHES; import static org.infinispan.server.core.BackupManager.Resources.Type.COUNTERS; import static org.infinispan.server.core.BackupManager.Resources.Type.PROTO_SCHEMAS; import static org.infinispan.server.core.BackupManager.Resources.Type.TASKS; import static org.infinispan.server.core.BackupManager.Resources.Type.TEMPLATES; import static org.infinispan.server.test.core.Common.assertStatus; import static org.infinispan.server.test.core.Common.assertStatusAndBodyContains; import static org.infinispan.server.test.core.Common.assertStatusAndBodyEquals; import static org.infinispan.server.test.core.Common.awaitResponse; import static org.infinispan.server.test.core.Common.awaitStatus; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.CompletionStage; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.zip.ZipFile; import org.infinispan.cli.commands.CLI; import org.infinispan.cli.impl.AeshDelegatingShell; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestCacheManagerClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestClusterClient; import org.infinispan.client.rest.RestCounterClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.RestTaskClient; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.counter.api.Storage; import org.infinispan.counter.configuration.Element; import org.infinispan.server.core.BackupManager; import org.infinispan.server.test.core.AeshTestConnection; import org.infinispan.server.test.core.Common; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; /** * @author Ryan Emerson * @since 12.0 */ public class BackupManagerIT extends AbstractMultiClusterIT { static final File WORKING_DIR = new File(CommonsTestingUtil.tmpDirectory(BackupManagerIT.class)); static final int NUM_ENTRIES = 10; public BackupManagerIT() { super(Common.NASHORN_DEPS); } @BeforeAll public static void setup() { WORKING_DIR.mkdirs(); } @AfterAll public static void teardown() { Util.recursiveFileRemove(WORKING_DIR); } @Test public void testManagerBackupUpload() throws Exception { String name = "testManagerBackup"; performTest( client -> { RestCacheManagerClient cm = client.cacheManager("clustered"); assertStatus(ACCEPTED, cm.createBackup(name)); return awaitOk(() -> cm.getBackup(name, false)); }, client -> await(client.cacheManager("clustered").deleteBackup(name)), (zip, client) -> { RestCacheManagerClient cm = client.cacheManager("clustered"); assertStatus(ACCEPTED, cm.restore(name, zip)); return awaitCreated(() -> cm.getRestore(name)); }, this::assertWildcardContent, false ); } @Test public void testManagerBackupFromFile() throws Exception { String name = "testManagerBackup"; performTest( client -> { RestCacheManagerClient cm = client.cacheManager("clustered"); assertStatus(ACCEPTED, cm.createBackup(name)); return awaitOk(() -> cm.getBackup(name, false)); }, client -> await(client.cacheManager("clustered").deleteBackup(name)), (zip, client) -> { RestCacheManagerClient cm = client.cacheManager("clustered"); assertStatus(ACCEPTED, cm.restore(name, zip.getPath(), null)); return awaitCreated(() -> cm.getRestore(name)); }, this::assertWildcardContent, true ); } @Test public void testManagerBackupParameters() throws Exception { String name = "testManagerBackupParameters"; performTest( client -> { Map<String, List<String>> params = new HashMap<>(); params.put("caches", Collections.singletonList("*")); params.put("counters", Collections.singletonList("weak-volatile")); RestCacheManagerClient cm = client.cacheManager("clustered"); assertStatus(ACCEPTED, cm.createBackup(name, params)); return awaitOk(() -> cm.getBackup(name, false)); }, client -> await(client.cacheManager("clustered").deleteBackup(name)), (zip, client) -> { Map<String, List<String>> params = new HashMap<>(); params.put("caches", Collections.singletonList("cache1")); params.put("counters", Collections.singletonList("*")); RestCacheManagerClient cm = client.cacheManager("clustered"); assertStatus(ACCEPTED, cm.restore(name, zip, params)); return awaitCreated(() -> cm.getRestore(name)); }, client -> { // Assert that only caches and the specified "weak-volatile" counter have been backed up. Internal caches will still be present assertStatusAndBodyEquals(OK, "[\"___protobuf_metadata\",\"memcachedCache\",\"cache1\",\"___script_cache\"]", client.caches()); assertStatusAndBodyEquals(OK, "[\"weak-volatile\"]", client.counters()); assertStatus(NOT_FOUND, client.schemas().get("schema.proto")); assertStatusAndBodyEquals(OK, "[]", client.tasks().list(RestTaskClient.ResultType.USER)); }, false ); } @Test public void testCreateDuplicateBackupResources() throws Exception { String backupName = "testCreateDuplicateBackupResources"; // Start the source cluster startSourceCluster(); RestClient client = source.getClient(); populateContainer(client); RestCacheManagerClient cm = client.cacheManager("clustered"); assertStatus(ACCEPTED, cm.createBackup(backupName)); assertStatus(CONFLICT, cm.createBackup(backupName)); // Expect a 202 response as the previous backup will be in progress, so the request is accepted for now assertStatus(ACCEPTED, cm.deleteBackup(backupName)); // Now wait until the backup has actually been deleted so that we successfully create another with the same name awaitStatus(() -> cm.deleteBackup(backupName), ACCEPTED, NO_CONTENT); assertStatus(NOT_FOUND, cm.deleteBackup(backupName)); assertStatus(ACCEPTED, cm.createBackup(backupName)); // Wait for the backup operation to finish awaitStatus(() -> cm.getBackup(backupName, false), ACCEPTED, OK); assertStatus(NO_CONTENT, cm.deleteBackup(backupName)); } @Test public void testManagerRestoreParameters() throws Exception { String name = "testManagerRestoreParameters"; performTest( client -> { // Create a backup of all container content RestCacheManagerClient cm = client.cacheManager("clustered"); assertStatus(ACCEPTED, cm.createBackup(name)); return awaitOk(() -> cm.getBackup(name, false)); }, client -> await(client.cacheManager("clustered").deleteBackup(name)), (zip, client) -> { // Request that only the 'test.js' script is restored Map<String, List<String>> params = new HashMap<>(); params.put("tasks", Collections.singletonList("scripts/test.js")); RestCacheManagerClient cm = client.cacheManager("clustered"); assertStatus(ACCEPTED, cm.restore(name, zip, params)); return awaitCreated(() -> cm.getRestore(name)); }, client -> { // Assert that the test.js task has been restored List<Json> tasks = Json.read(assertStatus(OK, client.tasks().list(RestTaskClient.ResultType.USER))).asJsonList(); assertEquals(1, tasks.size()); assertEquals("scripts/test.js", tasks.iterator().next().at("name").asString()); // Assert that no other content has been restored assertStatusAndBodyEquals(OK, "[\"___protobuf_metadata\",\"memcachedCache\",\"___script_cache\"]", client.caches()); assertStatusAndBodyEquals(OK, "[]", client.counters()); assertStatus(NOT_FOUND, client.schemas().get("schema.proto")); }, false ); } @Test public void testClusterBackupUpload() throws Exception { String name = "testClusterBackup"; performTest( client -> { RestClusterClient cluster = client.cluster(); assertStatus(ACCEPTED, cluster.createBackup(name)); return awaitOk(() -> cluster.getBackup(name, false)); }, client -> await(client.cacheManager("clustered").deleteBackup(name)), (zip, client) -> { RestClusterClient c = client.cluster(); assertStatus(ACCEPTED, c.restore(name, zip)); return awaitCreated(() -> c.getRestore(name)); }, this::assertWildcardContent, false ); } @Test public void testClusterBackupFromFile() throws Exception { String name = "testClusterBackup"; performTest( client -> { RestClusterClient cluster = client.cluster(); assertStatus(ACCEPTED, cluster.createBackup(name)); return awaitOk(() -> cluster.getBackup(name, false)); }, client -> await(client.cacheManager("clustered").deleteBackup(name)), (zip, client) -> { RestClusterClient c = client.cluster(); assertStatus(ACCEPTED, c.restore(name, zip.getPath())); return awaitCreated(() -> c.getRestore(name)); }, this::assertWildcardContent, true ); } @Test public void testCLIPartialBackup() throws Exception { startSourceCluster(); String backupName = "partial-backup"; String fileName = backupName + ".zip"; try (AeshTestConnection t = cli(source)) { t.send("backup create --templates=* -n " + backupName); // Ensure that the backup has finished before stopping the source cluster t.send("backup get --no-content " + backupName); } source.driver.syncFilesFromServer(0, "data"); Path createdBackup = source.driver.getRootDir().toPath().resolve("0/data/backups").resolve(backupName).resolve(fileName); try (ZipFile zip = new ZipFile(createdBackup.toFile())) { // Ensure that only cache-configs are present assertNotNull(zipResourceDir(TEMPLATES)); assertResourceDoesntExist(zip, CACHES, COUNTERS, PROTO_SCHEMAS, TASKS); } Files.delete(createdBackup); } private void assertResourceDoesntExist(ZipFile zip, BackupManager.Resources.Type... types) { for (BackupManager.Resources.Type type : types) { String dir = zipResourceDir(type); assertNull(zip.getEntry(dir)); } } private String zipResourceDir(BackupManager.Resources.Type type) { return "containers/default/" + type.toString(); } @Test public void testCLIBackupToCustomDir() { startSourceCluster(); String backupName = "server-backup"; String fileName = backupName + ".zip"; File localBackupDir = new File(WORKING_DIR, "custom-dir"); localBackupDir.mkdir(); localBackupDir.setWritable(true, false); File serverBackupDir = new File(source.driver.syncFilesToServer(0, localBackupDir.getAbsolutePath())); source.driver.syncFilesToServer(1, localBackupDir.getAbsolutePath()); try (AeshTestConnection t = cli(source)) { t.clear(); t.send(String.format("backup create -d %s -n %s", serverBackupDir.getPath(), backupName)); // Ensure that the backup has finished before stopping the source cluster t.send("backup get --no-content " + backupName); } localBackupDir = new File(source.driver.syncFilesFromServer(0, serverBackupDir.getAbsolutePath())); if (!localBackupDir.getName().equals("custom-dir")) { localBackupDir = new File(localBackupDir, "custom-dir"); } assertTrue(new File(localBackupDir, backupName + "/" + fileName).exists()); } @Test public void testCLIBackupFromServerDir() throws Exception { startSourceCluster(); String backupName = "server-backup"; String fileName = backupName + ".zip"; try (AeshTestConnection t = cli(source)) { t.send("create cache --template=org.infinispan.DIST_SYNC backupCache"); t.send("cd caches/backupCache"); t.send("put k1 v1"); t.send("ls"); t.assertContains("k1"); t.clear(); t.send("backup create -n " + backupName); // Ensure that the backup has finished before stopping the source cluster t.send("backup get --no-content " + backupName); } source.driver.syncFilesFromServer(0, "data"); stopSourceCluster(); startTargetCluster(); Path createdBackup = source.driver.getRootDir().toPath().resolve("0/data/backups").resolve(backupName).resolve(fileName); createdBackup = Paths.get(target.driver.syncFilesToServer(0, createdBackup.toString())); try (AeshTestConnection t = cli(target)) { t.send("backup restore " + createdBackup); Thread.sleep(1000); t.send("ls caches/backupCache"); t.assertContains("k1"); } Files.deleteIfExists(createdBackup); } @Test public void testCLIBackupUpload() throws Exception { startSourceCluster(); Path createdBackup; try (AeshTestConnection t = cli(source)) { t.send("create cache --template=org.infinispan.DIST_SYNC backupCache"); t.send("cd caches/backupCache"); t.send("put k1 v1"); t.send("ls"); t.assertContains("k1"); t.clear(); String backupName = "example-backup"; t.send("backup create -n " + backupName); t.send("backup get " + backupName); Thread.sleep(1000); t.send("backup delete " + backupName); String fileName = backupName + ".zip"; createdBackup = Paths.get(System.getProperty("user.dir")).resolve(fileName); } stopSourceCluster(); startTargetCluster(); try (AeshTestConnection t = cli(target)) { t.send("backup restore -u " + createdBackup); Thread.sleep(1000); t.send("ls caches/backupCache"); t.assertContains("k1"); } Files.delete(createdBackup); } private AeshTestConnection cli(Cluster cluster) { AeshTestConnection t = new AeshTestConnection(); CLI.main(new AeshDelegatingShell(t), new String[]{}, new Properties()); String host = cluster.driver.getServerAddress(0).getHostAddress(); int port = cluster.driver.getServerSocket(0, 11222).getPort(); t.send(String.format("connect %s:%d", host, port)); t.assertContains("//containers/default]>"); t.clear(); return t; } private static RestResponse awaitOk(Supplier<CompletionStage<RestResponse>> request) { return awaitResponse(request, ACCEPTED, OK); } private static RestResponse awaitCreated(Supplier<CompletionStage<RestResponse>> request) { return awaitResponse(request, ACCEPTED, CREATED); } private void performTest(Function<RestClient, RestResponse> backupAndDownload, Function<RestClient, RestResponse> delete, BiFunction<File, RestClient, RestResponse> restore, Consumer<RestClient> assertTargetContent, boolean syncToServer) throws Exception { // Start the source cluster startSourceCluster(); RestClient client = source.getClient(); // Populate the source container populateContainer(client); // Perform the backup and download RestResponse getResponse = backupAndDownload.apply(client); String fileName = getResponse.getHeader("Content-Disposition").split("=")[1]; // Delete the backup from the server try (RestResponse deleteResponse = delete.apply(client)) { assertEquals(204, deleteResponse.getStatus()); } // Ensure that all of the backup files have been deleted from the source cluster // We must wait for a short period time here to ensure that the returned entity has actually been removed from the filesystem Thread.sleep(50); assertNoServerBackupFilesExist(source); // Shutdown the source cluster stopSourceCluster(); // Start the target cluster startTargetCluster(); client = target.getClient(); // Copy the returned zip bytes to the local working dir File backupZip = new File(WORKING_DIR, fileName); try (InputStream is = getResponse.getBodyAsStream()) { Files.copy(is, backupZip.toPath(), StandardCopyOption.REPLACE_EXISTING); } getResponse.close(); if (syncToServer) { backupZip = new File(target.driver.syncFilesToServer(0, backupZip.getAbsolutePath())); } // Upload the backup to the target cluster try (RestResponse restoreResponse = restore.apply(backupZip, client)) { assertEquals(201, restoreResponse.getStatus(), restoreResponse.getBody()); } // Assert that all content has been restored as expected, connecting to the second node in the cluster to ensure // that configurations and caches are restored cluster-wide assertTargetContent.accept(target.getClient(1)); // Ensure that the backup files have been deleted from the target cluster assertNoServerBackupFilesExist(target); stopTargetCluster(); } private void populateContainer(RestClient client) throws Exception { String cacheName = "cache1"; ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); createCache(cacheName, builder, client); RestCacheClient cache = client.cache(cacheName); for (int i = 0; i < NUM_ENTRIES; i++) { assertStatus(NO_CONTENT, cache.put(String.valueOf(i), "Val-" + i)); } assertEquals(NUM_ENTRIES, getCacheSize(cacheName, client)); createCounter("weak-volatile", Element.WEAK_COUNTER, Storage.VOLATILE, client, 0); createCounter("weak-persistent", Element.WEAK_COUNTER, Storage.PERSISTENT, client, -100); createCounter("strong-volatile", Element.STRONG_COUNTER, Storage.VOLATILE, client, 50); createCounter("strong-persistent", Element.STRONG_COUNTER, Storage.PERSISTENT, client, 0); addSchema(client); try (InputStream is = BackupManagerIT.class.getResourceAsStream("/scripts/test.js")) { String script = CommonsTestingUtil.loadFileAsString(is); assertStatus(OK, client.tasks().uploadScript("scripts/test.js", RestEntity.create(MediaType.APPLICATION_JAVASCRIPT, script))); } } private void assertWildcardContent(RestClient client) { String cacheName = "cache1"; RestCacheClient cache = client.cache(cacheName); assertStatusAndBodyEquals(OK, Integer.toString(NUM_ENTRIES), cache.size()); for (int i = 0; i < NUM_ENTRIES; i++) { String index = String.valueOf(i); assertStatusAndBodyEquals(OK, "Val-" + index, cache.get(index)); } assertCounter(client, "weak-volatile", Element.WEAK_COUNTER, Storage.VOLATILE, 0); assertCounter(client, "weak-persistent", Element.WEAK_COUNTER, Storage.PERSISTENT, -100); assertCounter(client, "strong-volatile", Element.STRONG_COUNTER, Storage.VOLATILE, 50); assertCounter(client, "strong-persistent", Element.STRONG_COUNTER, Storage.PERSISTENT, 0); assertStatusAndBodyContains(OK, "message Person", client.schemas().get("schema.proto")); Json json = Json.read(assertStatus(OK, client.tasks().list(RestTaskClient.ResultType.USER))); assertTrue(json.isArray()); List<Json> tasks = json.asJsonList(); assertEquals(1, tasks.size()); assertEquals("scripts/test.js", tasks.get(0).at("name").asString()); } private void createCounter(String name, Element type, Storage storage, RestClient client, long delta) { String config = String.format("{\n" + " \"%s\":{\n" + " \"initial-value\":0,\n" + " \"storage\":\"%s\"\n" + " }\n" + "}", type, storage.toString()); RestCounterClient counterClient = client.counter(name); assertStatus(OK, counterClient.create(RestEntity.create(MediaType.APPLICATION_JSON, config))); if (delta != 0) { assertNotNull(assertStatus(name.contains("strong") ? OK : NO_CONTENT, counterClient.add(delta))); } } private void assertCounter(RestClient client, String name, Element type, Storage storage, long expectedValue) { RestResponse rsp = await(client.counter(name).configuration()); assertEquals(200, rsp.getStatus()); String content = rsp.getBody(); Json config = Json.read(content).at(type.toString()); assertEquals(storage.toString(), config.at("storage").asString()); assertEquals(0, config.at("initial-value").asInteger()); assertStatusAndBodyEquals(OK, Long.toString(expectedValue), client.counter(name).get()); } private void assertNoServerBackupFilesExist(Cluster cluster) { for (int i = 0; i < 2; i++) { cluster.driver.syncFilesFromServer(i, "data"); Path root = cluster.driver.getRootDir().toPath(); File workingDir = root.resolve(Integer.toString(i)).resolve("data").resolve("backups").toFile(); assertTrue(workingDir.isDirectory()); String[] files = workingDir.list(); assertNotNull(files); assertEquals(0, files.length, Arrays.toString(files)); } } }
23,612
41.932727
142
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/CloudEventsIntegrationIT.java
package org.infinispan.server.functional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Duration; import java.util.Collections; import java.util.Properties; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.server.test.core.InfinispanServerDriver; import org.infinispan.server.test.core.InfinispanServerListener; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.testcontainers.containers.KafkaContainer; import org.testcontainers.utility.DockerImageName; /** * @author Dan Berindei * @since 12.1 */ public class CloudEventsIntegrationIT { public static final String CACHE_ENTRIES_TOPIC = "cache-entries"; public static KafkaContainer KAFKA = new KafkaContainer(DockerImageName.parse("quay.io/cloudservices/cp-kafka:5.4.3") .asCompatibleSubstituteFor("confluentinc/cp-kafka")); @RegisterExtension public static final InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/CloudEventsIntegration.xml") .numServers(1) .runMode(ServerRunMode.EMBEDDED) .addListener(new InfinispanServerListener() { @Override public void before(InfinispanServerDriver driver) { KAFKA.start(); driver.getConfiguration().properties() .setProperty("kafka.bootstrap.servers", KAFKA.getBootstrapServers()); } @Override public void after(InfinispanServerDriver driver) { KAFKA.stop(); } }) .build(); @Test public void testSendCacheEntryEvent() { Properties kafkaProperties = new Properties(); kafkaProperties.setProperty("bootstrap.servers", KAFKA.getBootstrapServers()); kafkaProperties.setProperty("key.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer"); kafkaProperties.setProperty("value.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer"); kafkaProperties.setProperty("group.id", CloudEventsIntegrationIT.class.getSimpleName()); kafkaProperties.setProperty("auto.offset.reset", "earliest"); try (KafkaConsumer<byte[], byte[]> kafkaConsumer = new KafkaConsumer<>(kafkaProperties)) { assertTrue(kafkaConsumer.listTopics().containsKey(CACHE_ENTRIES_TOPIC)); kafkaConsumer.subscribe(Collections.singleton(CACHE_ENTRIES_TOPIC)); RemoteCacheManager rcm = SERVERS.hotrod().createRemoteCacheManager(); RemoteCache<String, String> cache = rcm.getCache("default"); assertNotNull(cache); cache.put("k1", "v1"); assertEquals("v1", cache.get("k1")); ConsumerRecords<byte[], byte[]> records = kafkaConsumer.poll(Duration.ofSeconds(1)); assertEquals(1, records.count()); ConsumerRecord<byte[], byte[]> eventRecord = records.iterator().next(); Json expectedKeyJson = Json.object().set("_type", "string").set("_value", "k1"); Json actualKeyJson = Json.read(new String(eventRecord.key())); assertEquals(expectedKeyJson, actualKeyJson); } } }
3,937
44.790698
119
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/RollingUpgradeCliIT.java
package org.infinispan.server.functional; import java.io.File; import java.util.Properties; import org.infinispan.cli.commands.CLI; import org.infinispan.cli.impl.AeshDelegatingShell; import org.infinispan.client.rest.RestClient; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.server.test.core.AeshTestConnection; import org.junit.jupiter.api.BeforeAll; /** * @since 11.0 */ public class RollingUpgradeCliIT extends RollingUpgradeIT { private static File workingDir; private static Properties properties; @BeforeAll public static void setup() { workingDir = new File(CommonsTestingUtil.tmpDirectory(RollingUpgradeCliIT.class)); Util.recursiveFileRemove(workingDir); workingDir.mkdirs(); properties = new Properties(System.getProperties()); properties.put("cli.dir", workingDir.getAbsolutePath()); } protected void disconnectSource(RestClient client) { try (AeshTestConnection terminal = new AeshTestConnection()) { CLI.main(new AeshDelegatingShell(terminal), new String[]{}, properties); terminal.send("connect " + target.driver.getServerAddress(0).getHostAddress() + ":" + target.getSinglePort(0)); terminal.assertContains("//containers/default]>"); terminal.clear(); terminal.send("migrate cluster disconnect --cache=" + CACHE_NAME); } } protected void doRollingUpgrade(RestClient client) { try (AeshTestConnection terminal = new AeshTestConnection()) { CLI.main(new AeshDelegatingShell(terminal), new String[]{}, properties); terminal.send("connect " + target.driver.getServerAddress(0).getHostAddress() + ":" + target.getSinglePort(0)); terminal.assertContains("//containers/default]>"); terminal.clear(); terminal.send("migrate cluster synchronize --cache=" + CACHE_NAME); } } }
1,935
36.960784
120
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/VersionsInteropTest.java
package org.infinispan.server.functional; import static org.junit.jupiter.api.Assertions.assertEquals; import org.infinispan.client.hotrod.DefaultTemplate; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.server.test.core.InfinispanContainer; import org.junit.jupiter.api.Test; public class VersionsInteropTest { @Test public void testOlderVersion() { // Reproducer for ISPN-14018. // We start a server with an older version than the client, they should negotiate the protocol correctly. try (InfinispanContainer container = new InfinispanContainer("quay.io/infinispan/server:13.0")) { container.start(); try (RemoteCacheManager cacheManager = container.getRemoteCacheManager()) { RemoteCache<Object, Object> testCache = cacheManager.administration().getOrCreateCache("test", DefaultTemplate.DIST_SYNC); testCache.put("key", "value"); assertEquals("value", testCache.get("key")); } } } }
1,066
38.518519
134
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/ShutdownContainerIT.java
package org.infinispan.server.functional; import static org.infinispan.client.rest.RestResponse.NO_CONTENT; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.client.rest.RestResponse.SERVICE_UNAVAILABLE; import static org.infinispan.server.test.core.Common.assertStatus; import org.infinispan.client.rest.RestClient; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @author Ryan Emerson * @since 13.0 */ public class ShutdownContainerIT { @RegisterExtension public static final InfinispanServerExtension SERVER = InfinispanServerExtensionBuilder.config("configuration/ClusteredServerTest.xml") .numServers(1) .runMode(ServerRunMode.CONTAINER) .build(); @Test public void testShutDown() { RestClient client = SERVER.rest().get(); String containerName = "default"; assertStatus(OK, client.cacheManager(containerName).caches()); assertStatus(NO_CONTENT, client.container().shutdown()); // Ensure operations on the cachemanager are not possible assertStatus(SERVICE_UNAVAILABLE, client.cacheManager(containerName).caches()); assertStatus(SERVICE_UNAVAILABLE, client.counters()); // Ensure that the K8s liveness pods will not fail assertStatus(OK, client.cacheManager(containerName).healthStatus()); } }
1,619
34.217391
89
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/RollingUpgradeDynamicStoreIT.java
package org.infinispan.server.functional; import static org.infinispan.client.rest.RestResponse.NOT_FOUND; import static org.infinispan.client.rest.RestResponse.NO_CONTENT; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.server.test.core.Common.assertStatus; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.List; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.remote.configuration.RemoteServerConfiguration; import org.infinispan.persistence.remote.configuration.RemoteStoreConfiguration; import org.infinispan.persistence.remote.upgrade.SerializationUtils; import org.junit.jupiter.api.Test; /** * @since 13.0 */ public class RollingUpgradeDynamicStoreIT extends RollingUpgradeIT { @Test @Override public void testRollingUpgrade() throws Exception { RestClient restClientSource = source.getClient(); RestClient restClientTarget = target.getClient(); // Create cache in the source cluster createSourceClusterCache(); // Create cache in the target cluster identical to the source, without any store createTargetClusterWithoutStore(); // Register proto schema addSchema(restClientSource); addSchema(restClientTarget); // Populate source cluster populateCluster(restClientSource); // Connect target cluster to the source cluster assertSourceDisconnected(); connectTargetCluster(); assertSourceConnected(); // Make sure data is accessible from the target cluster assertEquals("name-13", getPersonName("13", restClientTarget)); // Do a rolling upgrade from the target doRollingUpgrade(restClientTarget); // Do a second rolling upgrade, should be harmless and simply override the data doRollingUpgrade(restClientTarget); // Disconnect source from the remote store disconnectSource(restClientTarget); assertSourceDisconnected(); // Stop source cluster stopSourceCluster(); // Assert all nodes are disconnected and data was migrated successfully for (int i = 0; i < target.getMembers().size(); i++) { RestClient restClient = target.getClient(i); assertEquals(ENTRIES, getCacheSize(CACHE_NAME, restClient)); assertEquals("name-35", getPersonName("35", restClient)); } } private void createTargetClusterWithoutStore() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); createCache(CACHE_NAME, builder, target.getClient()); } protected void connectTargetCluster() throws IOException { RestCacheClient client = target.getClient().cache(CACHE_NAME); ConfigurationBuilder builder = new ConfigurationBuilder(); addRemoteStore(builder); RemoteStoreConfiguration remoteStore = (RemoteStoreConfiguration) builder.build().persistence().stores().iterator().next(); RestEntity restEntity = RestEntity.create(MediaType.APPLICATION_JSON, SerializationUtils.toJson(remoteStore)); assertStatus(NO_CONTENT, client.connectSource(restEntity)); String json = assertStatus(OK, client.sourceConnection()); RemoteStoreConfiguration remoteStoreConfiguration = SerializationUtils.fromJson(json); List<RemoteServerConfiguration> servers = remoteStoreConfiguration.servers(); assertEquals(1, servers.size()); RemoteServerConfiguration initialConfig = remoteStore.servers().iterator().next(); assertEquals(initialConfig.host(), servers.get(0).host()); assertEquals(initialConfig.port(), servers.get(0).port()); } protected void assertSourceConnected() { assertStatus(OK, target.getClient().cache(CACHE_NAME).sourceConnected()); } protected void assertSourceDisconnected() { assertStatus(NOT_FOUND, target.getClient().cache(CACHE_NAME).sourceConnected()); } }
4,256
37.7
129
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/ConcurrentShutdownRestIT.java
package org.infinispan.server.functional; import static org.infinispan.client.rest.RestResponse.NO_CONTENT; import static org.infinispan.commons.test.Eventually.eventually; import static org.infinispan.server.functional.ShutdownRestIT.isServerShutdown; import static org.infinispan.server.test.core.Common.assertStatus; import java.util.concurrent.CompletionStage; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @since 10.1 */ public class ConcurrentShutdownRestIT { @RegisterExtension public static final InfinispanServerExtension SERVER = InfinispanServerExtensionBuilder.config("configuration/ClusteredServerTest.xml") .numServers(2) .build(); @Test public void testShutDown() { RestClient client0 = SERVER.rest().create(); RestClient client1 = SERVER.rest().get(1); CompletionStage<RestResponse> stop0 = client0.server().stop(); CompletionStage<RestResponse> stop1 = client1.server().stop(); assertStatus(NO_CONTENT, stop0); assertStatus(NO_CONTENT, stop1); eventually(() -> isServerShutdown(client0)); eventually(() -> isServerShutdown(client1)); eventually(() -> !SERVER.getServerDriver().isRunning(0)); eventually(() -> !SERVER.getServerDriver().isRunning(1)); } }
1,626
36.837209
89
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/AbstractMultiClusterIT.java
package org.infinispan.server.functional; import static org.infinispan.client.rest.RestResponse.NOT_FOUND; import static org.infinispan.client.rest.RestResponse.NO_CONTENT; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME; import static org.infinispan.server.test.core.Common.assertStatus; import java.net.InetSocketAddress; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.client.rest.configuration.ServerConfigurationBuilder; import org.infinispan.client.rest.impl.okhttp.StringRestEntityOkHttp; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.server.test.core.AbstractInfinispanServerDriver; import org.infinispan.server.test.core.Common; import org.infinispan.server.test.core.InfinispanServerTestConfiguration; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.core.TestSystemPropertyNames; import org.infinispan.util.KeyValuePair; import org.junit.jupiter.api.AfterEach; /** * @author Ryan Emerson * @since 12.0 */ abstract class AbstractMultiClusterIT { protected final String config; protected final String[] mavenArtifacts; protected Cluster source, target; public AbstractMultiClusterIT(String... mavenArtifacts) { this.config = configFile(); this.mavenArtifacts = mavenArtifacts; } protected String configFile() { return "configuration/ClusteredServerTest.xml"; } @AfterEach public void cleanup() throws Exception { stopSourceCluster(); stopTargetCluster(); } protected void startSourceCluster() { source = new Cluster(new ClusterConfiguration(config, 2, 0, mavenArtifacts), getCredentials()); source.start(this.getClass().getName() + "-source"); } protected void stopSourceCluster() throws Exception { if (source != null) source.stop(this.getClass().getName() + "-source"); } protected void startTargetCluster() { target = new Cluster(new ClusterConfiguration(config, 2, 1000, mavenArtifacts), getCredentials()); target.start(this.getClass().getName() + "-target"); } protected void stopTargetCluster() throws Exception { if (target != null) target.stop(this.getClass().getName() + "-target"); } protected int getCacheSize(String cacheName, RestClient restClient) { RestCacheClient cache = restClient.cache(cacheName); return Integer.parseInt(assertStatus(OK, cache.size())); } protected void addSchema(RestClient client) { RestCacheClient cache = client.cache(PROTOBUF_METADATA_CACHE_NAME); assertStatus(NO_CONTENT, cache.put("schema.proto", "message Person {required string name = 1;}")); assertStatus(NOT_FOUND, client.cache(PROTOBUF_METADATA_CACHE_NAME).get("schema.proto.errors")); } protected void createCache(String cacheName, ConfigurationBuilder builder, RestClient client) { String cacheConfig = Common.cacheConfigToJson(cacheName, builder.build()); StringRestEntityOkHttp body = new StringRestEntityOkHttp(MediaType.APPLICATION_JSON, cacheConfig); assertStatus(OK, client.cache(cacheName).createWithConfiguration(body)); } protected KeyValuePair<String, String> getCredentials() { return null; } protected static class ClusterConfiguration extends InfinispanServerTestConfiguration { public ClusterConfiguration(String configurationFile, int numServers, int portOffset, String[] mavenArtifacts) { super(configurationFile, numServers, mavenArtifacts != null ? ServerRunMode.CONTAINER : ServerRunMode.EMBEDDED, new Properties(), mavenArtifacts, null, false, false, false, Collections.emptyList(), null, portOffset, new String[]{}); } } /** * A simplified embedded cluster not tied to junit */ static class Cluster { final AbstractInfinispanServerDriver driver; final Map<Integer, RestClient> serverClients = new HashMap<>(); private final KeyValuePair<String, String> credentials; Cluster(ClusterConfiguration simpleConfiguration) { this(simpleConfiguration, null); } Cluster(ClusterConfiguration simpleConfiguration, KeyValuePair<String, String> credentials) { this.credentials = credentials; Properties sysProps = System.getProperties(); for (String prop : sysProps.stringPropertyNames()) { if (prop.startsWith(TestSystemPropertyNames.PREFIX)) { simpleConfiguration.properties().put(prop, sysProps.getProperty(prop)); } } this.driver = simpleConfiguration.runMode().newDriver(simpleConfiguration); } void start(String name) { driver.prepare(name); driver.start(name); } void stop(String name) throws Exception { driver.stop(name); for (RestClient client : serverClients.values()) client.close(); } Set<String> getMembers() { String response = assertStatus(OK, getClient().cacheManager("default").info()); Json jsonNode = Json.read(response); return jsonNode.at("cluster_members").asJsonList().stream().map(Json::asString).collect(Collectors.toSet()); } int getSinglePort(int server) { return driver.getServerSocket(server, 11222).getPort(); } RestClient getClient() { return getClient(0); } RestClient getClient(int server) { return serverClients.computeIfAbsent(server, k -> { InetSocketAddress serverSocket = driver.getServerSocket(server, 11222); final ServerConfigurationBuilder configurationBuilder = new RestClientConfigurationBuilder().addServer() .host(serverSocket.getHostString()).port(serverSocket.getPort()); if (credentials != null) { String user = credentials.getKey(); String pass = credentials.getValue(); configurationBuilder.security().authentication().enable().mechanism("BASIC").username(user).password(pass); } return RestClient.forConfiguration(configurationBuilder.build()); }); } } }
6,703
38.904762
160
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/ProtocolManagementIT.java
package org.infinispan.server.functional; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.server.test.core.Common.assertStatus; import static org.infinispan.server.test.core.Common.sync; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.net.SocketException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ClientIntelligence; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.exceptions.TransportException; import org.infinispan.client.rest.IpFilterRule; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.test.Exceptions; import org.infinispan.server.hotrod.MultiHomedServerAddress; import org.infinispan.server.network.NetworkAddress; import org.infinispan.server.test.core.ServerRunMode; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.1 **/ public class ProtocolManagementIT { @RegisterExtension public static InfinispanServerExtension SERVERS = InfinispanServerExtensionBuilder.config("configuration/MultiEndpointClusteredServerTest.xml") .runMode(ServerRunMode.EMBEDDED) .numServers(2) .property("infinispan.bind.address", "0.0.0.0") .build(); @Test public void testIpFilter() throws IOException { NetworkAddress loopback = NetworkAddress.loopback("loopback"); RestClientConfigurationBuilder loopbackBuilder = new RestClientConfigurationBuilder(); loopbackBuilder.addServer().host(loopback.getAddress().getHostAddress()).port(11222); RestClient loopbackClient = SERVERS.rest().withClientConfiguration(loopbackBuilder).get(); assertStatus(200, loopbackClient.server().connectorNames()); NetworkAddress siteLocal = NetworkAddress.match("sitelocal", iF -> !iF.getName().startsWith("docker"), a -> a.getAddress().isSiteLocalAddress()); RestClientConfigurationBuilder siteLocalBuilder0 = new RestClientConfigurationBuilder(); siteLocalBuilder0.addServer().host(siteLocal.getAddress().getHostAddress()).port(11222); RestClient siteLocalClient0 = SERVERS.rest().withClientConfiguration(siteLocalBuilder0).get(); assertStatus(200, siteLocalClient0.server().connectorNames()); RestClientConfigurationBuilder siteLocalBuilder1 = new RestClientConfigurationBuilder(); siteLocalBuilder1.addServer().host(siteLocal.getAddress().getHostAddress()).port(11322); RestClient siteLocalClient1 = SERVERS.rest().withClientConfiguration(siteLocalBuilder1).get(); assertStatus(200, siteLocalClient1.server().connectorNames()); // Use the server connection list to determine the client address List<IpFilterRule> rules = new ArrayList<>(); Json connections = Json.read(assertStatus(OK, loopbackClient.server().listConnections(false))); for (Json connection : connections.asJsonList()) { String remoteAddress = connection.at("remote-address").asString(); NetworkAddress r = NetworkAddress.inetAddress("r", remoteAddress.substring(1, remoteAddress.lastIndexOf(':'))); try { NetworkAddress remote = NetworkAddress.match("remote", iF -> Exceptions.unchecked(() -> !iF.isLoopback()), a -> MultiHomedServerAddress.inetAddressMatchesInterfaceAddress(r.getAddress().getAddress(), a.getAddress().getAddress(), a.getNetworkPrefixLength()) ); rules.add(new IpFilterRule(IpFilterRule.RuleType.REJECT, remote.cidr())); } catch (IOException e) { // Ignore unmatched } } assertStatus(204, loopbackClient.server().connectorIpFilterSet("endpoint-default", rules)); Exceptions.expectException(RuntimeException.class, ExecutionException.class, SocketException.class, () -> sync(siteLocalClient0.server().connectorNames())); Exceptions.expectException(RuntimeException.class, ExecutionException.class, SocketException.class, () -> sync(siteLocalClient1.server().connectorNames())); assertStatus(204, loopbackClient.server().connectorIpFiltersClear("endpoint-default")); assertStatus(200, siteLocalClient0.server().connectorNames()); assertStatus(200, siteLocalClient1.server().connectorNames()); // Attempt to lock ourselves out assertStatus(409, siteLocalClient0.server().connectorIpFilterSet("endpoint-default", rules)); // Apply the filter just on the Hot Rod endpoint assertStatus(204, loopbackClient.server().connectorIpFilterSet("HotRod-hotrod", rules)); ConfigurationBuilder hotRodSiteLocalBuilder = new ConfigurationBuilder(); hotRodSiteLocalBuilder.addServer().host(siteLocal.getAddress().getHostAddress()).port(11222).clientIntelligence(ClientIntelligence.BASIC); RemoteCacheManager siteLocalRemoteCacheManager = SERVERS.hotrod().withClientConfiguration(hotRodSiteLocalBuilder).createRemoteCacheManager(); Exceptions.expectException(TransportException.class, siteLocalRemoteCacheManager::getCacheNames); // REST should still work, so let's clear the rules assertStatus(204, siteLocalClient0.server().connectorIpFiltersClear("HotRod-hotrod")); // And retry assertNotNull(siteLocalRemoteCacheManager.getCacheNames()); } @Test public void testConnectorStartStop() throws IOException { NetworkAddress loopback = NetworkAddress.loopback("loopback"); RestClientConfigurationBuilder defaultBuilder = new RestClientConfigurationBuilder(); defaultBuilder.addServer().host(loopback.getAddress().getHostAddress()).port(11222); RestClient defaultClient = SERVERS.rest().withClientConfiguration(defaultBuilder).get(); assertStatus(200, defaultClient.caches()); RestClientConfigurationBuilder alternateBuilder = new RestClientConfigurationBuilder(); alternateBuilder.addServer().host(loopback.getAddress().getHostAddress()).port(11223); RestClient alternateClient = SERVERS.rest().withClientConfiguration(alternateBuilder).get(); assertStatus(200, alternateClient.caches()); assertStatus(204, defaultClient.server().connectorStop("endpoint-alternate-1")); Exceptions.expectException(RuntimeException.class, ExecutionException.class, SocketException.class, () -> sync(alternateClient.caches())); assertStatus(204, defaultClient.server().connectorStart("endpoint-alternate-1")); assertStatus(200, alternateClient.caches()); // Attempt to lock ourselves out assertStatus(409, defaultClient.server().connectorStop("endpoint-default")); } }
7,161
56.758065
162
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/MainIT.java
package org.infinispan.server.functional; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class MainIT { @RegisterExtension public static final InfinispanServerExtension SERVER = InfinispanServerExtensionBuilder.config("configuration/ClusteredServerTest.xml") .numServers(1) .build(); @Test public void testExample() { System.out.println("Works"); } }
610
29.55
89
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/RollingUpgradeDynamicStoreCliIT.java
package org.infinispan.server.functional; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Properties; import org.infinispan.cli.commands.CLI; import org.infinispan.cli.impl.AeshDelegatingShell; import org.infinispan.client.rest.RestClient; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.server.test.core.AeshTestConnection; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; /** * @since 13.0 */ public class RollingUpgradeDynamicStoreCliIT extends RollingUpgradeDynamicStoreIT { private static File workingDir; private static Properties properties; private static Path dest; private static final String REMOTE_STORE_CFG_FILE = "remote-store.json"; @BeforeAll public static void setup() { workingDir = new File(CommonsTestingUtil.tmpDirectory(RollingUpgradeDynamicStoreCliIT.class)); Util.recursiveFileRemove(workingDir); workingDir.mkdirs(); properties = new Properties(System.getProperties()); properties.put("cli.dir", workingDir.getAbsolutePath()); dest = workingDir.toPath().resolve(REMOTE_STORE_CFG_FILE); try (InputStream is = RollingUpgradeDynamicStoreCliIT.class.getResourceAsStream("/cli/" + REMOTE_STORE_CFG_FILE)) { Files.copy(is, dest); } catch (IOException e) { throw new IllegalStateException(e); } } @AfterAll public static void teardown() { Util.recursiveFileRemove(workingDir); } @Override protected void connectTargetCluster() { try { String cfg = new String(Files.readAllBytes(dest), StandardCharsets.UTF_8); cfg = cfg.replace("127.0.0.1", source.driver.getServerAddress(0).getHostAddress()); cfg = cfg.replace("11222", Integer.toString(source.getSinglePort(0))); Files.write(dest, cfg.getBytes(StandardCharsets.UTF_8), StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException e) { throw new RuntimeException(e); } try (AeshTestConnection terminal = new AeshTestConnection()) { CLI.main(new AeshDelegatingShell(terminal), new String[]{}, properties); connectToCluster(terminal, target); terminal.assertContains("//containers/default]>"); terminal.clear(); terminal.send("migrate cluster connect --file=" + dest + " --cache=" + CACHE_NAME); terminal.clear(); terminal.send("migrate cluster source-connection --cache=" + CACHE_NAME); terminal.assertContains("remote-store"); } } @Override protected void assertSourceConnected() { try (AeshTestConnection terminal = new AeshTestConnection()) { CLI.main(new AeshDelegatingShell(terminal), new String[]{}, properties); connectToCluster(terminal, target); terminal.assertContains("//containers/default]>"); terminal.clear(); terminal.send("migrate cluster source-connection --cache=" + CACHE_NAME); terminal.assertContains("remote-store"); } } @Override protected void assertSourceDisconnected() { try (AeshTestConnection terminal = new AeshTestConnection()) { CLI.main(new AeshDelegatingShell(terminal), new String[]{}, properties); connectToCluster(terminal, target); terminal.assertContains("//containers/default]>"); terminal.clear(); terminal.send("migrate cluster source-connection --cache=" + CACHE_NAME); terminal.assertContains("Not Found"); } } @Override protected void doRollingUpgrade(RestClient client) { try (AeshTestConnection terminal = new AeshTestConnection()) { CLI.main(new AeshDelegatingShell(terminal), new String[]{}, properties); connectToCluster(terminal, target); terminal.assertContains("//containers/default]>"); terminal.clear(); terminal.send("migrate cluster synchronize --cache=" + CACHE_NAME); } } @Override protected void disconnectSource(RestClient client) { try (AeshTestConnection terminal = new AeshTestConnection()) { CLI.main(new AeshDelegatingShell(terminal), new String[]{}, properties); connectToCluster(terminal, target); terminal.assertContains("//containers/default]>"); terminal.clear(); terminal.send("migrate cluster disconnect --cache=" + CACHE_NAME); } } private void connectToCluster(AeshTestConnection terminal, Cluster cluster) { terminal.send("connect " + cluster.driver.getServerAddress(0).getHostAddress() + ":" + cluster.getSinglePort(0)); } }
4,825
37.919355
121
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/RollingUpgradeIT.java
package org.infinispan.server.functional; import static org.infinispan.client.rest.RestResponse.NO_CONTENT; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.server.test.core.Common.assertStatus; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotSame; import org.infinispan.client.hotrod.ProtocolVersion; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.remote.configuration.RemoteStoreConfigurationBuilder; import org.infinispan.util.KeyValuePair; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * @since 11.0 */ public class RollingUpgradeIT extends AbstractMultiClusterIT { protected static final String CACHE_NAME = "rolling"; protected static final int ENTRIES = 50; @BeforeEach public void before() { // Start two embedded clusters with 2-node each startSourceCluster(); startTargetCluster(); // Assert clusters are isolated and have 2 members each assertEquals(2, source.getMembers().size()); assertEquals(2, target.getMembers().size()); assertNotSame(source.getMembers(), target.getMembers()); } @AfterEach public void after() throws Exception { stopTargetCluster(); stopSourceCluster(); } @Test public void testRollingUpgrade() throws Exception { RestClient restClientSource = source.getClient(); RestClient restClientTarget = target.getClient(); // Create cache in the source cluster createSourceClusterCache(); // Create cache in the target cluster pointing to the source cluster via remote-store createTargetClusterCache(); // Register proto schema addSchema(restClientSource); addSchema(restClientTarget); // Populate source cluster populateCluster(restClientSource); // Make sure data is accessible from the target cluster assertEquals("name-20", getPersonName("20", restClientTarget)); // Do a rolling upgrade from the target doRollingUpgrade(restClientTarget); // Do a second rolling upgrade, should be harmless and simply override the data doRollingUpgrade(restClientTarget); // Disconnect source from the remote store disconnectSource(restClientTarget); // Stop source cluster stopSourceCluster(); // Assert all nodes are disconnected and data was migrated successfully for (int i = 0; i < target.getMembers().size(); i++) { RestClient restClient = target.getClient(i); assertEquals(ENTRIES, getCacheSize(CACHE_NAME, restClient)); assertEquals("name-35", getPersonName("35", restClient)); } } protected void disconnectSource(RestClient client) { assertStatus(NO_CONTENT, client.cache(CACHE_NAME).disconnectSource()); } protected void doRollingUpgrade(RestClient client) { assertStatus(OK, client.cache(CACHE_NAME).synchronizeData()); } protected String getPersonName(String id, RestClient client) { String body = assertStatus(OK,client.cache(CACHE_NAME).get(id)); return Json.read(body).at("name").asString(); } public void populateCluster(RestClient client) { RestCacheClient cache = client.cache(CACHE_NAME); for (int i = 0; i < ENTRIES; i++) { String person = createPerson("name-" + i); assertStatus(NO_CONTENT, cache.put(String.valueOf(i), person)); } assertEquals(ENTRIES, getCacheSize(CACHE_NAME, client)); } private String createPerson(String name) { return String.format("{\"_type\":\"Person\",\"name\":\"%s\"}", name); } void addRemoteStore(ConfigurationBuilder builder) { RemoteStoreConfigurationBuilder storeConfigurationBuilder = builder.clustering() .cacheMode(CacheMode.DIST_SYNC).persistence().addStore(RemoteStoreConfigurationBuilder.class); storeConfigurationBuilder .remoteCacheName(CACHE_NAME) .hotRodWrapping(true) .protocolVersion(ProtocolVersion.PROTOCOL_VERSION_25) .shared(true) .addServer() .host(source.driver.getServerAddress(0).getHostAddress()) .port(11222); final KeyValuePair<String, String> credentials = getCredentials(); if (getCredentials() != null) { storeConfigurationBuilder.remoteSecurity() .authentication().enable().saslMechanism("PLAIN") .username(credentials.getKey()) .password(credentials.getValue()) .realm("default"); } } private void createTargetClusterCache() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); addRemoteStore(builder); createCache(CACHE_NAME, builder, target.getClient()); } void createSourceClusterCache() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); createCache(CACHE_NAME, builder, source.getClient()); } }
5,405
35.281879
106
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/ShutdownRestIT.java
package org.infinispan.server.functional; import static org.infinispan.client.rest.RestResponse.NO_CONTENT; import static org.infinispan.commons.test.Eventually.eventually; import static org.infinispan.server.test.core.Common.assertStatus; import static org.infinispan.server.test.core.Common.sync; import java.net.ConnectException; import org.infinispan.client.rest.RestClient; import org.infinispan.commons.util.Util; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.server.test.junit5.InfinispanServerExtensionBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @since 10.0 */ public class ShutdownRestIT { @RegisterExtension public static final InfinispanServerExtension SERVER = InfinispanServerExtensionBuilder.config("configuration/ClusteredServerTest.xml") .numServers(1) .build(); @Test public void testShutDown() { RestClient client = SERVER.rest().create(); assertStatus(NO_CONTENT, client.server().stop()); eventually(() -> isServerShutdown(client)); eventually(() -> !SERVER.getServerDriver().isRunning(0)); } static boolean isServerShutdown(RestClient client) { try { sync(client.server().configuration()).close(); } catch (RuntimeException r) { return (Util.getRootCause(r) instanceof ConnectException); } return false; } }
1,513
32.644444
89
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/RollingUpgradeSecureIT.java
package org.infinispan.server.functional; import org.infinispan.util.KeyValuePair; /** * @since 12.1 */ public class RollingUpgradeSecureIT extends RollingUpgradeIT { static final String USER = "all_user"; static final String PASS = "all"; @Override protected String configFile() { return "configuration/AuthenticationServerTest.xml"; } @Override protected KeyValuePair<String, String> getCredentials() { return new KeyValuePair<>(USER, PASS); } }
492
19.541667
62
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/rest/XSiteRestCacheOperations.java
package org.infinispan.server.functional.rest; import static org.infinispan.client.rest.RestResponse.NOT_FOUND; import static org.infinispan.client.rest.RestResponse.NO_CONTENT; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.commons.test.Eventually.eventuallyEquals; import static org.infinispan.server.functional.XSiteIT.LON_CACHE_CONFIG; import static org.infinispan.server.functional.XSiteIT.LON_CACHE_CUSTOM_NAME_CONFIG; import static org.infinispan.server.functional.XSiteIT.LON_CACHE_OFF_HEAP; import static org.infinispan.server.functional.XSiteIT.MAX_COUNT_KEYS; import static org.infinispan.server.functional.XSiteIT.NR_KEYS; import static org.infinispan.server.functional.XSiteIT.NUM_SERVERS; import static org.infinispan.server.functional.XSiteIT.NYC_CACHE_CONFIG; import static org.infinispan.server.functional.XSiteIT.NYC_CACHE_CUSTOM_NAME_CONFIG; import static org.infinispan.server.test.core.Common.assertResponse; import static org.infinispan.server.test.core.Common.assertStatus; import static org.infinispan.server.test.core.Common.sync; import static org.infinispan.server.test.core.InfinispanServerTestConfiguration.LON; import static org.infinispan.server.test.core.InfinispanServerTestConfiguration.NYC; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.IntStream; import org.infinispan.client.hotrod.DefaultTemplate; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.server.functional.XSiteIT; import org.infinispan.server.test.junit5.InfinispanXSiteServerExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @author Pedro Ruivo * @author Gustavo Lira * @since 11.0 **/ public class XSiteRestCacheOperations { @RegisterExtension public static final InfinispanXSiteServerExtension SERVERS = XSiteIT.SERVERS; @Test public void testRestOperationsLonToNycBackup() { String lonXML = String.format(LON_CACHE_CONFIG, SERVERS.getMethodName()); RestCacheClient lonCache = createRestCacheClient(LON, SERVERS.getMethodName(), lonXML); RestCacheClient nycCache = createDefaultRestCacheClient(NYC, SERVERS.getMethodName()); //nyc doesn't backup to lon insertAndVerifyEntries(false, lonCache, nycCache); } @Test public void testRestOperationsAllSitesBackup() { String lonXML = String.format(LON_CACHE_CONFIG, SERVERS.getMethodName()); String nycXML = String.format(NYC_CACHE_CONFIG, SERVERS.getMethodName()); RestCacheClient lonCache = createRestCacheClient(LON, SERVERS.getMethodName(), lonXML); RestCacheClient nycCache = createRestCacheClient(NYC, SERVERS.getMethodName(), nycXML); insertAndVerifyEntries(true, lonCache, nycCache); } @Test public void testBackupStatus() { String lonXML = String.format(LON_CACHE_CONFIG, SERVERS.getMethodName()); RestCacheClient lonCache = createRestCacheClient(LON, SERVERS.getMethodName(), lonXML); RestCacheClient nycCache = createDefaultRestCacheClient(NYC, SERVERS.getMethodName()); assertStatus(NOT_FOUND, nycCache.xsiteBackups()); assertResponse(OK, lonCache.backupStatus(NYC), r -> assertEquals(NUM_SERVERS, Json.read(r.getBody()).asMap().size())); assertStatus(NOT_FOUND, nycCache.backupStatus(LON)); assertResponse(OK, lonCache.xsiteBackups(), r -> checkSiteStatus(r, NYC, "online")); assertStatus(OK, lonCache.takeSiteOffline(NYC)); assertResponse(OK, lonCache.xsiteBackups(), r -> checkSiteStatus(r, NYC, "offline")); assertStatus(OK, lonCache.bringSiteOnline(NYC)); assertResponse(OK, lonCache.xsiteBackups(), r -> checkSiteStatus(r, NYC, "online")); } @Test public void testWithDifferentCacheNames() { RestCacheClient lonCache = createRestCacheClient(LON, "lon-cache-rest", String.format(LON_CACHE_CUSTOM_NAME_CONFIG, "rest", "rest")); RestCacheClient nycCache = createRestCacheClient(NYC, "nyc-cache-rest", String.format(NYC_CACHE_CUSTOM_NAME_CONFIG, "rest", "rest")); assertResponse(OK, lonCache.xsiteBackups(), r -> checkSiteStatus(r, NYC, "online")); assertResponse(OK, nycCache.xsiteBackups(), r -> checkSiteStatus(r, LON, "online")); insertAndVerifyEntries(true, lonCache, nycCache); } private static void checkSiteStatus(RestResponse r, String site, String status) { Json backups = Json.read(r.getBody()); assertEquals(status, backups.asJsonMap().get(site).asJsonMap().get("status").asString()); } @Test public void testHotRodOperationsWithOffHeapSingleFileStore() { String lonXML = String.format(LON_CACHE_OFF_HEAP, SERVERS.getMethodName()); RestCacheClient lonCache = createRestCacheClient(LON, SERVERS.getMethodName(), lonXML); RestCacheClient nycCache = createDefaultRestCacheClient(NYC, SERVERS.getMethodName()); //Just to make sure that the file store is empty assertEquals(0, getTotalMemoryEntries(lonCache)); IntStream.range(0, NR_KEYS) .mapToObj(Integer::toString) .forEach(s -> assertStatus(NO_CONTENT, lonCache.put(s, s))); eventuallyEquals(Integer.toString(NR_KEYS), () -> sync(nycCache.size()).getBody()); assertEquals(MAX_COUNT_KEYS, getTotalMemoryEntries(lonCache)); } private int getTotalMemoryEntries(RestCacheClient restCache) { Json json = Json.read(assertStatus(OK, restCache.stats())); return json.asJsonMap().get("current_number_of_entries_in_memory").asInteger(); } private void insertAndVerifyEntries(boolean allSitesBackup, RestCacheClient lonCache, RestCacheClient nycCache) { assertStatus(NO_CONTENT, lonCache.put("k1", "v1")); assertStatus(NO_CONTENT, nycCache.put("k2", "v2")); assertEquals("v1", assertStatus(OK, lonCache.get("k1"))); assertEquals("v2", assertStatus(OK, nycCache.get("k2"))); eventuallyEquals("v1", () -> sync(nycCache.get("k1")).getBody()); if (allSitesBackup) { eventuallyEquals("v2", () -> sync(lonCache.get("k2")).getBody()); } else { assertStatus(NOT_FOUND, lonCache.get("k2")); } } private RestCacheClient createRestCacheClient(String siteName, String cacheName, String xml) { RestCacheClient cache = SERVERS.rest(siteName).get().cache(cacheName); assertStatus(200, cache.createWithConfiguration(RestEntity.create(MediaType.APPLICATION_XML, xml))); return cache; } private RestCacheClient createDefaultRestCacheClient(String siteName, String cacheName) { RestCacheClient cache = SERVERS.rest(siteName).get().cache(cacheName); assertStatus(200, cache.createWithTemplate(DefaultTemplate.DIST_SYNC.getTemplateName())); return cache; } }
6,981
47.486111
139
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/rest/RestServerResource.java
package org.infinispan.server.functional.rest; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.server.test.core.Common.assertResponse; import static org.infinispan.server.test.core.Common.assertStatus; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Set; import java.util.stream.Collectors; import org.infinispan.client.rest.RestClient; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.core.ContainerInfinispanServerDriver; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.testcontainers.shaded.com.google.common.collect.Sets; /** * @since 10.0 */ public class RestServerResource { @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; @Test public void testConfig() { RestClient client = SERVERS.rest().create(); Json configNode = Json.read(assertStatus(OK, client.server().configuration())); Json server = configNode.at("server"); Json interfaces = server.at("interfaces"); Json security = server.at("security"); Json endpoints = server.at("endpoints"); Json endpoint = endpoints.at("endpoint"); String inetAddress = SERVERS.getServerDriver() instanceof ContainerInfinispanServerDriver ? "SITE_LOCAL" : "127.0.0.1"; assertEquals(inetAddress, interfaces.at(0).at("inet-address").at("value").asString()); assertEquals("default", security.at("security-realms").at(0).at("name").asString()); assertEquals("hotrod", endpoint.at("hotrod-connector").at("name").asString()); assertEquals("rest", endpoint.at("rest-connector").at("name").asString()); assertEquals("memcachedCache", endpoint.at("memcached-connector").at("cache").asString()); } @Test public void testThreads() { RestClient client = SERVERS.rest().create(); assertResponse(OK, client.server().threads(), r -> { assertEquals(MediaType.TEXT_PLAIN, r.contentType()); assertTrue(r.getBody().contains("state=RUNNABLE")); }); } @Test public void testInfo() { RestClient client = SERVERS.rest().create(); Json infoNode = Json.read(assertStatus(OK, client.server().info())); assertNotNull(infoNode.at("version")); } @Test public void testMemory() { RestClient client = SERVERS.rest().create(); Json infoNode = Json.read(assertStatus(OK, client.server().memory())); Json memory = infoNode.at("heap"); assertTrue(memory.at("used").asInteger() > 0); assertTrue(memory.at("committed").asInteger() > 0); } @Test public void testEnv() { RestClient client = SERVERS.rest().create(); Json infoNode = Json.read(assertStatus(OK, client.server().env())); Json osVersion = infoNode.at("os.version"); assertEquals(System.getProperty("os.version"), osVersion.asString()); } @Test public void testCacheManagerNames() { RestClient client = SERVERS.rest().create(); Json cacheManagers = Json.read(assertStatus(OK, client.cacheManagers())); Set<String> cmNames = cacheManagers.asJsonList().stream().map(Json::asString).collect(Collectors.toSet()); assertEquals(cmNames, Sets.newHashSet("default")); } @Test public void testCacheDefaults() { RestClient client = SERVERS.rest().create(); Json cacheDefaults = Json.read(assertStatus(OK, client.server().cacheConfigDefaults())); assertEquals("HEAP", cacheDefaults.at("local-cache").at("memory").at("storage").asString()); assertEquals(2, cacheDefaults.at("local-cache").at("clustering").at("hash").at("owners").asInteger()); assertEquals(2, cacheDefaults.at("local-cache").at("clustering").at("hash").at("owners").asInteger()); assertEquals(-1, cacheDefaults.at("local-cache").at("expiration").at("lifespan").asInteger()); assertEquals("REPEATABLE_READ", cacheDefaults.at("local-cache").at("locking").at("isolation").asString()); assertEquals(30000, cacheDefaults.at("local-cache").at("transaction").at("reaper-interval").asInteger()); assertEquals(30000, cacheDefaults.at("local-cache").at("sites").at("max-cleanup-delay").asInteger()); } }
4,573
42.561905
125
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/rest/RestContainerListenerTest.java
package org.infinispan.server.functional.rest; import static org.infinispan.rest.assertion.ResponseAssertion.assertThat; import static org.infinispan.server.test.core.Common.HTTP_PROTOCOLS; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.Closeable; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.configuration.Protocol; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.rest.resources.WeakSSEListener; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; import org.testcontainers.shaded.org.yaml.snakeyaml.Yaml; /** * Listen the container endpoint and test different serializations. * * @since 14.0 */ public class RestContainerListenerTest { @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; static class ArgsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { return HTTP_PROTOCOLS.stream() .flatMap(protocol -> Arrays.stream(AcceptSerialization.values()) .map(serialization -> Arguments.of(protocol, serialization)) ); } } @ParameterizedTest(name = "{0}-{1}") @ArgumentsSource(ArgsProvider.class) public void testSSECluster(Protocol protocol, AcceptSerialization serialization) throws Exception { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.protocol(protocol); RestClient client = SERVERS.rest().withClientConfiguration(builder).create(); WeakSSEListener sseListener = new WeakSSEListener(); Map<String, String> headers = Collections.singletonMap("Accept", serialization.header()); try (Closeable ignored = client.raw().listen("/rest/v2/container?action=listen", headers, sseListener)) { assertTrue(sseListener.await(10, TimeUnit.SECONDS)); assertThat(client.cache("caching-listen").createWithTemplate("org.infinispan.DIST_SYNC")).isOk(); sseListener.expectEvent("create-cache", "caching-listen"); sseListener.expectEvent("lifecycle-event", "ISPN100002", pair -> { assertTrue(serialization.isAccepted(pair.getValue()), "Not a " + serialization.header() + ": " + pair.getValue()); }); sseListener.expectEvent("lifecycle-event", "ISPN100010", pair -> { assertTrue(serialization.isAccepted(pair.getValue()), "Not a " + serialization.header() + ": " + pair.getValue()); }); assertThat(client.cache("caching-listen").delete()).isOk(); sseListener.expectEvent("remove-cache", "caching-listen"); } } private enum AcceptSerialization { JSON { @Override public String header() { return MediaType.APPLICATION_JSON_TYPE; } @Override public boolean isAccepted(String s) { Json json = Json.read(s); if (!(json.isObject() && json.has("log"))) return false; Json log = json.at("log"); if (!(log.has("content") && log.has("meta") && log.has("category"))) return false; Json content = log.at("content"); Json meta = log.at("meta"); return content.has("level") && content.has("message") && content.has("detail") && meta.has("context") && meta.has("scope") && meta.has("who") && meta.has("instant"); } }, YAML { @Override public String header() { return MediaType.APPLICATION_YAML_TYPE; } @Override @SuppressWarnings("unchecked") public boolean isAccepted(String s) { Yaml yaml = new Yaml(); LinkedHashMap<String, LinkedHashMap> ev = yaml.load(s); if (!(ev != null && ev.containsKey("log"))) return false; LinkedHashMap<String, LinkedHashMap> log = ev.get("log"); if (!(log.containsKey("content") && log.containsKey("meta") && log.containsKey("category"))) return false; LinkedHashMap<String, String> content = log.get("content"); LinkedHashMap<String, String> meta = log.get("meta"); return content.containsKey("level") && content.containsKey("message") && content.containsKey("detail") && meta.containsKey("context") && meta.containsKey("scope") && meta.containsKey("who") && meta.containsKey("instant"); } }, XML { @Override public String header() { return MediaType.APPLICATION_XML_TYPE; } @Override public boolean isAccepted(String content) { return content.startsWith("<?xml version=\"1.0\"?><log category=") && content.endsWith("</log>"); } }; public abstract String header(); public abstract boolean isAccepted(String content); } }
5,704
39.75
136
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/rest/RestOperations.java
package org.infinispan.server.functional.rest; import static org.infinispan.client.rest.RestResponse.NOT_FOUND; import static org.infinispan.client.rest.RestResponse.NO_CONTENT; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.rest.assertion.ResponseAssertion.assertThat; import static org.infinispan.server.test.core.Common.assertResponse; import static org.infinispan.server.test.core.Common.assertStatus; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.Closeable; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestCounterClient; import org.infinispan.client.rest.RestEntity; import org.infinispan.client.rest.RestTaskClient.ResultType; import org.infinispan.client.rest.configuration.Protocol; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.configuration.AbstractCounterConfiguration; import org.infinispan.counter.configuration.ConvertUtil; import org.infinispan.rest.resources.AbstractRestResourceTest; import org.infinispan.rest.resources.WeakSSEListener; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class RestOperations { @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; @ParameterizedTest @EnumSource(Protocol.class) public void testRestOperations(Protocol protocol) { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.protocol(protocol); RestClient client = SERVERS.rest().withClientConfiguration(builder).create(); RestCacheClient cache = client.cache(SERVERS.getMethodName()); assertResponse(NO_CONTENT, cache.post("k1", "v1"), r -> assertEquals(protocol, r.getProtocol())); assertResponse(OK, cache.get("k1"), r -> { assertEquals(protocol, r.getProtocol()); assertEquals("v1", r.getBody()); }); assertResponse(NO_CONTENT, cache.remove("k1"), r -> assertEquals(protocol, r.getProtocol())); assertResponse(NOT_FOUND, cache.get("k1"), r -> assertEquals(protocol, r.getProtocol())); } @ParameterizedTest @EnumSource(Protocol.class) public void testPutWithTimeToLive(Protocol protocol) throws InterruptedException { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.protocol(protocol); RestClient client = SERVERS.rest().withClientConfiguration(builder).create(); RestCacheClient cache = client.cache(SERVERS.getMethodName()); assertStatus(NO_CONTENT, cache.post("k1", "v1", 1, 1)); assertStatus(OK, cache.get("k1")); Thread.sleep(2000); assertStatus(NOT_FOUND, cache.get("k1")); } @ParameterizedTest @EnumSource(Protocol.class) public void taskFilter(Protocol protocol) { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.protocol(protocol); RestClient client = SERVERS.rest().withClientConfiguration(builder).create(); List<Json> taskListNode = Json.read(assertStatus(OK, client.tasks().list(ResultType.USER))).asJsonList(); taskListNode.forEach(n -> assertFalse(n.at("name").asString().startsWith("@@"))); } @ParameterizedTest @EnumSource(Protocol.class) public void testCounter(Protocol protocol) { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.protocol(protocol); RestClient client = SERVERS.rest().withClientConfiguration(builder).create(); CounterConfiguration configuration = CounterConfiguration .builder(CounterType.WEAK) .initialValue(5) .concurrencyLevel(1) .build(); AbstractCounterConfiguration config = ConvertUtil.configToParsedConfig("test-counter", configuration); String configJson = AbstractRestResourceTest.counterConfigToJson(config); RestCounterClient counter = client.counter(SERVERS.getMethodName(protocol.name())); assertStatus(OK, counter.create(RestEntity.create(MediaType.APPLICATION_JSON, configJson))); assertEquals("5", assertStatus(OK, counter.get())); } @ParameterizedTest @EnumSource(Protocol.class) public void testSSECluster(Protocol protocol) throws Exception { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); builder.protocol(protocol); RestClient client = SERVERS.rest().withClientConfiguration(builder).create(); WeakSSEListener sseListener = new WeakSSEListener(); try (Closeable ignored = client.raw().listen("/rest/v2/container?action=listen", Collections.emptyMap(), sseListener)) { assertTrue(sseListener.await(10, TimeUnit.SECONDS)); assertThat(client.cache("caching-listen").createWithTemplate("org.infinispan.DIST_SYNC")).isOk(); sseListener.expectEvent("create-cache", "caching-listen"); sseListener.expectEvent("lifecycle-event", "ISPN100002"); sseListener.expectEvent("lifecycle-event", "ISPN100010"); assertThat(client.cache("caching-listen").delete()).isOk(); sseListener.expectEvent("remove-cache", "caching-listen"); } } }
6,017
44.590909
126
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/rest/RestRouter.java
package org.infinispan.server.functional.rest; import static org.infinispan.client.rest.RestResponse.NOT_FOUND; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.server.test.core.Common.assertStatus; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.function.Function; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @since 10.0 */ public class RestRouter { @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; @Test public void testRestRouting() throws IOException { Function<String, RestClient> client = c -> SERVERS.rest() .withClientConfiguration(new RestClientConfigurationBuilder().contextPath(c)) .get(); try (RestClient restCtx = client.apply("/rest"); RestClient invalidCtx = client.apply("/invalid"); RestClient emptyCtx = client.apply("/")) { String body = assertStatus(OK, restCtx.server().info()); assertTrue(body.contains("version"), body); assertStatus(NOT_FOUND, emptyCtx.server().info()); assertStatus(NOT_FOUND, invalidCtx.server().info()); } } }
1,518
32.755556
89
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/rest/RestMetricsResource.java
package org.infinispan.server.functional.rest; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.client.rest.RestResponse.NO_CONTENT; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.server.test.core.Common.assertStatus; import static org.infinispan.server.test.core.Common.sync; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestMetricsClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.prometheus.client.exporter.common.TextFormat; /** * Tests the Micrometer metrics exporter. * * @author anistor@redhat.com * @since 10.0 */ public class RestMetricsResource { @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; @Test public void testOpenMetrics() { RestMetricsClient metricsClient = SERVERS.rest().create().metrics(); String metricName = "cache_manager_default_cache_" + SERVERS.getMethodName() + "_statistics_stores"; try (RestResponse response = sync(metricsClient.metrics(true))) { assertEquals(200, response.getStatus()); checkIsOpenmetrics(response.contentType()); String metricsText = response.getBody(); assertTrue(metricsText.contains("# TYPE vendor_" + metricName + " gauge\n")); assertTrue(metricsText.contains("vendor_" + metricName + "{cache=\"" + SERVERS.getMethodName())); } } @Test public void testBaseAndVendorMetrics() throws Exception { RestMetricsClient metricsClient = SERVERS.rest().create().metrics(); try (RestResponse response = sync(metricsClient.metrics())) { assertEquals(200, response.getStatus()); checkIsPrometheus(response.contentType()); // that is the default String body = response.getBody(); checkRule(body, "base_classloader_loadedClasses_count", (stringValue) -> { double parsed = Double.parseDouble(stringValue); assertThat(parsed).isPositive(); }); checkRule(body, "vendor_memoryPool_Metaspace_usage_bytes", (stringValue) -> { double parsed = Double.parseDouble(stringValue); assertThat(parsed).isPositive(); }); } } @Test public void testMetrics() throws Exception { RestClient client = SERVERS.rest().create(); RestMetricsClient metricsClient = client.metrics(); String cacheName = SERVERS.getMethodName(); String metricName = String.format("cache_manager_default_cache_%s_statistics_stores{cache=\"%s\"", cacheName, cacheName); int NUM_PUTS = 10; try (RestResponse response = sync(metricsClient.metrics())) { assertEquals(200, response.getStatus()); checkIsPrometheus(response.contentType()); String body = response.getBody(); assertThat(body).contains("base", "vendor", metricName); checkRule(body, "vendor_" + metricName, (stringValue) -> { double parsed = Double.parseDouble(stringValue); assertThat(parsed).isZero(); }); } // put some entries then check that the stats were updated RestCacheClient cache = client.cache(SERVERS.getMethodName()); for (int i = 0; i < NUM_PUTS; i++) { assertStatus(NO_CONTENT, cache.put("k" + i, "v" + i)); } try (RestResponse response = sync(metricsClient.metrics())) { assertEquals(200, response.getStatus()); checkIsPrometheus(response.contentType()); String body = response.getBody(); assertThat(body).contains("base", "vendor", metricName); checkRule(body, "vendor_" + metricName, (stringValue) -> { double parsed = Double.parseDouble(stringValue); assertThat(parsed).isEqualTo(10.0); }); } // delete cache and check that the metric is gone assertStatus(OK, client.cache(SERVERS.getMethodName()).delete()); try (RestResponse response = sync(metricsClient.metrics())) { assertEquals(200, response.getStatus()); checkIsPrometheus(response.contentType()); String body = response.getBody(); assertThat(body).contains("base", "vendor"); // metric is not present anymore: assertThat(body).doesNotContain(metricName); } } @Test public void testTimerMetrics() throws Exception { RestClient client = SERVERS.rest().create(); RestMetricsClient metricsClient = client.metrics(); // this is a histogram of write times String metricName = "cache_manager_default_cache_" + SERVERS.getMethodName() + "_statistics_store_times"; int NUM_PUTS = 10; try (RestResponse response = sync(metricsClient.metrics())) { assertEquals(200, response.getStatus()); checkIsPrometheus(response.contentType()); String body = response.getBody(); assertThat(body).contains("base", "vendor", metricName); checkRule(body, "vendor_" + metricName, (stringValue) -> { double parsed = Double.parseDouble(stringValue); assertThat(parsed).isZero(); }); } // put some entries then check that the stats were updated RestCacheClient cache = client.cache(SERVERS.getMethodName()); for (int i = 0; i < NUM_PUTS; i++) { assertStatus(NO_CONTENT, cache.put("k" + i, "v" + i)); } try (RestResponse response = sync(metricsClient.metrics())) { assertEquals(200, response.getStatus()); checkIsPrometheus(response.contentType()); String body = response.getBody(); assertThat(body).contains("base", "vendor", metricName); checkRule(body, "vendor_" + metricName, (stringValue) -> { double parsed = Double.parseDouble(stringValue); assertThat(parsed).isPositive(); }); } } @Test public void testMetricsMetadata() throws Exception { RestClient client = SERVERS.rest().create(); RestMetricsClient metricsClient = client.metrics(); String cacheName = SERVERS.getMethodName(); String metricName = String.format("cache_manager_default_cache_%s_statistics_stores{cache=\"%s\"", cacheName, cacheName); try (RestResponse response = sync(metricsClient.metricsMetadata())) { assertEquals(200, response.getStatus()); checkIsPrometheus(response.contentType()); String body = response.getBody(); assertThat(body).contains("base", "vendor", metricName); checkRule(body, "vendor_" + metricName, (stringValue) -> { double parsed = Double.parseDouble(stringValue); assertThat(parsed).isZero(); }); } // delete cache and check that the metric is gone assertStatus(OK, client.cache(SERVERS.getMethodName()).delete()); try (RestResponse response = sync(metricsClient.metricsMetadata())) { assertEquals(200, response.getStatus()); checkIsPrometheus(response.contentType()); String body = response.getBody(); assertThat(body).contains("base", "vendor"); // metric is not present anymore: assertThat(body).doesNotContain(metricName); } } @Test public void testJGroupsMetrics() throws IOException, URISyntaxException { try (RestClient client = SERVERS.rest().create()) { RestMetricsClient metricsClient = client.metrics(); try (RestResponse response = sync(metricsClient.metricsMetadata())) { assertEquals(200, response.getStatus()); checkIsPrometheus(response.contentType()); String body = response.getBody(); assertThat(body).contains(Files.readAllLines(Path.of(Thread.currentThread().getContextClassLoader().getResource("jgroups_metrics.txt").toURI()))); } } } /** * Stream over the fields of a given JsonNode. */ private static Stream<Map.Entry<String, Json>> streamNodeFields(Json node) { if (node == null) { throw new IllegalArgumentException("Input node cannot be null"); } return StreamSupport.stream(Spliterators.spliteratorUnknownSize(node.asJsonMap().entrySet().iterator(), Spliterator.IMMUTABLE), false); } public static void checkIsPrometheus(MediaType contentType) { String[] expectedContentType = TextFormat.CONTENT_TYPE_004.split(";"); String[] actualContentType = contentType.toString().split(";"); assertThat(actualContentType).containsExactlyInAnyOrder(expectedContentType); } public static void checkIsOpenmetrics(MediaType contentType) { String[] expectedContentType = TextFormat.CONTENT_TYPE_OPENMETRICS_100.split(";"); String[] actualContentType = contentType.toString().split(";"); assertThat(actualContentType).containsExactlyInAnyOrder(expectedContentType); } public static void checkRule(String body, String key, Consumer<String> check) throws Exception { BufferedReader bufferedReader = new BufferedReader(new StringReader(body)); String line; while ((line = bufferedReader.readLine()) != null) { if (line.startsWith(key)) { String[] split = line.split(" "); assertThat(split).hasSize(2); check.accept(split[1]); return; } } fail("Key " + key + " not found in body"); } }
10,340
36.740876
158
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/rest/RestLoggingResource.java
package org.infinispan.server.functional.rest; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.server.test.core.Common.assertStatus; import static org.infinispan.server.test.core.Common.sync; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @since 11.0 */ public class RestLoggingResource { @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; @Test public void testListLoggers() { RestClient client = SERVERS.rest().create(); Json loggers = Json.read(assertStatus(OK, client.server().logging().listLoggers())); assertTrue(loggers.asJsonList().size() > 0); } @Test public void testListAppenders() { RestClient client = SERVERS.rest().create(); String body = assertStatus(OK, client.server().logging().listAppenders()); Json appenders = Json.read(body); assertEquals(5, appenders.asMap().size(), body); } @Test public void testManipulateLogger() { RestClient client = SERVERS.rest().create(); // Create the logger assertStatus(204, client.server().logging().setLogger("org.infinispan.TESTLOGGER", "WARN", "STDOUT")); try (RestResponse response = sync(client.server().logging().listLoggers())) { assertTrue(findLogger(response, "org.infinispan.TESTLOGGER", "WARN", "STDOUT"), "Logger not found"); } // Update it assertStatus(204, client.server().logging().setLogger("org.infinispan.TESTLOGGER", "ERROR", "FILE")); try (RestResponse response = sync(client.server().logging().listLoggers())) { assertTrue(findLogger(response, "org.infinispan.TESTLOGGER", "ERROR", "FILE"), "Logger not found"); } // Remove it assertStatus(204, client.server().logging().removeLogger("org.infinispan.TESTLOGGER")); try (RestResponse response = sync(client.server().logging().listLoggers())) { assertFalse(findLogger(response, "org.infinispan.TESTLOGGER", "ERROR"), "Logger should not be found"); } } private boolean findLogger(RestResponse response, String name, String level, String... appenders) { Json loggers = Json.read(response.getBody()); for (int i = 0; i < loggers.asJsonList().size(); i++) { Json logger = loggers.at(i); if (name.equals(logger.at("name").asString())) { assertEquals(level, logger.at("level").asString()); List<Json> loggerAppenders = logger.at("appenders").asJsonList(); assertEquals(appenders.length, loggerAppenders.size()); for (int j = 0; j < appenders.length; j++) { assertEquals(appenders[j], loggerAppenders.get(j).asString()); } return true; } } return false; } }
3,318
39.47561
111
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/rest/XSiteRestMetricsOperations.java
package org.infinispan.server.functional.rest; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.server.test.core.Common.sync; import static org.infinispan.server.test.core.InfinispanServerTestConfiguration.LON; import static org.infinispan.server.test.core.InfinispanServerTestConfiguration.NYC; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestMetricsClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.commons.configuration.StringConfiguration; import org.infinispan.server.functional.XSiteIT; import org.infinispan.server.test.junit5.InfinispanXSiteServerExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * Test site status metrics * * @since 14.0 */ public class XSiteRestMetricsOperations { private static final String LON_CACHE_XML_CONFIG = "<infinispan><cache-container>" + " <replicated-cache name=\"%s\" statistics=\"true\">" + " <backups>" + " <backup site=\"" + NYC + "\" strategy=\"ASYNC\"/>" + " </backups>" + " </replicated-cache>" + "</cache-container></infinispan>"; private static final String NYC_CACHE_XML_CONFIG = "<infinispan><cache-container>" + " <replicated-cache name=\"%s\" statistics=\"true\">" + " <backups>" + " <backup site=\"" + LON + "\" strategy=\"ASYNC\"/>" + " </backups>" + " </replicated-cache>" + "</cache-container></infinispan>"; @RegisterExtension public static final InfinispanXSiteServerExtension SERVERS = XSiteIT.SERVERS; @Test public void testSiteStatus() throws Exception { String lonXML = String.format(LON_CACHE_XML_CONFIG, SERVERS.getMethodName()); String nycXML = String.format(NYC_CACHE_XML_CONFIG, SERVERS.getMethodName()); RestClient client = SERVERS.rest(LON).withServerConfiguration(new StringConfiguration(lonXML)).create(); RestMetricsClient metricsClient = client.metrics(); // create cache in NYC SERVERS.rest(NYC).withServerConfiguration(new StringConfiguration(nycXML)).create(); String statusMetricName = "cache_manager_default_cache_" + SERVERS.getMethodName() + "_x_site_admin_nyc_status"; try (RestResponse response = sync(metricsClient.metrics(true))) { assertEquals(200, response.getStatus()); RestMetricsResource.checkIsOpenmetrics(response.contentType()); assertTrue(response.getBody().contains("# TYPE vendor_" + statusMetricName + " gauge\n")); } assertSiteStatusMetrics(metricsClient, statusMetricName, 1); try (RestResponse response = sync(client.cacheManager("default").takeOffline(NYC))) { assertEquals(200, response.getStatus()); } assertSiteStatusMetrics(metricsClient, statusMetricName, 0); } private static void assertSiteStatusMetrics(RestMetricsClient client, String metric, int expected) throws Exception { try (RestResponse response = sync(client.metrics())) { assertEquals(OK, response.getStatus()); RestMetricsResource.checkIsPrometheus(response.contentType()); RestMetricsResource.checkRule(response.getBody(), "vendor_" + metric, (stringValue) -> { int parsed = (int) Double.parseDouble(stringValue); assertThat(parsed).isEqualTo(expected); }); } } }
3,739
41.5
120
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/DistributedHelloServerTask.java
package org.infinispan.server.functional.extensions; import java.util.ArrayList; import java.util.Collection; import javax.security.auth.Subject; import org.infinispan.remoting.transport.Address; import org.infinispan.security.Security; import org.infinispan.tasks.ServerTask; import org.infinispan.tasks.TaskContext; import org.infinispan.tasks.TaskExecutionMode; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ public class DistributedHelloServerTask implements ServerTask<Object> { private TaskContext taskContext; @Override public void setTaskContext(TaskContext taskContext) { this.taskContext = taskContext; } @Override public Object call() { Address address = taskContext.getCacheManager().getAddress(); Object greetee = taskContext.getParameters().get().get("greetee"); if (greetee == null) { if (taskContext.getSubject().isPresent()) { Subject subject = Security.getSubject(); greetee = subject.getPrincipals().iterator().next().getName(); if (!greetee.equals(Security.getSubject().getPrincipals().iterator().next().getName())) { throw new RuntimeException("Subjects do not match"); } } else { greetee = "world"; } } // if we're dealing with a Collections of greetees we'll greet them individually if (greetee instanceof Collection) { ArrayList<String> messages = new ArrayList<>(); for (Object o : (Collection<?>) greetee) { messages.add(greet(o, address)); } return messages; } return greet(greetee, address); } private String greet(Object greetee, Address address) { return String.format("Hello %s from %s", greetee, address); } @Override public TaskExecutionMode getExecutionMode() { return TaskExecutionMode.ALL_NODES; } @Override public String getName() { return "dist-hello"; } }
2,009
28.130435
101
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/ScriptingTasks.java
package org.infinispan.server.functional.extensions; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_SERIALIZED_OBJECT_TYPE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class ScriptingTasks { @RegisterExtension public static final InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; @Test public void testSimpleScript() { RemoteCache<String, String> cache = SERVERS.hotrod().create(); String scriptName = SERVERS.addScript(cache.getRemoteCacheManager(), "scripts/test.js"); cache.put("keyA", "A"); cache.put("keyB", "B"); Map<String, Object> parameters = new HashMap<>(); parameters.put("key", "keyC"); parameters.put("value", "C"); int result = cache.execute(scriptName, parameters); assertEquals(3, result); } @Test public void testStreamingScript() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addJavaSerialAllowList(HashMap.class.getName()); org.infinispan.configuration.cache.ConfigurationBuilder cacheBuilder = new org.infinispan.configuration.cache.ConfigurationBuilder(); cacheBuilder.clustering().cacheMode(CacheMode.DIST_SYNC) .encoding().key().mediaType(APPLICATION_SERIALIZED_OBJECT_TYPE) .encoding().value().mediaType(APPLICATION_SERIALIZED_OBJECT_TYPE); RemoteCache<String, String> cache = SERVERS.hotrod() .withClientConfiguration(builder) .withMarshaller(JavaSerializationMarshaller.class) .withServerConfiguration(cacheBuilder) .create(); String scriptName = SERVERS.addScript(cache.getRemoteCacheManager(), "scripts/stream.js"); cache.put("key1", "Lorem ipsum dolor sit amet"); cache.put("key2", "consectetur adipiscing elit"); cache.put("key3", "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"); Map<String, Long> result = cache.execute(scriptName, Collections.emptyMap()); assertEquals(19, result.size()); } @Test public void testProtoStreamMarshaller() { RemoteCache<String, String> cache = SERVERS.hotrod().withMarshaller(ProtoStreamMarshaller.class).create(); List<String> greetings = cache.execute("dist-hello", Collections.singletonMap("greetee", "my friend")); assertEquals(2, greetings.size()); for(String greeting : greetings) { assertTrue(greeting.matches("Hello my friend .*")); } } }
3,251
39.148148
139
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/Person.java
package org.infinispan.server.functional.extensions; import java.io.Serializable; import java.util.Objects; public class Person implements Serializable { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return age == person.age && Objects.equals(name, person.name); } @Override public int hashCode() { return Objects.hash(name, age); } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
1,035
18.185185
71
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/SharedTask.java
package org.infinispan.server.functional.extensions; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.tasks.ServerTask; import org.infinispan.tasks.TaskContext; import org.infinispan.tasks.TaskInstantiationMode; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 14.0 **/ public class SharedTask implements ServerTask<Integer> { private final AtomicInteger invocationCount = new AtomicInteger(0); @Override public void setTaskContext(TaskContext taskContext) { // do nothing } @Override public TaskInstantiationMode getInstantiationMode() { return TaskInstantiationMode.SHARED; } @Override public Integer call() { return invocationCount.addAndGet(1); } @Override public String getName() { return "shared"; } }
825
21.944444
70
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/ServerTasks.java
package org.infinispan.server.functional.extensions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.jboss.marshalling.commons.GenericJBossMarshaller; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class ServerTasks { @RegisterExtension public static final InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; @Test public void testServerTaskNoParameters() { RemoteCache<String, String> cache = SERVERS.hotrod().create(); Object hello = cache.execute("hello"); assertEquals("Hello world", hello); } @Test public void testServerTaskWithParameters() { RemoteCache<String, String> cache = SERVERS.hotrod().create(); ArrayList<String> messages = cache.execute("hello", Collections.singletonMap("greetee", new ArrayList<>(Arrays.asList("nurse", "kitty")))); assertEquals(2, messages.size()); assertEquals("Hello nurse", messages.get(0)); assertEquals("Hello kitty", messages.get(1)); } @Test public void testDistributedServerTaskWithParameters() { // We must utilise the GenericJBossMarshaller due to ISPN-8814 RemoteCache<String, String> cache = SERVERS.hotrod().withMarshaller(GenericJBossMarshaller.class).create(); List<String> greetings = cache.execute("dist-hello", Collections.singletonMap("greetee", "my friend")); assertEquals(2, greetings.size()); for(String greeting : greetings) { assertTrue(greeting.matches("Hello my friend .*")); } } @Test public void testIsolatedTask() { RemoteCache<String, String> cache = SERVERS.hotrod().create(); Integer i = cache.execute("isolated"); assertEquals(1, i.intValue()); i = cache.execute("isolated"); assertEquals(1, i.intValue()); } @Test public void testSharedTask() { RemoteCache<String, String> cache = SERVERS.hotrod().create(); Integer i = cache.execute("shared", Collections.emptyMap(), "k"); assertEquals(1, i.intValue()); i = cache.execute("shared", Collections.emptyMap(), "k"); assertEquals(2, i.intValue()); } }
2,593
35.027778
145
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/IsolatedTask.java
package org.infinispan.server.functional.extensions; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.tasks.ServerTask; import org.infinispan.tasks.TaskContext; import org.infinispan.tasks.TaskInstantiationMode; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 14.0 **/ public class IsolatedTask implements ServerTask<Integer> { private final AtomicInteger invocationCount = new AtomicInteger(0); @Override public void setTaskContext(TaskContext taskContext) { // do nothing } @Override public TaskInstantiationMode getInstantiationMode() { return TaskInstantiationMode.ISOLATED; } @Override public Integer call() { return invocationCount.addAndGet(1); } @Override public String getName() { return "isolated"; } }
831
22.111111
70
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/HelloServerTask.java
package org.infinispan.server.functional.extensions; import java.util.ArrayList; import java.util.Collection; import javax.security.auth.Subject; import org.infinispan.security.Security; import org.infinispan.tasks.ServerTask; import org.infinispan.tasks.TaskContext; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class HelloServerTask implements ServerTask<Object> { private static final ThreadLocal<TaskContext> taskContext = new ThreadLocal<>(); @Override public void setTaskContext(TaskContext ctx) { taskContext.set(ctx); } @Override public Object call() { TaskContext ctx = taskContext.get(); Object greetee = ctx.getParameters().get().get("greetee"); if (greetee == null) { if (ctx.getSubject().isPresent()) { Subject subject = ctx.getSubject().get(); greetee = subject.getPrincipals().iterator().next().getName(); if (!greetee.equals(Security.getSubject().getPrincipals().iterator().next().getName())) { throw new RuntimeException("Subjects do not match"); } } else { greetee = "world"; } } // if we're dealing with a Collections of greetees we'll greet them individually if (greetee instanceof Collection) { ArrayList<String> messages = new ArrayList<>(); for (Object o : (Collection<?>) greetee) { messages.add(greet(o)); } return messages; } return greet(greetee); } private String greet(Object greetee) { return "Hello " + greetee; } @Override public String getName() { return "hello"; } }
1,709
26.142857
101
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/PojoMarshalling.java
package org.infinispan.server.functional.extensions; import static org.junit.jupiter.api.Assertions.assertEquals; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.1 **/ public class PojoMarshalling { @RegisterExtension public static final InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; @Test public void testPojoMarshalling() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addJavaSerialAllowList(".*"); org.infinispan.configuration.cache.ConfigurationBuilder cacheBuilder = new org.infinispan.configuration.cache.ConfigurationBuilder(); // If you use JavaSerializationMarshaller or GenericJBossMarshaller you should encode caches with the application/x-java-serialized-object or application/x-jboss-marshalling media type, respectively. cacheBuilder.encoding().key().mediaType(MediaType.APPLICATION_SERIALIZED_OBJECT_TYPE); cacheBuilder.encoding().value().mediaType(MediaType.APPLICATION_SERIALIZED_OBJECT_TYPE); cacheBuilder.clustering().cacheMode(CacheMode.DIST_SYNC); RemoteCache<String, Person> cache = SERVERS.hotrod().withServerConfiguration(cacheBuilder).withClientConfiguration(builder).withMarshaller(JavaSerializationMarshaller.class).create(); cache.put("123", new Person("Enrique", 29)); Person person = cache.get("123"); assertEquals("Enrique", person.getName()); assertEquals(29, person.getAge()); } }
1,979
48.5
205
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/filters/RawStaticCacheEventFilterFactory.java
package org.infinispan.server.functional.extensions.filters; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; import org.infinispan.filter.NamedFactory; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.filter.CacheEventFilter; import org.infinispan.notifications.cachelistener.filter.CacheEventFilterFactory; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.protostream.ProtobufUtil; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoName; @NamedFactory(name = "raw-static-filter-factory") public class RawStaticCacheEventFilterFactory implements CacheEventFilterFactory { @Override public CacheEventFilter<byte[], byte[]> getFilter(Object[] params) { try { // Static key is 2 marshalled byte[] staticKey = ProtobufUtil.toWrappedByteArray(ProtobufUtil.newSerializationContext(), 2); return new RawStaticCacheEventFilter(staticKey); } catch (IOException e) { throw new IllegalStateException(e); } } @ProtoName("RawStaticCacheEventFilter") public static class RawStaticCacheEventFilter implements CacheEventFilter<byte[], byte[]>, Serializable { @ProtoField(1) final byte[] staticKey; @ProtoFactory RawStaticCacheEventFilter(byte[] staticKey) { this.staticKey = staticKey; } @Override public boolean accept(byte[] key, byte[] previousValue, Metadata previousMetadata, byte[] value, Metadata metadata, EventType eventType) { return Arrays.equals(key, staticKey); } } }
1,774
35.979167
108
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/filters/DynamicConverterFactory.java
package org.infinispan.server.functional.extensions.filters; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.infinispan.filter.NamedFactory; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.filter.CacheEventConverter; import org.infinispan.notifications.cachelistener.filter.CacheEventConverterFactory; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.protostream.WrappedMessage; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.server.functional.extensions.entities.Entities; @NamedFactory(name = "dynamic-converter-factory") public class DynamicConverterFactory<K> implements CacheEventConverterFactory { @Override public CacheEventConverter<K, String, Entities.CustomEvent<K>> getConverter(final Object[] params) { return new DynamicConverter<>(params); } public static class DynamicConverter<K> implements CacheEventConverter<K, String, Entities.CustomEvent<K>>, Serializable { private final Object[] params; public DynamicConverter(Object[] params) { this.params = params; } @ProtoFactory DynamicConverter(ArrayList<WrappedMessage> wrappedParams) { this.params = wrappedParams == null ? null : wrappedParams.stream().map(WrappedMessage::getValue).toArray(); } @ProtoField(number = 1, collectionImplementation = ArrayList.class) List<WrappedMessage> getWrappedParams() { return Arrays.stream(params).map(WrappedMessage::new).collect(Collectors.toList()); } @Override public Entities.CustomEvent<K> convert(K key, String previousValue, Metadata previousMetadata, String value, Metadata metadata, EventType eventType) { if (params[0].equals(key)) return new Entities.CustomEvent<>(key, null, 0); return new Entities.CustomEvent<>(key, value, 0); } } }
2,136
39.320755
125
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/filters/RawStaticConverterFactory.java
package org.infinispan.server.functional.extensions.filters; import java.io.Serializable; import org.infinispan.commons.util.Util; import org.infinispan.filter.NamedFactory; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.filter.CacheEventConverter; import org.infinispan.notifications.cachelistener.filter.CacheEventConverterFactory; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.protostream.annotations.ProtoName; @NamedFactory(name = "raw-static-converter-factory") public class RawStaticConverterFactory implements CacheEventConverterFactory { @Override public CacheEventConverter<byte[], byte[], byte[]> getConverter(Object[] params) { return new RawStaticConverter(); } @ProtoName("RawStaticConverter") public static class RawStaticConverter implements CacheEventConverter<byte[], byte[], byte[]>, Serializable { @Override public byte[] convert(byte[] key, byte[] previousValue, Metadata previousMetadata, byte[] value, Metadata metadata, EventType eventType) { return value != null ? Util.concat(key, value) : key; } } }
1,198
40.344828
112
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/filters/FilterConverterFactory.java
package org.infinispan.server.functional.extensions.filters; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.infinispan.filter.NamedFactory; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.filter.AbstractCacheEventFilterConverter; import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverter; import org.infinispan.notifications.cachelistener.filter.CacheEventFilterConverterFactory; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.protostream.WrappedMessage; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.server.functional.extensions.entities.Entities; @NamedFactory(name = "filter-converter-factory") public class FilterConverterFactory implements CacheEventFilterConverterFactory { @Override public CacheEventFilterConverter<Integer, String, Entities.CustomEvent<Integer>> getFilterConverter(Object[] params) { return new FilterConverter(params); } public static class FilterConverter extends AbstractCacheEventFilterConverter<Integer, String, Entities.CustomEvent<Integer>> { private final Object[] params; @ProtoField(number = 1, defaultValue = "0") int count; FilterConverter(Object[] params) { this.params = params; this.count = 0; } @ProtoFactory FilterConverter(List<WrappedMessage> wrappedParams, int count) { this.params = wrappedParams == null ? null : wrappedParams.stream().map(WrappedMessage::getValue).toArray(); this.count = count; } @ProtoField(number = 2, collectionImplementation = ArrayList.class) List<WrappedMessage> getWrappedParams() { return Arrays.stream(params).map(WrappedMessage::new).collect(Collectors.toList()); } @Override public Entities.CustomEvent<Integer> filterAndConvert(Integer key, String oldValue, Metadata oldMetadata, String newValue, Metadata newMetadata, EventType eventType) { count++; if (params[0].equals(key)) return new Entities.CustomEvent<>(key, null, count); return new Entities.CustomEvent<>(key, newValue, count); } } }
2,341
39.37931
173
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/filters/StaticConverterFactory.java
package org.infinispan.server.functional.extensions.filters; import java.io.Serializable; import org.infinispan.filter.NamedFactory; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.filter.CacheEventConverter; import org.infinispan.notifications.cachelistener.filter.CacheEventConverterFactory; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.protostream.annotations.ProtoName; import org.infinispan.server.functional.extensions.entities.Entities; @NamedFactory(name = "static-converter-factory") public class StaticConverterFactory<K> implements CacheEventConverterFactory { @Override public CacheEventConverter<K, String, Entities.CustomEvent<K>> getConverter(Object[] params) { return new StaticConverter<>(); } @ProtoName("StaticConverter") public static class StaticConverter<K> implements CacheEventConverter<K, String, Entities.CustomEvent<K>>, Serializable { @Override public Entities.CustomEvent<K> convert(K key, String previousValue, Metadata previousMetadata, String value, Metadata metadata, EventType eventType) { return new Entities.CustomEvent<>(key, value, 0); } } }
1,268
42.758621
124
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/filters/SimpleConverterFactory.java
package org.infinispan.server.functional.extensions.filters; import java.io.Serializable; import org.infinispan.filter.NamedFactory; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.filter.CacheEventConverter; import org.infinispan.notifications.cachelistener.filter.CacheEventConverterFactory; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.protostream.annotations.ProtoName; import org.infinispan.server.functional.extensions.entities.Entities; @NamedFactory(name = "simple-converter-factory") public class SimpleConverterFactory<K> implements CacheEventConverterFactory { @Override @SuppressWarnings("unchecked") public CacheEventConverter<String, String, Entities.CustomEvent<String>> getConverter(Object[] params) { return new SimpleConverter(); } @ProtoName("SimpleConverter") public static class SimpleConverter<K> implements CacheEventConverter<K, String, String>, Serializable { @Override public String convert(K key, String oldValue, Metadata oldMetadata, String newValue, Metadata newMetadata, EventType eventType) { if (newValue != null) return newValue; return oldValue; } } }
1,242
40.433333
135
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/filters/StaticCacheEventFilterFactory.java
package org.infinispan.server.functional.extensions.filters; import java.io.Serializable; import org.infinispan.filter.NamedFactory; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.filter.CacheEventFilter; import org.infinispan.notifications.cachelistener.filter.CacheEventFilterFactory; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.protostream.WrappedMessage; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; @NamedFactory(name = "static-filter-factory") public class StaticCacheEventFilterFactory<K> implements CacheEventFilterFactory { @Override public CacheEventFilter<K, String> getFilter(Object[] params) { return new StaticCacheEventFilter<>((K) params[0]); } public static class StaticCacheEventFilter<K> implements CacheEventFilter<K, String>, Serializable { final K staticKey; StaticCacheEventFilter(K staticKey) { this.staticKey = staticKey; } @ProtoFactory StaticCacheEventFilter(WrappedMessage staticKey) { this.staticKey = (K) staticKey.getValue(); } @ProtoField(1) public WrappedMessage getStaticKey() { return new WrappedMessage(staticKey); } @Override public boolean accept(K key, String previousValue, Metadata previousMetadata, String value, Metadata metadata, EventType eventType) { return staticKey.equals(key); } } }
1,562
32.978261
103
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/filters/DynamicCacheEventFilterFactory.java
package org.infinispan.server.functional.extensions.filters; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.infinispan.filter.NamedFactory; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.cachelistener.filter.CacheEventFilter; import org.infinispan.notifications.cachelistener.filter.CacheEventFilterFactory; import org.infinispan.notifications.cachelistener.filter.EventType; import org.infinispan.protostream.WrappedMessage; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; @NamedFactory(name = "dynamic-filter-factory") public class DynamicCacheEventFilterFactory implements CacheEventFilterFactory { @Override public CacheEventFilter<Integer, String> getFilter(Object[] params) { return new DynamicCacheEventFilter(params); } public static class DynamicCacheEventFilter implements CacheEventFilter<Integer, String>, Serializable { private final Object[] params; public DynamicCacheEventFilter(Object[] params) { this.params = params; } @ProtoFactory DynamicCacheEventFilter(ArrayList<WrappedMessage> wrappedParams) { this.params = wrappedParams == null ? null : wrappedParams.stream().map(WrappedMessage::getValue).toArray(); } @ProtoField(number = 1, collectionImplementation = ArrayList.class) List<WrappedMessage> getWrappedParams() { return Arrays.stream(params).map(WrappedMessage::new).collect(Collectors.toList()); } @Override public boolean accept(Integer key, String previousValue, Metadata previousMetadata, String value, Metadata metadata, EventType eventType) { return params[0].equals(key); // dynamic } } }
1,893
37.653061
117
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/extensions/entities/Entities.java
package org.infinispan.server.functional.extensions.entities; import java.util.Objects; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.WrappedMessage; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.server.functional.extensions.filters.DynamicCacheEventFilterFactory; import org.infinispan.server.functional.extensions.filters.DynamicConverterFactory; import org.infinispan.server.functional.extensions.filters.FilterConverterFactory; import org.infinispan.server.functional.extensions.filters.RawStaticCacheEventFilterFactory; import org.infinispan.server.functional.extensions.filters.RawStaticConverterFactory; import org.infinispan.server.functional.extensions.filters.SimpleConverterFactory; import org.infinispan.server.functional.extensions.filters.StaticCacheEventFilterFactory; import org.infinispan.server.functional.extensions.filters.StaticConverterFactory; @AutoProtoSchemaBuilder( includeClasses = { Entities.CustomEvent.class, Entities.CustomKey.class, Entities.Person.class, DynamicCacheEventFilterFactory.DynamicCacheEventFilter.class, RawStaticCacheEventFilterFactory.RawStaticCacheEventFilter.class, StaticCacheEventFilterFactory.StaticCacheEventFilter.class, DynamicConverterFactory.DynamicConverter.class, FilterConverterFactory.FilterConverter.class, RawStaticConverterFactory.RawStaticConverter.class, SimpleConverterFactory.SimpleConverter.class, StaticConverterFactory.StaticConverter.class } ) public interface Entities extends GeneratedSchema { Entities INSTANCE = new EntitiesImpl(); /** * This class is annotated with the infinispan Protostream support annotations. With this method, you don't need to * define a protobuf file and a marshaller for the object. */ final class Person { @ProtoField(number = 1) String firstName; @ProtoField(number = 2) String lastName; @ProtoField(number = 3, defaultValue = "-1") int bornYear; @ProtoField(number = 4) String bornIn; @ProtoFactory public Person(String firstName, String lastName, int bornYear, String bornIn) { this.firstName = firstName; this.lastName = lastName; this.bornYear = bornYear; this.bornIn = bornIn; } @Override public String toString() { return "Person{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", bornYear='" + bornYear + '\'' + ", bornIn='" + bornIn + '\'' + '}'; } } final class CustomKey { @ProtoField(number = 1, defaultValue = "0") final int id; @ProtoFactory public CustomKey(int id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomKey customKey = (CustomKey) o; return id == customKey.id; } @Override public int hashCode() { return id; } } final class CustomEvent<K> { @ProtoField(1) final WrappedMessage key; @ProtoField(2) final String value; @ProtoField(number = 3, defaultValue = "-1") final long timestamp; @ProtoField(number = 4, defaultValue = "0") final int counter; public CustomEvent(K key, String value, int counter) { this(new WrappedMessage(key), value, System.nanoTime(), counter); } @ProtoFactory CustomEvent(WrappedMessage key, String value, long timestamp, int counter) { this.key = key; this.value = value; this.timestamp = timestamp; this.counter = counter; } public WrappedMessage getKey() { return key; } public String getValue() { return value; } public long getTimestamp() { return timestamp; } public int getCounter() { return counter; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomEvent<?> that = (CustomEvent<?>) o; if (counter != that.counter) return false; if (!key.getValue().equals(that.key.getValue())) return false; return Objects.equals(value, that.value); } @Override public int hashCode() { int result = key.getValue().hashCode(); result = 31 * result + (value != null ? value.hashCode() : 0); result = 31 * result + counter; return result; } @Override public String toString() { return "CustomEvent{" + "key=" + key.getValue() + ", value='" + value + '\'' + ", timestamp=" + timestamp + ", counter=" + counter + '}'; } } }
5,258
30.118343
118
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/hotrod/IgnoreCaches.java
package org.infinispan.server.functional.hotrod; import static java.util.Collections.singleton; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME; import static org.infinispan.rest.helper.RestResponses.assertStatus; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.rest.helper.RestResponses; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @since 10.0 */ public class IgnoreCaches { @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; private static final String CACHE_MANAGER = "default"; @Test public void testIgnoreCaches() { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); RestClient client = SERVERS.rest().withClientConfiguration(builder).create(); String testCache = SERVERS.getMethodName(); assertTrue(getIgnoredCaches(client, CACHE_MANAGER).isEmpty()); assertCacheResponse(client, testCache, 404); assertCacheResponse(client, PROTOBUF_METADATA_CACHE_NAME, 404); ignoreCache(client, testCache); assertEquals(singleton(testCache), getIgnoredCaches(client, CACHE_MANAGER)); assertCacheResponse(client, testCache, 503); assertCacheResponse(client, PROTOBUF_METADATA_CACHE_NAME, 404); ignoreCache(client, PROTOBUF_METADATA_CACHE_NAME); assertEquals(asSet(testCache, PROTOBUF_METADATA_CACHE_NAME), getIgnoredCaches(client, CACHE_MANAGER)); assertCacheResponse(client, testCache, 503); assertCacheResponse(client, PROTOBUF_METADATA_CACHE_NAME, 503); unIgnoreCache(client, testCache); assertEquals(singleton(PROTOBUF_METADATA_CACHE_NAME), getIgnoredCaches(client, CACHE_MANAGER)); assertCacheResponse(client, testCache, 404); assertCacheResponse(client, PROTOBUF_METADATA_CACHE_NAME, 503); unIgnoreCache(client, PROTOBUF_METADATA_CACHE_NAME); assertTrue(getIgnoredCaches(client, CACHE_MANAGER).isEmpty()); assertCacheResponse(client, testCache, 404); assertCacheResponse(client, PROTOBUF_METADATA_CACHE_NAME, 404); } private Set<String> asSet(String... elements) { return Arrays.stream(elements).collect(Collectors.toSet()); } private void assertCacheResponse(RestClient client, String cacheName, int code) { assertStatus(code, client.cache(cacheName).get("whatever")); } private void unIgnoreCache(RestClient client, String cacheName) { assertStatus(204, client.server().unIgnoreCache(CACHE_MANAGER, cacheName)); } private void ignoreCache(RestClient client, String cacheName) { assertStatus(204, client.server().ignoreCache(CACHE_MANAGER, cacheName)); } private Set<String> getIgnoredCaches(RestClient client, String cacheManagerName) { Json body = RestResponses.jsonResponseBody(client.server().listIgnoredCaches(cacheManagerName)); return body.asJsonList().stream().map(Json::asString).collect(Collectors.toSet()); } }
3,523
40.952381
111
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/hotrod/HotRodCacheOperations.java
package org.infinispan.server.functional.hotrod; import static org.infinispan.commons.test.Exceptions.expectException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; import java.util.stream.Stream; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.ProtocolVersion; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.VersionedValue; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.exceptions.TransportException; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class HotRodCacheOperations<K, V> { private static final String TEST_OUTPUT = "{0}-{1}"; @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; static class ArgsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { return Arrays.stream(ProtocolVersion.values()) .flatMap(version -> Stream.of( Arguments.of(version, KeyValueGenerator.STRING_GENERATOR), Arguments.of(version, KeyValueGenerator.BYTE_ARRAY_GENERATOR), Arguments.of(version, KeyValueGenerator.GENERIC_ARRAY_GENERATOR) ) ); } } private RemoteCache<K, V> remoteCache(ProtocolVersion protocolVersion, boolean frv) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.version(protocolVersion).forceReturnValues(frv); return SERVERS.hotrod().withClientConfiguration(builder).withCacheMode(CacheMode.DIST_SYNC).create(); } private RemoteCache<K, V> remoteCache(ProtocolVersion protocolVersion) { return remoteCache(protocolVersion, false); } @ParameterizedTest(name = TEST_OUTPUT) @ArgumentsSource(ArgsProvider.class) public void testCompute(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) { RemoteCache<K, V> cache = remoteCache(protocolVersion); final K key = generator.key(0); final V value = generator.value(0); BiFunction<K, V, V> sameValueFunction = (k, v) -> v; cache.put(key, value); generator.assertEquals(value, cache.compute(key, sameValueFunction)); generator.assertEquals(value, cache.get(key)); final V value1 = generator.value(1); BiFunction<K, V, V> differentValueFunction = (k, v) -> value1; generator.assertEquals(value1, cache.compute(key, differentValueFunction)); generator.assertEquals(value1, cache.get(key)); final K notPresentKey = generator.key(1); generator.assertEquals(value1, cache.compute(notPresentKey, differentValueFunction)); generator.assertEquals(value1, cache.get(notPresentKey)); BiFunction<K, V, V> mappingToNull = (k, v) -> null; assertNull(cache.compute(key, mappingToNull), "mapping to null returns null"); assertNull(cache.get(key), "the key is removed"); int cacheSizeBeforeNullValueCompute = cache.size(); K nonExistantKey = generator.key(3); assertNull(cache.compute(nonExistantKey, mappingToNull), "mapping to null returns null"); assertNull(cache.get(nonExistantKey), "the key does not exist"); assertEquals(cacheSizeBeforeNullValueCompute, cache.size()); RuntimeException computeRaisedException = new RuntimeException("hi there"); BiFunction<Object, Object, V> mappingToException = (k, v) -> { throw computeRaisedException; }; expectException(TransportException.class, RuntimeException.class, "hi there", () -> cache.compute(key, mappingToException)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testComputeIfAbsentMethods(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) { RemoteCache<K, V> cache = remoteCache(protocolVersion); final K targetKey = generator.key(0); V value = generator.value(1); assertNull(cache.computeIfAbsent(targetKey, ignore -> null)); // Exception are only thrown when value not exists. expectException(TransportException.class, RuntimeException.class, "expected exception", () -> cache.computeIfAbsent(targetKey, ignore -> { throw new RuntimeException("expected exception"); })); generator.assertEquals(value, cache.computeIfAbsent(targetKey, ignore -> value)); generator.assertEquals(value, cache.get(targetKey)); generator.assertEquals(value, cache.computeIfAbsent(targetKey, ignore -> generator.value(2))); generator.assertEquals(value, cache.get(targetKey)); K anotherKey = generator.key(1); V anotherValue = generator.value(3); generator.assertEquals(anotherValue, cache.computeIfAbsent(anotherKey, ignore -> anotherValue, 1, TimeUnit.MINUTES, 3, TimeUnit.MINUTES)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testComputeIfPresentMethods(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) { RemoteCache<K, V> cache = remoteCache(protocolVersion); final K targetKey = generator.key(0); V value = generator.value(0); assertNull(cache.computeIfPresent(targetKey, (k, v) -> value)); assertNull(cache.get(targetKey)); assertNull(cache.put(targetKey, value)); generator.assertEquals(value, cache.get(targetKey)); V anotherValue = generator.value(1); generator.assertEquals(anotherValue, cache.computeIfPresent(targetKey, (k, v) -> anotherValue)); generator.assertEquals(anotherValue, cache.get(targetKey)); // Exception are only thrown if a value exists. expectException(TransportException.class, RuntimeException.class, "expected exception", () -> cache.computeIfPresent(targetKey, (k, v) -> { throw new RuntimeException("expected exception"); })); int beforeSize = cache.size(); assertNull(cache.computeIfPresent(targetKey, (k, v) -> null)); assertNull(cache.get(targetKey)); assertEquals(beforeSize - 1, cache.size()); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testMergeMethods(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) { RemoteCache<K, V> cache = remoteCache(protocolVersion); final K targetKey = generator.key(0); V targetValue = generator.value(0); BiFunction<? super V, ? super V, ? extends V> remappingFunction = (value1, value2) -> generator.value(2); Exceptions.expectException(UnsupportedOperationException.class, () -> cache.merge(targetKey, targetValue, remappingFunction)); Exceptions.expectException(UnsupportedOperationException.class, () -> cache.merge(targetKey, targetValue, remappingFunction, 1, TimeUnit.SECONDS)); Exceptions.expectException(UnsupportedOperationException.class, () -> cache.merge(targetKey, targetValue, remappingFunction, 1, TimeUnit.SECONDS, 10, TimeUnit.SECONDS)); Exceptions.expectException(UnsupportedOperationException.class, () -> cache.mergeAsync(targetKey, targetValue, remappingFunction)); Exceptions.expectException(UnsupportedOperationException.class, () -> cache.mergeAsync(targetKey, targetValue, remappingFunction, 1, TimeUnit.SECONDS)); Exceptions.expectException(UnsupportedOperationException.class, () -> cache.mergeAsync(targetKey, targetValue, remappingFunction, 1, TimeUnit.SECONDS, 10, TimeUnit.SECONDS)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testPut(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) { RemoteCache<K, V> cache = remoteCache(protocolVersion); final K targetKey = generator.key(0); V targetValue = generator.value(0); assertNull(cache.put(targetKey, targetValue)); generator.assertEquals(targetValue, cache.withFlags(Flag.FORCE_RETURN_VALUE).put(targetKey, generator.value(2))); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testPutIfAbsent(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) { RemoteCache<K, V> cache = remoteCache(protocolVersion); final K targetKey = generator.key(0); V targetValue = generator.value(0); assertNull(cache.putIfAbsent(targetKey, targetValue)); generator.assertEquals(targetValue, cache.withFlags(Flag.FORCE_RETURN_VALUE).putIfAbsent(targetKey, generator.value(2))); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testRemove(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) { RemoteCache<K, V> cache = remoteCache(protocolVersion); final K targetKey = generator.key(0); V targetValue = generator.value(0); assertNull(cache.put(targetKey, targetValue)); generator.assertEquals(targetValue, cache.withFlags(Flag.FORCE_RETURN_VALUE).remove(targetKey)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testPutAsync(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); final K k = generator.key(0); final V v = generator.value(0); final V v2 = generator.value(2); Future<V> f = cache.putAsync(k, v); testFuture(generator, f, null); generator.assertEquals(v, cache.get(k)); f = cache.putAsync(k, v2); testFuture(generator, f, v); generator.assertEquals(v2, cache.get(k)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testPutAsyncWithListener(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); final K k = generator.key(0); final V v = generator.value(0); final V v2 = generator.value(2); CompletableFuture<V> f = cache.putAsync(k, v); testFutureWithListener(generator, f, null); generator.assertEquals(v, cache.get(k)); f = cache.putAsync(k, v2); testFutureWithListener(generator, f, v); generator.assertEquals(v2, cache.get(k)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testPutAllAsync(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); final K k = generator.key(0); final V v3 = generator.value(3); Future<Void> f = cache.putAllAsync(Collections.singletonMap(k, v3)); assertNull(f.get()); generator.assertEquals(v3, cache.get(k)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testPutAllAsyncWithListener(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); final K k = generator.key(0); final V v3 = generator.value(3); CompletableFuture<Void> f = cache.putAllAsync(Collections.singletonMap(k, v3)); testFutureWithListener(f); generator.assertEquals(v3, cache.get(k)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testPutIfAbsentAsync(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); final K k = generator.key(0); final V v3 = generator.value(3); final V v4 = generator.value(4); final V v5 = generator.value(5); cache.put(k, v3); generator.assertEquals(v3, cache.get(k)); Future<V> f = cache.putIfAbsentAsync(k, v4); testFuture(generator, f, v3); generator.assertEquals(v3, cache.remove(k)); f = cache.putIfAbsentAsync(k, v5); testFuture(generator, f, null); generator.assertEquals(v5, cache.get(k)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testPutIfAbsentAsyncWithListener(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); final K k = generator.key(0); final V v3 = generator.value(3); final V v4 = generator.value(4); final V v5 = generator.value(5); cache.put(k, v3); generator.assertEquals(v3, cache.get(k)); CompletableFuture<V> f = cache.putIfAbsentAsync(k, v4); testFutureWithListener(generator, f, v3); generator.assertEquals(v3, cache.remove(k)); f = cache.putIfAbsentAsync(k, v5); testFutureWithListener(generator, f, null); generator.assertEquals(v5, cache.get(k)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testRemoveAsync(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); final K k = generator.key(0); final V v3 = generator.value(3); cache.put(k, v3); generator.assertEquals(v3, cache.get(k)); Future<V> f = cache.removeAsync(k); testFuture(generator, f, v3); assertNull(cache.get(k)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testRemoveAsyncWithListener(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); final K k = generator.key(0); final V v3 = generator.value(3); cache.put(k, v3); generator.assertEquals(v3, cache.get(k)); CompletableFuture<V> f = cache.removeAsync(k); testFutureWithListener(generator, f, v3); assertNull(cache.get(k)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testGetAsync(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); final K k = generator.key(0); final V v = generator.value(0); cache.put(k, v); generator.assertEquals(v, cache.get(k)); Future<V> f = cache.getAsync(k); testFuture(generator, f, v); generator.assertEquals(v, cache.get(k)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testGetAsyncWithListener(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); final K k = generator.key(0); final V v = generator.value(0); cache.put(k, v); generator.assertEquals(v, cache.get(k)); CompletableFuture<V> f = cache.getAsync(k); testFutureWithListener(generator, f, v); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testRemoveWithVersionAsync(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); final K k = generator.key(0); final V v4 = generator.value(4); cache.put(k, v4); VersionedValue<V> value = cache.getWithMetadata(k); Future<Boolean> f = cache.removeWithVersionAsync(k, value.getVersion() + 1); assertFalse(f.get()); generator.assertEquals(v4, cache.get(k)); f = cache.removeWithVersionAsync(k, value.getVersion()); assertTrue(f.get()); assertNull(cache.get(k)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testRemoveWithVersionAsyncWithListener(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); final K k = generator.key(0); final V v4 = generator.value(4); cache.put(k, v4); VersionedValue<V> value = cache.getWithMetadata(k); CompletableFuture<Boolean> f = cache.removeWithVersionAsync(k, value.getVersion() + 1); testFutureWithListener(f, false); generator.assertEquals(v4, cache.get(k)); f = cache.removeWithVersionAsync(k, value.getVersion()); testFutureWithListener(f, true); assertNull(cache.get(k)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testReplaceAsync(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); K k = generator.key(0); V v = generator.value(0); V v5 = generator.value(5); assertNull(cache.get(k)); Future<V> f = cache.replaceAsync(k, v5); testFuture(generator, f, null); assertNull(cache.get(k)); cache.put(k, v); generator.assertEquals(v, cache.get(k)); f = cache.replaceAsync(k, v5); testFuture(generator, f, v); generator.assertEquals(v5, cache.get(k)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testReplaceAsyncWithListener(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); K k = generator.key(0); V v = generator.value(0); V v5 = generator.value(5); assertNull(cache.get(k)); CompletableFuture<V> f = cache.replaceAsync(k, v5); testFutureWithListener(generator, f, null); assertNull(cache.get(k)); cache.put(k, v); generator.assertEquals(v, cache.get(k)); f = cache.replaceAsync(k, v5); testFutureWithListener(generator, f, v); generator.assertEquals(v5, cache.get(k)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testReplaceWithVersionAsync(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); K k = generator.key(0); V v = generator.value(0); V v2 = generator.value(2); V v3 = generator.value(3); cache.put(k, v); VersionedValue<V> versioned1 = cache.getWithMetadata(k); Future<Boolean> f = cache.replaceWithVersionAsync(k, v2, versioned1.getVersion()); assertTrue(f.get()); VersionedValue<V> versioned2 = cache.getWithMetadata(k); assertNotEquals(versioned1.getVersion(), versioned2.getVersion()); generator.assertEquals(versioned2.getValue(), v2); f = cache.replaceWithVersionAsync(k, v3, versioned1.getVersion()); assertFalse(f.get()); generator.assertEquals(v2, cache.get(k)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testReplaceWithVersionAsyncWithListener(ProtocolVersion protocolVersion, KeyValueGenerator<K, V> generator) throws Exception { RemoteCache<K, V> cache = remoteCache(protocolVersion, true); K k = generator.key(0); V v = generator.value(0); V v2 = generator.value(2); V v3 = generator.value(3); cache.put(k, v); VersionedValue<V> versioned1 = cache.getWithMetadata(k); CompletableFuture<Boolean> f = cache.replaceWithVersionAsync(k, v2, versioned1.getVersion()); testFutureWithListener(f, true); VersionedValue<V> versioned2 = cache.getWithMetadata(k); assertNotEquals(versioned1.getVersion(), versioned2.getVersion()); generator.assertEquals(versioned2.getValue(), v2); f = cache.replaceWithVersionAsync(k, v3, versioned1.getVersion()); testFutureWithListener(f, false); generator.assertEquals(v2, cache.get(k)); } private void testFuture(KeyValueGenerator<K, V> generator, Future<V> f, V expected) throws ExecutionException, InterruptedException { assertNotNull(f); assertFalse(f.isCancelled()); V value = f.get(); generator.assertEquals(expected, value); assertTrue(f.isDone()); } private void testFutureWithListener(KeyValueGenerator<K, V> generator, CompletableFuture<V> f, V expected) throws InterruptedException { assertNotNull(f); AtomicReference<Throwable> ex = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); f.whenComplete((v, t) -> { if (t != null) { ex.set(t); } generator.assertEquals(expected, v); latch.countDown(); }); if (!latch.await(5, TimeUnit.SECONDS)) { fail("Not finished within 5 seconds"); } if (ex.get() != null) { throw new AssertionError(ex.get()); } } private void testFutureWithListener(CompletableFuture<Boolean> f, boolean expected) throws InterruptedException { assertNotNull(f); AtomicReference<Throwable> ex = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); f.whenComplete((v, t) -> { if (t != null) { ex.set(t); } assertEquals(expected, v); latch.countDown(); }); if (!latch.await(5, TimeUnit.SECONDS)) { fail("Not finished within 5 seconds"); } if (ex.get() != null) { throw new AssertionError(ex.get()); } } private void testFutureWithListener(CompletableFuture<Void> f) throws InterruptedException { assertNotNull(f); AtomicReference<Throwable> ex = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); f.whenComplete((v, t) -> { if (t != null) { ex.set(t); } assertNull(v); latch.countDown(); }); if (!latch.await(5, TimeUnit.SECONDS)) { fail("Not finished within 5 seconds"); } if (ex.get() != null) { throw new AssertionError(ex.get()); } } }
23,176
40.610413
180
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/hotrod/HotRodCounterOperations.java
package org.infinispan.server.functional.hotrod; import static org.junit.jupiter.api.Assertions.assertEquals; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.SyncStrongCounter; import org.infinispan.counter.api.SyncWeakCounter; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class HotRodCounterOperations { @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; @Test public void testCounters() { CounterManager counterManager = SERVERS.getCounterManager(); counterManager.defineCounter("c1", CounterConfiguration.builder(CounterType.BOUNDED_STRONG) .upperBound(10) .initialValue(1) .build()); counterManager.defineCounter("c2", CounterConfiguration.builder(CounterType.WEAK) .initialValue(5) .build()); SyncStrongCounter c1 = counterManager.getStrongCounter("c1").sync(); SyncWeakCounter c2 = counterManager.getWeakCounter("c2").sync(); assertEquals(1, c1.getValue()); assertEquals(5, c2.getValue()); } }
1,462
32.25
97
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/hotrod/XSiteHotRodCacheOperations.java
package org.infinispan.server.functional.hotrod; import static org.infinispan.client.rest.RestResponse.OK; import static org.infinispan.commons.test.Eventually.eventuallyEquals; import static org.infinispan.server.functional.XSiteIT.LON_CACHE_CUSTOM_NAME_CONFIG; import static org.infinispan.server.functional.XSiteIT.LON_CACHE_OFF_HEAP; import static org.infinispan.server.functional.XSiteIT.MAX_COUNT_KEYS; import static org.infinispan.server.functional.XSiteIT.NR_KEYS; import static org.infinispan.server.functional.XSiteIT.NYC_CACHE_CUSTOM_NAME_CONFIG; import static org.infinispan.server.test.core.Common.assertStatus; import static org.infinispan.server.test.core.InfinispanServerTestConfiguration.LON; import static org.infinispan.server.test.core.InfinispanServerTestConfiguration.NYC; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.IntStream; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.multimap.MultimapCacheManager; import org.infinispan.client.hotrod.multimap.RemoteMultimapCache; import org.infinispan.client.rest.RestCacheClient; import org.infinispan.client.rest.RestClient; import org.infinispan.commons.configuration.StringConfiguration; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.server.functional.XSiteIT; import org.infinispan.server.test.junit5.InfinispanXSiteServerExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @author Pedro Ruivo * @author Gustavo Lira * @since 11.0 **/ public class XSiteHotRodCacheOperations { @RegisterExtension public static final InfinispanXSiteServerExtension SERVERS = XSiteIT.SERVERS; @Test public void testHotRodOperations() { String lonXML = String.format(XSiteIT.LON_CACHE_CONFIG, SERVERS.getMethodName()); RemoteCache<String, String> lonCache = SERVERS.hotrod(LON) .withServerConfiguration(new StringConfiguration(lonXML)).create(); RemoteCache<String, String> nycCache = SERVERS.hotrod(NYC).create(); //nyc cache don't backup to lon insertAndVerifyEntries(lonCache, nycCache, false); } @Test public void testHotRodOperationsWithDifferentCacheName() { RemoteCache<String, String> lonCache = SERVERS.hotrod(LON) .createRemoteCacheManager() .administration() .createCache("lon-cache-hotrod", new StringConfiguration(String.format(LON_CACHE_CUSTOM_NAME_CONFIG, "hotrod", "hotrod"))); RemoteCache<String, String> nycCache = SERVERS.hotrod(NYC) .createRemoteCacheManager() .administration() .createCache("nyc-cache-hotrod", new StringConfiguration(String.format(NYC_CACHE_CUSTOM_NAME_CONFIG, "hotrod", "hotrod"))); insertAndVerifyEntries(lonCache, nycCache, true); } @Test public void testHotRodOperationsWithOffHeapFileStore() { String lonXML = String.format(LON_CACHE_OFF_HEAP, SERVERS.getMethodName()); RemoteCache<Integer, Integer> lonCache = SERVERS.hotrod(LON) .withServerConfiguration(new StringConfiguration(lonXML)).create(); RemoteCache<Integer, Integer> nycCache = SERVERS.hotrod(NYC).create(); //nyc cache don't backup to lon //Just to make sure that the file store is empty assertEquals(0, getTotalMemoryEntries(lonXML)); IntStream.range(0, NR_KEYS).forEach(i -> lonCache.put(i, i)); eventuallyEquals(NR_KEYS, nycCache::size); assertEquals(MAX_COUNT_KEYS, getTotalMemoryEntries(lonXML)); } @Test public void testMultimap() { String multimapCacheName = "multimap"; ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); builder.sites().addBackup() .site(NYC).strategy(BackupConfiguration.BackupStrategy.SYNC).backupFailurePolicy(BackupFailurePolicy.WARN); builder.sites().addBackup() .site(LON).strategy(BackupConfiguration.BackupStrategy.SYNC).backupFailurePolicy(BackupFailurePolicy.WARN); SERVERS.hotrod(LON).createRemoteCacheManager().administration().getOrCreateCache(multimapCacheName, builder.build()); SERVERS.hotrod(NYC).createRemoteCacheManager().administration().getOrCreateCache(multimapCacheName, builder.build()); RemoteMultimapCache<String, String> lonCache = multimapCache(LON, multimapCacheName); RemoteMultimapCache<String, String> nycCache = multimapCache(NYC, multimapCacheName); String key = Util.threadLocalRandomUUID().toString(); Collection<String> values = createValues(4); storeMultimapValues(lonCache, key, values); assertMultimapData(lonCache, key, values); assertMultimapData(nycCache, key, values); key = Util.threadLocalRandomUUID().toString(); values = createValues(5); storeMultimapValues(nycCache, key, values); assertMultimapData(lonCache, key, values); assertMultimapData(nycCache, key, values); } private void assertMultimapData(RemoteMultimapCache<String, String> cache, String key, Collection<String> values) { Collection<String> data = cache.get(key).join(); assertEquals(values.size(), data.size()); for (String v : values) { assertTrue(data.contains(v)); } } private RemoteMultimapCache<String, String> multimapCache(String site, String cacheName) { MultimapCacheManager<String, String> multimapCacheManager = SERVERS.getMultimapCacheManager(site); return multimapCacheManager.get(cacheName); } private static void storeMultimapValues(RemoteMultimapCache<String, String> rmc, String key, Collection<String> values) { for (String v : values) { rmc.put(key, v).join(); } } private static List<String> createValues(int size) { List<String> values = new ArrayList<>(size); for (int i = 0; i < size; ++i) { values.add(Util.threadLocalRandomUUID().toString()); } return values; } private int getTotalMemoryEntries(String lonXML) { RestClient restClient = SERVERS.rest(LON) .withServerConfiguration(new StringConfiguration(lonXML)).get(); RestCacheClient client = restClient.cache(SERVERS.getMethodName()); Json json = Json.read(assertStatus(OK, client.stats())); return json.asJsonMap().get("current_number_of_entries_in_memory").asInteger(); } private void insertAndVerifyEntries(RemoteCache<String, String> lonCache, RemoteCache<String, String> nycCache, boolean allSitesBackup) { lonCache.put("k1", "v1"); nycCache.put("k2", "v2"); assertEquals("v1", lonCache.get("k1")); eventuallyEquals("v1", () -> nycCache.get("k1")); if(allSitesBackup) { eventuallyEquals("v2", () -> lonCache.get("k2")); } else { assertNull(lonCache.get("k2")); } assertEquals ("v2", nycCache.get("k2")); } }
7,435
43
140
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/hotrod/HotRodCacheQueries.java
package org.infinispan.server.functional.hotrod; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME; import static org.infinispan.server.test.core.Common.createQueryableCache; import static org.infinispan.server.test.core.Common.sync; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; 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.Search; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.client.rest.RestClient; import org.infinispan.client.rest.RestResponse; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.dataconversion.internal.Json; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.protostream.sampledomain.Address; import org.infinispan.protostream.sampledomain.User; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.functional.extensions.entities.Entities; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class HotRodCacheQueries { public static final String BANK_PROTO_FILE = "/sample_bank_account/bank.proto"; public static final String ENTITY_USER = "sample_bank_account.User"; @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; @ParameterizedTest @ValueSource(booleans = {true, false}) public void testAttributeQuery(boolean indexed) { RemoteCache<Integer, User> remoteCache = createQueryableCache(SERVERS, indexed, BANK_PROTO_FILE, ENTITY_USER); remoteCache.put(1, createUser1()); remoteCache.put(2, createUser2()); // 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<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(User.class, list.get(0).getClass()); assertUser1(list.get(0)); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testEmbeddedAttributeQuery(boolean indexed) { RemoteCache<Integer, User> remoteCache = createQueryableCache(SERVERS, indexed, BANK_PROTO_FILE, ENTITY_USER); remoteCache.put(1, createUser1()); remoteCache.put(2, createUser2()); // 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(User.class, list.get(0).getClass()); assertUser1(list.get(0)); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testProjections(boolean indexed) { RemoteCache<Integer, User> remoteCache = createQueryableCache(SERVERS, indexed, BANK_PROTO_FILE, ENTITY_USER); remoteCache.put(1, createUser1()); remoteCache.put(2, createUser2()); // 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]); } /** * Sorting on a field that does not contain DocValues so Hibernate Search is forced to uninvert it. * * @see <a href="https://issues.jboss.org/browse/ISPN-5729">https://issues.jboss.org/browse/ISPN-5729</a> */ @ParameterizedTest @ValueSource(booleans = {true, false}) public void testUninverting(boolean indexed) { RemoteCache<Integer, User> remoteCache = createQueryableCache(SERVERS, indexed, BANK_PROTO_FILE, ENTITY_USER); remoteCache.put(1, createUser1()); remoteCache.put(2, createUser2()); QueryFactory qf = Search.getQueryFactory(remoteCache); Query<User> query = qf.create("FROM sample_bank_account.User WHERE name = 'John' ORDER BY id ASC"); assertEquals(0, query.execute().list().size()); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testIteratorWithQuery(boolean indexed) { RemoteCache<Integer, User> remoteCache = createQueryableCache(SERVERS, indexed, BANK_PROTO_FILE, ENTITY_USER); remoteCache.put(1, createUser1()); remoteCache.put(2, createUser2()); QueryFactory qf = Search.getQueryFactory(remoteCache); Query<User> simpleQuery = qf.create("FROM sample_bank_account.User WHERE name = 'Tom'"); List<Map.Entry<Object, Object>> entries = new ArrayList<>(1); try (CloseableIterator<Map.Entry<Object, Object>> iter = remoteCache.retrieveEntriesByQuery(simpleQuery, null, 3)) { while (iter.hasNext()) { entries.add(iter.next()); } } assertEquals(1, entries.size()); assertEquals("Cat", ((User) entries.get(0).getValue()).getSurname()); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testIteratorWithQueryAndProjections(boolean indexed) { RemoteCache<Integer, User> remoteCache = createQueryableCache(SERVERS, indexed, BANK_PROTO_FILE, ENTITY_USER); remoteCache.put(1, createUser1()); remoteCache.put(2, createUser2()); QueryFactory qf = Search.getQueryFactory(remoteCache); Query<Object[]> simpleQuery = qf.create("SELECT surname, name FROM sample_bank_account.User WHERE name = 'Tom'"); List<Map.Entry<Object, Object>> entries = new ArrayList<>(1); try (CloseableIterator<Map.Entry<Object, Object>> iter = remoteCache.retrieveEntriesByQuery(simpleQuery, null, 3)) { while (iter.hasNext()) { entries.add(iter.next()); } } assertEquals(1, entries.size()); Object[] projections = (Object[]) entries.get(0).getValue(); assertEquals("Cat", projections[0]); assertEquals("Tom", projections[1]); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testQueryViaRest(boolean indexed) { RemoteCache<Integer, User> remoteCache = createQueryableCache(SERVERS, indexed, BANK_PROTO_FILE, ENTITY_USER); remoteCache.put(1, createUser1()); remoteCache.put(2, createUser2()); String query = "FROM sample_bank_account.User WHERE name='Adrian'"; RestClient restClient = SERVERS.rest().withClientConfiguration(new RestClientConfigurationBuilder()).get(); try (RestResponse response = sync(restClient.cache(SERVERS.getMethodName()).query(query))) { Json results = Json.read(response.getBody()); assertEquals(1, results.at("hit_count").asInteger()); } } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testManyInClauses(boolean indexed) { RemoteCache<Integer, User> remoteCache = createQueryableCache(SERVERS, indexed, BANK_PROTO_FILE, ENTITY_USER); remoteCache.put(1, createUser1()); remoteCache.put(2, createUser2()); // get user back from remote cache and check its attributes User fromCache = remoteCache.get(1); assertUser1(fromCache); QueryFactory qf = Search.getQueryFactory(remoteCache); Set<String> values = new HashSet<>(); values.add("Tom"); for (int i = 0; i < 1024; i++) { values.add("test" + i); } Query<User> query = qf.from(User.class).having("name").in(values).build(); // this Ickle query translates to a BooleanQuery with 1025 clauses, 1 more than the max default (1024) so // executing it will fail unless the server jvm arg -Dinfinispan.query.lucene.max-boolean-clauses=1025 takes effect List<User> list = query.execute().list(); assertNotNull(list); assertEquals(1, list.size()); assertEquals(User.class, list.get(0).getClass()); assertUser1(list.get(0)); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testWayTooManyInClauses(boolean indexed) { RemoteCache<Integer, User> remoteCache = createQueryableCache(SERVERS, indexed, BANK_PROTO_FILE, ENTITY_USER); Set<String> values = new HashSet<>(); for (int i = 0; i < 1026; i++) { values.add("test" + i); } QueryFactory qf = Search.getQueryFactory(remoteCache); Query<User> query = qf.from(User.class).having("name").in(values).build(); // this Ickle query translates to a BooleanQuery with 1026 clauses, 1 more than the configured // -Dinfinispan.query.lucene.max-boolean-clauses=1025, so executing the query is expected to fail if (indexed) { Exception expectedException = assertThrows(HotRodClientException.class, query::execute); assertTrue(expectedException.getMessage().contains("org.apache.lucene.search.BooleanQuery$TooManyClauses: maxClauseCount is set to 1025")); } else { query.execute(); } } @Test public void testWithSCI() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addContextInitializer(Entities.INSTANCE); org.infinispan.configuration.cache.ConfigurationBuilder cache = new org.infinispan.configuration.cache.ConfigurationBuilder(); cache.clustering().cacheMode(CacheMode.DIST_SYNC).encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); RemoteCache<String, Entities.Person> peopleCache = SERVERS.hotrod().withClientConfiguration(builder).withServerConfiguration(cache).create(); RemoteCache<String, String> metadataCache = peopleCache.getRemoteCacheContainer().getCache(PROTOBUF_METADATA_CACHE_NAME); metadataCache.put(Entities.INSTANCE.getProtoFileName(), Entities.INSTANCE.getProtoFile()); Map<String, Entities.Person> people = new HashMap<>(); people.put("1", new Entities.Person("Oihana", "Rossignol", 2016, "Paris")); people.put("2", new Entities.Person("Elaia", "Rossignol", 2018, "Paris")); people.put("3", new Entities.Person("Yago", "Steiner", 2013, "Saint-Mandé")); people.put("4", new Entities.Person("Alberto", "Steiner", 2016, "Paris")); peopleCache.putAll(people); QueryFactory queryFactory = Search.getQueryFactory(peopleCache); Query<Entities.Person> query = queryFactory.create("FROM Person p where p.lastName = :lastName"); query.setParameter("lastName", "Rossignol"); List<Entities.Person> rossignols = query.execute().list(); assertThat(rossignols).extracting("firstName").containsExactlyInAnyOrder("Oihana", "Elaia"); RestClient restClient = SERVERS.rest().get(); try (RestResponse response = sync(restClient.cache(peopleCache.getName()).entries(1000))) { if (response.getStatus() != 200) { fail(response.getBody()); } Collection<?> entities = (Collection<?>) Json.read(response.getBody()).getValue(); assertThat(entities).hasSize(4); } } public static User createUser1() { User user = new User(); user.setId(1); user.setName("Tom"); user.setSurname("Cat"); user.setGender(User.Gender.MALE); user.setAccountIds(Collections.singleton(12)); Address address = new Address(); address.setStreet("Dark Alley"); address.setPostCode("1234"); user.setAddresses(Collections.singletonList(address)); return user; } public static User createUser2() { User user = new User(); user.setId(2); user.setName("Adrian"); user.setSurname("Nistor"); user.setGender(User.Gender.MALE); Address address = new Address(); address.setStreet("Old Street"); address.setPostCode("XYZ"); user.setAddresses(Collections.singletonList(address)); return user; } public static 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()); } }
14,158
42.835913
148
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/hotrod/HotRodTransactionalCacheOperations.java
package org.infinispan.server.functional.hotrod; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.configuration.TransactionMode; import org.infinispan.client.hotrod.transaction.lookup.RemoteTransactionManagerLookup; import org.infinispan.commons.configuration.StringConfiguration; import org.infinispan.configuration.parsing.Parser; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import jakarta.transaction.TransactionManager; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @author Pedro Ruivo * @since 10.0 **/ public class HotRodTransactionalCacheOperations { private static final String TEST_CACHE_XML_CONFIG = "<infinispan><cache-container>" + " <distributed-cache-configuration name=\"%s\">" + " <locking isolation=\"REPEATABLE_READ\"/>" + " <transaction locking=\"PESSIMISTIC\" mode=\"%s\" />" + " </distributed-cache-configuration>" + "</cache-container></infinispan>"; @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; @ParameterizedTest(name = "{0}") @EnumSource(value = Parser.TransactionMode.class, names = {"NON_XA", "NON_DURABLE_XA", "FULL_XA"}) public void testTransactionalCache(Parser.TransactionMode txMode) throws Exception { ConfigurationBuilder config = new ConfigurationBuilder(); config.remoteCache(SERVERS.getMethodName()) .transactionMode(TransactionMode.NON_XA) .transactionManagerLookup(RemoteTransactionManagerLookup.getInstance()); String xml = String.format(TEST_CACHE_XML_CONFIG, SERVERS.getMethodName(), txMode.name()); RemoteCache<String, String> cache = SERVERS.hotrod().withClientConfiguration(config).withServerConfiguration(new StringConfiguration(xml)).create(); TransactionManager tm = cache.getTransactionManager(); tm.begin(); cache.put("k", "v1"); assertEquals("v1", cache.get("k")); tm.commit(); assertEquals("v1", cache.get("k")); tm.begin(); cache.put("k", "v2"); cache.put("k2", "v1"); assertEquals("v2", cache.get("k")); assertEquals("v1", cache.get("k2")); tm.rollback(); assertEquals("v1", cache.get("k")); assertNull(cache.get("k2")); } }
2,768
40.328358
154
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/hotrod/CustomEventLogListener.java
package org.infinispan.server.functional.hotrod; import static org.infinispan.server.test.core.Common.assertAnyEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated; import org.infinispan.client.hotrod.annotation.ClientCacheEntryExpired; import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified; import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.event.ClientCacheEntryCustomEvent; import org.infinispan.client.hotrod.event.ClientEvent; import org.infinispan.server.functional.extensions.entities.Entities.CustomEvent; @ClientListener(converterFactoryName = "test-converter-factory") public abstract class CustomEventLogListener<K, V, E> { BlockingQueue<E> createdCustomEvents = new ArrayBlockingQueue<>(128); BlockingQueue<E> modifiedCustomEvents = new ArrayBlockingQueue<>(128); BlockingQueue<E> removedCustomEvents = new ArrayBlockingQueue<>(128); BlockingQueue<E> expiredCustomEvents = new ArrayBlockingQueue<>(128); private final RemoteCache<K, V> remote; protected CustomEventLogListener(RemoteCache<K, V> remote) { this.remote = remote; } public E pollEvent(ClientEvent.Type type) { try { E event = queue(type).poll(10, TimeUnit.SECONDS); assertNotNull(event); return event; } catch (InterruptedException e) { throw new AssertionError(e); } } protected BlockingQueue<E> queue(ClientEvent.Type type) { switch (type) { case CLIENT_CACHE_ENTRY_CREATED: return createdCustomEvents; case CLIENT_CACHE_ENTRY_MODIFIED: return modifiedCustomEvents; case CLIENT_CACHE_ENTRY_REMOVED: return removedCustomEvents; case CLIENT_CACHE_ENTRY_EXPIRED: return expiredCustomEvents; default: throw new IllegalArgumentException("Unknown event type: " + type); } } public void expectNoEvents(ClientEvent.Type type) { assertEquals(0, queue(type).size()); } public void expectNoEvents() { expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED); } public void expectSingleCustomEvent(ClientEvent.Type type, E expected) { E event = pollEvent(type); assertAnyEquals(expected, event); } public void expectCreatedEvent(E expected) { expectSingleCustomEvent(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED, expected); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED); } public void expectModifiedEvent(E expected) { expectSingleCustomEvent(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED, expected); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED); } public void expectRemovedEvent(E expected) { expectSingleCustomEvent(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED, expected); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED); } public void expectExpiredEvent(E expected) { expectSingleCustomEvent(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED, expected); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED); } public void accept(BiConsumer<CustomEventLogListener<K, V, E>, RemoteCache<K, V>> cons) { remote.addClientListener(this); try { cons.accept(this, remote); } finally { remote.removeClientListener(this); } } public void accept(Object[] fparams, Object[] cparams, BiConsumer<CustomEventLogListener<K, V, E>, RemoteCache<K, V>> cons) { remote.addClientListener(this, fparams, cparams); try { cons.accept(this, remote); } finally { remote.removeClientListener(this); } } @ClientCacheEntryCreated @SuppressWarnings("unused") public void handleCustomCreatedEvent(ClientCacheEntryCustomEvent<E> e) { assertEquals(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED, e.getType()); createdCustomEvents.add(e.getEventData()); } @ClientCacheEntryModified @SuppressWarnings("unused") public void handleCustomModifiedEvent(ClientCacheEntryCustomEvent<E> e) { assertEquals(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED, e.getType()); modifiedCustomEvents.add(e.getEventData()); } @ClientCacheEntryRemoved @SuppressWarnings("unused") public void handleCustomRemovedEvent(ClientCacheEntryCustomEvent<E> e) { assertEquals(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED, e.getType()); removedCustomEvents.add(e.getEventData()); } @ClientCacheEntryExpired @SuppressWarnings("unused") public void handleCustomExpiredEvent(ClientCacheEntryCustomEvent<E> e) { assertEquals(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED, e.getType()); expiredCustomEvents.add(e.getEventData()); } public void expectOrderedEventQueue(ClientEvent.Type type) { // NO OP } @ClientListener(converterFactoryName = "static-converter-factory") public static class StaticCustomEventLogListener<K, V> extends CustomEventLogListener<K, V, CustomEvent<K>> { public StaticCustomEventLogListener(RemoteCache<K, V> r) { super(r); } @Override public void expectSingleCustomEvent(ClientEvent.Type type, CustomEvent<K> expected) { CustomEvent<K> event = pollEvent(type); assertNotNull(event.getKey()); assertAnyEquals(expected, event); } @Override public void expectOrderedEventQueue(ClientEvent.Type type) { BlockingQueue<CustomEvent<K>> queue = queue(type); if (queue.size() < 2) return; try { CustomEvent<K> before = queue.poll(10, TimeUnit.SECONDS); for (CustomEvent<K> after : queue) { expectTimeOrdered(before, after); before = after; } } catch (InterruptedException e) { throw new AssertionError(e); } } private void expectTimeOrdered(CustomEvent<K> before, CustomEvent<K> after) { assertTrue(before.getTimestamp() < after.getTimestamp(), "Before timestamp=" + before.getTimestamp() + ", after timestamp=" + after.getTimestamp()); } } @ClientListener(converterFactoryName = "raw-static-converter-factory", useRawData = true) public static class RawStaticCustomEventLogListener<K, V> extends CustomEventLogListener<K, V, byte[]> { public RawStaticCustomEventLogListener(RemoteCache<K, V> r) { super(r); } } @ClientListener(converterFactoryName = "static-converter-factory", includeCurrentState = true) public static class StaticCustomEventLogWithStateListener<K, V> extends CustomEventLogListener<K, V, CustomEvent<K>> { public StaticCustomEventLogWithStateListener(RemoteCache<K, V> r) { super(r); } } @ClientListener(converterFactoryName = "dynamic-converter-factory") public static class DynamicCustomEventLogListener<K, V> extends CustomEventLogListener<K, V, CustomEvent<K>> { public DynamicCustomEventLogListener(RemoteCache<K, V> r) { super(r); } } @ClientListener(converterFactoryName = "dynamic-converter-factory", includeCurrentState = true) public static class DynamicCustomEventWithStateLogListener<K, V> extends CustomEventLogListener<K, V, CustomEvent<K>> { public DynamicCustomEventWithStateLogListener(RemoteCache<K, V> r) { super(r); } } @ClientListener(converterFactoryName = "simple-converter-factory") public static class SimpleListener<K, V> extends CustomEventLogListener<K, V, String> { public SimpleListener(RemoteCache<K, V> r) { super(r); } } @ClientListener(filterFactoryName = "filter-converter-factory", converterFactoryName = "filter-converter-factory") public static class FilterCustomEventLogListener<K, V> extends CustomEventLogListener<K, V, CustomEvent> { public FilterCustomEventLogListener(RemoteCache<K, V> r) { super(r); } } @ClientListener public static class NoConverterFactoryListener<K, V> extends CustomEventLogListener<K, V, Object> { public NoConverterFactoryListener(RemoteCache<K, V> r) { super(r); } } }
9,446
38.3625
128
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/hotrod/EventLogListener.java
package org.infinispan.server.functional.hotrod; import static org.infinispan.server.test.core.Common.assertAnyEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated; import org.infinispan.client.hotrod.annotation.ClientCacheEntryExpired; import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified; import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.event.ClientCacheEntryCreatedEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryExpiredEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryModifiedEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryRemovedEvent; import org.infinispan.client.hotrod.event.ClientEvent; @ClientListener public class EventLogListener<K, V> { public BlockingQueue<ClientCacheEntryCreatedEvent<K>> createdEvents = new ArrayBlockingQueue<>(128); public BlockingQueue<ClientCacheEntryModifiedEvent<K>> modifiedEvents = new ArrayBlockingQueue<>(128); public BlockingQueue<ClientCacheEntryRemovedEvent<K>> removedEvents = new ArrayBlockingQueue<>(128); public BlockingQueue<ClientCacheEntryExpiredEvent<K>> expiredEvents = new ArrayBlockingQueue<>(128); private final RemoteCache<K, V> remote; public EventLogListener(RemoteCache<K, V> remote) { this.remote = remote; } @SuppressWarnings("unchecked") public <E extends ClientEvent> E pollEvent(ClientEvent.Type type) { try { E event = (E) queue(type).poll(10, TimeUnit.SECONDS); assertNotNull(event); return event; } catch (InterruptedException e) { throw new AssertionError(e); } } @SuppressWarnings("unchecked") public <E extends ClientEvent> BlockingQueue<E> queue(ClientEvent.Type type) { switch (type) { case CLIENT_CACHE_ENTRY_CREATED: return (BlockingQueue<E>) createdEvents; case CLIENT_CACHE_ENTRY_MODIFIED: return (BlockingQueue<E>) modifiedEvents; case CLIENT_CACHE_ENTRY_REMOVED: return (BlockingQueue<E>) removedEvents; case CLIENT_CACHE_ENTRY_EXPIRED: return (BlockingQueue<E>) expiredEvents; default: throw new IllegalArgumentException("Unknown event type: " + type); } } @ClientCacheEntryCreated @SuppressWarnings("unused") public void handleCreatedEvent(ClientCacheEntryCreatedEvent<K> e) { createdEvents.add(e); } @ClientCacheEntryModified @SuppressWarnings("unused") public void handleModifiedEvent(ClientCacheEntryModifiedEvent<K> e) { modifiedEvents.add(e); } @ClientCacheEntryRemoved @SuppressWarnings("unused") public void handleRemovedEvent(ClientCacheEntryRemovedEvent<K> e) { removedEvents.add(e); } @ClientCacheEntryExpired @SuppressWarnings("unused") public void handleExpiredEvent(ClientCacheEntryExpiredEvent<K> e) { expiredEvents.add(e); } public void expectNoEvents() { expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED); } public void expectNoEvents(ClientEvent.Type type) { switch (type) { case CLIENT_CACHE_ENTRY_CREATED: assertEquals(0, createdEvents.size(), createdEvents.toString()); break; case CLIENT_CACHE_ENTRY_MODIFIED: assertEquals(0, modifiedEvents.size(), modifiedEvents.toString()); break; case CLIENT_CACHE_ENTRY_REMOVED: assertEquals(0, removedEvents.size(), removedEvents.toString()); break; case CLIENT_CACHE_ENTRY_EXPIRED: assertEquals(0, expiredEvents.size(), expiredEvents.toString()); break; } } public void expectOnlyCreatedEvent(K key) { expectSingleEvent(key, ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED); } public void expectOnlyModifiedEvent(K key) { expectSingleEvent(key, ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED); } public void expectOnlyRemovedEvent(K key) { expectSingleEvent(key, ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED); } public void expectOnlyExpiredEvent(K key) { expectSingleEvent(key, ClientEvent.Type.CLIENT_CACHE_ENTRY_EXPIRED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED); expectNoEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED); } public void expectSingleEvent(K key, ClientEvent.Type type) { switch (type) { case CLIENT_CACHE_ENTRY_CREATED: ClientCacheEntryCreatedEvent<K> createdEvent = pollEvent(type); assertAnyEquals(key, createdEvent.getKey()); assertAnyEquals(serverDataVersion(remote, key), createdEvent.getVersion()); break; case CLIENT_CACHE_ENTRY_MODIFIED: ClientCacheEntryModifiedEvent<K> modifiedEvent = pollEvent(type); assertAnyEquals(key, modifiedEvent.getKey()); assertAnyEquals(serverDataVersion(remote, key), modifiedEvent.getVersion()); break; case CLIENT_CACHE_ENTRY_REMOVED: ClientCacheEntryRemovedEvent<K> removedEvent = pollEvent(type); assertAnyEquals(key, removedEvent.getKey()); break; case CLIENT_CACHE_ENTRY_EXPIRED: ClientCacheEntryExpiredEvent<K> expiredEvent = pollEvent(type); assertAnyEquals(key, expiredEvent.getKey()); break; } assertEquals(0, queue(type).size()); } private long serverDataVersion(RemoteCache<K, ?> cache, K key) { return cache.getWithMetadata(key).getVersion(); } @SafeVarargs public final void expectUnorderedEvents(ClientEvent.Type type, K... keys) { List<K> assertedKeys = new ArrayList<>(); for (int i = 0; i < keys.length; i++) { ClientEvent event = pollEvent(type); int initialSize = assertedKeys.size(); for (K key : keys) { K eventKey = null; switch (event.getType()) { case CLIENT_CACHE_ENTRY_CREATED: eventKey = ((ClientCacheEntryCreatedEvent<K>) event).getKey(); break; case CLIENT_CACHE_ENTRY_MODIFIED: eventKey = ((ClientCacheEntryModifiedEvent<K>) event).getKey(); break; case CLIENT_CACHE_ENTRY_REMOVED: eventKey = ((ClientCacheEntryRemovedEvent<K>) event).getKey(); break; case CLIENT_CACHE_ENTRY_EXPIRED: eventKey = ((ClientCacheEntryExpiredEvent<K>) event).getKey(); break; } checkUnorderedKeyEvent(assertedKeys, key, eventKey); } int finalSize = assertedKeys.size(); assertEquals(initialSize + 1, finalSize); } } private boolean checkUnorderedKeyEvent(List<K> assertedKeys, K key, K eventKey) { if (key.equals(eventKey)) { assertFalse(assertedKeys.contains(key)); assertedKeys.add(key); return true; } return false; } public void expectFailoverEvent() { pollEvent(ClientEvent.Type.CLIENT_CACHE_FAILOVER); } public void accept(BiConsumer<EventLogListener<K, V>, RemoteCache<K, V>> cons) { remote.addClientListener(this); try { cons.accept(this, remote); } finally { remote.removeClientListener(this); } } public void accept(Object[] fparams, Object[] cparams, BiConsumer<EventLogListener<K, V>, RemoteCache<K, V>> cons) { remote.addClientListener(this, fparams, cparams); try { cons.accept(this, remote); } finally { remote.removeClientListener(this); } } @ClientListener(filterFactoryName = "static-filter-factory") public static class StaticFilteredEventLogListener<K, V> extends EventLogListener<K, V> { public StaticFilteredEventLogListener(RemoteCache<K, V> r) { super(r); } } @ClientListener(filterFactoryName = "raw-static-filter-factory", useRawData = true) public static class RawStaticFilteredEventLogListener<K, V> extends EventLogListener<K, V> { public RawStaticFilteredEventLogListener(RemoteCache<K, V> r) { super(r); } } @ClientListener(filterFactoryName = "static-filter-factory", includeCurrentState = true) public static class StaticFilteredEventLogWithStateListener<K, V> extends EventLogListener<K, V> { public StaticFilteredEventLogWithStateListener(RemoteCache<K, V> r) { super(r); } } @ClientListener(filterFactoryName = "dynamic-filter-factory") public static class DynamicFilteredEventLogListener<K, V> extends EventLogListener<K, V> { public DynamicFilteredEventLogListener(RemoteCache<K, V> r) { super(r); } } @ClientListener(filterFactoryName = "dynamic-filter-factory", includeCurrentState = true) public static class DynamicFilteredEventLogWithStateListener<K, V> extends EventLogListener<K, V> { public DynamicFilteredEventLogWithStateListener(RemoteCache<K, V> r) { super(r); } } @ClientListener(includeCurrentState = true) public static class WithStateEventLogListener<K, V> extends EventLogListener<K, V> { public WithStateEventLogListener(RemoteCache<K, V> remote) { super(remote); } } @ClientListener(filterFactoryName = "non-existing-test-filter-factory") public static class NonExistingFilterFactoryListener<K, V> extends EventLogListener<K, V> { public NonExistingFilterFactoryListener(RemoteCache<K, V> r) { super(r); } } }
10,886
40.553435
119
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/hotrod/HotRodAdmin.java
package org.infinispan.server.functional.hotrod; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.commons.configuration.StringConfiguration; import org.infinispan.commons.test.Exceptions; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @author Ryan Emerson * @since 12.0 */ public class HotRodAdmin { @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; @Test public void testCreateDeleteCache() { RemoteCacheManager rcm = SERVERS.hotrod().createRemoteCacheManager(); String cacheName = "testCreateDeleteCache"; String config = String.format("<infinispan><cache-container><distributed-cache name=\"%s\"/></cache-container></infinispan>", cacheName); RemoteCache<String, String> cache = rcm.administration().createCache(cacheName, new StringConfiguration(config)); cache.put("k", "v"); assertNotNull(cache.get("k")); rcm.administration().removeCache(cacheName); assertNull(rcm.getCache(cacheName)); } @Test public void testCreateDeleteCacheFragment() { RemoteCacheManager rcm = SERVERS.hotrod().createRemoteCacheManager(); String cacheName = "testCreateDeleteCacheFragment"; String config = String.format("<distributed-cache name=\"%s\"/>", cacheName); RemoteCache<String, String> cache = rcm.administration().createCache(cacheName, new StringConfiguration(config)); cache.put("k", "v"); assertNotNull(cache.get("k")); rcm.administration().removeCache(cacheName); assertNull(rcm.getCache(cacheName)); } @Test public void testCreateDeleteTemplate() { RemoteCacheManager rcm = SERVERS.hotrod().createRemoteCacheManager(); String templateName = "template"; String template = String.format("<infinispan><cache-container><distributed-cache name=\"%s\"/></cache-container></infinispan>", templateName); rcm.administration().createTemplate(templateName, new StringConfiguration(template)); RemoteCache<String, String> cache = rcm.administration().createCache("testCreateDeleteTemplate", templateName); cache.put("k", "v"); assertNotNull(cache.get("k")); rcm.administration().removeTemplate(templateName); Exceptions.expectException(HotRodClientException.class, () -> rcm.administration().createCache("anotherCache", templateName)); } @Test public void testCreateDeleteTemplateFragment() { RemoteCacheManager rcm = SERVERS.hotrod().createRemoteCacheManager(); String templateName = "templateFragment"; String template = String.format("<distributed-cache name=\"%s\"/>", templateName); rcm.administration().createTemplate(templateName, new StringConfiguration(template)); RemoteCache<String, String> cache = rcm.administration().createCache("testCreateDeleteTemplateFragment", templateName); cache.put("k", "v"); assertNotNull(cache.get("k")); rcm.administration().removeTemplate(templateName); Exceptions.expectException(HotRodClientException.class, () -> rcm.administration().createCache("anotherCache", templateName)); } }
3,555
44.012658
148
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/hotrod/HotRodListenerWithDslFilter.java
package org.infinispan.server.functional.hotrod; import static org.infinispan.server.functional.hotrod.HotRodCacheQueries.BANK_PROTO_FILE; import static org.infinispan.server.functional.hotrod.HotRodCacheQueries.ENTITY_USER; import static org.infinispan.server.test.core.Common.createQueryableCache; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated; import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified; import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.event.ClientCacheEntryCustomEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryRemovedEvent; import org.infinispan.client.hotrod.event.ClientEvents; import org.infinispan.client.hotrod.filter.Filters; import org.infinispan.client.hotrod.marshall.MarshallerUtil; import org.infinispan.protostream.ProtobufUtil; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.sampledomain.Address; import org.infinispan.protostream.sampledomain.User; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.query.remote.client.FilterResult; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * Basic test for query DSL based remote event filters. * * @author anistor@redhat.com * @since 8.1 */ public class HotRodListenerWithDslFilter { @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; @Test public void testEventFilter() { RemoteCache<Integer, User> remoteCache = createQueryableCache(SERVERS, true, BANK_PROTO_FILE, ENTITY_USER); User user1 = new User(); user1.setId(1); user1.setName("John"); user1.setSurname("Doe"); user1.setGender(User.Gender.MALE); user1.setAge(22); user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2))); user1.setNotes("Lorem ipsum dolor sit amet"); Address address1 = new Address(); address1.setStreet("Main Street"); address1.setPostCode("X1234"); user1.setAddresses(Collections.singletonList(address1)); User user2 = new User(); user2.setId(2); user2.setName("Spider"); user2.setSurname("Man"); user2.setGender(User.Gender.MALE); user2.setAge(32); user2.setAccountIds(Collections.singleton(3)); Address address2 = new Address(); address2.setStreet("Old Street"); address2.setPostCode("Y12"); Address address3 = new Address(); address3.setStreet("Bond Street"); address3.setPostCode("ZZ"); user2.setAddresses(Arrays.asList(address2, address3)); User user3 = new User(); user3.setId(3); user3.setName("Spider"); user3.setSurname("Woman"); user3.setGender(User.Gender.FEMALE); user3.setAge(31); user3.setAccountIds(Collections.emptySet()); remoteCache.put(user1.getId(), user1); remoteCache.put(user2.getId(), user2); remoteCache.put(user3.getId(), user3); assertEquals(3, remoteCache.size()); SerializationContext serCtx = MarshallerUtil.getSerializationContext(remoteCache.getRemoteCacheManager()); QueryFactory qf = Search.getQueryFactory(remoteCache); Query<User> query = qf.<User>create("SELECT age FROM sample_bank_account.User WHERE age <= :ageParam") .setParameter("ageParam", 32); ClientEntryListener listener = new ClientEntryListener(serCtx); ClientEvents.addClientQueryListener(remoteCache, listener, query); expectElementsInQueue(listener.createEvents, 3); user3.setAge(40); remoteCache.put(user1.getId(), user1); remoteCache.put(user2.getId(), user2); remoteCache.put(user3.getId(), user3); assertEquals(3, remoteCache.size()); expectElementsInQueue(listener.modifyEvents, 2); remoteCache.removeClientListener(listener); } private void expectElementsInQueue(BlockingQueue<?> queue, int numElements) { for (int i = 0; i < numElements; i++) { try { Object e = queue.poll(5, TimeUnit.SECONDS); assertNotNull(e, "Queue was empty!"); } catch (InterruptedException e) { throw new AssertionError("Interrupted while waiting for condition", e); } } try { // no more elements expected here Object e = queue.poll(5, TimeUnit.SECONDS); assertNull(e, "No more elements expected in queue!"); } catch (InterruptedException e) { throw new AssertionError("Interrupted while waiting for condition", e); } } @ClientListener(filterFactoryName = Filters.QUERY_DSL_FILTER_FACTORY_NAME, converterFactoryName = Filters.QUERY_DSL_FILTER_FACTORY_NAME, useRawData = true, includeCurrentState = true) public static class ClientEntryListener { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); public final BlockingQueue<FilterResult> createEvents = new LinkedBlockingQueue<>(); public final BlockingQueue<FilterResult> modifyEvents = new LinkedBlockingQueue<>(); private final SerializationContext serializationContext; public ClientEntryListener(SerializationContext serializationContext) { this.serializationContext = serializationContext; } @ClientCacheEntryCreated @SuppressWarnings("unused") public void handleClientCacheEntryCreatedEvent(ClientCacheEntryCustomEvent event) throws IOException { FilterResult r = ProtobufUtil.fromWrappedByteArray(serializationContext, (byte[]) event.getEventData()); createEvents.add(r); log.debugf("handleClientCacheEntryCreatedEvent instance=%s projection=%s sortProjection=%s\n", r.getInstance(), r.getProjection() == null ? null : Arrays.asList(r.getProjection()), r.getSortProjection() == null ? null : Arrays.asList(r.getSortProjection())); } @ClientCacheEntryModified @SuppressWarnings("unused") public void handleClientCacheEntryModifiedEvent(ClientCacheEntryCustomEvent event) throws IOException { FilterResult r = ProtobufUtil.fromWrappedByteArray(serializationContext, (byte[]) event.getEventData()); modifyEvents.add(r); log.debugf("handleClientCacheEntryModifiedEvent instance=%s projection=%s sortProjection=%s\n", r.getInstance(), r.getProjection() == null ? null : Arrays.asList(r.getProjection()), r.getSortProjection() == null ? null : Arrays.asList(r.getSortProjection())); } @ClientCacheEntryRemoved @SuppressWarnings("unused") public void handleClientCacheEntryRemovedEvent(ClientCacheEntryRemovedEvent event) { log.debugf("handleClientCacheEntryRemovedEvent %s\n", event.getKey()); } } }
7,751
40.234043
113
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/hotrod/HotRodCacheContinuousQueries.java
package org.infinispan.server.functional.hotrod; import static org.infinispan.server.functional.hotrod.HotRodCacheQueries.BANK_PROTO_FILE; import static org.infinispan.server.functional.hotrod.HotRodCacheQueries.ENTITY_USER; import static org.infinispan.server.test.core.Common.createQueryableCache; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.Search; import org.infinispan.protostream.sampledomain.User; import org.infinispan.query.api.continuous.ContinuousQuery; import org.infinispan.query.api.continuous.ContinuousQueryListener; import org.infinispan.query.dsl.Query; import org.infinispan.query.dsl.QueryFactory; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class HotRodCacheContinuousQueries { @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; @ParameterizedTest @ValueSource(booleans = {true, false}) public void testQueries(boolean indexed) { RemoteCache<Integer, User> remoteCache = createQueryableCache(SERVERS, indexed, BANK_PROTO_FILE, ENTITY_USER); remoteCache.put(1, createUser(1, 25)); remoteCache.put(2, createUser(2, 25)); remoteCache.put(3, createUser(3, 20)); assertEquals(3, remoteCache.size()); QueryFactory qf = Search.getQueryFactory(remoteCache); Query<User> query = qf.create("FROM sample_bank_account.User WHERE name = 'user1' AND age > 20"); final BlockingQueue<Integer> joined = new LinkedBlockingQueue<>(); final BlockingQueue<Integer> updated = new LinkedBlockingQueue<>(); final BlockingQueue<Integer> left = new LinkedBlockingQueue<>(); ContinuousQueryListener<Integer, User> listener = new ContinuousQueryListener<Integer, User>() { @Override public void resultJoining(Integer key, User value) { joined.add(key); } @Override public void resultUpdated(Integer key, User value) { updated.add(key); } @Override public void resultLeaving(Integer key) { left.add(key); } }; ContinuousQuery<Integer, User> continuousQuery = Search.getContinuousQuery(remoteCache); continuousQuery.addContinuousQueryListener(query, listener); expectElementsInQueue(joined, 1); expectElementsInQueue(updated, 0); expectElementsInQueue(left, 0); User user4 = createUser(4, 30); user4.setName("user1"); remoteCache.put(4, user4); expectElementsInQueue(joined, 1); expectElementsInQueue(updated, 0); expectElementsInQueue(left, 0); User user1 = remoteCache.get(1); user1.setAge(19); remoteCache.put(1, user1); expectElementsInQueue(joined, 0); expectElementsInQueue(updated, 0); expectElementsInQueue(left, 1); user4 = remoteCache.get(4); user4.setAge(32); remoteCache.put(4, user4); expectElementsInQueue(joined, 0); expectElementsInQueue(updated, 1); expectElementsInQueue(left, 0); remoteCache.clear(); expectElementsInQueue(joined, 0); expectElementsInQueue(updated, 0); expectElementsInQueue(left, 1); continuousQuery.removeContinuousQueryListener(listener); user1.setAge(25); remoteCache.put(1, user1); expectElementsInQueue(joined, 0); expectElementsInQueue(updated, 0); expectElementsInQueue(left, 0); } private User createUser(int id, int age) { User user = new User(); user.setId(id); user.setName("user" + id); user.setAge(age); user.setSurname("Doesn't matter"); user.setGender(User.Gender.MALE); return user; } private void expectElementsInQueue(BlockingQueue<?> queue, int numElements) { for (int i = 0; i < numElements; i++) { try { Object e = queue.poll(5, TimeUnit.SECONDS); assertNotNull(e, "Queue was empty!"); } catch (InterruptedException e) { throw new AssertionError("Interrupted while waiting for condition", e); } } try { // no more elements expected here Object e = queue.poll(500, TimeUnit.MILLISECONDS); assertNull(e, "No more elements expected in queue!"); } catch (InterruptedException e) { throw new AssertionError("Interrupted while waiting for condition", e); } } }
5,033
35.478261
116
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/hotrod/KeyValueGenerator.java
package org.infinispan.server.functional.hotrod; import static org.infinispan.test.TestingUtil.v; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.infinispan.commons.jdkspecific.CallerId; import org.infinispan.test.TestingUtil; import org.junit.jupiter.api.Assertions; /** * A key and value generator for Hot Rod testing. * * @author Pedro Ruivo * @since 9.3 */ public interface KeyValueGenerator<K, V> { KeyValueGenerator<String, String> STRING_GENERATOR = new KeyValueGenerator<>() { @Override public String key(int index) { return TestingUtil.k(CallerId.getCallerMethodName(3), index); } @Override public String value(int index) { return v(CallerId.getCallerMethodName(3), index); } @Override public void assertEquals(String expected, String actual) { Assertions.assertEquals(expected, actual); } @Override public String toString() { return "STRING"; } }; KeyValueGenerator<byte[], byte[]> BYTE_ARRAY_GENERATOR = new KeyValueGenerator<>() { @Override public byte[] key(int index) { return TestingUtil.k(CallerId.getCallerMethodName(3), index).getBytes(); } @Override public byte[] value(int index) { return v(CallerId.getCallerMethodName(3), index).getBytes(); } @Override public void assertEquals(byte[] expected, byte[] actual) { assertArrayEquals(expected, actual); } @Override public String toString() { return "BYTE_ARRAY"; } }; KeyValueGenerator<Object[], Object[]> GENERIC_ARRAY_GENERATOR = new KeyValueGenerator<>() { @Override public Object[] key(int index) { return new Object[]{CallerId.getCallerMethodName(3), "key", index}; } @Override public Object[] value(int index) { return new Object[]{CallerId.getCallerMethodName(3), "value", index}; } @Override public void assertEquals(Object[] expected, Object[] actual) { assertArrayEquals(expected, actual); } @Override public String toString() { return "GENERIC_ARRAY"; } }; K key(int index); V value(int index); void assertEquals(V expected, V actual); }
2,322
24.25
94
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/hotrod/HotRodMultiMapOperations.java
package org.infinispan.server.functional.hotrod; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Collection; import java.util.concurrent.CompletableFuture; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.multimap.MetadataCollection; import org.infinispan.client.hotrod.multimap.MultimapCacheManager; import org.infinispan.client.hotrod.multimap.RemoteMultimapCache; import org.infinispan.client.hotrod.multimap.RemoteMultimapCacheManagerFactory; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class HotRodMultiMapOperations { @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; @Test public void testMultiMap() { RemoteMultimapCache<Integer, String> people = multimapCache(); CompletableFuture<Void> elaia = people.put(1, "Elaia"); people.put(1, "Oihana").join(); elaia.join(); Collection<String> littles = people.get(1).join(); assertEquals(2, littles.size()); assertTrue(littles.contains("Elaia")); assertTrue(littles.contains("Oihana")); } @Test public void testPutWithDuplicates() { RemoteMultimapCache<String, String> multimapCache = multimapCache(); multimapCache.put("k", "a").join(); multimapCache.put("k", "a").join(); multimapCache.put("k", "a").join(); Collection<String> kValues = multimapCache.get("k").join(); assertEquals(1, kValues.size()); assertTrue(kValues.contains("a")); } @Test public void testGetWithMetadata() { RemoteMultimapCache<String, String> multimapCache = multimapCache(); multimapCache.put("k", "a").join(); MetadataCollection<String> metadataCollection = multimapCache.getWithMetadata("k").join(); assertEquals(1, metadataCollection.getCollection().size()); assertTrue(metadataCollection.getCollection().contains("a")); assertEquals(-1, metadataCollection.getLifespan()); assertEquals(0, metadataCollection.getVersion()); } @Test public void testRemoveKey() { RemoteMultimapCache<String, String> multimapCache = multimapCache(); multimapCache.put("k", "a").join(); Collection<String> kValues = multimapCache.get("k").join(); assertEquals(1, kValues.size()); assertTrue(kValues.contains("a")); assertTrue(multimapCache.remove("k").join()); assertEquals(0, multimapCache.get("k").join().size()); assertFalse(multimapCache.remove("k").join()); } @Test public void testRemoveKeyValue() { RemoteMultimapCache<String, String> multimapCache = multimapCache(); multimapCache.put("k", "a").join(); multimapCache.put("k", "b").join(); multimapCache.put("k", "c").join(); Collection<String> kValues = multimapCache.get("k").join(); assertEquals(3, kValues.size()); assertTrue(multimapCache.remove("k", "a").join()); assertEquals(2, multimapCache.get("k").join().size()); } @Test public void testSize() { RemoteMultimapCache<String, String> multimapCache = multimapCache(); assertEquals(Long.valueOf(0), multimapCache.size().join()); multimapCache.put("k", "a").join(); assertEquals(Long.valueOf(1), multimapCache.size().join()); multimapCache.put("k", "b").join(); assertEquals(Long.valueOf(2), multimapCache.size().join()); } @Test public void testContainsEntry() { RemoteMultimapCache<String, String> multimapCache = multimapCache(); multimapCache.put("k", "a").join(); assertTrue(multimapCache.containsEntry("k", "a").join()); assertFalse(multimapCache.containsEntry("k", "b").join()); } @Test public void testContainsKey() { RemoteMultimapCache<String, String> multimapCache = multimapCache(); multimapCache.put("k", "a").join(); assertTrue(multimapCache.containsKey("k").join()); assertFalse(multimapCache.containsKey("l").join()); } @Test public void testContainsValue() { RemoteMultimapCache<String, String> multimapCache = multimapCache(); multimapCache.put("k", "a").join(); assertTrue(multimapCache.containsValue("a").join()); assertFalse(multimapCache.containsValue("b").join()); } private <K, V> RemoteMultimapCache<K, V> multimapCache() { RemoteCache<K, V> cache = SERVERS.hotrod().create(); MultimapCacheManager<K, V> multimapCacheManager = RemoteMultimapCacheManagerFactory.from(cache.getRemoteCacheManager()); return multimapCacheManager.get(cache.getName()); } }
4,955
35.175182
126
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/hotrod/HotRodCacheEvents.java
package org.infinispan.server.functional.hotrod; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON; import static org.infinispan.server.test.core.Common.createQueryableCache; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import static org.wildfly.common.Assert.assertTrue; import java.io.IOException; import java.util.Arrays; import java.util.Set; import java.util.stream.Stream; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.ProtocolVersion; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.VersionedValue; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.event.ClientEvent; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.commons.marshall.Marshaller; import org.infinispan.commons.marshall.UTF8StringMarshaller; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.functional.extensions.entities.Entities; import org.infinispan.server.test.core.Common; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class HotRodCacheEvents { @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; static class ArgsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { return Arrays.stream(ProtocolVersion.values()) .filter(v -> v != ProtocolVersion.PROTOCOL_VERSION_20) // Listeners were introduced in 2.1 .map(Arguments::of); } } private <K, V> RemoteCache<K, V> remoteCache(ProtocolVersion protocolVersion) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.version(protocolVersion).addContextInitializer(Entities.INSTANCE); return SERVERS.hotrod().withClientConfiguration(builder).withCacheMode(CacheMode.DIST_SYNC).create(); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testCreatedEvent(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.put(1, "one"); l.expectOnlyCreatedEvent(1); remote.put(2, "two"); l.expectOnlyCreatedEvent(2); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testModifiedEvent(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.put(1, "one"); l.expectOnlyCreatedEvent(1); remote.put(1, "newone"); l.expectOnlyModifiedEvent(1); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testRemovedEvent(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.remove(1); l.expectNoEvents(); remote.put(1, "one"); l.expectOnlyCreatedEvent(1); remote.remove(1); l.expectOnlyRemovedEvent(1); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testReplaceEvents(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.replace(1, "one"); l.expectNoEvents(); remote.put(1, "one"); l.expectOnlyCreatedEvent(1); remote.replace(1, "newone"); l.expectOnlyModifiedEvent(1); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testPutIfAbsentEvents(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.putIfAbsent(1, "one"); l.expectOnlyCreatedEvent(1); remote.putIfAbsent(1, "newone"); l.expectNoEvents(); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testReplaceIfUnmodifiedEvents(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.replaceWithVersion(1, "one", 0); l.expectNoEvents(); remote.putIfAbsent(1, "one"); l.expectOnlyCreatedEvent(1); remote.replaceWithVersion(1, "one", 0); l.expectNoEvents(); VersionedValue<?> versioned = remote.getWithMetadata(1); remote.replaceWithVersion(1, "one", versioned.getVersion()); l.expectOnlyModifiedEvent(1); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testRemoveIfUnmodifiedEvents(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.removeWithVersion(1, 0); l.expectNoEvents(); remote.putIfAbsent(1, "one"); l.expectOnlyCreatedEvent(1); remote.removeWithVersion(1, 0); l.expectNoEvents(); VersionedValue<?> versioned = remote.getWithMetadata(1); remote.removeWithVersion(1, versioned.getVersion()); l.expectOnlyRemovedEvent(1); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testClearEvents(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.put(1, "one"); l.expectOnlyCreatedEvent(1); remote.put(2, "two"); l.expectOnlyCreatedEvent(2); remote.put(3, "three"); l.expectOnlyCreatedEvent(3); remote.clear(); l.expectUnorderedEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_REMOVED, 1, 2, 3); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testNoEventsBeforeAddingListener(ProtocolVersion protocolVersion) { RemoteCache<Integer, String> rcache = remoteCache(protocolVersion); final EventLogListener<Integer, String> l = new EventLogListener<>(rcache); rcache.put(1, "one"); l.expectNoEvents(); rcache.put(1, "newone"); l.expectNoEvents(); rcache.remove(1); l.expectNoEvents(); createUpdateRemove(l); } private void createUpdateRemove(EventLogListener<Integer, String> listener) { listener.accept((l, remote) -> { remote.put(1, "one"); l.expectOnlyCreatedEvent(1); remote.put(1, "newone"); l.expectOnlyModifiedEvent(1); remote.remove(1); l.expectOnlyRemovedEvent(1); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testNoEventsAfterRemovingListener(ProtocolVersion protocolVersion) { final RemoteCache<Integer, String> rcache = remoteCache(protocolVersion); final EventLogListener<Integer, String> l = new EventLogListener<>(rcache); createUpdateRemove(l); rcache.put(1, "one"); l.expectNoEvents(); rcache.put(1, "newone"); l.expectNoEvents(); rcache.remove(1); l.expectNoEvents(); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testSetListeners(ProtocolVersion protocolVersion) { final RemoteCache<Integer, String> rcache = remoteCache(protocolVersion); new EventLogListener<>(rcache).accept((l1, remote1) -> { Set<?> listeners1 = remote1.getListeners(); assertEquals(1, listeners1.size()); assertEquals(l1, listeners1.iterator().next()); new EventLogListener<>(rcache).accept((l2, remote2) -> { Set<?> listeners2 = remote2.getListeners(); assertEquals(2, listeners2.size()); assertTrue(listeners2.contains(l1)); assertTrue(listeners2.contains(l2)); }); }); Set<Object> listeners = rcache.getListeners(); assertEquals(0, listeners.size()); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testCustomTypeEvents(ProtocolVersion protocolVersion) { final EventLogListener<Entities.CustomKey, String> listener = new EventLogListener<>(remoteCache(protocolVersion)); listener.accept((l, remote) -> { l.expectNoEvents(); Entities.CustomKey key = new Entities.CustomKey(1); remote.put(key, "one"); l.expectOnlyCreatedEvent(key); remote.replace(key, "newone"); l.expectOnlyModifiedEvent(key); remote.remove(key); l.expectOnlyRemovedEvent(key); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testEventReplayAfterAddingListener(ProtocolVersion protocolVersion) { RemoteCache<Integer, String> cache = remoteCache(protocolVersion); final EventLogListener.WithStateEventLogListener<Integer, String> listener = new EventLogListener.WithStateEventLogListener<>(cache); cache.put(1, "one"); cache.put(2, "two"); listener.expectNoEvents(); listener.accept((l, remote) -> l.expectUnorderedEvents(ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED, 1, 2)); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testNoEventReplayAfterAddingListener(ProtocolVersion protocolVersion) { RemoteCache<Integer, String> cache = remoteCache(protocolVersion); final EventLogListener<Integer, String> listener = new EventLogListener<>(cache); cache.put(1, "one"); cache.put(2, "two"); listener.expectNoEvents(); listener.accept((l, remote) -> l.expectNoEvents()); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testCreatedEventSkipListener(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).put(1, "one"); l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).put(2, "two"); l.expectNoEvents(); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testModifiedEventSkipListener(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).put(1, "one"); l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).put(1, "newone"); l.expectNoEvents(); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testRemovedEventSkipListener(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).remove(1); l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).put(1, "one"); l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).remove(1); l.expectNoEvents(); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testReplaceEventsSkipListener(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).replace(1, "one"); l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).put(1, "one"); l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).replace(1, "newone"); l.expectNoEvents(); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testPutIfAbsentEventsSkipListener(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).putIfAbsent(1, "one"); l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).putIfAbsent(1, "newone"); l.expectNoEvents(); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testReplaceIfUnmodifiedEventsSkipListener(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).replaceWithVersion(1, "one", 0); l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).putIfAbsent(1, "one"); l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).replaceWithVersion(1, "one", 0); l.expectNoEvents(); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testRemoveIfUnmodifiedEventsSkipListener(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).removeWithVersion(1, 0); l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).putIfAbsent(1, "one"); l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).removeWithVersion(1, 0); l.expectNoEvents(); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testClearEventsSkipListener(ProtocolVersion protocolVersion) { new EventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).put(1, "one"); l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).put(2, "two"); l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).put(3, "three"); l.expectNoEvents(); remote.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).clear(); l.expectNoEvents(); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testFilteredEvents(ProtocolVersion protocolVersion) { new EventLogListener.StaticFilteredEventLogListener<>(remoteCache(protocolVersion)).accept(new Object[]{2}, null, (l, remote) -> { l.expectNoEvents(); remote.put(1, "one"); l.expectNoEvents(); remote.put(2, "two"); l.expectOnlyCreatedEvent(2); remote.remove(1); l.expectNoEvents(); remote.remove(2); l.expectOnlyRemovedEvent(2); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testParameterBasedFiltering(ProtocolVersion protocolVersion) { new EventLogListener.DynamicFilteredEventLogListener<>(remoteCache(protocolVersion)).accept(new Object[]{3}, null, (l, remote) -> { l.expectNoEvents(); remote.put(1, "one"); l.expectNoEvents(); remote.put(2, "two"); l.expectNoEvents(); remote.put(3, "three"); l.expectOnlyCreatedEvent(3); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testFilteredEventsReplay(ProtocolVersion protocolVersion) { RemoteCache<Integer, String> cache = remoteCache(protocolVersion); final EventLogListener.StaticFilteredEventLogWithStateListener<Integer, String> staticEventListener = new EventLogListener.StaticFilteredEventLogWithStateListener<>(cache); cache.put(1, "one"); cache.put(2, "two"); staticEventListener.accept(new Object[]{2}, null, (l, remote) -> { l.expectOnlyCreatedEvent(2); remote.remove(1); remote.remove(2); l.expectOnlyRemovedEvent(2); }); final EventLogListener.DynamicFilteredEventLogWithStateListener<Integer, String> dynamicEventListener = new EventLogListener.DynamicFilteredEventLogWithStateListener<>(cache); cache.put(1, "one"); cache.put(2, "two"); cache.put(3, "three"); dynamicEventListener.accept(new Object[]{3}, null, (l, remote) -> { l.expectOnlyCreatedEvent(3); remote.remove(1); remote.remove(2); remote.remove(3); l.expectOnlyRemovedEvent(3); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testFilteredNoEventsReplay(ProtocolVersion protocolVersion) { RemoteCache<Integer, String> cache = remoteCache(protocolVersion); final EventLogListener.StaticFilteredEventLogListener<Integer, String> staticEventListener = new EventLogListener.StaticFilteredEventLogListener<>(cache); cache.put(1, "one"); cache.put(2, "two"); staticEventListener.accept(new Object[]{2}, null, (l, remote) -> { l.expectNoEvents(); remote.remove(1); remote.remove(2); l.expectOnlyRemovedEvent(2); }); final EventLogListener.DynamicFilteredEventLogListener<Integer, String> dynamicEventListener = new EventLogListener.DynamicFilteredEventLogListener<>(cache); cache.put(1, "one"); cache.put(2, "two"); cache.put(3, "three"); dynamicEventListener.accept(new Object[]{3}, null, (l, remote) -> { staticEventListener.expectNoEvents(); remote.remove(1); remote.remove(2); remote.remove(3); l.expectOnlyRemovedEvent(3); }); } /** * Test that the HotRod server returns an error when a ClientListener is registered with a non-existing * 'filterFactoryName'. */ @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testNonExistingConverterFactoryCustomEvents(ProtocolVersion protocolVersion) { assertThrows(HotRodClientException.class, () -> { EventLogListener.NonExistingFilterFactoryListener<Integer, String> listener = new EventLogListener.NonExistingFilterFactoryListener<>(remoteCache(protocolVersion)); listener.accept((l, remote) -> { }); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testRawFilteredEvents(ProtocolVersion protocolVersion) { final EventLogListener.RawStaticFilteredEventLogListener<Integer, String> listener = new EventLogListener.RawStaticFilteredEventLogListener<>(remoteCache(protocolVersion)); listener.accept((l, remote) -> { l.expectNoEvents(); remote.put(1, "one"); l.expectNoEvents(); remote.put(2, "two"); l.expectOnlyCreatedEvent(2); remote.remove(1); l.expectNoEvents(); remote.remove(2); l.expectOnlyRemovedEvent(2); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testCustomEvents(ProtocolVersion protocolVersion) { final CustomEventLogListener.StaticCustomEventLogListener<Integer, String> listener = new CustomEventLogListener.StaticCustomEventLogListener<>(remoteCache(protocolVersion)); listener.accept((l, remote) -> { l.expectNoEvents(); remote.put(1, "one"); l.expectCreatedEvent(new Entities.CustomEvent<>(1, "one", 0)); remote.put(1, "newone"); l.expectModifiedEvent(new Entities.CustomEvent<>(1, "newone", 0)); remote.remove(1); l.expectRemovedEvent(new Entities.CustomEvent<>(1, null, 0)); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testCustomEvents2(ProtocolVersion protocolVersion) { final CustomEventLogListener.SimpleListener<String, String> listener = new CustomEventLogListener.SimpleListener<>(remoteCache(protocolVersion)); listener.accept((l, remote) -> { l.expectNoEvents(); remote.put("1", "one"); l.expectCreatedEvent("one"); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testTimeOrderedEvents(ProtocolVersion protocolVersion) { new CustomEventLogListener.StaticCustomEventLogListener<>(remoteCache(protocolVersion)).accept((l, remote) -> { l.expectNoEvents(); remote.put(1, "one"); remote.replace(1, "newone"); remote.replace(1, "newnewone"); remote.replace(1, "newnewnewone"); remote.replace(1, "newnewnewnewone"); remote.replace(1, "newnewnewnewnewone"); l.expectOrderedEventQueue(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testNoConverterFactoryCustomEvents(ProtocolVersion protocolVersion) { CustomEventLogListener.NoConverterFactoryListener<Integer, String> listener = new CustomEventLogListener.NoConverterFactoryListener<>(remoteCache(protocolVersion)); listener.accept((l, remote) -> { l.expectNoEvents(); remote.put(1, "one"); // We don't get an event, since we don't have a converter and we only allow custom events l.expectNoEvents(); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testParameterBasedConversion(ProtocolVersion protocolVersion) { final CustomEventLogListener.DynamicCustomEventLogListener<Integer, String> listener = new CustomEventLogListener.DynamicCustomEventLogListener<>(remoteCache(protocolVersion)); listener.accept(null, new Object[]{2}, (l, remote) -> { l.expectNoEvents(); remote.put(1, "one"); l.expectCreatedEvent(new Entities.CustomEvent<>(1, "one", 0)); remote.put(2, "two"); l.expectCreatedEvent(new Entities.CustomEvent<>(2, null, 0)); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testConvertedEventsReplay(ProtocolVersion protocolVersion) { RemoteCache<Integer, String> cache = remoteCache(protocolVersion); cache.put(1, "one"); CustomEventLogListener.StaticCustomEventLogWithStateListener<Integer, String> staticEventListener = new CustomEventLogListener.StaticCustomEventLogWithStateListener<>(cache); staticEventListener.accept((l, remote) -> l.expectCreatedEvent(new Entities.CustomEvent<>(1, "one", 0))); CustomEventLogListener.DynamicCustomEventWithStateLogListener<Integer, String> dynamicEventListener = new CustomEventLogListener.DynamicCustomEventWithStateLogListener<>(cache); dynamicEventListener.accept(null, new Object[]{2}, (l, remote) -> { l.expectCreatedEvent(new Entities.CustomEvent<>(1, "one", 0)); remote.put(2, "two"); l.expectCreatedEvent(new Entities.CustomEvent<>(2, null, 0)); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testConvertedNoEventsReplay(ProtocolVersion protocolVersion) { RemoteCache<Integer, String> cache = remoteCache(protocolVersion); CustomEventLogListener.StaticCustomEventLogListener<Integer, String> staticListener = new CustomEventLogListener.StaticCustomEventLogListener<>(cache); cache.put(1, "one"); staticListener.accept((l, remote) -> l.expectNoEvents()); CustomEventLogListener.DynamicCustomEventLogListener<Integer, String> dynamicListener = new CustomEventLogListener.DynamicCustomEventLogListener<>(cache); cache.put(2, "two"); dynamicListener.accept(null, new Object[]{2}, (l, remote) -> l.expectNoEvents()); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testRawCustomEvents(ProtocolVersion protocolVersion) { CustomEventLogListener.RawStaticCustomEventLogListener<Integer, String> listener = new CustomEventLogListener.RawStaticCustomEventLogListener<>(remoteCache(protocolVersion)); listener.accept((l, remote) -> { l.expectNoEvents(); Marshaller marshaller = remote.getRemoteCacheContainer().getMarshaller(); Integer key = 1; String value = "one"; try { byte[] keyBytes = marshaller.objectToByteBuffer(key); byte[] valBytes = marshaller.objectToByteBuffer(value); // Put initial value and assert converter creates a byte[] of the key + value bytes remote.put(key, value); l.expectCreatedEvent(Util.concat(keyBytes, valBytes)); value = "newone"; // Repeat with new value valBytes = marshaller.objectToByteBuffer(value); remote.put(key, value); l.expectModifiedEvent(Util.concat(keyBytes, valBytes)); // Only keyBytes should be returned as no value in remove event remote.remove(key); l.expectRemovedEvent(keyBytes); } catch (InterruptedException | IOException e) { fail(e.getMessage()); } }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testEventForwarding(ProtocolVersion protocolVersion) { RemoteCache<Integer, String> cache = remoteCache(protocolVersion); final Integer key0 = Common.getIntKeyForServer(cache, 0); final Integer key1 = Common.getIntKeyForServer(cache, 1); final EventLogListener<Integer, String> listener = new EventLogListener<>(cache); listener.accept((l, remote) -> { l.expectNoEvents(); remote.put(key0, "one"); l.expectOnlyCreatedEvent(key0); remote.put(key1, "two"); l.expectOnlyCreatedEvent(key1); remote.replace(key0, "new-one"); l.expectOnlyModifiedEvent(key0); remote.replace(key1, "new-two"); l.expectOnlyModifiedEvent(key1); remote.remove(key0); l.expectOnlyRemovedEvent(key0); remote.remove(key1); l.expectOnlyRemovedEvent(key1); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testFilteringInCluster(ProtocolVersion protocolVersion) { RemoteCache<Integer, String> cache = remoteCache(protocolVersion); final Integer key0 = Common.getIntKeyForServer(cache, 0); final Integer key1 = Common.getIntKeyForServer(cache, 1); final EventLogListener.StaticFilteredEventLogListener<Integer, String> listener = new EventLogListener.StaticFilteredEventLogListener<>(cache); listener.accept(new Object[]{key1}, null, (l, remote) -> { l.expectNoEvents(); remote.put(key0, "one"); l.expectNoEvents(); remote.put(key1, "two"); l.expectOnlyCreatedEvent(key1); remote.remove(key0); l.expectNoEvents(); remote.remove(key1); l.expectOnlyRemovedEvent(key1); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testConversionInCluster(ProtocolVersion protocolVersion) { RemoteCache<Integer, String> cache = remoteCache(protocolVersion); final Integer key0 = Common.getIntKeyForServer(cache, 0); final Integer key1 = Common.getIntKeyForServer(cache, 1); final CustomEventLogListener.StaticCustomEventLogListener<Integer, String> listener = new CustomEventLogListener.StaticCustomEventLogListener<>(cache); listener.accept((l, remote) -> { l.expectNoEvents(); remote.put(key0, "one"); l.expectCreatedEvent(new Entities.CustomEvent<>(key0, "one", 0)); remote.put(key1, "two"); l.expectCreatedEvent(new Entities.CustomEvent<>(key1, "two", 0)); remote.remove(key0); l.expectRemovedEvent(new Entities.CustomEvent<>(key0, null, 0)); remote.remove(key1); l.expectRemovedEvent(new Entities.CustomEvent<>(key1, null, 0)); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testFilterCustomEventsInCluster(ProtocolVersion protocolVersion) { RemoteCache<Integer, String> cache = remoteCache(protocolVersion); final Integer key0 = Common.getIntKeyForServer(cache, 0); final Integer key1 = Common.getIntKeyForServer(cache, 1); final CustomEventLogListener.FilterCustomEventLogListener<Integer, String> listener = new CustomEventLogListener.FilterCustomEventLogListener<>(cache); listener.accept(new Object[]{key0}, null, (l, remote) -> { remote.put(key0, "one"); l.expectCreatedEvent(new Entities.CustomEvent<>(key0, null, 1)); remote.put(key0, "newone"); l.expectModifiedEvent(new Entities.CustomEvent<>(key0, null, 2)); remote.put(key1, "two"); l.expectCreatedEvent(new Entities.CustomEvent<>(key1, "two", 1)); remote.put(key1, "dos"); l.expectModifiedEvent(new Entities.CustomEvent<>(key1, "dos", 2)); remote.remove(key0); l.expectRemovedEvent(new Entities.CustomEvent<>(key0, null, 3)); remote.remove(key1); l.expectRemovedEvent(new Entities.CustomEvent<>(key1, null, 3)); }); } @ParameterizedTest @ArgumentsSource(ArgsProvider.class) public void testJsonEvent(ProtocolVersion protocolVersion) { DataFormat jsonValues = DataFormat.builder().valueType(APPLICATION_JSON).valueMarshaller(new UTF8StringMarshaller()).build(); RemoteCache<Integer, String> remoteCache = createQueryableCache(SERVERS, false, "/proto/json.proto", "proto.JSON").withDataFormat(jsonValues); new EventLogListener<>(remoteCache).accept((l, cache) -> { l.expectNoEvents(); cache.put(1, "{\"_type\":\"proto.JSON\",\"key\":\"one\"}"); l.expectOnlyCreatedEvent(1); cache.put(2, "{\"_type\":\"proto.JSON\",\"key\":\"two\"}"); l.expectOnlyCreatedEvent(2); }); } }
30,704
41.004104
173
java
null
infinispan-main/server/tests/src/test/java/org/infinispan/server/functional/memcached/MemcachedOperations.java
package org.infinispan.server.functional.memcached; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.server.functional.ClusteredIT; import org.infinispan.server.test.junit5.InfinispanServerExtension; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import net.spy.memcached.ConnectionFactoryBuilder; import net.spy.memcached.MemcachedClient; import net.spy.memcached.internal.GetFuture; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class MemcachedOperations { @RegisterExtension public static InfinispanServerExtension SERVERS = ClusteredIT.SERVERS; private static final AtomicInteger KCOUNTER = new AtomicInteger(0); @ParameterizedTest @EnumSource(ConnectionFactoryBuilder.Protocol.class) public void testMemcachedOperations(ConnectionFactoryBuilder.Protocol protocol) throws ExecutionException, InterruptedException, TimeoutException { MemcachedClient client = client(protocol); String k = k(); client.set(k, 0, "v1").get(10, TimeUnit.SECONDS); assertEquals("v1", client.get(k)); } @ParameterizedTest @EnumSource(ConnectionFactoryBuilder.Protocol.class) public void testSetGetNewLineChars(ConnectionFactoryBuilder.Protocol protocol) throws ExecutionException, InterruptedException, TimeoutException { MemcachedClient client = client(protocol); // make sure the set() finishes before retrieving the key String k = k(); client.set(k, 0, "A\r\nA").get(10, TimeUnit.SECONDS); assertEquals("A\r\nA", client.get(k)); } @ParameterizedTest @EnumSource(ConnectionFactoryBuilder.Protocol.class) public void testFlush(ConnectionFactoryBuilder.Protocol protocol) throws Exception { MemcachedClient client = client(protocol); String k1 = k(); String k2 = k(); client.set(k1, 0, "v1"); client.set(k2, 0, "v2").get(10, TimeUnit.SECONDS); assertTrue(client.flush().get()); assertNull(client.get(k1)); assertNull(client.get(k2)); } @ParameterizedTest @EnumSource(ConnectionFactoryBuilder.Protocol.class) public void testPutAsync(ConnectionFactoryBuilder.Protocol protocol) throws ExecutionException, InterruptedException { MemcachedClient client = client(protocol); String k = k(); Future<Boolean> key1 = client.add(k, 10, "v1"); assertTrue(key1.get()); assertEquals("v1", client.get(k)); assertNull(client.get(k())); } @ParameterizedTest @EnumSource(ConnectionFactoryBuilder.Protocol.class) public void testNonExistentkey(ConnectionFactoryBuilder.Protocol protocol) { MemcachedClient client = client(protocol); assertNull(client.get(k())); } @ParameterizedTest @EnumSource(ConnectionFactoryBuilder.Protocol.class) public void testConcurrentGets(ConnectionFactoryBuilder.Protocol protocol) throws ExecutionException, InterruptedException, TimeoutException { MemcachedClient client = client(protocol); String k = k() + "-"; int nKeys = 10; for (int i = 1; i < nKeys; ++i) { client.set(k + i, 0, "v-" + i); } // responses are sent ordered, waiting on the last one ensures that all the previous set() are completed! client.set(k + nKeys, 0, "v-" + nKeys).get(10, TimeUnit.SECONDS); List<GetFuture<Object>> getFutureList = new ArrayList<>(nKeys); for (int i = 1; i <= nKeys; ++i) { getFutureList.add(client.asyncGet(k + i)); } for (int i = 1; i <= nKeys; ++i) { assertEquals("v-" + i, getFutureList.get(i - 1).get(10, TimeUnit.SECONDS)); } } private MemcachedClient client(ConnectionFactoryBuilder.Protocol protocol) { ConnectionFactoryBuilder builder = new ConnectionFactoryBuilder(); builder.setProtocol(protocol); return SERVERS.memcached().withClientConfiguration(builder).withPort(11221).get(); } public static final String k() { return "k-" + KCOUNTER.incrementAndGet(); } }
4,523
37.338983
150
java
null
infinispan-main/server/hotrod/src/test/java/org/infinispan/server/hotrod/HotRodMarshallingTest.java
package org.infinispan.server.hotrod; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.commands.remote.ClusteredGetCommand; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.util.EnumUtil; import org.infinispan.server.core.AbstractMarshallingTest; import org.infinispan.util.ByteString; import org.testng.annotations.Test; /** * Tests marshalling of Hot Rod classes. * * @author Galder Zamarreño * @since 4.1 */ @Test(groups = "functional", testName = "server.hotrod.HotRodMarshallingTest") public class HotRodMarshallingTest extends AbstractMarshallingTest { public void testMarshallingBigByteArrayKey() throws Exception { byte[] cacheKey = getBigByteArray(); byte[] bytes = marshaller.objectToByteBuffer(cacheKey); byte[] readKey = (byte[]) marshaller.objectFromByteBuffer(bytes); assertEquals(readKey, cacheKey); } public void testMarshallingCommandWithBigByteArrayKey() throws Exception { byte[] cacheKey = getBigByteArray(); ClusteredGetCommand command = new ClusteredGetCommand(new WrappedByteArray(cacheKey), ByteString.fromString("c"), 0, EnumUtil.EMPTY_BIT_SET); byte[] bytes = marshaller.objectToByteBuffer(command); ClusteredGetCommand readCommand = (ClusteredGetCommand) marshaller.objectFromByteBuffer(bytes); assertEquals(readCommand, command); } }
1,413
36.210526
123
java