repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
null |
infinispan-main/client/rest-client/src/main/java/org/infinispan/client/rest/impl/okhttp/RestClientOkHttp.java
|
package org.infinispan.client.rest.impl.okhttp;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.StringJoiner;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
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.RestContainerClient;
import org.infinispan.client.rest.RestCounterClient;
import org.infinispan.client.rest.RestMetricsClient;
import org.infinispan.client.rest.RestRawClient;
import org.infinispan.client.rest.RestResponse;
import org.infinispan.client.rest.RestSchemaClient;
import org.infinispan.client.rest.RestSecurityClient;
import org.infinispan.client.rest.RestServerClient;
import org.infinispan.client.rest.RestTaskClient;
import org.infinispan.client.rest.configuration.AuthenticationConfiguration;
import org.infinispan.client.rest.configuration.RestClientConfiguration;
import org.infinispan.client.rest.configuration.ServerConfiguration;
import org.infinispan.client.rest.configuration.SslConfiguration;
import org.infinispan.client.rest.impl.okhttp.auth.AbstractAuthenticator;
import org.infinispan.client.rest.impl.okhttp.auth.AutoDetectAuthenticator;
import org.infinispan.client.rest.impl.okhttp.auth.BasicAuthenticator;
import org.infinispan.client.rest.impl.okhttp.auth.BearerAuthenticator;
import org.infinispan.client.rest.impl.okhttp.auth.CachingAuthenticator;
import org.infinispan.client.rest.impl.okhttp.auth.CachingAuthenticatorInterceptor;
import org.infinispan.client.rest.impl.okhttp.auth.CachingAuthenticatorWrapper;
import org.infinispan.client.rest.impl.okhttp.auth.DigestAuthenticator;
import org.infinispan.client.rest.impl.okhttp.auth.NegotiateAuthenticator;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.util.SslContextFactory;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.ConnectionPool;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 10.0
**/
public class RestClientOkHttp implements RestClient {
static final Log log = LogFactory.getLog(RestClientOkHttp.class);
static final MediaType TEXT_PLAIN = MediaType.parse("text/plain; charset=utf-8");
static final RequestBody EMPTY_BODY = RequestBody.create(null, new byte[0]);
private final RestClientConfiguration configuration;
private final OkHttpClient httpClient;
private final String baseURL;
public RestClientOkHttp(RestClientConfiguration configuration) {
this.configuration = configuration;
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder
.connectTimeout(configuration.connectionTimeout(), TimeUnit.MILLISECONDS)
.readTimeout(configuration.socketTimeout(), TimeUnit.MILLISECONDS).followRedirects(configuration.followRedirects());
SslConfiguration ssl = configuration.security().ssl();
if (ssl.enabled()) {
SSLContext sslContext = ssl.sslContext();
if (sslContext == null) {
SslContextFactory sslContextFactory = new SslContextFactory()
.keyStoreFileName(ssl.keyStoreFileName())
.keyStorePassword(ssl.keyStorePassword())
.keyStoreType(ssl.keyStoreType())
.trustStoreFileName(ssl.trustStoreFileName())
.trustStorePassword(ssl.trustStorePassword())
.trustStoreType(ssl.trustStoreType())
.sslProtocol(ssl.protocol())
.provider(ssl.provider())
.classLoader(Thread.currentThread().getContextClassLoader())
.useNativeIfAvailable(false);
sslContext = sslContextFactory.getContext();
try {
TrustManagerFactory tmf = sslContextFactory.getTrustManagerFactory();
builder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) tmf.getTrustManagers()[0]);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
builder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) ssl.trustManagers()[0]);
}
if (ssl.hostnameVerifier() != null) {
builder.hostnameVerifier(ssl.hostnameVerifier());
}
}
switch (configuration.protocol()) {
case HTTP_11:
builder.protocols(Collections.singletonList(Protocol.HTTP_1_1));
break;
case HTTP_20:
if (!ssl.enabled()) {
builder.protocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE));
} else {
builder.protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1));
}
// OkHttp might retry infinitely on HTTP/2.
builder.retryOnConnectionFailure(false);
break;
}
AuthenticationConfiguration authentication = configuration.security().authentication();
if (authentication.enabled()) {
Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
CachingAuthenticator authenticator;
switch (authentication.mechanism()) {
case "AUTO":
authenticator = new AutoDetectAuthenticator(authentication);
break;
case "BASIC":
authenticator = new BasicAuthenticator(authentication);
break;
case "BEARER_TOKEN":
authenticator = new BearerAuthenticator(authentication);
break;
case "DIGEST":
authenticator = new DigestAuthenticator(authentication);
break;
case "SPNEGO":
authenticator = new NegotiateAuthenticator(authentication);
break;
default:
throw new IllegalArgumentException("Cannot handle " + authentication.mechanism());
}
builder.addInterceptor(new CachingAuthenticatorInterceptor(authCache));
builder.authenticator(new CachingAuthenticatorWrapper(authenticator, authCache));
}
httpClient = builder.build();
ServerConfiguration server = configuration.servers().get(0);
baseURL = String.format("%s://%s:%d", ssl.enabled() ? "https" : "http", server.host(), server.port()).replaceAll("//", "/");
}
@Override
public RestClientConfiguration getConfiguration() {
return configuration;
}
@Override
public void close() throws IOException {
httpClient.dispatcher().executorService().shutdownNow();
ConnectionPool connectionPool = httpClient.connectionPool();
connectionPool.evictAll();
Cache cache = httpClient.cache();
if (cache != null) {
cache.close();
}
}
@Override
public CompletionStage<RestResponse> cacheManagers() {
return execute(baseURL, configuration.contextPath(), "v2", "server", "cache-managers");
}
@Override
public RestCacheManagerClient cacheManager(String name) {
return new RestCacheManagerClientOkHttp(this, name);
}
@Override
public RestContainerClient container() {
return new RestContainerClientOkHttp(this);
}
@Override
public CompletionStage<RestResponse> caches() {
return execute(baseURL, configuration.contextPath(), "v2", "caches");
}
@Override
public RestClusterClient cluster() {
return new RestClusterClientOkHttp(this);
}
@Override
public RestServerClient server() {
return new RestServerClientOkHttp(this);
}
@Override
public RestCacheClient cache(String name) {
return new RestCacheClientOkHttp(this, name);
}
@Override
public CompletionStage<RestResponse> counters() {
return execute(baseURL, configuration.contextPath(), "v2", "counters");
}
@Override
public RestCounterClient counter(String name) {
return new RestCounterClientOkHttp(this, name);
}
@Override
public RestTaskClient tasks() {
return new RestTaskClientOkHttp(this);
}
@Override
public RestRawClient raw() {
return new RestRawClientOkHttp(this);
}
static String sanitize(String s) {
return URLEncoder.encode(s, StandardCharsets.UTF_8);
}
static Request.Builder addEnumHeader(String name, Request.Builder builder, Enum<?>[] es) {
if (es != null && es.length > 0) {
StringJoiner joined = new StringJoiner(" ");
for (Enum<?> e : es) {
joined.add(e.name());
}
builder.header(name, joined.toString());
}
return builder;
}
@Override
public RestMetricsClient metrics() {
return new RestMetricsClientOkHttp(this);
}
@Override
public RestSchemaClient schemas() {
return new RestSchemasClientOkHttp(this);
}
@Override
public RestSecurityClient security() {
return new RestSecurityClientOkHttp(this);
}
CompletionStage<RestResponse> execute(Request.Builder builder) {
configuration.headers().forEach(builder::header);
Request request = builder.build();
log.tracef("Request %s", request);
CompletableFuture<RestResponse> response = new CompletableFuture<>();
httpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if (e.getSuppressed().length > 0 && e.getSuppressed()[0] instanceof AbstractAuthenticator.AuthenticationException) {
Throwable t = e.getSuppressed()[0];
Response.Builder builder = new Response.Builder()
.code(403)
.body(ResponseBody.create(MediaType.parse("text/plain"), t.getMessage()))
.request(call.request())
.message(t.getMessage())
.protocol(Protocol.HTTP_1_1); // Doesn't really matter
log.trace("Response unauthorized", t);
response.complete(new RestResponseOkHttp(builder.build()));
} else {
log.trace("Response error", e);
response.completeExceptionally(e);
}
}
@Override
public void onResponse(Call call, Response r) {
log.tracef("Response %s", r);
response.complete(new RestResponseOkHttp(r));
}
});
return response;
}
CompletionStage<RestResponse> execute(String basePath, String... subPaths) {
return execute(new Request.Builder(), basePath, subPaths);
}
CompletionStage<RestResponse> execute(Request.Builder builder, String basePath, String... subPaths) {
if (subPaths != null) {
StringBuilder sb = new StringBuilder(basePath);
for (String subPath : subPaths) {
if (subPath == null) {
continue;
}
if (!subPath.startsWith("/")) {
sb.append("/");
}
sb.append(subPath);
}
builder.url(sb.toString());
} else {
builder.url(basePath);
}
return execute(builder);
}
String getBaseURL() {
return baseURL;
}
OkHttpClient client() {
return httpClient;
}
}
| 11,889
| 35.925466
| 130
|
java
|
null |
infinispan-main/client/rest-client/src/main/java/org/infinispan/client/rest/impl/okhttp/RestMetricsClientOkHttp.java
|
package org.infinispan.client.rest.impl.okhttp;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OPENMETRICS_TYPE;
import static org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN_TYPE;
import java.util.concurrent.CompletionStage;
import org.infinispan.client.rest.RestMetricsClient;
import org.infinispan.client.rest.RestResponse;
import okhttp3.Request;
public class RestMetricsClientOkHttp implements RestMetricsClient {
private final RestClientOkHttp client;
private final String baseMetricsURL;
RestMetricsClientOkHttp(RestClientOkHttp client) {
this.client = client;
this.baseMetricsURL = String.format("%s/metrics", client.getBaseURL());
}
@Override
public CompletionStage<RestResponse> metrics() {
return metricsGet(false);
}
@Override
public CompletionStage<RestResponse> metrics(boolean openMetricsFormat) {
return metricsGet(openMetricsFormat);
}
@Override
public CompletionStage<RestResponse> metricsMetadata() {
return metricsOptions();
}
private CompletionStage<RestResponse> metricsGet(boolean openMetricsFormat) {
Request.Builder builder = new Request.Builder()
.addHeader("ACCEPT", openMetricsFormat ? APPLICATION_OPENMETRICS_TYPE : TEXT_PLAIN_TYPE);
return client.execute(builder, baseMetricsURL);
}
private CompletionStage<RestResponse> metricsOptions() {
Request.Builder builder = new Request.Builder()
.method("OPTIONS", null);
return client.execute(builder, baseMetricsURL);
}
}
| 1,576
| 29.921569
| 101
|
java
|
null |
infinispan-main/client/rest-client/src/main/java/org/infinispan/client/rest/impl/okhttp/auth/DigestAuthenticator.java
|
package org.infinispan.client.rest.impl.okhttp.auth;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.Formatter;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.infinispan.client.rest.configuration.AuthenticationConfiguration;
import okhttp3.Authenticator;
import okhttp3.Headers;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Route;
import okhttp3.internal.http.RequestLine;
public class DigestAuthenticator extends AbstractAuthenticator implements CachingAuthenticator {
private static final Pattern HEADER_REGEX = Pattern.compile("\\s([a-z]+)=\"?([\\p{Alnum}\\s\\t!#$%&'()*+\\-./:;<=>?@\\[\\\\\\]^_`{|}~]+)\"?");
private static final String CREDENTIAL_CHARSET = "http.auth.credential-charset";
private static final int QOP_UNKNOWN = -1;
private static final int QOP_MISSING = 0;
private static final int QOP_AUTH_INT = 1;
private static final int QOP_AUTH = 2;
private static final char[] HEXADECIMAL = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f'
};
private final AtomicReference<Map<String, String>> parametersRef = new AtomicReference<>();
private final Charset credentialsCharset = StandardCharsets.US_ASCII;
private final AuthenticationConfiguration configuration;
private String lastNonce;
private long nounceCount;
private String cnonce;
public DigestAuthenticator(AuthenticationConfiguration configuration) {
this.configuration = configuration;
}
public static String createCnonce() {
final SecureRandom rnd = new SecureRandom();
final byte[] tmp = new byte[8];
rnd.nextBytes(tmp);
return encode(tmp);
}
static String encode(final byte[] binaryData) {
final int n = binaryData.length;
final char[] buffer = new char[n * 2];
for (int i = 0; i < n; i++) {
final int low = (binaryData[i] & 0x0f);
final int high = ((binaryData[i] & 0xf0) >> 4);
buffer[i * 2] = HEXADECIMAL[high];
buffer[(i * 2) + 1] = HEXADECIMAL[low];
}
return new String(buffer);
}
@Override
public synchronized Request authenticate(Route route, Response response) throws IOException {
String header = findHeader(response.headers(), WWW_AUTH, "Digest");
Matcher matcher = HEADER_REGEX.matcher(header);
Map<String, String> parameters = new ConcurrentHashMap<>(8);
while (matcher.find()) {
parameters.put(matcher.group(1), matcher.group(2));
}
copyHeaderMap(response.headers(), parameters);
parametersRef.set(Collections.unmodifiableMap(parameters));
if (parameters.get("nonce") == null) {
throw new IllegalArgumentException("missing nonce in challenge header: " + header);
}
return authenticateWithState(route, response.request(), parameters);
}
@Override
public Request authenticateWithState(Route route, Request request) throws IOException {
Map<String, String> ref = parametersRef.get();
Map<String, String> parameters = ref == null
? new ConcurrentHashMap<>() : new ConcurrentHashMap<>(ref);
return authenticateWithState(route, request, parameters);
}
private Request authenticateWithState(Route route, Request request, Map<String, String> parameters) throws IOException {
final String realm = parameters.get("realm");
if (realm == null) {
return null;
}
final String nonce = parameters.get("nonce");
if (nonce == null) {
throw new IllegalArgumentException("missing nonce in challenge");
}
String stale = parameters.get("stale");
boolean isStale = "true".equalsIgnoreCase(stale);
if (havePreviousDigestAuthorizationAndShouldAbort(request, nonce, isStale)) {
return null;
}
// Add method name and request-URI to the parameter map
if (route == null || !route.requiresTunnel()) {
final String method = request.method();
final String uri = RequestLine.requestPath(request.url());
parameters.put("methodname", method);
parameters.put("uri", uri);
} else {
final String method = "CONNECT";
final String uri = request.url().host() + ':' + request.url().port();
parameters.put("methodname", method);
parameters.put("uri", uri);
}
final String charset = parameters.get("charset");
if (charset == null) {
String credentialsCharset = getCredentialsCharset(request);
parameters.put("charset", credentialsCharset);
}
return request.newBuilder()
.header(WWW_AUTH_RESP, createDigestHeader(request, parameters))
.tag(Authenticator.class, this)
.build();
}
private boolean havePreviousDigestAuthorizationAndShouldAbort(Request request, String nonce, boolean isStale) {
final String headerKey;
headerKey = WWW_AUTH_RESP;
final String previousAuthorizationHeader = request.header(headerKey);
if (previousAuthorizationHeader != null && previousAuthorizationHeader.startsWith("Digest")) {
return !isStale;
}
return false;
}
private void copyHeaderMap(Headers headers, Map<String, String> dest) {
for (int i = 0; i < headers.size(); i++) {
dest.put(headers.name(i), headers.value(i));
}
}
private synchronized String createDigestHeader(
final Request request,
final Map<String, String> parameters) throws AuthenticationException {
final String uri = parameters.get("uri");
final String realm = parameters.get("realm");
final String nonce = parameters.get("nonce");
final String opaque = parameters.get("opaque");
final String method = parameters.get("methodname");
String algorithm = parameters.get("algorithm");
// If an algorithm is not specified, default to MD5.
if (algorithm == null) {
algorithm = "MD5";
}
final Set<String> qopset = new HashSet<>(8);
int qop = QOP_UNKNOWN;
final String qoplist = parameters.get("qop");
if (qoplist != null) {
final StringTokenizer tok = new StringTokenizer(qoplist, ",");
while (tok.hasMoreTokens()) {
final String variant = tok.nextToken().trim();
qopset.add(variant.toLowerCase(Locale.US));
}
if (request.body() != null && qopset.contains("auth-int")) {
qop = QOP_AUTH_INT;
} else if (qopset.contains("auth")) {
qop = QOP_AUTH;
}
} else {
qop = QOP_MISSING;
}
if (qop == QOP_UNKNOWN) {
throw new AuthenticationException("None of the qop methods is supported: " + qoplist);
}
String charset = parameters.get("charset");
if (charset == null) {
charset = StandardCharsets.ISO_8859_1.name();
}
String digAlg = algorithm;
if ("MD5-sess".equalsIgnoreCase(digAlg)) {
digAlg = "MD5";
}
final MessageDigest digester;
try {
digester = MessageDigest.getInstance(digAlg);
} catch (Exception ex) {
throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg, ex);
}
final String uname = configuration.username();
final String pwd = new String(configuration.password());
if (nonce.equals(this.lastNonce)) {
nounceCount++;
} else {
nounceCount = 1;
cnonce = null;
lastNonce = nonce;
}
final StringBuilder sb = new StringBuilder(256);
final Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("%08x", nounceCount);
formatter.close();
final String nc = sb.toString();
if (cnonce == null) {
cnonce = createCnonce();
}
String s1;
String s2;
if ("MD5-sess".equalsIgnoreCase(algorithm)) {
sb.setLength(0);
sb.append(uname).append(':').append(realm).append(':').append(pwd);
final String checksum = encode(digester.digest(getBytes(sb.toString(), charset)));
sb.setLength(0);
sb.append(checksum).append(':').append(nonce).append(':').append(cnonce);
s1 = sb.toString();
} else {
sb.setLength(0);
sb.append(uname).append(':').append(realm).append(':').append(pwd);
s1 = sb.toString();
}
final String hasha1 = encode(digester.digest(getBytes(s1, charset)));
if (qop == QOP_AUTH) {
s2 = method + ':' + uri;
} else if (qop == QOP_AUTH_INT) {
RequestBody entity = request.body();
if (entity != null) {
if (qopset.contains("auth")) {
qop = QOP_AUTH;
s2 = method + ':' + uri;
} else {
throw new AuthenticationException("Qop auth-int cannot be used with " +
"a non-repeatable entity");
}
} else {
digester.reset();
// empty content
s2 = method + ':' + uri + ':' + encode(digester.digest());
}
} else {
s2 = method + ':' + uri;
}
final String h2 = encode(digester.digest(getBytes(s2, charset)));
final String digestValue;
if (qop == QOP_MISSING) {
sb.setLength(0);
sb.append(hasha1).append(':').append(nonce).append(':').append(h2);
digestValue = sb.toString();
} else {
sb.setLength(0);
sb.append(hasha1).append(':').append(nonce).append(':').append(nc).append(':')
.append(cnonce).append(':').append(qop == QOP_AUTH_INT ? "auth-int" : "auth")
.append(':').append(h2);
digestValue = sb.toString();
}
final String digest = encode(digester.digest(getAsciiBytes(digestValue)));
final StringBuilder buffer = new StringBuilder(128);
buffer.append("Digest username=\"");
buffer.append(uname);
buffer.append("\", realm=\"");
buffer.append(realm);
buffer.append("\", nonce=\"");
buffer.append(nonce);
buffer.append("\", uri=\"");
buffer.append(uri);
buffer.append("\", response=\"");
buffer.append(digest);
buffer.append("\", ");
if (qop != QOP_MISSING) {
buffer.append("qop=");
buffer.append(qop == QOP_AUTH_INT ? "auth-int" : "auth");
buffer.append(", nc=");
buffer.append(nc);
buffer.append(", cnonce=\"");
buffer.append(cnonce);
buffer.append("\", ");
}
buffer.append("algorithm=");
buffer.append(algorithm);
if (opaque != null) {
buffer.append(", opaque=\"");
buffer.append(opaque);
buffer.append('"');
}
return buffer.toString();
}
/**
* Returns the charset used for the credentials.
*
* @return the credentials charset
*/
public Charset getCredentialsCharset() {
return credentialsCharset;
}
String getCredentialsCharset(final Request request) {
String charset = request.header(CREDENTIAL_CHARSET);
if (charset == null) {
charset = getCredentialsCharset().name();
}
return charset;
}
private byte[] getBytes(final String s, final String charset) {
try {
return s.getBytes(charset);
} catch (UnsupportedEncodingException e) {
// try again with default encoding
return s.getBytes();
}
}
public static byte[] getAsciiBytes(String data) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
} else {
return data.getBytes(StandardCharsets.US_ASCII);
}
}
}
| 12,219
| 33.325843
| 145
|
java
|
null |
infinispan-main/client/rest-client/src/main/java/org/infinispan/client/rest/impl/okhttp/auth/AbstractAuthenticator.java
|
package org.infinispan.client.rest.impl.okhttp.auth;
import java.util.List;
import okhttp3.Headers;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 10.1
**/
public abstract class AbstractAuthenticator {
public static final String WWW_AUTH = "WWW-Authenticate";
public static final String WWW_AUTH_RESP = "Authorization";
static String findHeader(Headers headers, String name, String prefix) {
final List<String> authHeaders = headers.values(name);
for (String header : authHeaders) {
if (header.startsWith(prefix)) {
return header;
}
}
throw new AuthenticationException("unsupported auth scheme: " + authHeaders);
}
public static class AuthenticationException extends SecurityException {
public AuthenticationException(String s) {
super(s);
}
public AuthenticationException(String message, Exception ex) {
super(message, ex);
}
}
}
| 977
| 26.942857
| 83
|
java
|
null |
infinispan-main/client/rest-client/src/main/java/org/infinispan/client/rest/impl/okhttp/auth/CachingAuthenticatorInterceptor.java
|
package org.infinispan.client.rest.impl.okhttp.auth;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import java.io.IOException;
import java.util.Map;
import okhttp3.Connection;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
public class CachingAuthenticatorInterceptor implements Interceptor {
private final Map<String, CachingAuthenticator> authCache;
public CachingAuthenticatorInterceptor(Map<String, CachingAuthenticator> authCache) {
this.authCache = authCache;
}
@Override
public Response intercept(Chain chain) throws IOException {
final Request request = chain.request();
final String key = CachingAuthenticator.getCachingKey(request);
CachingAuthenticator authenticator = authCache.get(key);
Request authRequest = null;
Connection connection = chain.connection();
Route route = connection != null ? connection.route() : null;
if (authenticator != null) {
authRequest = authenticator.authenticateWithState(route, request);
}
if (authRequest == null) {
authRequest = request;
}
Response response = chain.proceed(authRequest);
int responseCode = response != null ? response.code() : 0;
if (authenticator != null && (responseCode == HTTP_UNAUTHORIZED)) {
if (authCache.remove(key) != null) {
response.body().close();
// Force sending a new request without "Authorization" header
response = chain.proceed(request);
}
}
return response;
}
}
| 1,603
| 31.734694
| 88
|
java
|
null |
infinispan-main/client/rest-client/src/main/java/org/infinispan/client/rest/impl/okhttp/auth/CachingAuthenticator.java
|
package org.infinispan.client.rest.impl.okhttp.auth;
import java.io.IOException;
import okhttp3.Authenticator;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Route;
public interface CachingAuthenticator extends Authenticator {
Request authenticateWithState(Route route, Request request) throws IOException;
static String getCachingKey(Request request) {
final HttpUrl url = request.url();
if (url == null)
return null;
return url.scheme() + ":" + url.host() + ":" + url.port();
}
}
| 538
| 25.95
| 82
|
java
|
null |
infinispan-main/client/rest-client/src/main/java/org/infinispan/client/rest/impl/okhttp/auth/NegotiateAuthenticator.java
|
package org.infinispan.client.rest.impl.okhttp.auth;
import java.io.IOException;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Base64;
import java.util.concurrent.atomic.AtomicReference;
import javax.security.auth.Subject;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.ietf.jgss.Oid;
import org.infinispan.client.rest.configuration.AuthenticationConfiguration;
import okhttp3.Authenticator;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
public class NegotiateAuthenticator extends AbstractAuthenticator implements CachingAuthenticator {
private static final String SPNEGO_OID = "1.3.6.1.5.5.2";
private final AuthenticationConfiguration configuration;
private final GSSManager gssManager;
private final Oid oid;
private final AtomicReference<String> token = new AtomicReference<>();
public NegotiateAuthenticator(AuthenticationConfiguration configuration) {
this.configuration = configuration;
this.gssManager = GSSManager.getInstance();
try {
this.oid = new Oid(SPNEGO_OID);
} catch (GSSException e) {
throw new RuntimeException(e); // This will never happen
}
}
@Override
public Request authenticate(Route route, Response response) {
Request request = response.request();
return authenticateInternal(route, request);
}
@Override
public Request authenticateWithState(Route route, Request request) throws IOException {
return request.newBuilder()
.header(WWW_AUTH_RESP, "Negotiate " + token.get())
.build();
}
private Request authenticateInternal(Route route, Request request) {
try {
// Initial empty challenge
String host = route.address().url().host();
token.set(generateToken(null, host));
return request.newBuilder()
.header(WWW_AUTH_RESP, "Negotiate " + token.get())
.tag(Authenticator.class, this)
.build();
} catch (GSSException e) {
throw new AuthenticationException(e.getMessage(), e);
}
}
protected String generateToken(byte[] input, String authServer) throws GSSException {
GSSName serverName = gssManager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
GSSContext gssContext = gssManager.createContext(serverName.canonicalize(oid), oid, null, GSSContext.DEFAULT_LIFETIME);
gssContext.requestMutualAuth(true);
try {
byte[] bytes = Subject.doAs(configuration.clientSubject(), (PrivilegedExceptionAction<byte[]>) () ->
input != null
? gssContext.initSecContext(input, 0, input.length)
: gssContext.initSecContext(new byte[]{}, 0, 0)
);
return Base64.getEncoder().encodeToString(bytes);
} catch (PrivilegedActionException e) {
throw new SecurityException(e);
}
}
}
| 3,067
| 35.52381
| 125
|
java
|
null |
infinispan-main/client/rest-client/src/main/java/org/infinispan/client/rest/impl/okhttp/auth/AutoDetectAuthenticator.java
|
package org.infinispan.client.rest.impl.okhttp.auth;
import java.io.IOException;
import java.util.List;
import org.infinispan.client.rest.configuration.AuthenticationConfiguration;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 10.0
**/
public class AutoDetectAuthenticator extends AbstractAuthenticator implements CachingAuthenticator {
private final BasicAuthenticator basic;
private final BearerAuthenticator bearer;
private final DigestAuthenticator digest;
private final NegotiateAuthenticator negotiate;
public AutoDetectAuthenticator(AuthenticationConfiguration configuration) {
basic = new BasicAuthenticator(configuration);
bearer = new BearerAuthenticator(configuration);
digest = new DigestAuthenticator(configuration);
negotiate = new NegotiateAuthenticator(configuration);
}
@Override
public Request authenticate(Route route, Response response) throws IOException {
List<String> headers = response.headers(WWW_AUTH);
for (String header : headers) {
int space = header.indexOf(' ');
String mech = header.substring(0, space);
switch (mech) {
case "Digest":
return digest.authenticate(route, response);
case "Basic":
return basic.authenticate(route, response);
case "Bearer":
return bearer.authenticate(route, response);
case "Negotiate":
return negotiate.authenticate(route, response);
}
}
return null;
}
@Override
public Request authenticateWithState(Route route, Request request) throws IOException {
// This should never get called
throw new IllegalStateException();
}
}
| 1,831
| 31.140351
| 100
|
java
|
null |
infinispan-main/client/rest-client/src/main/java/org/infinispan/client/rest/impl/okhttp/auth/BasicAuthenticator.java
|
package org.infinispan.client.rest.impl.okhttp.auth;
import org.infinispan.client.rest.configuration.AuthenticationConfiguration;
import okhttp3.Authenticator;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
public class BasicAuthenticator extends AbstractAuthenticator implements CachingAuthenticator {
private final AuthenticationConfiguration configuration;
public BasicAuthenticator(AuthenticationConfiguration configuration) {
this.configuration = configuration;
}
@Override
public Request authenticate(Route route, Response response) {
Request request = response.request();
return authenticateInternal(request);
}
@Override
public Request authenticateWithState(Route route, Request request) {
return authenticateInternal(request);
}
private Request authenticateInternal(Request request) {
String authorization = request.header(WWW_AUTH_RESP);
if (authorization != null && authorization.startsWith("Basic")) {
// We have already attempted to authenticate, fail
return null;
}
String authValue = okhttp3.Credentials.basic(configuration.username(), new String(configuration.password()));
return request.newBuilder()
.header(WWW_AUTH_RESP, authValue)
.tag(Authenticator.class, this)
.build();
}
}
| 1,370
| 32.439024
| 115
|
java
|
null |
infinispan-main/client/rest-client/src/main/java/org/infinispan/client/rest/impl/okhttp/auth/CachingAuthenticatorWrapper.java
|
package org.infinispan.client.rest.impl.okhttp.auth;
import java.io.IOException;
import java.util.Map;
import okhttp3.Authenticator;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
public class CachingAuthenticatorWrapper implements Authenticator {
private final Authenticator innerAuthenticator;
private final Map<String, CachingAuthenticator> authCache;
public CachingAuthenticatorWrapper(Authenticator innerAuthenticator, Map<String, CachingAuthenticator> authCache) {
this.innerAuthenticator = innerAuthenticator;
this.authCache = authCache;
}
@Override
public Request authenticate(Route route, Response response) throws IOException {
Request authenticated = innerAuthenticator.authenticate(route, response);
if (authenticated != null) {
String authorizationValue = authenticated.header("Authorization");
if (authorizationValue != null && innerAuthenticator instanceof CachingAuthenticator) {
final String key = CachingAuthenticator.getCachingKey(authenticated);
authCache.put(key, (CachingAuthenticator) authenticated.tag(Authenticator.class));
}
}
return authenticated;
}
}
| 1,252
| 36.969697
| 119
|
java
|
null |
infinispan-main/client/rest-client/src/main/java/org/infinispan/client/rest/impl/okhttp/auth/BearerAuthenticator.java
|
package org.infinispan.client.rest.impl.okhttp.auth;
import org.infinispan.client.rest.configuration.AuthenticationConfiguration;
import okhttp3.Authenticator;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
public class BearerAuthenticator extends AbstractAuthenticator implements CachingAuthenticator {
private final AuthenticationConfiguration configuration;
public BearerAuthenticator(AuthenticationConfiguration configuration) {
this.configuration = configuration;
}
@Override
public Request authenticate(Route route, Response response) {
final Request request = response.request();
return authenticateInternal(request);
}
@Override
public Request authenticateWithState(Route route, Request request) {
return authenticateInternal(request);
}
private Request authenticateInternal(Request request) {
final String authorization = request.header(WWW_AUTH_RESP);
if (authorization != null && authorization.startsWith("Bearer")) {
// We have already attempted to authenticate, fail
return null;
}
return request.newBuilder()
.header(WWW_AUTH_RESP, "Bearer " + configuration.username())
.tag(Authenticator.class, this)
.build();
}
}
| 1,298
| 29.928571
| 96
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ConsistentHashPerformanceTest.java
|
package org.infinispan.client.hotrod;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHash;
import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHashV2;
import org.testng.annotations.Test;
/**
* @author Mircea Markus <mircea.markus@jboss.com> (C) 2011 Red Hat Inc.
* @since 5.1
*/
@Test (groups = "profiling", testName = "client.hotrod.ConsistentHashPerformanceTest")
public class ConsistentHashPerformanceTest {
public static final int KEY_POOL_SIZE = 1000;
static List<byte[]> keys = new ArrayList<byte[]>(KEY_POOL_SIZE);
static {
Random rnd = new Random();
for (int i = 0; i < KEY_POOL_SIZE; i++) {
byte[] bytes = new byte[12];
rnd.nextBytes(bytes);
keys.add(bytes);
}
}
private void testConsistentHashSpeed(ConsistentHash ch) {
int loopSize = 1000000;
Random rnd = new Random();
long duration = 0;
for (int i = 0; i < loopSize; i++) {
int keyIndex = rnd.nextInt(KEY_POOL_SIZE);
long start = System.nanoTime();
SocketAddress server = ch.getServer(keys.get(keyIndex));
duration += System.nanoTime() - start;
//just make sure this code is not removed from JIT
if (server.hashCode() == loopSize) {
System.out.println("");
}
}
System.out.printf("It took %s millis for consistent hash %s to execute %s operations \n" , TimeUnit.NANOSECONDS.toMillis(duration), ch.getClass().getSimpleName(), loopSize);
}
public void testVariousVersion1() {
ConsistentHashV2 dch2 = new ConsistentHashV2();
initConsistentHash(dch2);
testConsistentHashSpeed(dch2);
}
private void initConsistentHash(ConsistentHashV2 dch) {
int numAddresses = 1500;
LinkedHashMap<SocketAddress, Set<Integer>> map = new LinkedHashMap<SocketAddress, Set<Integer>>();
for (int i = 0; i < numAddresses; i++) {
map.put(new InetSocketAddress(i), Collections.singleton(i * 1000));
}
dch.init(map, 2, 10024);
}
}
| 2,328
| 29.644737
| 179
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/CacheContainerTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.test.TestingUtil.killCacheManagers;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test(groups = "functional", testName = "client.hotrod.CacheContainerTest")
public class CacheContainerTest extends SingleCacheManagerTest {
private static final String CACHE_NAME = "someName";
EmbeddedCacheManager cacheManager = null;
HotRodServer hotrodServer = null;
RemoteCacheManager remoteCacheManager;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
cacheManager = TestCacheManagerFactory.createCacheManager(
hotRodCacheConfiguration());
cacheManager.defineConfiguration(CACHE_NAME, hotRodCacheConfiguration().build());
hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotrodServer.getPort());
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
return cacheManager;
}
@AfterClass(alwaysRun = true)
public void release() {
killCacheManagers(cacheManager);
killRemoteCacheManager(remoteCacheManager);
killServers(hotrodServer);
hotrodServer = null;
}
public void testObtainingSameInstanceMultipleTimes() {
RemoteCache<Object, Object> objectCache = remoteCacheManager.getCache();
RemoteCache<Object, Object> objectCache2 = remoteCacheManager.getCache();
assert objectCache == objectCache2;
}
public void testObtainingSameInstanceMultipleTimes2() {
RemoteCache<Object, Object> objectCache = remoteCacheManager.getCache(CACHE_NAME);
RemoteCache<Object, Object> objectCache2 = remoteCacheManager.getCache(CACHE_NAME);
assert objectCache == objectCache2;
}
}
| 2,581
| 40.645161
| 95
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/MillisecondExpirationTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertFalse;
import java.util.concurrent.TimeUnit;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* @author gustavonalle
* @since 8.0
*/
@Test(testName = "client.hotrod.MillisecondExpirationTest", groups = "functional")
public class MillisecondExpirationTest extends DefaultExpirationTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder builder = hotRodCacheConfiguration(
getDefaultStandaloneCacheConfig(false));
return TestCacheManagerFactory.createCacheManager(builder);
}
@Test
public void testDefaultExpiration() throws Exception {
remoteCache.put("Key", "Value", 50, TimeUnit.MILLISECONDS);
Thread.sleep(100);
assertFalse(remoteCache.containsKey("Key"));
}
}
| 1,122
| 32.029412
| 91
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/SegmentOwnershipLocalTest.java
|
package org.infinispan.client.hotrod;
import static org.testng.Assert.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import java.net.SocketAddress;
import java.util.Map;
import java.util.Set;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.manager.EmbeddedCacheManager;
import org.testng.annotations.Test;
/**
* @author gustavonalle
* @since 8.0
*/
@Test(groups = "functional", testName = "client.hotrod.SegmentOwnershipLocalTest")
public class SegmentOwnershipLocalTest extends SingleHotRodServerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
return super.createCacheManager();
}
@Test
public void testSegmentMap() throws Exception {
RemoteCache<Object, Object> cache = remoteCacheManager.getCache();
Map<SocketAddress, Set<Integer>> segmentsByServer = cache.getCacheTopologyInfo().getSegmentsPerServer();
assertNotNull(segmentsByServer);
assertEquals(segmentsByServer.keySet().size(), 1);
assertEquals(segmentsByServer.values().iterator().next().size(), 0);
}
}
| 1,128
| 29.513514
| 110
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/GetAllDistTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
/**
* Tests functionality related to getting getting multiple entries using a distributed
* cache
*
* @author William Burns
* @since 7.2
*/
@Test(testName = "client.hotrod.GetAllDistTest", groups = "functional")
public class GetAllDistTest extends BaseGetAllTest {
@Override
protected int numberOfHotRodServers() {
return 3;
}
@Override
protected ConfigurationBuilder clusterConfig() {
return hotRodCacheConfiguration(getDefaultClusteredCacheConfig(
CacheMode.DIST_SYNC, false));
}
}
| 820
| 26.366667
| 91
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/SegmentOwnershipDistTest.java
|
package org.infinispan.client.hotrod;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.net.SocketAddress;
import java.util.Map;
import java.util.Set;
import org.infinispan.configuration.cache.CacheMode;
import org.testng.annotations.Test;
/**
* @author gustavonalle
* @since 8.0
*/
@Test(groups = "functional", testName = "client.hotrod.SegmentOwnershipDistTest")
public class SegmentOwnershipDistTest extends BaseSegmentOwnershipTest {
public void testObtainSegmentOwnership() throws Exception {
RemoteCache<Object, Object> remoteCache = client(0).getCache();
Map<SocketAddress, Set<Integer>> segmentsByServer = remoteCache.getCacheTopologyInfo().getSegmentsPerServer();
Map<Integer, Set<SocketAddress>> serversBySegment = invertMap(segmentsByServer);
assertEquals(segmentsByServer.keySet().size(), NUM_SERVERS);
assertTrue(serversBySegment.entrySet().stream().allMatch(e -> e.getValue().size() == NUM_OWNERS));
}
@Override
protected CacheMode getCacheMode() {
return CacheMode.DIST_SYNC;
}
}
| 1,108
| 31.617647
| 116
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/MixedExpiryMaxIdleDefaultTest.java
|
package org.infinispan.client.hotrod;
import java.util.concurrent.TimeUnit;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
/**
* This test verifies that an entry has the proper lifespan when a default value is applied
*
* @author William Burns
* @since 8.0
*/
@Test(groups = "functional", testName = "client.hotrod.MixedExpiryMaxIdleDefaultTest")
public class MixedExpiryMaxIdleDefaultTest extends MixedExpiryTest {
@Override
protected void configure(ConfigurationBuilder configurationBuilder) {
configurationBuilder.expiration().maxIdle(3, TimeUnit.MINUTES);
}
}
| 640
| 29.52381
| 91
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/HotRodClientJmxTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.remoteCacheManagerObjectName;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.remoteCacheObjectName;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.commons.jmx.MBeanServerLookup;
import org.infinispan.commons.jmx.TestMBeanServerLookup;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.CacheContainer;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.HotRodClientJmxTest")
public class HotRodClientJmxTest extends AbstractInfinispanTest {
private static final String JMX_DOMAIN = HotRodClientJmxTest.class.getSimpleName();
private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create();
private HotRodServer hotrodServer;
private CacheContainer cacheContainer;
private RemoteCacheManager rcm;
private RemoteCache<String, String> remoteCache;
@BeforeMethod
void setup() {
ConfigurationBuilder cfg = hotRodCacheConfiguration();
cfg.statistics().enable();
GlobalConfigurationBuilder globalCfg = GlobalConfigurationBuilder.defaultClusteredBuilder();
TestCacheManagerFactory.configureJmx(globalCfg, JMX_DOMAIN, mBeanServerLookup);
cacheContainer = TestCacheManagerFactory.createClusteredCacheManager(globalCfg, cfg);
hotrodServer = HotRodClientTestingUtil.startHotRodServer((EmbeddedCacheManager) cacheContainer);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotrodServer.getPort());
clientBuilder.statistics()
.enable()
.jmxEnable()
.jmxDomain(JMX_DOMAIN)
.mBeanServerLookup(mBeanServerLookup);
rcm = new RemoteCacheManager(clientBuilder.build());
remoteCache = rcm.getCache();
}
@AfterMethod
void tearDown() {
TestingUtil.killCacheManagers(cacheContainer);
killRemoteCacheManager(rcm);
killServers(hotrodServer);
hotrodServer = null;
}
public void testRemoteCacheManagerMBean() throws Exception {
MBeanServer mbeanServer = mBeanServerLookup.getMBeanServer();
ObjectName objectName = remoteCacheManagerObjectName(rcm);
String[] servers = (String[]) mbeanServer.getAttribute(objectName, "Servers");
assertEquals(1, servers.length);
assertEquals("localhost:" + hotrodServer.getPort(), servers[0]);
assertEquals(1, mbeanServer.getAttribute(objectName, "ConnectionCount"));
assertEquals(1, mbeanServer.getAttribute(objectName, "IdleConnectionCount"));
assertEquals(0, mbeanServer.getAttribute(objectName, "ActiveConnectionCount"));
}
public void testRemoteCacheMBean() throws Exception {
MBeanServer mbeanServer = mBeanServerLookup.getMBeanServer();
ObjectName objectName = remoteCacheObjectName(rcm, "org.infinispan.default");
assertEquals(0L, mbeanServer.getAttribute(objectName, "AverageRemoteReadTime"));
assertEquals(0L, mbeanServer.getAttribute(objectName, "AverageRemoteStoreTime"));
remoteCache.get("a"); // miss
assertEquals(1L, mbeanServer.getAttribute(objectName, "RemoteMisses"));
assertEquals(0L, mbeanServer.getAttribute(objectName, "RemoteHits"));
assertEquals(0L, mbeanServer.getAttribute(objectName, "RemoteStores"));
remoteCache.put("a", "a");
assertEquals(1L, mbeanServer.getAttribute(objectName, "RemoteStores"));
assertEquals("a", remoteCache.get("a")); // hit
assertEquals(1L, mbeanServer.getAttribute(objectName, "RemoteHits"));
remoteCache.putIfAbsent("a", "a1");
assertEquals(1L, mbeanServer.getAttribute(objectName, "RemoteStores"));
assertNull(remoteCache.putIfAbsent("b", "b"));
assertEquals(2L, mbeanServer.getAttribute(objectName, "RemoteStores"));
assertFalse(remoteCache.replace("b", "a", "c"));
assertEquals(2L, mbeanServer.getAttribute(objectName, "RemoteStores"));
assertTrue(remoteCache.replace("b", "b", "c"));
assertEquals(3L, mbeanServer.getAttribute(objectName, "RemoteStores"));
assertEquals(2, remoteCache.entrySet().stream().count());
assertEquals(3L, mbeanServer.getAttribute(objectName, "RemoteHits"));
Map<String, String> map = new HashMap<>(2);
map.put("c", "c");
map.put("d", "d");
remoteCache.putAll(map);
assertEquals(5L, mbeanServer.getAttribute(objectName, "RemoteStores"));
Set<String> set = new HashSet<>(3);
set.add("a");
set.add("c");
set.add("e"); // non-existent
remoteCache.getAll(set);
assertEquals(5L, mbeanServer.getAttribute(objectName, "RemoteHits"));
assertEquals(2L, mbeanServer.getAttribute(objectName, "RemoteMisses"));
assertEquals(0L, mbeanServer.getAttribute(objectName, "RemoteRemoves"));
remoteCache.remove("b");
assertEquals(1L, mbeanServer.getAttribute(objectName, "RemoteRemoves"));
OutputStream os = remoteCache.streaming().put("s");
os.write('s');
os.close();
assertEquals(6L, mbeanServer.getAttribute(objectName, "RemoteStores"));
InputStream is = remoteCache.streaming().get("s");
while (is.read() >= 0) {
//consume
}
is.close();
assertEquals(6L, mbeanServer.getAttribute(objectName, "RemoteHits"));
assertNull(remoteCache.streaming().get("t"));
assertEquals(6L, mbeanServer.getAttribute(objectName, "RemoteHits"));
}
}
| 6,783
| 44.226667
| 102
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/MixedExpiryLifespanDefaultTest.java
|
package org.infinispan.client.hotrod;
import java.util.concurrent.TimeUnit;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
/**
* This test verifies that an entry has the proper lifespan when a default value is applied
*
* @author William Burns
* @since 8.0
*/
@Test(groups = "functional", testName = "client.hotrod.MixedExpiryLifespanDefaultTest")
public class MixedExpiryLifespanDefaultTest extends MixedExpiryTest {
@Override
protected void configure(ConfigurationBuilder configurationBuilder) {
configurationBuilder.expiration().lifespan(3, TimeUnit.MINUTES);
}
}
| 643
| 29.666667
| 91
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/SkipIndexingFlagTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.Flag.FORCE_RETURN_VALUE;
import static org.infinispan.client.hotrod.Flag.SKIP_INDEXING;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.commands.FlagAffectedCommand;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commons.CacheException;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.interceptors.BaseAsyncInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.CleanupAfterTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Tests if the {@link org.infinispan.client.hotrod.Flag#SKIP_INDEXING} flag is received on HotRod server.
*
* @author Tristan Tarrant
* @author Pedro Ruivo
* @since 7.0
*/
@Test(testName = "client.hotrod.SkipIndexingFlagTest", groups = "functional")
@CleanupAfterTest
public class SkipIndexingFlagTest extends SingleCacheManagerTest {
private static final String KEY = "key";
private static final String VALUE = "value";
private FlagCheckCommandInterceptor commandInterceptor;
private RemoteCache<String, String> remoteCache;
private RemoteCacheManager remoteCacheManager;
private HotRodServer hotRodServer;
public void testPut() {
performTest(RequestType.PUT);
}
public void testReplace() {
performTest(RequestType.REPLACE);
}
public void testPutIfAbsent() {
performTest(RequestType.PUT_IF_ABSENT);
}
public void testReplaceIfUnmodified() {
performTest(RequestType.REPLACE_IF_UNMODIFIED);
}
public void testGet() {
performTest(RequestType.GET);
}
public void testGetWithMetadata() {
performTest(RequestType.GET_WITH_METADATA);
}
public void testRemove() {
performTest(RequestType.REMOVE);
}
public void testRemoveIfUnmodified() {
performTest(RequestType.REMOVE_IF_UNMODIFIED);
}
public void testContainsKey() {
performTest(RequestType.CONTAINS);
}
public void testPutAll() {
performTest(RequestType.PUT_ALL);
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration());
cache = cacheManager.getCache();
hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
Properties hotRodClientConf = new Properties();
hotRodClientConf.put("infinispan.client.hotrod.server_list", "localhost:" + hotRodServer.getPort());
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotRodServer.getPort());
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
remoteCache = remoteCacheManager.getCache();
return cacheManager;
}
@Override
protected void teardown() {
HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager);
remoteCacheManager = null;
HotRodClientTestingUtil.killServers(hotRodServer);
hotRodServer = null;
super.teardown();
}
private void performTest(RequestType type) {
commandInterceptor.expectSkipIndexingFlag = false;
type.execute(remoteCache);
commandInterceptor.expectSkipIndexingFlag = RequestType.expectsFlag(type);
type.execute(remoteCache.withFlags(SKIP_INDEXING));
type.execute(remoteCache.withFlags(SKIP_INDEXING, FORCE_RETURN_VALUE));
}
@BeforeClass(alwaysRun = true)
private void injectCommandInterceptor() {
if (remoteCache == null) {
return;
}
this.commandInterceptor = new FlagCheckCommandInterceptor();
extractInterceptorChain(cache).addInterceptor(commandInterceptor, 1);
}
@AfterClass(alwaysRun = true)
private void resetCommandInterceptor() {
if (commandInterceptor != null) {
commandInterceptor.expectSkipIndexingFlag = false;
}
}
private static enum RequestType {
PUT {
@Override
void execute(RemoteCache<String, String> cache) {
cache.put(KEY, VALUE);
}
},
REPLACE {
@Override
void execute(RemoteCache<String, String> cache) {
cache.replace(KEY, VALUE);
}
},
PUT_IF_ABSENT {
@Override
void execute(RemoteCache<String, String> cache) {
cache.putIfAbsent(KEY, VALUE);
}
},
REPLACE_IF_UNMODIFIED {
@Override
void execute(RemoteCache<String, String> cache) {
cache.replaceWithVersion(KEY, VALUE, 0);
}
},
GET {
@Override
void execute(RemoteCache<String, String> cache) {
cache.get(KEY);
}
},
GET_WITH_METADATA {
@Override
void execute(RemoteCache<String, String> cache) {
cache.getWithMetadata(KEY);
}
},
REMOVE {
@Override
void execute(RemoteCache<String, String> cache) {
cache.remove(KEY);
}
},
REMOVE_IF_UNMODIFIED {
@Override
void execute(RemoteCache<String, String> cache) {
cache.removeWithVersion(KEY, 0);
}
},
CONTAINS {
@Override
void execute(RemoteCache<String, String> cache) {
cache.containsKey(KEY);
}
},
PUT_ALL {
@Override
void execute(RemoteCache<String, String> cache) {
Map<String, String> data = new HashMap<String, String>();
data.put(KEY, VALUE);
cache.putAll(data);
}
},
;
private static boolean expectsFlag(RequestType type) {
return type != CONTAINS && type != GET && type != GET_WITH_METADATA;
}
abstract void execute(RemoteCache<String, String> cache);
}
static class FlagCheckCommandInterceptor extends BaseAsyncInterceptor {
private volatile boolean expectSkipIndexingFlag;
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
if (command instanceof FlagAffectedCommand) {
boolean hasFlag = ((FlagAffectedCommand) command).hasAnyFlag(FlagBitSets.SKIP_INDEXING);
if (expectSkipIndexingFlag && !hasFlag) {
throw new CacheException("SKIP_INDEXING flag is expected!");
} else if (!expectSkipIndexingFlag && hasFlag) {
throw new CacheException("SKIP_INDEXING flag is *not* expected!");
}
}
return invokeNext(ctx, command);
}
}
}
| 7,276
| 30.63913
| 106
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/SomeRequestBalancingStrategy.java
|
package org.infinispan.client.hotrod;
import org.infinispan.client.hotrod.impl.transport.tcp.RoundRobinBalancingStrategy;
public class SomeRequestBalancingStrategy extends RoundRobinBalancingStrategy {
}
| 207
| 25
| 83
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/HotRodNonOwnerStatisticsTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.startHotRodServer;
import static org.testng.AssertJUnit.assertEquals;
import org.infinispan.client.hotrod.configuration.ClientIntelligence;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.commons.jmx.TestMBeanServerLookup;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.stats.Stats;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
/**
* Test that statistics are updated properly when a client reads a key from a non-owner.
*
* @author Dan Berindei
* @since 9.4
*/
@Test(groups = "functional", testName = "client.hotrod.HotRodNonOwnerStatisticsTest")
public class HotRodNonOwnerStatisticsTest extends MultipleCacheManagersTest {
private HotRodServer hotRodServer;
private RemoteCacheManager remoteCacheManager;
private RemoteCache<Object, Object> remoteCache;
@Override
protected void createCacheManagers() throws Throwable {
// Add 3 new nodes, but only start one server, so the client only has one connection
newCacheManager();
newCacheManager();
newCacheManager();
hotRodServer = startHotRodServer(cacheManagers.get(0));
org.infinispan.client.hotrod.configuration.ConfigurationBuilder
clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(hotRodServer);
clientBuilder.statistics().enable();
// We only need one connection, avoid topology updates
clientBuilder.clientIntelligence(ClientIntelligence.BASIC);
remoteCacheManager = new InternalRemoteCacheManager(clientBuilder.build());
remoteCache = remoteCacheManager.getCache();
}
@AfterClass(alwaysRun = true)
@Override
protected void destroy() {
remoteCacheManager.stop();
hotRodServer.stop();
super.destroy();
}
private void newCacheManager() {
ConfigurationBuilder cfg = hotRodCacheConfiguration();
cfg.statistics().enable();
cfg.clustering().cacheMode(CacheMode.DIST_SYNC).hash().numOwners(2);
GlobalConfigurationBuilder globalCfg = GlobalConfigurationBuilder.defaultClusteredBuilder();
globalCfg.jmx().mBeanServerLookup(TestMBeanServerLookup.create()).enable();
addClusterEnabledCacheManager(globalCfg, cfg);
}
@AfterMethod(alwaysRun = true)
@Override
protected void clearContent() throws Throwable {
super.clearContent();
Stats cacheStats = advancedCache(0).getStats();
cacheStats.reset();
remoteCache.clientStatistics().resetStatistics();
log.debugf("Stats reset on %s", address(0));
}
public void testNonPrimaryGetStats() {
// We want at least one key for which cache(0) is primary/backup/non-owner
// 10 keys do not guarantee that 100%, but it's good enough
int keyCount = 10;
for (int i = 0; i < keyCount; i++) {
remoteCache.put("k" + i, "v" + i);
remoteCache.get("k" + i);
remoteCache.get("not_presented" + i);
}
assertEquals(keyCount, (int) remoteCache.serverStatistics().getIntStatistic(ServerStatistics.HITS));
assertEquals(keyCount, (int) remoteCache.serverStatistics().getIntStatistic(ServerStatistics.MISSES));
}
}
| 3,748
| 38.463158
| 108
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/DistTopologyChangeTest.java
|
package org.infinispan.client.hotrod;
import org.infinispan.configuration.cache.CacheMode;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test(groups = "functional" , testName = "client.hotrod.DistTopologyChangeTest")
public class DistTopologyChangeTest extends ReplTopologyChangeTest {
protected CacheMode getCacheMode() {
return CacheMode.DIST_SYNC;
}
}
| 417
| 25.125
| 80
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/RemoteCacheManagerTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test(testName = "client.hotrod.RemoteCacheManagerTest", groups = "functional")
public class RemoteCacheManagerTest extends SingleCacheManagerTest {
HotRodServer hotrodServer;
int port;
RemoteCacheManager remoteCacheManager;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
return TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration());
}
@Override
protected void setup() throws Exception {
super.setup();
hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
port = hotrodServer.getPort();
remoteCacheManager = null;
}
@Override
protected void teardown() {
HotRodClientTestingUtil.killServers(hotrodServer);
hotrodServer = null;
super.teardown();
}
@AfterMethod(alwaysRun = true)
protected void stopClient() {
HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager);
}
public void testStartStopAsync() throws Exception {
remoteCacheManager = new RemoteCacheManager(false);
remoteCacheManager.startAsync().get();
assertTrue(remoteCacheManager.isStarted());
remoteCacheManager.stopAsync().get();
assertFalse(remoteCacheManager.isStarted());
}
public void testNoArgConstructor() {
remoteCacheManager = new RemoteCacheManager();
assertTrue(remoteCacheManager.isStarted());
}
public void testBooleanConstructor() {
remoteCacheManager = new RemoteCacheManager(false);
assertFalse(remoteCacheManager.isStarted());
remoteCacheManager.start();
}
public void testConfigurationConstructor() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder
.addServer()
.host("127.0.0.1")
.port(port);
remoteCacheManager = new RemoteCacheManager(builder.build());
assertTrue(remoteCacheManager.isStarted());
}
}
| 2,677
| 31.26506
| 93
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/GetAllReplTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
/**
* Tests functionality related to getting getting multiple entries using a replicated
* cache
*
* @author William Burns
* @since 7.2
*/
@Test(testName = "client.hotrod.GetAllReplTest", groups = "functional")
public class GetAllReplTest extends BaseGetAllTest {
@Override
protected int numberOfHotRodServers() {
return 3;
}
@Override
protected ConfigurationBuilder clusterConfig() {
return hotRodCacheConfiguration(getDefaultClusteredCacheConfig(
CacheMode.REPL_SYNC, false));
}
}
| 819
| 26.333333
| 91
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/TestsModule.java
|
package org.infinispan.client.hotrod;
import org.infinispan.factories.annotations.InfinispanModule;
/**
* {@code InfinispanModule} annotation is required for component annotation processing
*/
@InfinispanModule(name = "client-hotrod-tests")
public class TestsModule implements org.infinispan.lifecycle.ModuleLifecycle {
}
| 326
| 28.727273
| 86
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/AsymmetricRoutingDefaultLocalCacheTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.AsymmetricRoutingDefaultLocalCacheTest")
public class AsymmetricRoutingDefaultLocalCacheTest extends AsymmetricRoutingTest {
@Override
protected ConfigurationBuilder defaultCacheConfigurationBuilder() {
return hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.LOCAL));
}
}
| 647
| 35
| 95
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ServerShutdownTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withRemoteCacheManager;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.test.TestingUtil.withCacheManager;
import static org.testng.AssertJUnit.assertEquals;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.RemoteCacheManagerCallable;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.CacheManagerCallable;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test(testName = "client.hotrod.ServerShutdownTest", groups = "functional")
public class ServerShutdownTest extends AbstractInfinispanTest {
public void testServerShutdownWithConnectedClient() {
withCacheManager(new CacheManagerCallable(
TestCacheManagerFactory.createCacheManager(
hotRodCacheConfiguration())) {
@Override
public void call() {
HotRodServer hotrodServer = HotRodClientTestingUtil.startHotRodServer(cm);
try {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotrodServer.getPort());
withRemoteCacheManager(new RemoteCacheManagerCallable(
new RemoteCacheManager(clientBuilder.build())) {
@Override
public void call() {
RemoteCache remoteCache = rcm.getCache();
remoteCache.put("k","v");
assertEquals("v", remoteCache.get("k"));
}
});
} finally {
killServers(hotrodServer);
}
}
});
}
public void testServerShutdownWithoutConnectedClient() {
withCacheManager(new CacheManagerCallable(
TestCacheManagerFactory.createCacheManager(
hotRodCacheConfiguration())) {
@Override
public void call() {
HotRodServer hotrodServer = HotRodClientTestingUtil.startHotRodServer(cm);
try {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotrodServer.getPort());
withRemoteCacheManager(new RemoteCacheManagerCallable(
new RemoteCacheManager(clientBuilder.build())) {
@Override
public void call() {
RemoteCache remoteCache = rcm.getCache();
remoteCache.put("k","v");
assertEquals("v", remoteCache.get("k"));
}
});
} finally {
killServers(hotrodServer);
}
}
});
}
}
| 3,314
| 40.962025
| 95
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/DefaultExpirationTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.util.concurrent.TimeUnit;
import org.infinispan.AdvancedCache;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
/**
* @author Tristan Tarrant
* @since 5.2
*/
@Test (testName = "client.hotrod.DefaultExpirationTest", groups = "functional" )
public class DefaultExpirationTest extends SingleCacheManagerTest {
protected RemoteCache<String, String> remoteCache;
protected RemoteCacheManager remoteCacheManager;
protected HotRodServer hotrodServer;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder builder = hotRodCacheConfiguration(
getDefaultStandaloneCacheConfig(false));
builder.expiration().lifespan(3, TimeUnit.SECONDS).maxIdle(2, TimeUnit.SECONDS);
return TestCacheManagerFactory.createCacheManager(builder);
}
@Override
protected void setup() throws Exception {
super.setup();
//pass the config file to the cache
hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
log.info("Started server on port: " + hotrodServer.getPort());
remoteCacheManager = getRemoteCacheManager();
remoteCache = remoteCacheManager.getCache();
}
protected RemoteCacheManager getRemoteCacheManager() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotrodServer.getPort());
return new RemoteCacheManager(clientBuilder.build());
}
@AfterClass
public void testDestroyRemoteCacheFactory() {
HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager);
HotRodClientTestingUtil.killServers(hotrodServer);
hotrodServer = null;
}
@Test
public void testDefaultExpiration() throws Exception {
remoteCache.put("Key", "Value");
AdvancedCache<String, String> embeddedCache = cacheManager.<String, String>getCache().getAdvancedCache();
InternalCacheEntry entry = (InternalCacheEntry) embeddedCache.getCacheEntry("Key");
assertEquals("Value", entry.getValue());
assertTrue(entry.canExpire());
assertEquals(3000, entry.getLifespan());
assertEquals(2000, entry.getMaxIdle());
Thread.sleep(5000);
assertFalse(remoteCache.containsKey("Key"));
}
}
| 3,078
| 38.474359
| 111
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/HotRodServerStartStopTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNull;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.Arrays;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test(testName = "client.hotrod.HotRodServerStartStopTest", groups = "functional")
public class HotRodServerStartStopTest extends MultipleCacheManagersTest {
private static int randomPort() {
try {
ServerSocket socket = new ServerSocket(0);
return socket.getLocalPort();
} catch (IOException e) {
return 56001;
}
}
private final static int FIRST_SERVER_PORT = randomPort();
private HotRodServer hotRodServer1;
private HotRodServer hotRodServer2;
private HotRodServer hotRodServer3;
@AfterMethod
@Override
protected void clearContent() {
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = hotRodCacheConfiguration(
getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
addClusterEnabledCacheManager(builder);
addClusterEnabledCacheManager(builder);
addClusterEnabledCacheManager(builder);
hotRodServer1 = HotRodClientTestingUtil.startHotRodServer(manager(0), FIRST_SERVER_PORT, new HotRodServerConfigurationBuilder());
hotRodServer2 = HotRodClientTestingUtil.startHotRodServer(manager(1));
hotRodServer3 = HotRodClientTestingUtil.startHotRodServer(manager(2));
waitForClusterToForm();
}
public void testTouchServer() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotRodServer1.getPort());
RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build(), true);
RemoteCache<Object, Object> remoteCache = remoteCacheManager.getCache();
remoteCache.put("k", "v");
assertEquals("v", remoteCache.get("k"));
CacheTopologyInfo info = remoteCache.getCacheTopologyInfo();
Integer prevTop = info.getTopologyId();
killServers(hotRodServer1, hotRodServer2, hotRodServer3);
Arrays.stream(managers()).forEach(EmbeddedCacheManager::stop);
cacheManagers.clear();
hotRodServer1 = null;
hotRodServer2 = null;
hotRodServer3 = null;
ConfigurationBuilder builder = hotRodCacheConfiguration(
getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
addClusterEnabledCacheManager(builder);
hotRodServer1 = HotRodClientTestingUtil.startHotRodServer(manager(0), FIRST_SERVER_PORT, new HotRodServerConfigurationBuilder());
// data was loss on restart
assertNull(remoteCache.get("k1"));
if (prevTop != null) {
assertFalse("Topology is still the same: " + prevTop, prevTop.equals(remoteCache.getCacheTopologyInfo().getTopologyId()));
}
killRemoteCacheManager(remoteCacheManager);
killServers(hotRodServer1);
hotRodServer1 = null;
}
}
| 3,977
| 37.25
| 135
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/SecureListenerTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM_TYPE;
import static org.testng.AssertJUnit.assertEquals;
import java.util.Collections;
import java.util.Map;
import javax.security.auth.Subject;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.event.ClientEvent;
import org.infinispan.client.hotrod.event.EventLogListener;
import org.infinispan.client.hotrod.exceptions.HotRodClientException;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalAuthorizationConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.cachelistener.CacheNotifier;
import org.infinispan.security.AuthorizationPermission;
import org.infinispan.security.Security;
import org.infinispan.security.mappers.IdentityRoleMapper;
import org.infinispan.server.core.security.simple.SimpleSaslAuthenticator;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.test.TestCallbackHandler;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* Tests verifying client listeners with authentication enabled.
*
* @author Dan Berindei
*/
@Test(testName = "client.hotrod.SecureListenerTest", groups = "functional")
public class SecureListenerTest extends AbstractAuthenticationTest {
static final Subject ADMIN = TestingUtil.makeSubject("admin");
static final String CACHE_NAME = "secured-listen";
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
GlobalConfigurationBuilder global = new GlobalConfigurationBuilder();
GlobalAuthorizationConfigurationBuilder globalRoles =
global.security().authorization().enable().principalRoleMapper(new IdentityRoleMapper()).groupOnlyMapping(false);
globalRoles.role("admin").permission(AuthorizationPermission.ALL)
.role("RWLuser").permission(AuthorizationPermission.READ, AuthorizationPermission.WRITE,
AuthorizationPermission.LISTEN)
.role("RWUser").permission(AuthorizationPermission.READ, AuthorizationPermission.WRITE);
ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(true);
config.security().authorization().enable()
.role("admin").role("RWLuser").role("RWUser");
config.encoding().key().mediaType(APPLICATION_PROTOSTREAM_TYPE);
config.encoding().value().mediaType(APPLICATION_PROTOSTREAM_TYPE);
cacheManager = TestCacheManagerFactory.createCacheManager(global, config);
cacheManager.defineConfiguration(CACHE_NAME, config.build());
cacheManager.getCache();
hotrodServer = initServer(Collections.emptyMap(), 0);
return cacheManager;
}
@Override
protected SimpleSaslAuthenticator createAuthenticationProvider() {
SimpleSaslAuthenticator sap = new SimpleSaslAuthenticator();
sap.addUser("RWLuser", "realm", "password".toCharArray(), null);
sap.addUser("RWuser", "realm", "password".toCharArray(), null);
return sap;
}
@Override
protected void setup() throws Exception {
Security.doAs(ADMIN, () -> {
try {
SecureListenerTest.super.setup();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
@Override
protected void teardown() {
Security.doAs(ADMIN, () -> SecureListenerTest.super.teardown());
}
@Override
protected void clearCacheManager() {
Security.doAs(ADMIN, () -> cacheManager.getCache().clear());
if (remoteCacheManager != null) {
HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager);
remoteCacheManager = null;
}
}
@Override
protected HotRodServer initServer(Map<String, String> mechProperties, int index) {
return Security.doAs(ADMIN, () -> SecureListenerTest.super.initServer(mechProperties, index));
}
public void testImplicitRemoveOnClose() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = newClientBuilder();
clientBuilder.security().authentication().callbackHandler(new TestCallbackHandler("RWLuser",null, "password"));
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
RemoteCache<Object, Object> clientCache = remoteCacheManager.getCache(CACHE_NAME);
EventLogListener<Object> listener = new EventLogListener<>(clientCache);
clientCache.addClientListener(listener);
Cache<Object, Object> serverCache = cacheManager.getCache(CACHE_NAME);
CacheNotifier cacheNotifier = TestingUtil.extractComponent(serverCache, CacheNotifier.class);
assertEquals(1, cacheNotifier.getListeners().size());
clientCache.put("key", "value");
listener.expectSingleEvent("key", ClientEvent.Type.CLIENT_CACHE_ENTRY_CREATED);
remoteCacheManager.close();
eventuallyEquals(0, () -> cacheNotifier.getListeners().size());
}
public void testAddListenerWithoutPermission() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = newClientBuilder();
clientBuilder.security().authentication().saslMechanism("CRAM-MD5").username("RWuser").password("password");
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
RemoteCache<Object, Object> clientCache = remoteCacheManager.getCache(CACHE_NAME);
EventLogListener<Object> listener = new EventLogListener<>(clientCache);
Exceptions.expectException(HotRodClientException.class, () -> clientCache.addClientListener(listener));
Cache<Object, Object> serverCache = cacheManager.getCache(CACHE_NAME);
CacheNotifier cacheNotifier = TestingUtil.extractComponent(serverCache, CacheNotifier.class);
assertEquals(0, cacheNotifier.getListeners().size());
remoteCacheManager.close();
assertEquals(0, cacheNotifier.getListeners().size());
}
}
| 6,303
| 42.178082
| 125
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/SkipNotificationsFlagTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.Flag.SKIP_LISTENER_NOTIFICATION;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.commands.FlagAffectedCommand;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commons.CacheException;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.interceptors.BaseAsyncInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.CleanupAfterTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Tests if the {@link Flag#SKIP_LISTENER_NOTIFICATION} flag is received on HotRod server.
*
* @author Katia Aresti, karesti@redhat.com
* @since 10
*/
@Test(testName = "client.hotrod.SkipNotificationsFlagTest", groups = "functional")
@CleanupAfterTest
public class SkipNotificationsFlagTest extends SingleCacheManagerTest {
private static final String KEY = "key";
private static final String VALUE = "value";
private FlagCheckCommandInterceptor commandInterceptor;
private RemoteCache<String, String> remoteCache;
private RemoteCacheManager remoteCacheManager;
private HotRodServer hotRodServer;
public void testPut() {
performTest(RequestType.PUT);
}
public void testReplace() {
performTest(RequestType.REPLACE);
}
public void testPutIfAbsent() {
performTest(RequestType.PUT_IF_ABSENT);
}
public void testReplaceIfUnmodified() {
performTest(RequestType.REPLACE_IF_UNMODIFIED);
}
public void testRemove() {
performTest(RequestType.REMOVE);
}
public void testRemoveIfUnmodified() {
performTest(RequestType.REMOVE_IF_UNMODIFIED);
}
public void testPutAll() {
performTest(RequestType.PUT_ALL);
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration());
cache = cacheManager.getCache();
hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
Properties hotRodClientConf = new Properties();
hotRodClientConf.put("infinispan.client.hotrod.server_list", "localhost:" + hotRodServer.getPort());
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotRodServer.getPort());
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
remoteCache = remoteCacheManager.getCache();
return cacheManager;
}
@Override
protected void teardown() {
HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager);
remoteCacheManager = null;
HotRodClientTestingUtil.killServers(hotRodServer);
hotRodServer = null;
super.teardown();
}
private void performTest(RequestType type) {
commandInterceptor.expectSkipIndexingFlag = true;
type.execute(remoteCache.withFlags(SKIP_LISTENER_NOTIFICATION));
}
@BeforeClass(alwaysRun = true)
private void injectCommandInterceptor() {
if (remoteCache == null) {
return;
}
this.commandInterceptor = new FlagCheckCommandInterceptor();
extractInterceptorChain(cache).addInterceptor(commandInterceptor, 1);
}
@AfterClass(alwaysRun = true)
private void resetCommandInterceptor() {
if (commandInterceptor != null) {
commandInterceptor.expectSkipIndexingFlag = false;
}
}
private enum RequestType {
PUT {
@Override
void execute(RemoteCache<String, String> cache) {
cache.put(KEY, VALUE);
}
},
REPLACE {
@Override
void execute(RemoteCache<String, String> cache) {
cache.replace(KEY, VALUE);
}
},
PUT_IF_ABSENT {
@Override
void execute(RemoteCache<String, String> cache) {
cache.putIfAbsent(KEY, VALUE);
}
},
REPLACE_IF_UNMODIFIED {
@Override
void execute(RemoteCache<String, String> cache) {
cache.replaceWithVersion(KEY, VALUE, 0);
}
},
REMOVE {
@Override
void execute(RemoteCache<String, String> cache) {
cache.remove(KEY);
}
},
REMOVE_IF_UNMODIFIED {
@Override
void execute(RemoteCache<String, String> cache) {
cache.removeWithVersion(KEY, 0);
}
},
PUT_ALL {
@Override
void execute(RemoteCache<String, String> cache) {
Map<String, String> data = new HashMap<>();
data.put(KEY, VALUE);
cache.putAll(data);
}
},
;
abstract void execute(RemoteCache<String, String> cache);
}
static class FlagCheckCommandInterceptor extends BaseAsyncInterceptor {
private volatile boolean expectSkipIndexingFlag;
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) {
if (command instanceof FlagAffectedCommand) {
boolean hasFlag = ((FlagAffectedCommand) command).hasAnyFlag(FlagBitSets.SKIP_LISTENER_NOTIFICATION);
if (expectSkipIndexingFlag && !hasFlag) {
throw new CacheException("SKIP_LISTENER_NOTIFICATION flag is expected!");
} else if (!expectSkipIndexingFlag && hasFlag) {
throw new CacheException("SKIP_LISTENER_NOTIFICATION flag is *not* expected!");
}
}
return invokeNext(ctx, command);
}
}
}
| 6,181
| 31.536842
| 113
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ExecTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.loadScript;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withClientListener;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withScript;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT_TYPE;
import static org.infinispan.commons.test.CommonsTestingUtil.loadFileAsString;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import org.infinispan.client.hotrod.event.EventLogListener;
import org.infinispan.client.hotrod.exceptions.HotRodClientException;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.marshall.JavaSerializationMarshaller;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.scripting.ScriptingManager;
import org.infinispan.scripting.utils.ScriptingUtils;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.AssertJUnit;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* ExecTest.
*
* @author Tristan Tarrant
* @since 7.2
*/
@Test(groups = {"functional", "smoke"}, testName = "client.hotrod.ExecTest")
public class ExecTest extends MultiHotRodServersTest {
static final String REPL_CACHE = "R";
static final String DIST_CACHE = "D";
static final int NUM_SERVERS = 2;
static final int SIZE = 20;
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(NUM_SERVERS, new ConfigurationBuilder());
defineInAll(REPL_CACHE, CacheMode.REPL_SYNC);
defineInAll(DIST_CACHE, CacheMode.DIST_SYNC);
}
@Override
protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(HotRodServer server) {
// Remote scripting must use the JavaSerializationMarshaller for now due to IPROTO-118
return createHotRodClientConfigurationBuilder(server.getHost(), server.getPort()).marshaller(JavaSerializationMarshaller.class).addJavaSerialAllowList("java.*");
}
@AfterMethod
@Override
protected void clearContent() throws Throwable {
clients.get(0).getCache(REPL_CACHE).clear();
clients.get(0).getCache(DIST_CACHE).clear();
}
private void defineInAll(String cacheName, CacheMode mode) {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(mode, true);
builder.encoding().key().mediaType(APPLICATION_OBJECT_TYPE);
builder.encoding().value().mediaType(APPLICATION_OBJECT_TYPE)
.locking().isolationLevel(IsolationLevel.READ_COMMITTED);
defineInAll(cacheName, builder);
}
@Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*Unknown task 'nonExistent\\.js'.*")
public void testRemovingNonExistentScript() {
clients.get(0).getCache().execute("nonExistent.js", new HashMap<>());
}
@Test(dataProvider = "CacheNameProvider")
public void testEmbeddedScriptRemoteExecution(String cacheName) throws IOException {
withScript(manager(0), "/test.js", scriptName -> {
populateCache(cacheName);
assertEquals(SIZE, clients.get(0).getCache(cacheName).size());
Map<String, String> params = new HashMap<>();
params.put("parameter", "guinness");
Integer result = clients.get(0).getCache(cacheName).execute(scriptName, params);
assertEquals(SIZE + 1, result.intValue());
assertEquals("guinness", clients.get(0).getCache(cacheName).get("parameter"));
});
}
@Test(dataProvider = "CacheNameProvider")
public void testRemoteScriptRemoteExecution(String cacheName) throws IOException {
withScript(manager(0), "/test.js", scriptName -> {
populateCache(cacheName);
assertEquals(SIZE, clients.get(0).getCache(cacheName).size());
Map<String, String> params = new HashMap<>();
params.put("parameter", "hoptimus prime");
Integer result = clients.get(0).getCache(cacheName).execute(scriptName, params);
assertEquals(SIZE + 1, result.intValue());
assertEquals("hoptimus prime", clients.get(0).getCache(cacheName).get("parameter"));
});
}
@Test(enabled = false, dataProvider = "CacheModeProvider", description = "Enable when ISPN-6300 is fixed.")
public void testScriptExecutionWithPassingParams(CacheMode cacheMode) throws IOException {
String cacheName = "testScriptExecutionWithPassingParams_" + cacheMode.toString();
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(cacheMode, true);
builder.encoding().key().mediaType(APPLICATION_OBJECT_TYPE)
.encoding().value().mediaType(APPLICATION_OBJECT_TYPE);
defineInAll(cacheName, builder);
try (InputStream is = this.getClass().getResourceAsStream("/distExec.js")) {
String script = loadFileAsString(is);
manager(0).getCache(ScriptingManager.SCRIPT_CACHE).put("testScriptExecutionWithPassingParams.js", script);
}
populateCache(cacheName);
assertEquals(SIZE, clients.get(0).getCache(cacheName).size());
Map<String, String> params = new HashMap<>();
params.put("a", "hoptimus prime");
List<String> result = clients.get(0).getCache(cacheName).execute("testScriptExecutionWithPassingParams.js", params);
assertEquals(SIZE + 1, client(0).getCache(cacheName).size());
assertEquals("hoptimus prime", clients.get(0).getCache(cacheName).get("a"));
assertEquals(2, result.size());
assertTrue(result.contains(manager(0).getAddress()));
assertTrue(result.contains(manager(1).getAddress()));
}
private void populateCache(String cacheName) {
for (int i = 0; i < SIZE; i++)
clients.get(i % NUM_SERVERS).getCache(cacheName).put(String.format("Key %d", i), String.format("Value %d", i));
}
@Test(enabled = false, dataProvider = "CacheModeProvider",
description = "Disabling this test until the distributed scripts in DIST mode are fixed - ISPN-6173")
public void testRemoteMapReduceWithStreams(CacheMode cacheMode) throws Exception {
String cacheName = "testRemoteMapReduce_Streams_dist_" + cacheMode.toString();
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(cacheMode, true);
builder.encoding().key().mediaType(APPLICATION_OBJECT_TYPE);
builder.encoding().value().mediaType(APPLICATION_OBJECT_TYPE);
defineInAll(cacheName, builder);
waitForClusterToForm(cacheName);
RemoteCache<String, String> cache = clients.get(0).getCache(cacheName);
ScriptingUtils.loadData(cache, "/macbeth.txt");
ScriptingManager scriptingManager = manager(0).getGlobalComponentRegistry().getComponent(ScriptingManager.class);
loadScript("/wordCountStream_dist.js", scriptingManager, "wordCountStream_dist.js");
ArrayList<Map<String, Long>> results = cache.execute("wordCountStream_dist.js", new HashMap<String, String>());
assertEquals(2, results.size());
assertEquals(3202, results.get(0).size());
assertEquals(3202, results.get(1).size());
assertTrue(results.get(0).get("macbeth").equals(287L));
assertTrue(results.get(1).get("macbeth").equals(287L));
}
@Test(dataProvider = "CacheNameProvider")
public void testExecPutConstantGet(String cacheName) throws IOException {
withScript(manager(0), "/test-put-constant-get.js", scriptName -> {
Map<String, String> params = new HashMap<>();
String result = clients.get(0).getCache(cacheName).execute(scriptName, params);
assertEquals("hoptimus prime", result);
assertEquals("hoptimus prime", clients.get(0).getCache(cacheName).get("a"));
});
}
@Test(dataProvider = "CacheNameProvider")
public void testExecReturnNull(String cacheName) throws IOException {
withScript(manager(0), "/test-null-return.js", scriptName -> {
Object result = clients.get(0).getCache(cacheName).execute(scriptName, new HashMap<>());
assertEquals(null, result);
});
}
@Test(dataProvider = "CacheNameProvider")
public void testLocalExecPutGet(String cacheName) {
execPutGet(cacheName, "/test-put-get.js", ExecMode.LOCAL, "local-key", "local-value");
}
@Test(dataProvider = "CacheNameProvider")
public void testDistExecPutGet(String cacheName) {
execPutGet(cacheName, "/test-put-get-dist.js", ExecMode.DIST, "dist-key", "dist-value");
}
@Test(dataProvider = "CacheNameProvider")
public void testLocalExecPutGetWithListener(String cacheName) {
final EventLogListener<String> l = new EventLogListener<>(clients.get(0).getCache(cacheName));
withClientListener(l, remote ->
withScript(manager(0), "/test-put-get.js", scriptName -> {
Map<String, String> params = new HashMap<>();
params.put("k", "local-key-listen");
params.put("v", "local-value-listen");
String result = remote.execute(scriptName, params);
l.expectOnlyCreatedEvent("local-key-listen");
assertEquals("local-value-listen", result);
}));
}
@Test(dataProvider = "CacheNameProvider")
public void testExecWithHint(String cacheName) {
withScript(manager(0), "/test-is-primary-owner.js", scriptName -> {
RemoteCache<Object, Object> cache = clients.get(0).getCache(cacheName);
for (int i = 0; i < 50; ++i) {
String someKey = "someKey" + i;
assertTrue(cache.execute(scriptName, Collections.singletonMap("k", someKey), someKey));
}
int notHinted = 0;
for (int i = 0; i < 50; ++i) {
String someKey = "someKey" + i;
if (cache.execute(scriptName, Collections.singletonMap("k", someKey))) {
++notHinted;
}
}
assertTrue("Not hinted: " + notHinted, notHinted > 0);
assertTrue("Not hinted: " + notHinted, notHinted < 50);
});
}
private void execPutGet(String cacheName, String path, ExecMode mode, String key, String value) {
withScript(manager(0), path, scriptName -> {
Map<String, String> params = new HashMap<>();
params.put("k", key);
params.put("v", value);
params.put("cacheName", cacheName);
Object results = clients.get(0).getCache(cacheName).execute(scriptName, params);
mode.assertResult.accept(value, results);
});
}
@DataProvider(name = "CacheNameProvider")
private static Object[][] provideCacheMode() {
return new Object[][]{{REPL_CACHE}, {DIST_CACHE}};
}
enum ExecMode {
LOCAL(AssertJUnit::assertEquals),
DIST((v, r) -> assertEquals(Arrays.asList(v, v), r));
final BiConsumer<String, Object> assertResult;
ExecMode(BiConsumer<String, Object> assertResult) {
this.assertResult = assertResult;
}
}
}
| 11,444
| 43.882353
| 167
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/CSAIntegrationTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.assertHotRodEquals;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.marshall;
import static org.infinispan.test.TestingUtil.blockUntilCacheStatusAchieved;
import static org.infinispan.test.TestingUtil.blockUntilViewReceived;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.infinispan.client.hotrod.impl.protocol.HotRodConstants;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelRecord;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.client.hotrod.test.NoopChannelOperation;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.manager.CacheContainer;
import org.infinispan.remoting.transport.Address;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import io.netty.channel.Channel;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test(groups = "functional", testName = "client.hotrod.CSAIntegrationTest")
public class CSAIntegrationTest extends HitsAwareCacheManagersTest {
private HotRodServer hotRodServer1;
private HotRodServer hotRodServer2;
private HotRodServer hotRodServer3;
private RemoteCacheManager remoteCacheManager;
private RemoteCache<Object, Object> remoteCache;
private ChannelFactory channelFactory;
private static final Log log = LogFactory.getLog(CSAIntegrationTest.class);
@AfterMethod
@Override
protected void clearContent() throws Throwable {
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = hotRodCacheConfiguration(
getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
builder.clustering().hash().numOwners(1);
builder.unsafe().unreliableReturnValues(true);
addClusterEnabledCacheManager(builder);
addClusterEnabledCacheManager(builder);
addClusterEnabledCacheManager(builder);
hotRodServer1 = HotRodClientTestingUtil.startHotRodServer(manager(0));
addr2hrServer.put(InetSocketAddress.createUnresolved(hotRodServer1.getHost(), hotRodServer1.getPort()), hotRodServer1);
hotRodServer2 = HotRodClientTestingUtil.startHotRodServer(manager(1));
addr2hrServer.put(InetSocketAddress.createUnresolved(hotRodServer2.getHost(), hotRodServer2.getPort()), hotRodServer2);
hotRodServer3 = HotRodClientTestingUtil.startHotRodServer(manager(2));
addr2hrServer.put(InetSocketAddress.createUnresolved(hotRodServer3.getHost(), hotRodServer3.getPort()), hotRodServer3);
assert manager(0).getCache() != null;
assert manager(1).getCache() != null;
assert manager(2).getCache() != null;
blockUntilViewReceived(manager(0).getCache(), 3);
blockUntilCacheStatusAchieved(manager(0).getCache(), ComponentStatus.RUNNING, 10000);
blockUntilCacheStatusAchieved(manager(1).getCache(), ComponentStatus.RUNNING, 10000);
blockUntilCacheStatusAchieved(manager(2).getCache(), ComponentStatus.RUNNING, 10000);
//Important: this only connects to one of the two servers!
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder(hotRodServer2);
remoteCacheManager = new InternalRemoteCacheManager(clientBuilder.build());
remoteCache = remoteCacheManager.getCache();
channelFactory = ((InternalRemoteCacheManager) remoteCacheManager).getChannelFactory();
}
protected void setHotRodProtocolVersion(org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder) {
// No-op, use default Hot Rod protocol version
}
@AfterClass
@Override
protected void destroy() {
killRemoteCacheManager(remoteCacheManager);
killServers(hotRodServer1, hotRodServer2, hotRodServer3);
hotRodServer1 = null;
hotRodServer2 = null;
hotRodServer3 = null;
super.destroy();
}
public void testHashInfoRetrieved() throws InterruptedException {
assertEquals(3, channelFactory.getServers().size());
for (int i = 0; i < 10; i++) {
remoteCache.put("k", "v");
if (channelFactory.getServers().size() == 3) break;
Thread.sleep(1000);
}
assertEquals(3, channelFactory.getServers().size());
assertNotNull(channelFactory.getConsistentHash(HotRodConstants.DEFAULT_CACHE_NAME_BYTES));
}
@Test(dependsOnMethods = "testHashInfoRetrieved")
public void testCorrectSetup() {
remoteCache.put("k", "v");
assert remoteCache.get("k").equals("v");
}
@Test(dependsOnMethods = "testCorrectSetup")
public void testHashFunctionReturnsSameValues() throws InterruptedException {
for (int i = 0; i < 1000; i++) {
byte[] key = generateKey(i);
Channel channel = channelFactory.fetchChannelAndInvoke(key, null, HotRodConstants.DEFAULT_CACHE_NAME_BYTES, new NoopChannelOperation()).join();
SocketAddress serverAddress = ChannelRecord.of(channel).getUnresolvedAddress();
CacheContainer cacheContainer = addr2hrServer.get(serverAddress).getCacheManager();
assertNotNull("For server address " + serverAddress + " found " + cacheContainer + ". Map is: " + addr2hrServer, cacheContainer);
DistributionManager distributionManager = cacheContainer.getCache().getAdvancedCache().getDistributionManager();
Address clusterAddress = cacheContainer.getCache().getAdvancedCache().getRpcManager().getAddress();
ConsistentHash serverCh = distributionManager.getReadConsistentHash();
int numSegments = serverCh.getNumSegments();
int keySegment = distributionManager.getCacheTopology().getSegment(key);
Address serverOwner = serverCh.locatePrimaryOwnerForSegment(keySegment);
Address serverPreviousOwner = serverCh.locatePrimaryOwnerForSegment((keySegment - 1 + numSegments) % numSegments);
assert clusterAddress.equals(serverOwner) || clusterAddress.equals(serverPreviousOwner);
channelFactory.releaseChannel(channel);
}
}
@Test(dependsOnMethods = "testHashFunctionReturnsSameValues")
public void testRequestsGoToExpectedServer() throws Exception {
addInterceptors();
List<byte[]> keys = new ArrayList<byte[]>();
for (int i = 0; i < 500; i++) {
byte[] key = generateKey(i);
keys.add(key);
String keyStr = new String(key);
remoteCache.put(keyStr, "value");
Channel channel = channelFactory.fetchChannelAndInvoke(marshall(keyStr), null, RemoteCacheManager.cacheNameBytes(), new NoopChannelOperation()).join();
assertHotRodEquals(addr2hrServer.get(ChannelRecord.of(channel).getUnresolvedAddress()).getCacheManager(), keyStr, "value");
channelFactory.releaseChannel(channel);
}
log.info("Right before first get.");
for (byte[] key : keys) {
resetStats();
String keyStr = new String(key);
assert remoteCache.get(keyStr).equals("value");
Channel channel = channelFactory.fetchChannelAndInvoke(marshall(keyStr), null, HotRodConstants.DEFAULT_CACHE_NAME_BYTES, new NoopChannelOperation()).join();
assertOnlyServerHit(ChannelRecord.of(channel).getUnresolvedAddress());
channelFactory.releaseChannel(channel);
}
}
private byte[] generateKey(int i) {
Random r = new Random();
byte[] result = new byte[i];
r.nextBytes(result);
return result;
}
}
| 8,575
| 45.608696
| 165
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/DistTopologyChangeUnderLoadTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.getLoadBalancer;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import java.net.SocketAddress;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import org.infinispan.client.hotrod.impl.transport.tcp.RoundRobinBalancingStrategy;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.DistTopologyChangeUnderLoadTest")
public class DistTopologyChangeUnderLoadTest extends MultiHotRodServersTest {
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(1, getCacheConfiguration());
}
private ConfigurationBuilder getCacheConfiguration() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
builder.clustering().hash().numOwners(2);
return hotRodCacheConfiguration(builder);
}
@Override
protected int maxRetries() {
return 1;
}
public void testPutsSucceedWhileTopologyChanges() throws Exception {
RemoteCache<Integer, String> remote = client(0).getCache();
remote.put(1, "v1");
assertEquals("v1", remote.get(1));
PutHammer putHammer = new PutHammer();
Future<Void> putHammerFuture = fork(putHammer);
HotRodServer newServer = addHotRodServer(getCacheConfiguration());
// Wait for 2 seconds
TestingUtil.sleepThread(2000);
HotRodClientTestingUtil.killServers(newServer);
TestingUtil.killCacheManagers(newServer.getCacheManager());
TestingUtil.waitForNoRebalance(cache(0));
// Execute one more operation to guarantee topology update on the client
remote.put(-1, "minus one");
RoundRobinBalancingStrategy strategy = getLoadBalancer(client(0));
SocketAddress[] servers = strategy.getServers();
putHammer.stop = true;
putHammerFuture.get();
assertEquals(1, servers.length);
}
private class PutHammer implements Callable<Void> {
volatile boolean stop;
@Override
public Void call() throws Exception {
RemoteCache<Integer, String> remote = client(0).getCache();
int i = 2;
while (!stop) {
remote.put(i, "v" + i);
i += 1;
}
// Rehash completed only signals that server side caches have
// completed, but the client might not yet have updated its topology.
// So, run a fair few operations after rehashing has completed server
// side to verify it's all working fine.
for (int j = i + 1; j < i + 100 ; j++)
remote.put(j, "v" + j);
return null;
}
}
}
| 3,154
| 33.67033
| 96
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/MultipleCacheTopologyChangeTest.java
|
package org.infinispan.client.hotrod;
import static java.util.Arrays.stream;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.startHotRodServer;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.test.TestingUtil.killCacheManagers;
import static org.infinispan.test.fwk.TestCacheManagerFactory.createClusteredCacheManager;
import static org.testng.AssertJUnit.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
/**
* @since 9.0
*/
@Test(testName = "client.hotrod.MultipleCacheTopologyChangeTest", groups = "functional")
public class MultipleCacheTopologyChangeTest extends MultipleCacheManagersTest {
private final List<Node> nodes = new ArrayList<>();
private RemoteCacheManager client;
public void testRoundRobinLoadBalancing() throws InterruptedException, IOException {
String[] caches = new String[]{"cache1", "cache2"};
Node nodeA = startNewNode(caches);
Node nodeB = startNewNode(caches);
ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServers(getServerList(nodeA, nodeB));
client = new RemoteCacheManager(clientBuilder.build());
RemoteCache<Integer, String> cache1 = client.getCache("cache1");
RemoteCache<Integer, String> cache2 = client.getCache("cache2");
startNewNode(caches);
nodeB.kill();
assertTrue(cache1.isEmpty());
assertTrue(cache2.isEmpty());
nodeA.kill();
assertTrue(cache1.isEmpty());
assertTrue(cache2.isEmpty());
}
private String getServerList(Node... nodes) {
return String.join(";", stream(nodes).map(n -> "127.0.0.1:" + n.getPort()).collect(Collectors.toSet()));
}
@Override
protected void createCacheManagers() throws Throwable {
}
private Node startNewNode(String... caches) {
Node node = new Node(caches);
node.start();
waitForClusterToForm();
nodes.add(node);
return node;
}
class Node {
private final String[] cacheNames;
HotRodServer server;
EmbeddedCacheManager cacheManager;
private boolean stopped;
public Node(String... cacheNames) {
this.cacheNames = cacheNames;
}
public void start() {
cacheManager = createClusteredCacheManager(hotRodCacheConfiguration(getConfigurationBuilder()));
registerCacheManager(cacheManager);
stream(cacheNames).forEach(cacheName -> {
cacheManager.defineConfiguration(cacheName, getConfigurationBuilder().build());
cacheManager.getCache(cacheName);
});
server = startHotRodServer(cacheManager);
waitForClusterToForm(cacheNames);
}
public int getPort() {
return server.getPort();
}
void kill() {
if (!stopped) {
if (server != null) {
killServers(server);
}
killCacheManagers(cacheManager);
stopped = true;
}
}
}
protected org.infinispan.configuration.cache.ConfigurationBuilder getConfigurationBuilder() {
org.infinispan.configuration.cache.ConfigurationBuilder c =
new org.infinispan.configuration.cache.ConfigurationBuilder();
c.clustering().cacheMode(CacheMode.DIST_SYNC);
return c;
}
@AfterClass
@Override
protected void destroy() {
HotRodClientTestingUtil.killRemoteCacheManager(client);
nodes.forEach(Node::kill);
nodes.clear();
}
}
| 4,153
| 31.708661
| 110
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/PingOnStartupTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withRemoteCacheManager;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import org.infinispan.client.hotrod.configuration.ClientIntelligence;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.client.hotrod.test.RemoteCacheManagerCallable;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
/**
* Tests ping-on-startup logic whose objective is to retrieve the Hot Rod
* server topology before a client executes an operation against the server.
*
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test(groups = "functional", testName = "client.hotrod.PingOnStartupTest")
public class PingOnStartupTest extends MultiHotRodServersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = hotRodCacheConfiguration(
getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
createHotRodServers(2, builder);
}
public void testTopologyFetched() {
HotRodServer hotRodServer2 = server(1);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder(hotRodServer2);
withRemoteCacheManager(new RemoteCacheManagerCallable(
new InternalRemoteCacheManager(clientBuilder.build())) {
@Override
public void call() {
ChannelFactory channelFactory = ((InternalRemoteCacheManager) rcm).getChannelFactory();
for (int i = 0; i < 10; i++) {
if (channelFactory.getServers().size() == 1) {
TestingUtil.sleepThread(1000);
} else {
break;
}
}
assertEquals(2, channelFactory.getServers().size());
}
});
}
public void testBasicIntelligence() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(server(0).getPort());
clientBuilder.clientIntelligence(ClientIntelligence.BASIC);
withRemoteCacheManager(new RemoteCacheManagerCallable(
new InternalRemoteCacheManager(clientBuilder.build())) {
@Override
public void call() {
rcm.getCache();
ChannelFactory channelFactory = ((InternalRemoteCacheManager) rcm).getChannelFactory();
assertEquals(1, channelFactory.getServers().size());
}
});
}
public void testTopologyAwareIntelligence() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("127.0.0.1").port(server(0).getPort());
clientBuilder.clientIntelligence(ClientIntelligence.TOPOLOGY_AWARE);
withRemoteCacheManager(new RemoteCacheManagerCallable(
new InternalRemoteCacheManager(clientBuilder.build())) {
@Override
public void call() {
rcm.getCache();
ChannelFactory channelFactory = ((InternalRemoteCacheManager) rcm).getChannelFactory();
assertEquals(2, channelFactory.getServers().size());
}
});
}
public void testHashAwareIntelligence() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("127.0.0.1").port(server(0).getPort());
clientBuilder.clientIntelligence(ClientIntelligence.HASH_DISTRIBUTION_AWARE);
withRemoteCacheManager(new RemoteCacheManagerCallable(
new InternalRemoteCacheManager(clientBuilder.build())) {
@Override
public void call() {
rcm.getCache();
ChannelFactory channelFactory = ((InternalRemoteCacheManager) rcm).getChannelFactory();
assertEquals(2, channelFactory.getServers().size());
}
});
}
public void testGetCacheWithPingOnStartupDisabledMultipleNodes() {
HotRodServer hotRodServer2 = server(1);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder
.addServers("boomoo:12345;localhost:" + hotRodServer2.getPort());
withRemoteCacheManager(new RemoteCacheManagerCallable(
new RemoteCacheManager(clientBuilder.build())) {
@Override
public void call() {
RemoteCache<Object, Object> cache = rcm.getCache();
assertFalse(cache.containsKey("k"));
}
});
}
public void testGetCacheWorksIfNodeDown() {
HotRodServer hotRodServer2 = server(1);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder
.addServers("boomoo:12345;localhost:" + hotRodServer2.getPort());
withRemoteCacheManager(new RemoteCacheManagerCallable(
new RemoteCacheManager(clientBuilder.build())) {
@Override
public void call() {
rcm.getCache();
}
});
}
public void testGetCacheWorksIfNodeNotDown() {
HotRodServer hotRodServer2 = server(1);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder
.addServers("localhost:" + hotRodServer2.getPort());
withRemoteCacheManager(new RemoteCacheManagerCallable(
new RemoteCacheManager(clientBuilder.build())) {
@Override
public void call() {
rcm.getCache();
}
});
}
}
| 6,513
| 41.575163
| 99
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ServerErrorTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.commons.test.Exceptions.expectException;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.unmarshall;
import static org.infinispan.test.TestingUtil.k;
import static org.infinispan.test.TestingUtil.v;
import static org.testng.AssertJUnit.assertEquals;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.util.Queue;
import org.infinispan.client.hotrod.exceptions.HotRodClientException;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory;
import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.client.hotrod.test.NoopChannelOperation;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestException;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
import io.netty.channel.Channel;
import io.netty.util.concurrent.AbstractScheduledEventExecutor;
/**
* Tests HotRod client and server behaviour when server throws a server error
*
* @author Galder Zamarreño
* @since 4.2
*/
@Test(groups = "functional", testName = "client.hotrod.ServerErrorTest")
public class ServerErrorTest extends SingleCacheManagerTest {
private HotRodServer hotrodServer;
private InternalRemoteCacheManager remoteCacheManager;
private RemoteCache<String, String> remoteCache;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
cacheManager = TestCacheManagerFactory
.createCacheManager(hotRodCacheConfiguration());
hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
remoteCacheManager = getRemoteCacheManager();
remoteCache = remoteCacheManager.getCache();
return cacheManager;
}
protected InternalRemoteCacheManager getRemoteCacheManager() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host(hotrodServer.getHost()).port(hotrodServer.getPort());
clientBuilder.connectionPool().maxActive(1).minIdle(1);
return new InternalRemoteCacheManager(clientBuilder.build());
}
@AfterClass
public void shutDownHotrod() {
killRemoteCacheManager(remoteCacheManager);
remoteCacheManager = null;
killServers(hotrodServer);
hotrodServer = null;
}
public void testErrorWhileDoingPut(Method m) {
cache.getAdvancedCache().withStorageMediaType().addListener(new ErrorInducingListener());
remoteCache = remoteCacheManager.getCache();
remoteCache.put(k(m), v(m));
assertEquals(v(m), remoteCache.get(k(m)));
// Obtain a reference to the single connection in the pool
ChannelFactory channelFactory = remoteCacheManager.getChannelFactory();
InetSocketAddress address = InetSocketAddress.createUnresolved(hotrodServer.getHost(), hotrodServer.getPort());
Channel channel = channelFactory.fetchChannelAndInvoke(address, new NoopChannelOperation()).join();
// Obtain a reference to the scheduled executor and its task queue
AbstractScheduledEventExecutor scheduledExecutor = ((AbstractScheduledEventExecutor) channel.eventLoop());
Queue<?> scheduledTaskQueue = TestingUtil.extractField(scheduledExecutor, "scheduledTaskQueue");
int scheduledTasksBaseline = scheduledTaskQueue.size();
// Release the channel back into the pool
channelFactory.releaseChannel(channel);
assertEquals(0, channelFactory.getNumActive(address));
assertEquals(1, channelFactory.getNumIdle(address));
log.debug("Sending failing operation to server");
expectException(HotRodClientException.class,
() -> remoteCache.put("FailFailFail", "whatever..."));
assertEquals(0, channelFactory.getNumActive(address));
assertEquals(1, channelFactory.getNumIdle(address));
// Check that the operation was completed
HeaderDecoder headerDecoder = channel.pipeline().get(HeaderDecoder.class);
assertEquals(0, headerDecoder.registeredOperations());
// Check that the timeout task was cancelled
assertEquals(scheduledTasksBaseline, scheduledTaskQueue.size());
log.debug("Sending new request after server failure");
remoteCache.put(k(m, 2), v(m, 2));
assertEquals(v(m, 2), remoteCache.get(k(m, 2)));
}
@Listener
public static class ErrorInducingListener {
@CacheEntryCreated
@SuppressWarnings("unused")
public void entryCreated(CacheEntryEvent<byte[], byte[]> event) throws Exception {
if (event.isPre() && unmarshall(event.getKey()).equals("FailFailFail")) {
throw new TestException("Simulated server failure");
}
}
}
}
| 5,636
| 42.697674
| 117
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/AuthenticationTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import java.util.Collections;
import javax.security.sasl.Sasl;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.exceptions.HotRodClientException;
import org.infinispan.client.hotrod.exceptions.TransportException;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.test.TestResourceTracker;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.core.security.simple.SimpleSaslAuthenticator;
import org.infinispan.server.core.test.ServerTestingUtil;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.test.TestCallbackHandler;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* @author Tristan Tarrant
* @since 7.0
*/
@Test(testName = "client.hotrod.AuthenticationTest", groups = "functional")
public class AuthenticationTest extends AbstractAuthenticationTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration());
cacheManager.getCache();
hotrodServer = initServer(Collections.emptyMap(), 0);
return cacheManager;
}
@Override
protected SimpleSaslAuthenticator createAuthenticationProvider() {
SimpleSaslAuthenticator sap = new SimpleSaslAuthenticator();
sap.addUser("user", "realm", "password".toCharArray());
return sap;
}
@Test
public void testAuthentication() {
ConfigurationBuilder clientBuilder = newClientBuilder();
clientBuilder.security().authentication().callbackHandler(new TestCallbackHandler("user", "realm", "password"));
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
RemoteCache<String, String> defaultRemote = remoteCacheManager.getCache();
defaultRemote.put("a", "a");
assertEquals("a", defaultRemote.get("a"));
}
@Test
public void testAuthenticationViaURI() {
remoteCacheManager = new RemoteCacheManager("hotrod://user:password@127.0.0.1:" + hotrodServer.getPort() + "?auth_realm=realm&socket_timeout=3000&max_retries=3&connection_pool.max_active=1&sasl_mechanism=CRAM-MD5&default_executor_factory.threadname_prefix=" + TestResourceTracker.getCurrentTestShortName() + "-Client-Async");
RemoteCache<String, String> defaultRemote = remoteCacheManager.getCache();
defaultRemote.put("a", "a");
assertEquals("a", defaultRemote.get("a"));
}
@Test(expectedExceptions = TransportException.class)
public void testAuthenticationFailWrongAuth() {
ConfigurationBuilder clientBuilder = newClientBuilder();
clientBuilder.security().authentication().callbackHandler(new TestCallbackHandler("user", "realm", "foobar"));
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
remoteCacheManager.getCache();
}
@Test(expectedExceptions = HotRodClientException.class, expectedExceptionsMessageRegExp = ".*ISPN006017:.*")
public void testAuthenticationFailNoAuth() {
HotRodServer noAnonymousServer = initServer(Collections.singletonMap(Sasl.POLICY_NOANONYMOUS, "true"), 1);
try {
ConfigurationBuilder clientBuilder = newClientBuilder(1);
clientBuilder.security().authentication().disable();
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
RemoteCache<String, String> cache = remoteCacheManager.getCache();
cache.put("a", "a");
} finally {
ServerTestingUtil.killServer(noAnonymousServer);
}
}
@Test
public void testAuthenticationUsername() {
ConfigurationBuilder clientBuilder = newClientBuilder();
clientBuilder.security().authentication().username("user").realm("realm").password("password");
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
RemoteCache<String, String> defaultRemote = remoteCacheManager.getCache();
defaultRemote.put("a", "a");
assertEquals("a", defaultRemote.get("a"));
}
@Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = ".*ISPN004067.*")
public void testAuthenticationUsernameWithCallbackFail() {
ConfigurationBuilder clientBuilder = newClientBuilder();
clientBuilder.security().authentication().username("user").realm("realm").password("password")
.callbackHandler(new TestCallbackHandler("user", "realm", "foobar"));
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
}
}
| 4,800
| 43.869159
| 331
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/SizeTest.java
|
package org.infinispan.client.hotrod;
import static org.testng.AssertJUnit.assertEquals;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.SizeTest")
public class SizeTest extends MultiHotRodServersTest {
static final int NUM_SERVERS = 3;
static final int SIZE = 20;
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(NUM_SERVERS, new ConfigurationBuilder());
}
public void testLocalCacheSize() {
String cacheName = "local-size";
defineInAll(cacheName, new ConfigurationBuilder());
// Create a brand new client so that as a local cache it does not do load balancing
// This is important for size assertions since there's data is not clustered
RemoteCacheManager newClient = createClient(0);
try {
RemoteCache<Integer, Integer> newRemoteCache = newClient.getCache(cacheName);
populateCache(newRemoteCache);
assertEquals(SIZE, newRemoteCache.size());
} finally {
HotRodClientTestingUtil.killRemoteCacheManager(newClient);
}
}
public void testReplicatedCacheSize() {
String cacheName = "replicated-size";
defineInAll(cacheName, getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false));
populateCache(cacheName);
assertEquals(SIZE, clients.get(0).getCache(cacheName).size());
}
public void testDistributeCacheSize() {
String cacheName = "distributed-size";
defineInAll(cacheName, getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
populateCache(cacheName);
assertEquals(SIZE, clients.get(0).getCache(cacheName).size());
}
public void testPersistentDistributedCacheSize() {
String cacheName = "persistent-distributed-size";
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
builder.memory().size(1);
builder.persistence()
.addStore(DummyInMemoryStoreConfigurationBuilder.class)
.storeName(getClass().getName())
.purgeOnStartup(true);
defineInAll(cacheName, builder);
assertEquals(0, clients.get(0).getCache(cacheName).size());
populateCache(cacheName);
assertEquals(SIZE, server(0).getCacheManager().getCache(cacheName).size());
assertEquals(SIZE, clients.get(0).getCache(cacheName).size());
}
public void testPersistentSizeWithFlag() {
String cacheName = "persistent-size-with-flag";
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.LOCAL, false);
int evictionSize = 2;
builder.memory().maxCount(evictionSize);
builder.persistence()
.addStore(DummyInMemoryStoreConfigurationBuilder.class)
.storeName(getClass().getName())
.purgeOnStartup(true);
defineInAll(cacheName, builder);
RemoteCache<Integer, Integer> remoteCache = clients.get(0).getCache(cacheName);
assertEquals(0, remoteCache.size());
populateCache(remoteCache);
assertEquals(SIZE, remoteCache.size());
assertEquals(evictionSize, remoteCache.withFlags(Flag.SKIP_CACHE_LOAD).size());
}
private void populateCache(String cacheName) {
for (int i = 0; i < SIZE; i++) {
clients.get(i % NUM_SERVERS).getCache(cacheName).put(i, i);
}
}
private void populateCache(RemoteCache<Integer, Integer> remote) {
for (int i = 0; i < SIZE; i++)
remote.put(i, i);
}
}
| 3,823
| 38.42268
| 96
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/HotRodAsyncReplicationTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.test.TestingUtil.v;
import static org.testng.AssertJUnit.assertEquals;
import java.lang.reflect.Method;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.ReplListener;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.HotRodAsyncReplicationTest")
public class HotRodAsyncReplicationTest extends MultiHotRodServersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = hotRodCacheConfiguration(
getDefaultClusteredCacheConfig(CacheMode.REPL_ASYNC, false));
builder.memory().size(3);
createHotRodServers(2, builder);
}
public void testPutKeyValue(Method m) {
final RemoteCache<Object, Object> remoteCache0 = client(0).getCache();
final RemoteCache<Object, Object> remoteCache1 = client(1).getCache();
ReplListener replList0 = getReplListener(0);
ReplListener replList1 = getReplListener(1);
replList0.expect(PutKeyValueCommand.class);
replList1.expect(PutKeyValueCommand.class);
final String v1 = v(m);
remoteCache0.put(1, v1);
replList0.waitForRpc();
replList1.waitForRpc();
assertEquals(v1, remoteCache1.get(1));
assertEquals(v1, remoteCache1.get(1)); // Called twice to cover all round robin options
assertEquals(v1, remoteCache0.get(1));
assertEquals(v1, remoteCache0.get(1)); // Called twice to cover all round robin options
}
private ReplListener getReplListener(int cacheIndex) {
ReplListener replList = listeners.get(cache(cacheIndex));
if (replList == null)
replList = new ReplListener(cache(cacheIndex), true, true);
else
replList.reconfigureListener(true);
return replList;
}
}
| 2,144
| 34.163934
| 93
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ConsistentHashV2Test.java
|
package org.infinispan.client.hotrod;
import static org.testng.Assert.assertEquals;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHashV2;
import org.infinispan.commons.hash.Hash;
import org.infinispan.commons.util.Util;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.0
*/
@Test(groups = "unit", testName = "client.hotrod.ConsistentHashV2Test")
public class ConsistentHashV2Test {
private InetSocketAddress a1;
private InetSocketAddress a2;
private InetSocketAddress a3;
private InetSocketAddress a4;
private DummyHash hash;
private ConsistentHashV2 v1;
private void setUp(int numOwners) {
a1 = new InetSocketAddress(1);
a2 = new InetSocketAddress(2);
a3 = new InetSocketAddress(3);
a4 = new InetSocketAddress(4);
LinkedHashMap<SocketAddress, Set<Integer>> map = new LinkedHashMap<SocketAddress, Set<Integer>>();
map.put(a1, Collections.singleton(0));
map.put(a2, Collections.singleton(1000));
map.put(a3, Collections.singleton(2000));
map.put(a4, Collections.singleton(3000));
hash = new DummyHash();
this.v1 = new ConsistentHashV2(new Random(), hash);
this.v1.init(map, numOwners, 10000);
}
public void simpleTest() {
setUp(1);
hash.value = 0;
assert v1.getServer(Util.EMPTY_BYTE_ARRAY).equals(a1);
hash.value = 1;
assert v1.getServer(Util.EMPTY_BYTE_ARRAY).equals(a2);
hash.value = 1001;
assert v1.getServer(Util.EMPTY_BYTE_ARRAY).equals(a3);
hash.value = 2001;
assertEquals(v1.getServer(Util.EMPTY_BYTE_ARRAY), a4);
hash.value = 3001;
assert v1.getServer(Util.EMPTY_BYTE_ARRAY).equals(a1);
}
public void numOwners2Test() {
setUp(2);
hash.value = 0;
assert list(a1, a2).contains(v1.getServer(Util.EMPTY_BYTE_ARRAY));
hash.value = 1;
assert list(a2, a3).contains(v1.getServer(Util.EMPTY_BYTE_ARRAY));
hash.value = 1001;
assert list(a3, a4).contains(v1.getServer(Util.EMPTY_BYTE_ARRAY));
hash.value = 2001;
assert list(a4, a1).contains(v1.getServer(Util.EMPTY_BYTE_ARRAY));
hash.value = 3001;
assert list(a1, a2).contains(v1.getServer(Util.EMPTY_BYTE_ARRAY));
}
public void numOwners3Test() {
setUp(3);
hash.value = 0;
assert list(a1, a2, a3).contains(v1.getServer(Util.EMPTY_BYTE_ARRAY));
hash.value = 1;
assert list(a2, a3, a4).contains(v1.getServer(Util.EMPTY_BYTE_ARRAY));
hash.value = 1001;
assert list(a3, a4, a1).contains(v1.getServer(Util.EMPTY_BYTE_ARRAY));
hash.value = 2001;
assert list(a4, a1, a2).contains(v1.getServer(Util.EMPTY_BYTE_ARRAY));
hash.value = 3001;
assert list(a1, a2, a3).contains(v1.getServer(Util.EMPTY_BYTE_ARRAY));
}
//now a bit more extreme...
public void numOwners4Test() {
setUp(4);
List<InetSocketAddress> list = list(a1, a2, a3, a4);
hash.value = 0;
assert list.contains(v1.getServer(Util.EMPTY_BYTE_ARRAY));
hash.value = 1;
assert list.contains(v1.getServer(Util.EMPTY_BYTE_ARRAY));
hash.value = 1001;
assert list.contains(v1.getServer(Util.EMPTY_BYTE_ARRAY));
hash.value = 2001;
assert list.contains(v1.getServer(Util.EMPTY_BYTE_ARRAY));
hash.value = 3001;
assert list.contains(v1.getServer(Util.EMPTY_BYTE_ARRAY));
}
private List<InetSocketAddress> list(InetSocketAddress... a) {
return Arrays.asList(a);
}
public void testCorrectHash() {
hash.value = 1;
v1.getServer(Util.EMPTY_BYTE_ARRAY);
}
public static class DummyHash implements Hash {
public int value;
@Override
public int hash(byte[] payload) {
return value;
}
@Override
public int hash(int hashcode) {
return value;
}
@Override
public int hash(Object o) {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DummyHash dummyHash = (DummyHash) o;
if (value != dummyHash.value) return false;
return true;
}
@Override
public int hashCode() {
return value;
}
}
}
| 4,574
| 25.754386
| 104
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ConsistentHashFactoryTest.java
|
package org.infinispan.client.hotrod;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.impl.consistenthash.CRC16ConsistentHashV2;
import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHash;
import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHashFactory;
import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHashV2;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.test.AbstractInfinispanTest;
import org.testng.annotations.Test;
/**
* Tester for ConsistentHashFactory.
*
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test(testName = "client.hotrod.ConsistentHashFactoryTest", groups = "functional")
public class ConsistentHashFactoryTest extends AbstractInfinispanTest {
public void testPropertyCorrectlyRead() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.consistentHashImpl(2, SomeCustomConsistentHashV2.class);
ConsistentHashFactory chf = new ConsistentHashFactory();
chf.init(builder.build());
ConsistentHash hash = chf.newConsistentHash(2);
assertNotNull(hash);
assertEquals(hash.getClass(), SomeCustomConsistentHashV2.class);
}
public void testNoChDefined() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
ConsistentHashFactory chf = new ConsistentHashFactory();
chf.init(builder.build());
ConsistentHash hash = chf.newConsistentHash(2);
assertNotNull(hash);
assertEquals(hash.getClass(), ConsistentHashV2.class);
}
public void testCRC16HashDefined() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.consistentHashImpl(2, CRC16ConsistentHashV2.class);
ConsistentHashFactory chf = new ConsistentHashFactory();
chf.init(builder.build());
ConsistentHash hash = chf.newConsistentHash(2);
assertNotNull(hash);
assertEquals(hash.getClass(), CRC16ConsistentHashV2.class);
}
}
| 2,213
| 40.773585
| 93
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ReplTopologyChangeTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import java.net.InetSocketAddress;
import java.util.Collection;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.manager.CacheContainer;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test(testName = "client.hotrod.ReplTopologyChangeTest", groups = "functional")
public class ReplTopologyChangeTest extends MultipleCacheManagersTest {
HotRodServer hotRodServer1;
HotRodServer hotRodServer2;
HotRodServer hotRodServer3 ;
RemoteCache remoteCache;
private RemoteCacheManager remoteCacheManager;
private ChannelFactory channelFactory;
private ConfigurationBuilder config;
@AfterMethod
@Override
protected void clearContent() {
}
@AfterClass
@Override
protected void destroy() {
super.destroy();
killServers(hotRodServer1, hotRodServer2, hotRodServer3);
killRemoteCacheManager(remoteCacheManager);
hotRodServer1 = null;
hotRodServer2 = null;
hotRodServer3 = null;
remoteCacheManager = null;
}
@Override
protected void createCacheManagers() throws Throwable {
config = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(getCacheMode(), false));
CacheContainer cm1 = TestCacheManagerFactory.createClusteredCacheManager(config);
CacheContainer cm2 = TestCacheManagerFactory.createClusteredCacheManager(config);
registerCacheManager(cm1);
registerCacheManager(cm2);
waitForClusterToForm();
}
@BeforeClass
@Override
public void createBeforeClass() throws Throwable {
super.createBeforeClass(); // Create cache managers
hotRodServer1 = HotRodClientTestingUtil.startHotRodServer(manager(0));
hotRodServer2 = HotRodClientTestingUtil.startHotRodServer(manager(1));
//Important: this only connects to one of the two servers!
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("127.0.0.1").port(hotRodServer2.getPort());
remoteCacheManager = new InternalRemoteCacheManager(clientBuilder.build());
remoteCache = remoteCacheManager.getCache();
channelFactory = ((InternalRemoteCacheManager) remoteCacheManager).getChannelFactory();
}
protected CacheMode getCacheMode() {
return CacheMode.REPL_SYNC;
}
public void testTwoMembers() {
InetSocketAddress server1Address = InetSocketAddress.createUnresolved(hotRodServer1.getHost(), hotRodServer1.getPort());
expectTopologyChange(server1Address, true);
assertEquals(2, channelFactory.getServers().size());
}
@Test(dependsOnMethods = "testTwoMembers")
public void testAddNewServer() {
CacheContainer cm3 = TestCacheManagerFactory.createClusteredCacheManager(config);
registerCacheManager(cm3);
hotRodServer3 = HotRodClientTestingUtil.startHotRodServer(manager(2));
manager(2).getCache();
waitForClusterToForm();
try {
expectTopologyChange(InetSocketAddress.createUnresolved(hotRodServer3.getHost(), hotRodServer3.getPort()), true);
assertEquals(3, channelFactory.getServers().size());
} finally {
log.info("Members are: " + manager(0).getCache().getAdvancedCache().getRpcManager().getTransport().getMembers());
log.info("Members are: " + manager(1).getCache().getAdvancedCache().getRpcManager().getTransport().getMembers());
log.info("Members are: " + manager(2).getCache().getAdvancedCache().getRpcManager().getTransport().getMembers());
}
}
@Test(dependsOnMethods = "testAddNewServer")
public void testDropServer() {
hotRodServer3.stop();
manager(2).stop();
log.trace("Just stopped server 2");
waitForServerToDie(2);
InetSocketAddress server3Address = InetSocketAddress.createUnresolved(hotRodServer3.getHost(), hotRodServer3.getPort());
try {
expectTopologyChange(server3Address, false);
assertEquals(2, channelFactory.getServers().size());
} finally {
log.info("Members are: " + manager(0).getCache().getAdvancedCache().getRpcManager().getTransport().getMembers());
log.info("Members are: " + manager(1).getCache().getAdvancedCache().getRpcManager().getTransport().getMembers());
if (manager(2).getStatus() != ComponentStatus.RUNNING)
log.info("Members are: 0");
else
log.info("Members are: " + manager(2).getCache().getAdvancedCache().getRpcManager().getTransport().getMembers());
}
}
private void expectTopologyChange(InetSocketAddress server1Address, boolean added) {
for (int i = 0; i < 10; i++) {
remoteCache.put("k" + i, "v" + i);
if (added == channelFactory.getServers().contains(server1Address)) break;
}
Collection<InetSocketAddress> addresses = channelFactory.getServers();
assertEquals(server1Address + " not found in " + addresses, added, addresses.contains(server1Address));
}
protected void waitForServerToDie(int memberCount) {
TestingUtil.blockUntilViewReceived(manager(0).getCache(), memberCount, 30000, false);
}
}
| 6,234
| 40.019737
| 126
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/AbstractAuthenticationTest.java
|
package org.infinispan.client.hotrod;
import java.util.Map;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.core.security.simple.SimpleSaslAuthenticator;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder;
import org.infinispan.server.hotrod.test.HotRodTestingUtil;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.CleanupAfterTest;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.AfterMethod;
/**
* @author vjuranek
* @since 9.0
*/
@CleanupAfterTest
public abstract class AbstractAuthenticationTest extends SingleCacheManagerTest {
private static final Log log = LogFactory.getLog(AuthenticationTest.class);
// Each method should open its own RemoteCacheManager
protected RemoteCacheManager remoteCacheManager;
// All the methods should use the same HotRodServer
protected HotRodServer hotrodServer;
@Override
protected abstract EmbeddedCacheManager createCacheManager() throws Exception;
protected abstract SimpleSaslAuthenticator createAuthenticationProvider();
protected HotRodServer initServer(Map<String, String> mechProperties, int index) {
HotRodServerConfigurationBuilder serverBuilder = HotRodTestingUtil.getDefaultHotRodConfiguration();
serverBuilder.authentication()
.enable()
.sasl()
.serverName("localhost")
.addAllowedMech("CRAM-MD5")
.authenticator(createAuthenticationProvider());
serverBuilder.authentication().sasl().mechProperties(mechProperties);
int port = HotRodTestingUtil.serverPort() + index;
HotRodServer server = HotRodTestingUtil.startHotRodServer(cacheManager, port, serverBuilder);
log.info("Started server on port: " + server.getPort());
return server;
}
protected ConfigurationBuilder newClientBuilder() {
return newClientBuilder(0);
}
protected ConfigurationBuilder newClientBuilder(int index) {
ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder
.addServer()
.host(hotrodServer.getHost())
.port(hotrodServer.getPort())
.socketTimeout(3000)
.maxRetries(3)
.connectionPool()
.maxActive(1)
.security()
.authentication()
.enable()
.saslMechanism("CRAM-MD5")
.connectionPool()
.maxActive(1);
return clientBuilder;
}
@Override
protected void teardown() {
HotRodClientTestingUtil.killServers(hotrodServer);
hotrodServer = null;
super.teardown();
}
@AfterMethod(alwaysRun = true)
@Override
protected void destroyAfterMethod() {
HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager);
remoteCacheManager = null;
super.destroyAfterMethod();
}
}
| 3,161
| 33.747253
| 105
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ExpiryTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.ControlledTimeService;
import org.infinispan.commons.time.TimeService;
import org.testng.annotations.Test;
/**
* This test verifies that an entry can be expired from the Hot Rod server
* using the default expiry lifespan or maxIdle. </p>
*
* @author Galder Zamarreño
* @since 5.0
*/
@Test(groups = "functional", testName = "client.hotrod.ExpiryTest")
public class ExpiryTest extends MultiHotRodServersTest {
public static final int EXPIRATION_TIMEOUT = 6000;
private ControlledTimeService timeService;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false));
builder.expiration().lifespan(EXPIRATION_TIMEOUT);
createHotRodServers(1, builder);
timeService = new ControlledTimeService();
TestingUtil.replaceComponent(cacheManagers.get(0), TimeService.class, timeService, true);
}
public void testGlobalExpiryPut() {
RemoteCache<Integer, String> cache0 = client(0).getCache();
Req.PUT.execute(cache0,0,"v0");
expectCachedThenExpired(cache0, 0, "v0");
}
public void testGlobalExpiryPutWithFlag() {
RemoteCache<Integer, String> cache0 = client(0).<Integer, String>getCache().withFlags(Flag.SKIP_INDEXING);
Req.PUT.execute(cache0,1,"v0");
expectCachedThenExpired(cache0, 1, "v0");
}
public void testGlobalExpiryPutAll() {
RemoteCache<Integer, String> cache0 = client(0).getCache();
Map<Integer, String> data = new HashMap<Integer, String>();
data.put(2,"v0");
Req.PUT_ALL.execute(cache0,data);
expectCachedThenExpired(cache0, 2, "v0");
}
public void testGlobalExpiryPutAllWithFlag() {
RemoteCache<Integer, String> cache0 = client(0).<Integer, String>getCache().withFlags(Flag.SKIP_INDEXING);
Map<Integer, String> data = new HashMap<Integer, String>();
data.put(3, "v0");
Req.PUT_ALL.execute(cache0,data);
expectCachedThenExpired(cache0, 3, "v0");
}
public void testGlobalExpiryPutIfAbsent() {
RemoteCache<Integer, String> cache0 = client(0).getCache();
Req.PUT_IF_ABSENT.execute(cache0, 4, "v0");
expectCachedThenExpired(cache0, 4, "v0");
}
public void testGlobalExpiryPutIfAbsentWithFlag() {
RemoteCache<Integer, String> cache0 = client(0).<Integer, String>getCache().withFlags(Flag.SKIP_INDEXING);
Req.PUT_IF_ABSENT.execute(cache0, 5, "v0");
expectCachedThenExpired(cache0, 5, "v0");
}
public void testGlobalExpiryReplace() {
RemoteCache<Integer, String> cache0 = client(0).getCache();
cache0.put(6,"v1");
Req.REPLACE.execute(cache0, 6, "v0");
expectCachedThenExpired(cache0, 6, "v0");
}
public void testGlobalExpiryReplaceFlag() {
RemoteCache<Integer, String> cache0 = client(0).<Integer, String>getCache().withFlags(Flag.SKIP_INDEXING);
cache0.put(7,"v1");
Req.REPLACE.execute(cache0, 7, "v0");
expectCachedThenExpired(cache0, 7, "v0");
}
public void testGlobalExpiryReplaceWithVersion() {
client(0).getCache().put(8, "v0");
long version = client(0).getCache().getWithMetadata(8).getVersion();
RemoteCache<Integer, String> cache0 = client(0).getCache();
Req.REPLACE_WITH_VERSION.execute(cache0, 8,"v1",version);
expectCachedThenExpired(cache0, 8, "v1");
}
public void testGlobalExpiryReplaceWithVersionFlag() {
client(0).getCache().put(9, "v0");
long version = client(0).getCache().getWithMetadata(9).getVersion();
RemoteCache<Integer, String> cache0 = client(0).getCache();
Req.REPLACE_WITH_VERSION.execute(client(0).<Integer, String>getCache().withFlags(Flag.SKIP_INDEXING),9,"v1",version);
expectCachedThenExpired(cache0,9,"v1");
}
private void expectCachedThenExpired(RemoteCache<Integer, String> cache, int key, String value) {
assertEquals(value, cache.get(key));
timeService.advance(EXPIRATION_TIMEOUT + 100);
assertNull(cache.get(key));
}
public void testLifespanMaxIdleOverflow() {
long time = 2147484L;
client(0).getCache().put(10, "v0", time, TimeUnit.SECONDS, time, TimeUnit.SECONDS);
MetadataValue<Object> withMetadata = client(0).getCache().getWithMetadata(10);
assertEquals(time, withMetadata.getLifespan());
assertEquals(time, withMetadata.getMaxIdle());
}
private enum Req {
PUT {
@Override
void execute(RemoteCache<Integer, String> c, int key ,String value) {
c.put(key, value);
}
},
PUT_IF_ABSENT {
@Override
void execute(RemoteCache<Integer, String> c, int key, String value) {
c.putIfAbsent(key, value);
}
},
PUT_ALL {
@Override
void execute(RemoteCache<Integer, String> c,Map<Integer, String> data) {
c.putAll(data);
}
},
REPLACE {
@Override
void execute(RemoteCache<Integer, String> c, int key, String value) {
c.replace(key, value);
}
},
REPLACE_WITH_VERSION {
@Override
void execute(RemoteCache<Integer, String> c, int key, String value, Long version) {
c.replaceWithVersion(key, value, version);
}
},
;
void execute(RemoteCache<Integer, String> c, int key, String value, Long version) {
execute(c,key,value,version);
}
void execute(RemoteCache<Integer, String> c, int key, String value) {
execute(c,key,value);
}
void execute(RemoteCache<Integer, String> c, Map<Integer, String> data) {
execute(c,data);
}
}
}
| 6,298
| 33.994444
| 123
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ExecTypedTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withClientListener;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withScript;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON;
import static org.infinispan.scripting.ScriptingManager.SCRIPT_CACHE;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import org.infinispan.client.hotrod.event.EventLogListener;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.marshall.UTF8StringMarshaller;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
/**
* These tests mimic how Javascript clients remotely execute typed scripts.
* To help bridge the gap between the Javascript client and these tests, the
* scripts are added by remotely storing them via the script cache, and the
* execution is done with a String marshaller.
*/
@Test(groups = "functional", testName = "client.hotrod.ExecTypedTest")
public class ExecTypedTest extends MultiHotRodServersTest {
private static final int NUM_SERVERS = 2;
static final String NAME = "exec-typed-cache";
RemoteCacheManager execClient;
RemoteCacheManager addScriptClient;
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(NUM_SERVERS, new ConfigurationBuilder());
ConfigurationBuilder builder = hotRodCacheConfiguration(
getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false));
defineInAll(NAME, builder);
execClient = createExecClient();
clients.add(execClient);
addScriptClient = createAddScriptClient();
clients.add(addScriptClient);
}
protected ProtocolVersion getProtocolVersion() {
return ProtocolVersion.DEFAULT_PROTOCOL_VERSION;
}
private RemoteCacheManager createExecClient() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
super.createHotRodClientConfigurationBuilder(servers.get(0));
clientBuilder.marshaller(new UTF8StringMarshaller());
clientBuilder.version(getProtocolVersion());
return new InternalRemoteCacheManager(clientBuilder.build());
}
private RemoteCacheManager createAddScriptClient() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
super.createHotRodClientConfigurationBuilder(servers.get(0));
clientBuilder.version(getProtocolVersion());
return new InternalRemoteCacheManager(clientBuilder.build());
}
public void testLocalTypedExecPutGet() {
execPutGet("/typed-put-get.js", ExecMode.LOCAL, "local-typed-key", "local-typed-value");
}
public void testLocalTypedExecPutGetCyrillic() {
execPutGet("/typed-put-get.js", ExecMode.LOCAL, "բարև", "привет");
}
public void testLocalTypedExecPutGetEmptyString() {
withScript(addScriptClient.getCache(SCRIPT_CACHE), "/typed-put-get.js", scriptName -> {
Map<String, String> params = new HashMap<>();
params.put("k", "empty-key");
params.put("v", "");
String result = execClient.getCache(NAME).execute(scriptName, params);
assertEquals(null, result);
});
}
public void testLocalTypedExecSize() {
withScript(addScriptClient.getCache(SCRIPT_CACHE), "/typed-size.js", scriptName -> {
execClient.getCache(NAME).clear();
String result = execClient.getCache(NAME).execute(scriptName, new HashMap<>());
assertEquals("0", result);
});
}
public void testLocalTypedExecWithCacheManager() {
withScript(addScriptClient.getCache(SCRIPT_CACHE), "/typed-cachemanager-put-get.js", scriptName -> {
String result = execClient.getCache(NAME).execute(scriptName, new HashMap<>());
assertEquals("a", result);
});
}
public void testLocalTypedExecNullReturn() {
withScript(addScriptClient.getCache(SCRIPT_CACHE), "/typed-null-return.js", scriptName -> {
String result = execClient.getCache(NAME).execute(scriptName, new HashMap<>());
assertEquals(null, result);
});
}
public void testDistTypedExecNullReturn() {
withScript(addScriptClient.getCache(SCRIPT_CACHE), "/typed-dist-null-return.js", scriptName -> {
String result = execClient.getCache(NAME).execute(scriptName, new HashMap<>());
assertEquals("[null,null]", result.replaceAll("\\s", ""));
String resultAsJson = execClient.getCache(NAME)
.withDataFormat(DataFormat.builder().valueType(APPLICATION_JSON).build())
.execute(scriptName, new HashMap<>());
assertEquals("[null,null]", resultAsJson.replaceAll("\\s", ""));
});
}
public void testDistTypedExecPutGet() {
execPutGet("/typed-put-get-dist.js", ExecMode.DIST, "dist-typed-key", "dist-typed-value");
}
public void testLocalTypedExecPutGetWithListener() {
EventLogListener<String> l = new EventLogListener<>(execClient.getCache(NAME));
withClientListener(l, remote -> {
withScript(addScriptClient.getCache(SCRIPT_CACHE), "/typed-put-get.js", scriptName -> {
Map<String, String> params = new HashMap<>();
params.put("k", "local-typed-key-listen");
params.put("v", "local-typed-value-listen");
String result = remote.execute(scriptName, params);
l.expectOnlyCreatedEvent("local-typed-key-listen");
assertEquals("local-typed-value-listen", result);
});
});
}
private void execPutGet(String path, ExecMode mode, String key, String value) {
withScript(addScriptClient.getCache(SCRIPT_CACHE), path, scriptName -> {
Map<String, String> params = new HashMap<>();
params.put("k", key);
params.put("v", value);
String result = execClient.getCache(NAME).execute(scriptName, params);
mode.assertResult.accept(value, result);
});
}
enum ExecMode {
LOCAL(AssertJUnit::assertEquals),
DIST((v, r) -> assertEquals(String.format("[\"%1$s\", \"%1$s\"]", v), r));
final BiConsumer<String, String> assertResult;
ExecMode(BiConsumer<String, String> assertResult) {
this.assertResult = assertResult;
}
}
}
| 6,684
| 40.521739
| 106
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ObjectStorageRoutingTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT_TYPE;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.remoting.rpc.RpcManagerImpl;
import org.testng.annotations.Test;
@Test(testName = "client.hotrod.ObjectStorageRoutingTest", groups = "functional")
public class ObjectStorageRoutingTest extends MultiHotRodServersTest {
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(2, getCacheConfiguration());
}
private ConfigurationBuilder getCacheConfiguration() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
builder.clustering().hash().numOwners(1)
.encoding().key().mediaType(APPLICATION_OBJECT_TYPE)
.encoding().value().mediaType(APPLICATION_OBJECT_TYPE);
builder.statistics().enable();
return builder;
}
public void testGetWithObjectStorage() {
RemoteCache<String, String> client = client(0).getCache();
HashMap<String, String> cachedValues = new HashMap<>();
for (int i = 0; i < 100; i++) {
String key = String.format("key-%d", i);
String value = String.format("value-%d", i);
client.put(key, value);
cachedValues.put(key, value);
}
int startRpcs = 0;
for (Cache cache : caches()) {
startRpcs += ((RpcManagerImpl) cache.getAdvancedCache().getRpcManager()).getReplicationCount();
}
assertTrue(startRpcs > 0);
for (Map.Entry<String, String> entry : cachedValues.entrySet()) {
String value = client.get(entry.getKey());
assertEquals(entry.getValue(), value);
}
int endRpcs = 0;
for (Cache cache : caches()) {
endRpcs += ((RpcManagerImpl) cache.getAdvancedCache().getRpcManager()).getReplicationCount();
}
assertEquals(startRpcs, endRpcs);
}
}
| 2,252
| 35.33871
| 104
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/HotRodClientNearCacheJmxTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.remoteCacheObjectName;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import java.lang.invoke.MethodHandles;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.infinispan.client.hotrod.configuration.NearCacheMode;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.commons.jmx.MBeanServerLookup;
import org.infinispan.commons.jmx.TestMBeanServerLookup;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.CacheContainer;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.HotRodClientNearCacheJmxTest")
public class HotRodClientNearCacheJmxTest extends AbstractInfinispanTest {
private HotRodServer hotrodServer;
private CacheContainer cacheContainer;
private RemoteCacheManager[] rcms;
private RemoteCache<String, String>[] remoteCaches;
private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create();
@BeforeMethod
protected void setup() throws Exception {
ConfigurationBuilder cfg = hotRodCacheConfiguration();
cfg.statistics().enable();
GlobalConfigurationBuilder globalCfg = GlobalConfigurationBuilder.defaultClusteredBuilder();
TestCacheManagerFactory.configureJmx(globalCfg, getClass().getSimpleName(), mBeanServerLookup);
cacheContainer = TestCacheManagerFactory.createClusteredCacheManager(globalCfg, cfg);
hotrodServer = HotRodClientTestingUtil.startHotRodServer((EmbeddedCacheManager) cacheContainer);
rcms = new RemoteCacheManager[2];
remoteCaches = new RemoteCache[2];
for (int i = 0; i < 2; i++) {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotrodServer.getPort());
clientBuilder.nearCache().mode(NearCacheMode.INVALIDATED).maxEntries(100);
clientBuilder.statistics().enable()
.jmxEnable()
.jmxDomain(MethodHandles.lookup().lookupClass().getSimpleName() + i)
.mBeanServerLookup(mBeanServerLookup);
rcms[i] = new RemoteCacheManager(clientBuilder.build());
remoteCaches[i] = rcms[i].getCache();
}
}
@AfterMethod
void tearDown() {
for (int i = 0; i < 2; i++) {
killRemoteCacheManager(rcms[i]);
}
killServers(hotrodServer);
hotrodServer = null;
TestingUtil.killCacheManagers(cacheContainer);
}
public void testNearRemoteCacheMBean() throws Exception {
MBeanServer mbeanServer = mBeanServerLookup.getMBeanServer();
ObjectName objectName = remoteCacheObjectName(rcms[0], "org.infinispan.default");
remoteCaches[0].get("a"); // miss
assertEquals(1L, mbeanServer.getAttribute(objectName, "RemoteMisses"));
assertEquals(1L, mbeanServer.getAttribute(objectName, "NearCacheMisses"));
assertEquals(0L, mbeanServer.getAttribute(objectName, "NearCacheSize"));
remoteCaches[0].put("a", "a");
assertEquals(1L, mbeanServer.getAttribute(objectName, "RemoteStores"));
assertEquals(0L, mbeanServer.getAttribute(objectName, "NearCacheSize"));
remoteCaches[0].get("a"); // remote hit
assertEquals(1L, mbeanServer.getAttribute(objectName, "RemoteHits"));
assertEquals(2L, mbeanServer.getAttribute(objectName, "NearCacheMisses"));
assertEquals(0L, mbeanServer.getAttribute(objectName, "NearCacheHits"));
assertEquals(1L, mbeanServer.getAttribute(objectName, "NearCacheSize"));
remoteCaches[0].get("a"); // near hit
assertEquals(1L, mbeanServer.getAttribute(objectName, "RemoteHits"));
assertEquals(2L, mbeanServer.getAttribute(objectName, "NearCacheMisses"));
assertEquals(1L, mbeanServer.getAttribute(objectName, "NearCacheHits"));
assertEquals(1L, mbeanServer.getAttribute(objectName, "NearCacheSize"));
assertEquals(0L, mbeanServer.getAttribute(objectName, "NearCacheInvalidations"));
remoteCaches[1].put("a", "b"); // cause an invalidation from the other client
eventually(() -> ((Long) mbeanServer.getAttribute(objectName, "NearCacheInvalidations")) == 1L, 1000);
}
}
| 5,066
| 50.181818
| 108
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/BaseSegmentOwnershipTest.java
|
package org.infinispan.client.hotrod;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.server.hotrod.test.HotRodTestingUtil;
/**
* @author gustavonalle
* @since 8.0
*/
public abstract class BaseSegmentOwnershipTest extends MultiHotRodServersTest {
static final int NUM_SEGMENTS = 20;
static final int NUM_OWNERS = 2;
static final int NUM_SERVERS = 3;
protected Map<Integer, Set<SocketAddress>> invertMap(Map<SocketAddress, Set<Integer>> segmentsByServer) {
Map<Integer, Set<SocketAddress>> serversBySegment = new HashMap<>();
for (Map.Entry<SocketAddress, Set<Integer>> entry : segmentsByServer.entrySet()) {
for (Integer seg : entry.getValue()) {
serversBySegment.computeIfAbsent(seg, v -> new HashSet<>()).add(entry.getKey());
}
}
return serversBySegment;
}
protected abstract CacheMode getCacheMode();
protected ConfigurationBuilder getCacheConfiguration() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(getCacheMode(), false);
builder.clustering().hash().numOwners(NUM_OWNERS).numSegments(NUM_SEGMENTS);
return HotRodTestingUtil.hotRodCacheConfiguration(builder);
}
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(NUM_SERVERS, getCacheConfiguration());
}
@Override
protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(String host, int serverPort) {
return super.createHotRodClientConfigurationBuilder(host, serverPort);
}
}
| 1,864
| 34.188679
| 146
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ConsistentHashV2IntegrationTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.infinispan.affinity.KeyAffinityService;
import org.infinispan.affinity.KeyAffinityServiceFactory;
import org.infinispan.client.hotrod.impl.RemoteCacheImpl;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory;
import org.infinispan.client.hotrod.retry.DistributionRetryTest;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.LocalizedCacheTopology;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
*/
@Test (groups = "functional", testName = "client.hotrod.ConsistentHashV2IntegrationTest")
public class ConsistentHashV2IntegrationTest extends MultipleCacheManagersTest {
public static final int NUM_KEYS = 200;
private HotRodServer hotRodServer1;
private HotRodServer hotRodServer2;
private HotRodServer hotRodServer3;
private HotRodServer hotRodServer4; //tod add shutdown behaviour
private RemoteCacheManager remoteCacheManager;
private RemoteCacheImpl remoteCache;
private KeyAffinityService kas;
private ExecutorService ex;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = buildConfiguration();
addClusterEnabledCacheManager(builder);
addClusterEnabledCacheManager(builder);
addClusterEnabledCacheManager(builder);
addClusterEnabledCacheManager(builder);
hotRodServer1 = HotRodClientTestingUtil.startHotRodServer(manager(0));
hotRodServer2 = HotRodClientTestingUtil.startHotRodServer(manager(1));
hotRodServer3 = HotRodClientTestingUtil.startHotRodServer(manager(2));
hotRodServer4 = HotRodClientTestingUtil.startHotRodServer(manager(3));
waitForClusterToForm();
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotRodServer2.getPort());
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
remoteCache = (RemoteCacheImpl) remoteCacheManager.getCache();
assert super.cacheManagers.size() == 4;
ex = Executors.newSingleThreadExecutor(getTestThreadFactory("KeyGenerator"));
kas = KeyAffinityServiceFactory.newKeyAffinityService(cache(0),
ex, new DistributionRetryTest.ByteKeyGenerator(), 2, true);
for (int i = 0; i < 4; i++) {
advancedCache(i).getAsyncInterceptorChain()
.addInterceptor(new HitsAwareCacheManagersTest.HitCountInterceptor(), 1);
}
}
private ConfigurationBuilder buildConfiguration() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
builder.statistics().enable();
builder.clustering().hash().numOwners(2).stateTransfer().fetchInMemoryState(false);
return hotRodCacheConfiguration(builder);
}
@AfterMethod
@Override
protected void clearContent() throws Throwable {
}
@AfterClass(alwaysRun = true)
public void cleanUp() {
ex.shutdownNow();
kas.stop();
stopServer(hotRodServer1);
stopServer(hotRodServer2);
stopServer(hotRodServer3);
stopServer(hotRodServer4);
hotRodServer1 = null;
hotRodServer2 = null;
hotRodServer3 = null;
hotRodServer4 = null;
remoteCache.stop();
remoteCacheManager.stop();
}
private void stopServer(HotRodServer hrs) {
killServers(hrs);
}
public void testCorrectBalancingOfKeys() {
runTest(0);
runTest(1);
runTest(2);
runTest(3);
}
private void runTest(int cacheIndex) {
LocalizedCacheTopology serverTopology = advancedCache(cacheIndex).getDistributionManager().getCacheTopology();
for (int i = 0; i < NUM_KEYS; i++) {
byte[] keyBytes = (byte[]) kas.getKeyForAddress(address(cacheIndex));
String key = DistributionRetryTest.ByteKeyGenerator.getStringObject(keyBytes);
Address serverPrimary = serverTopology.getDistribution(keyBytes).primary();
assertEquals(address(cacheIndex), serverPrimary);
remoteCache.put(key, "v");
}
// support for 1.0/1.1 clients is not perfect, so we must allow for some misses
assertTrue(hitCountInterceptor(cacheIndex).getHits() > NUM_KEYS * 0.99);
hitCountInterceptor(cacheIndex).reset();
}
public void testCorrectBalancingOfKeysAfterNodeKill() {
//final AtomicInteger clientTopologyId = TestingUtil.extractField(remoteCacheManager, "defaultCacheTopologyId");
ChannelFactory channelFactory = TestingUtil.extractField(remoteCacheManager, "channelFactory");
final int topologyIdBeforeJoin = channelFactory.getTopologyId(new byte[]{});
log.tracef("Starting test with client topology id %d", topologyIdBeforeJoin);
EmbeddedCacheManager cm5 = addClusterEnabledCacheManager(buildConfiguration());
HotRodServer hotRodServer5 = HotRodClientTestingUtil.startHotRodServer(cm5);
// Rebalancing to include the joiner will increment the topology id by 2
eventually(() -> {
// The get operation will update the client topology (if necessary)
remoteCache.get("k");
CacheTopologyInfo topology = channelFactory.getCacheTopologyInfo(new byte[]{});
return topology.getSegmentsPerServer().size() == 5;
});
resetHitInterceptors();
runTest(0);
runTest(1);
runTest(2);
runTest(3);
stopServer(hotRodServer5);
killMember(4);
// Rebalancing to exclude the leaver will again increment the topology id by 2
eventually(() -> {
// The get operation will update the client topology (if necessary)
remoteCache.get("k");
CacheTopologyInfo topology = channelFactory.getCacheTopologyInfo(new byte[]{});
return topology.getSegmentsPerServer().size() == 4;
});
resetHitInterceptors();
runTest(0);
runTest(1);
runTest(2);
runTest(3);
}
private void resetHitInterceptors() {
for (int i = 0; i < 4; i++) {
HitsAwareCacheManagersTest.HitCountInterceptor interceptor = hitCountInterceptor(i);
interceptor.reset();
}
}
private HitsAwareCacheManagersTest.HitCountInterceptor hitCountInterceptor(int i) {
AsyncInterceptorChain ic = advancedCache(i).getAsyncInterceptorChain();
return ic.findInterceptorWithClass(HitsAwareCacheManagersTest.HitCountInterceptor.class);
}
}
| 7,409
| 37.59375
| 118
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/HotRodStatisticsTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Map;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.commons.jmx.MBeanServerLookup;
import org.infinispan.commons.jmx.TestMBeanServerLookup;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.CacheContainer;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test(groups = "functional", testName = "client.hotrod.HotRodStatisticsTest")
public class HotRodStatisticsTest extends AbstractInfinispanTest {
private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create();
private HotRodServer hotrodServer;
private CacheContainer cacheContainer;
private RemoteCacheManager rcm;
private RemoteCache<String, String> remoteCache;
private long startTime;
@BeforeMethod
protected void setup() throws Exception {
ConfigurationBuilder cfg = hotRodCacheConfiguration();
cfg.statistics().enable();
GlobalConfigurationBuilder globalCfg = GlobalConfigurationBuilder.defaultClusteredBuilder();
TestCacheManagerFactory.configureJmx(globalCfg, getClass().getSimpleName(), mBeanServerLookup);
globalCfg.metrics().accurateSize(true);
cacheContainer = TestCacheManagerFactory.createClusteredCacheManager(globalCfg, cfg);
hotrodServer = HotRodClientTestingUtil.startHotRodServer((EmbeddedCacheManager) cacheContainer);
startTime = System.currentTimeMillis();
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotrodServer.getPort());
clientBuilder.statistics().enable();
rcm = new RemoteCacheManager(clientBuilder.build());
remoteCache = rcm.getCache();
}
@AfterMethod
void tearDown() {
TestingUtil.killCacheManagers(cacheContainer);
killRemoteCacheManager(rcm);
killServers(hotrodServer);
hotrodServer = null;
}
public void testAllStatsArePresent() {
ServerStatistics serverStatistics = remoteCache.serverStatistics();
Map<String, String> statsMap = serverStatistics.getStatsMap();
assertEquals(statsMap.get(ServerStatistics.STORES), "0");
assertEquals(statsMap.get(ServerStatistics.CURRENT_NR_OF_ENTRIES), "0");
assertEquals(statsMap.get(ServerStatistics.HITS),"0");
assertEquals(statsMap.get(ServerStatistics.MISSES),"0");
assertEquals(statsMap.get(ServerStatistics.REMOVE_HITS),"0");
assertEquals(statsMap.get(ServerStatistics.REMOVE_MISSES),"0");
assertEquals(statsMap.get(ServerStatistics.RETRIEVALS),"0");
assertEquals(statsMap.get(ServerStatistics.APPROXIMATE_ENTRIES), "0");
assertEquals(statsMap.get(ServerStatistics.APPROXIMATE_ENTRIES_UNIQUE), "0");
assertEquals(0, remoteCache.size());
assertTrue(remoteCache.isEmpty());
Integer number = serverStatistics.getIntStatistic(ServerStatistics.TIME_SINCE_START);
assertTrue(number >= 0);
}
public void testStoresAndEntries() {
assertEquals(0, remoteCache.size());
assertTrue(remoteCache.isEmpty());
remoteCache.put("a","v");
ServerStatistics serverStatistics = remoteCache.serverStatistics();
assertIntStatistic(1, serverStatistics, ServerStatistics.STORES);
assertEquals(1, remoteCache.clientStatistics().getRemoteStores());
assertIntStatistic(1, serverStatistics, ServerStatistics.CURRENT_NR_OF_ENTRIES);
assertIntStatistic(1, serverStatistics, ServerStatistics.APPROXIMATE_ENTRIES);
assertIntStatistic(1, serverStatistics, ServerStatistics.APPROXIMATE_ENTRIES_UNIQUE);
assertEquals(1, remoteCache.size());
assertFalse(remoteCache.isEmpty());
remoteCache.put("a2","v2");
serverStatistics = remoteCache.serverStatistics();
assertIntStatistic(2, serverStatistics, ServerStatistics.STORES);
assertEquals(2, remoteCache.clientStatistics().getRemoteStores());
assertIntStatistic(2, serverStatistics, ServerStatistics.CURRENT_NR_OF_ENTRIES);
assertIntStatistic(2, serverStatistics, ServerStatistics.APPROXIMATE_ENTRIES);
assertIntStatistic(2, serverStatistics, ServerStatistics.APPROXIMATE_ENTRIES_UNIQUE);
assertEquals(2,remoteCache.size());
assertFalse(remoteCache.isEmpty());
remoteCache.put("a2","v3");
serverStatistics = remoteCache.serverStatistics();
assertIntStatistic(3, serverStatistics, ServerStatistics.STORES);
assertEquals(3, remoteCache.clientStatistics().getRemoteStores());
assertIntStatistic(2, serverStatistics, ServerStatistics.CURRENT_NR_OF_ENTRIES);
assertIntStatistic(2, serverStatistics, ServerStatistics.APPROXIMATE_ENTRIES);
assertIntStatistic(2, serverStatistics, ServerStatistics.APPROXIMATE_ENTRIES_UNIQUE);
assertEquals(2, remoteCache.size());
assertFalse(remoteCache.isEmpty());
}
public void testHitsAndMisses() {
remoteCache.get("a");
assertIntStatistic(0, remoteCache.serverStatistics(), ServerStatistics.HITS);
assertEquals(0, remoteCache.clientStatistics().getRemoteHits());
assertIntStatistic(1, remoteCache.serverStatistics(), ServerStatistics.MISSES);
assertEquals(1, remoteCache.clientStatistics().getRemoteMisses());
remoteCache.put("a","v");
assertIntStatistic(0, remoteCache.serverStatistics(), ServerStatistics.HITS);
assertEquals(0, remoteCache.clientStatistics().getRemoteHits());
assertIntStatistic(1, remoteCache.serverStatistics(), ServerStatistics.MISSES);
assertEquals(1, remoteCache.clientStatistics().getRemoteMisses());
remoteCache.get("a");
assertIntStatistic(1, remoteCache.serverStatistics(), ServerStatistics.HITS);
assertEquals(1, remoteCache.clientStatistics().getRemoteHits());
assertIntStatistic(1, remoteCache.serverStatistics(), ServerStatistics.MISSES);
assertEquals(1, remoteCache.clientStatistics().getRemoteMisses());
remoteCache.get("a");
remoteCache.get("a");
remoteCache.get("a");
assertIntStatistic(4, remoteCache.serverStatistics(), ServerStatistics.HITS);
assertEquals(4, remoteCache.clientStatistics().getRemoteHits());
assertIntStatistic(1, remoteCache.serverStatistics(), ServerStatistics.MISSES);
assertEquals(1, remoteCache.clientStatistics().getRemoteMisses());
}
public void testRemoveHitsAndMisses() {
remoteCache.remove("a");
assertIntStatistic(0, remoteCache.serverStatistics(), ServerStatistics.REMOVE_HITS);
assertIntStatistic(1, remoteCache.serverStatistics(), ServerStatistics.REMOVE_MISSES);
remoteCache.put("a","v");
remoteCache.remove("a");
assertIntStatistic(1, remoteCache.serverStatistics(), ServerStatistics.REMOVE_HITS);
assertIntStatistic(1, remoteCache.serverStatistics(), ServerStatistics.REMOVE_MISSES);
remoteCache.put("a","v");
remoteCache.put("b","v");
remoteCache.put("c","v");
remoteCache.remove("a");
remoteCache.remove("b");
remoteCache.remove("c");
assertIntStatistic(4, remoteCache.serverStatistics(), ServerStatistics.REMOVE_HITS);
assertIntStatistic(1, remoteCache.serverStatistics(), ServerStatistics.REMOVE_MISSES);
}
public void testNumberOfEntriesAfterClear() {
ServerStatistics serverStatistics = remoteCache.serverStatistics();
assertIntStatistic(0, serverStatistics, ServerStatistics.CURRENT_NR_OF_ENTRIES);
assertIntStatistic(0, serverStatistics, ServerStatistics.APPROXIMATE_ENTRIES);
assertIntStatistic(0, serverStatistics, ServerStatistics.APPROXIMATE_ENTRIES_UNIQUE);
remoteCache.put("k", "v");
remoteCache.put("k2", "v");
serverStatistics = remoteCache.serverStatistics();
assertIntStatistic(2, serverStatistics, ServerStatistics.CURRENT_NR_OF_ENTRIES);
assertIntStatistic(2, serverStatistics, ServerStatistics.APPROXIMATE_ENTRIES);
assertIntStatistic(2, serverStatistics, ServerStatistics.APPROXIMATE_ENTRIES_UNIQUE);
remoteCache.clear();
serverStatistics = remoteCache.serverStatistics();
assertIntStatistic(0, serverStatistics, ServerStatistics.CURRENT_NR_OF_ENTRIES);
assertIntStatistic(0, serverStatistics, ServerStatistics.APPROXIMATE_ENTRIES);
assertIntStatistic(0, serverStatistics, ServerStatistics.APPROXIMATE_ENTRIES_UNIQUE);
}
private void assertIntStatistic(int expected, ServerStatistics serverStatistics, String statName) {
assertEquals((Integer) expected, serverStatistics.getIntStatistic(statName));
}
}
| 9,531
| 49.168421
| 102
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/WorkerThread.java
|
package org.infinispan.client.hotrod;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author Mircea.Markus@jboss.com
* @author dberinde@redhat.com
* @since 4.1
*/
public class WorkerThread {
private static final AtomicInteger WORKER_INDEX = new AtomicInteger();
private final RemoteCache remoteCache;
private final ExecutorService executor = Executors.newSingleThreadExecutor(
r -> new Thread(r, String.format("%s-Worker-%d", Thread.currentThread().getName(), WORKER_INDEX.getAndIncrement())));
public WorkerThread(RemoteCache remoteCache) {
this.remoteCache = remoteCache;
}
private void stressInternal(AtomicLong opCounter) throws Exception {
Random rnd = new Random();
while (!executor.isShutdown()) {
remoteCache.put(rnd.nextLong(), rnd.nextLong());
opCounter.incrementAndGet();
Thread.sleep(50);
}
}
/**
* Only returns when this thread added the given key value.
*/
public String put(final String key, final String value) {
Future<?> result = executor.submit(new Callable<Object>() {
public Object call() {
return remoteCache.put(key, value);
}
});
try {
return (String) result.get();
} catch (InterruptedException e) {
throw new IllegalStateException();
} catch (ExecutionException e) {
throw new RuntimeException("Error during put", e.getCause());
}
}
/**
* Does a put on the worker thread.
* Doesn't wait for the put operation to finish. However, it will wait for the previous operation on this thread to finish.
*/
public Future<?> putAsync(final String key, final String value) throws ExecutionException, InterruptedException {
return executor.submit(() -> remoteCache.put(key, value));
}
/**
* Starts doing cache put operations in a loop on the worker thread.
* Doesn't wait for the loop to finish - in fact the loop will finish only when the worker is stopped.
* However, it will wait for the previous operation on this thread to finish.
*/
public Future<?> stress(AtomicLong opCounter) throws InterruptedException, ExecutionException {
return executor.submit(() -> {
stressInternal(opCounter);
return null;
});
}
/**
* Returns without waiting for the threads to finish.
*/
public void stop() {
executor.shutdown();
}
/**
* Only returns when the last operation on this thread has finished.
*/
public void awaitTermination() throws InterruptedException, ExecutionException {
executor.awaitTermination(1, TimeUnit.SECONDS);
}
}
| 2,999
| 31.258065
| 126
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/CacheManagerNotStartedTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import java.util.HashMap;
import org.infinispan.client.hotrod.exceptions.RemoteCacheManagerNotStartedException;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test (testName = "client.hotrod.CacheManagerNotStartedTest", groups = "functional")
public class CacheManagerNotStartedTest extends SingleCacheManagerTest {
private static final String CACHE_NAME = "someName";
EmbeddedCacheManager cacheManager = null;
HotRodServer hotrodServer = null;
RemoteCacheManager remoteCacheManager;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
cacheManager = TestCacheManagerFactory
.createCacheManager(hotRodCacheConfiguration());
cacheManager.defineConfiguration(CACHE_NAME, hotRodCacheConfiguration().build());
return cacheManager;
}
@Override
protected void setup() throws Exception {
super.setup();
hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotrodServer.getPort());
remoteCacheManager = new RemoteCacheManager(clientBuilder.build(), false);
}
@AfterClass
@Override
protected void destroyAfterClass() {
super.destroyAfterClass();
killRemoteCacheManager(remoteCacheManager);
killServers(hotrodServer);
hotrodServer = null;
}
public void testGetCacheOperations() {
assert remoteCacheManager.getCache() != null;
assert remoteCacheManager.getCache(CACHE_NAME) != null;
assert !remoteCacheManager.isStarted();
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class)
public void testGetCacheOperations2() {
remoteCacheManager.getCache().put("k", "v");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class)
public void testGetCacheOperations3() {
remoteCacheManager.getCache(CACHE_NAME).put("k", "v");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class)
public void testPut() {
remoteCache().put("k", "v");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class)
public void testPutAsync() {
remoteCache().putAsync("k", "v");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class)
public void testGet() {
remoteCache().get("k");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class)
public void testReplace() {
remoteCache().replace("k", "v");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class)
public void testReplaceAsync() {
remoteCache().replaceAsync("k", "v");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class)
public void testPutAll() {
remoteCache().putAll(new HashMap<Object, Object>());
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class)
public void testPutAllAsync() {
remoteCache().putAllAsync(new HashMap<Object, Object>());
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class)
public void testGetWithMetadata() {
remoteCache().getWithMetadata("key");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class)
public void testVersionedRemove() {
remoteCache().removeWithVersion("key", 12312321l);
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class)
public void testVersionedRemoveAsync() {
remoteCache().removeWithVersionAsync("key", 12312321l);
}
private RemoteCache<Object, Object> remoteCache() {
return remoteCacheManager.getCache();
}
}
| 4,486
| 34.054688
| 95
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/SkipCacheLoadFlagTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.Flag.FORCE_RETURN_VALUE;
import static org.infinispan.client.hotrod.Flag.SKIP_CACHE_LOAD;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.commands.FlagAffectedCommand;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commons.CacheException;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.interceptors.BaseAsyncInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.CleanupAfterTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Tests if the {@link org.infinispan.client.hotrod.Flag#SKIP_CACHE_LOAD} flag is received on HotRod server.
*
* @author Pedro Ruivo
* @since 7.0
*/
@Test(testName = "client.hotrod.SkipCacheLoadFlagTest", groups = "functional")
@CleanupAfterTest
public class SkipCacheLoadFlagTest extends SingleCacheManagerTest {
private static final String KEY = "key";
private static final String VALUE = "value";
private FlagCheckCommandInterceptor commandInterceptor;
private RemoteCache<String, String> remoteCache;
private RemoteCacheManager remoteCacheManager;
private HotRodServer hotRodServer;
public void testPut() {
performTest(RequestType.PUT);
}
public void testReplace() {
performTest(RequestType.REPLACE);
}
public void testPutIfAbsent() {
performTest(RequestType.PUT_IF_ABSENT);
}
public void testReplaceIfUnmodified() {
performTest(RequestType.REPLACE_IF_UNMODIFIED);
}
public void testGet() {
performTest(RequestType.GET);
}
public void testGetWithMetadata() {
performTest(RequestType.GET_WITH_METADATA);
}
public void testRemove() {
performTest(RequestType.REMOVE);
}
public void testRemoveIfUnmodified() {
performTest(RequestType.REMOVE_IF_UNMODIFIED);
}
public void testContainsKey() {
performTest(RequestType.CONTAINS);
}
public void testPutAll() {
performTest(RequestType.PUT_ALL);
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration());
cache = cacheManager.getCache();
hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotRodServer.getPort());
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
remoteCache = remoteCacheManager.getCache();
return cacheManager;
}
@Override
protected void teardown() {
HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager);
remoteCacheManager = null;
HotRodClientTestingUtil.killServers(hotRodServer);
hotRodServer = null;
super.teardown();
}
private void performTest(RequestType type) {
commandInterceptor.expectSkipLoadFlag = false;
type.execute(remoteCache);
commandInterceptor.expectSkipLoadFlag = RequestType.expectsFlag(type);
type.execute(remoteCache.withFlags(SKIP_CACHE_LOAD));
type.execute(remoteCache.withFlags(SKIP_CACHE_LOAD, FORCE_RETURN_VALUE));
}
@BeforeClass(alwaysRun = true)
private void injectCommandInterceptor() {
if (remoteCache == null) {
return;
}
this.commandInterceptor = new FlagCheckCommandInterceptor();
extractInterceptorChain(cache).addInterceptor(commandInterceptor, 1);
}
@AfterClass(alwaysRun = true)
private void resetCommandInterceptor() {
if (commandInterceptor != null) {
commandInterceptor.expectSkipLoadFlag = false;
}
}
private enum RequestType {
PUT {
@Override
void execute(RemoteCache<String, String> cache) {
cache.put(KEY, VALUE);
}
},
REPLACE {
@Override
void execute(RemoteCache<String, String> cache) {
cache.replace(KEY, VALUE);
}
},
PUT_IF_ABSENT {
@Override
void execute(RemoteCache<String, String> cache) {
cache.putIfAbsent(KEY, VALUE);
}
},
REPLACE_IF_UNMODIFIED {
@Override
void execute(RemoteCache<String, String> cache) {
cache.replaceWithVersion(KEY, VALUE, 0);
}
},
GET {
@Override
void execute(RemoteCache<String, String> cache) {
cache.get(KEY);
}
},
GET_WITH_METADATA {
@Override
void execute(RemoteCache<String, String> cache) {
cache.getWithMetadata(KEY);
}
},
REMOVE {
@Override
void execute(RemoteCache<String, String> cache) {
cache.remove(KEY);
}
},
REMOVE_IF_UNMODIFIED {
@Override
void execute(RemoteCache<String, String> cache) {
cache.removeWithVersion(KEY, 0);
}
},
CONTAINS {
@Override
void execute(RemoteCache<String, String> cache) {
cache.containsKey(KEY);
}
},
PUT_ALL {
@Override
void execute(RemoteCache<String, String> cache) {
Map<String, String> data = new HashMap<>();
data.put(KEY, VALUE);
cache.putAll(data);
}
},
;
private static boolean expectsFlag(RequestType type) {
return type != PUT_IF_ABSENT && type != REMOVE_IF_UNMODIFIED && type != REPLACE && type != REPLACE_IF_UNMODIFIED;
}
abstract void execute(RemoteCache<String, String> cache);
}
static class FlagCheckCommandInterceptor extends BaseAsyncInterceptor {
private volatile boolean expectSkipLoadFlag;
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) {
if (command instanceof FlagAffectedCommand) {
FlagAffectedCommand cmd = (FlagAffectedCommand) command;
if (cmd.hasAnyFlag(FlagBitSets.CACHE_MODE_LOCAL)) {
// this is the fast non-blocking read
return invokeNext(ctx, command);
}
boolean hasFlag = cmd.hasAnyFlag(FlagBitSets.SKIP_CACHE_LOAD);
if (expectSkipLoadFlag && !hasFlag) {
throw new CacheException("SKIP_CACHE_LOAD flag is expected!");
} else if (!expectSkipLoadFlag && hasFlag) {
throw new CacheException("SKIP_CACHE_LOAD flag is *not* expected!");
}
}
return invokeNext(ctx, command);
}
}
}
| 7,278
| 30.510823
| 122
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/StreamingOpsTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
/**
* @author Tristan Tarrant
* @since 9.0
*/
@Test(testName = "client.hotrod.StreamingOpsTest", groups = "functional")
public class StreamingOpsTest extends SingleCacheManagerTest {
private static final Log log = LogFactory.getLog(StreamingOpsTest.class);
private static final String CACHE_NAME = "theCache";
private static final int V1_SIZE = 2_000;
private static final int V2_SIZE = 1_000;
RemoteCache<String, byte[]> remoteCache;
StreamingRemoteCache<String> streamingRemoteCache;
private RemoteCacheManager remoteCacheManager;
protected HotRodServer hotrodServer;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder builder = hotRodCacheConfiguration(
getDefaultStandaloneCacheConfig(false));
EmbeddedCacheManager cm = TestCacheManagerFactory
.createCacheManager(hotRodCacheConfiguration());
cm.defineConfiguration(CACHE_NAME, builder.build());
cm.getCache(CACHE_NAME);
return cm;
}
@Override
protected void setup() throws Exception {
super.setup();
//pass the config file to the cache
hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
log.info("Started server on port: " + hotrodServer.getPort());
remoteCacheManager = getRemoteCacheManager();
remoteCache = remoteCacheManager.getCache(CACHE_NAME);
streamingRemoteCache = remoteCache.streaming();
}
protected RemoteCacheManager getRemoteCacheManager() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotrodServer.getPort());
return new RemoteCacheManager(clientBuilder.build());
}
@AfterClass(alwaysRun = true)
public void testDestroyRemoteCacheFactory() {
HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager);
remoteCacheManager = null;
HotRodClientTestingUtil.killServers(hotrodServer);
hotrodServer = null;
}
private void consumeAndCloseStream(InputStream is) throws Exception {
if (is != null) {
try {
while (is.read() >= 0) {
//consume
}
} finally {
is.close();
}
}
}
private void writeDataToStream(OutputStream os, int length) throws Exception {
for (int i = 0; i < length; i++) {
os.write(i % 256);
}
}
public void testPutGetStream() throws Exception {
OutputStream k1os = streamingRemoteCache.put("k1");
writeDataToStream(k1os, V1_SIZE);
k1os.close();
InputStream k1is = streamingRemoteCache.get("k1");
int count = readAndCheckDataFromStream(k1is);
assertEquals(V1_SIZE, count);
}
private int readAndCheckDataFromStream(InputStream k1is) throws IOException {
int count = 0;
try {
for (int b = k1is.read(); b >= 0; b = k1is.read(), count++) {
assertEquals(count % 256, b);
}
} finally {
k1is.close();
}
return count;
}
public void testGetStreamWithMetadata() throws Exception {
InputStream k1is = streamingRemoteCache.get("k1");
assertNull("expected null but received a stream", k1is);
consumeAndCloseStream(k1is);
OutputStream k1os = streamingRemoteCache.put("k1");
writeDataToStream(k1os, V1_SIZE);
k1os.close();
k1is = streamingRemoteCache.get("k1");
assertNotNull("expected a stream but received null", k1is);
VersionedMetadata k1metadata = (VersionedMetadata) k1is;
assertEquals(-1, k1metadata.getLifespan());
assertEquals(-1, k1metadata.getMaxIdle());
consumeAndCloseStream(k1is);
k1os = streamingRemoteCache.put("k1", 5, TimeUnit.MINUTES);
writeDataToStream(k1os, V1_SIZE);
k1os.close();
k1is = streamingRemoteCache.get("k1");
assertNotNull("expected a stream but received null", k1is);
k1metadata = (VersionedMetadata) k1is;
assertEquals(TimeUnit.MINUTES.toSeconds(5), k1metadata.getLifespan());
assertEquals(-1, k1metadata.getMaxIdle());
consumeAndCloseStream(k1is);
k1os = streamingRemoteCache.put("k1", 5, TimeUnit.MINUTES, 3, TimeUnit.MINUTES);
writeDataToStream(k1os, V1_SIZE);
k1os.close();
k1is = streamingRemoteCache.get("k1");
assertNotNull("expected a stream but received null", k1is);
k1metadata = (VersionedMetadata) k1is;
assertEquals(TimeUnit.MINUTES.toSeconds(5), k1metadata.getLifespan());
assertEquals(TimeUnit.MINUTES.toSeconds(3), k1metadata.getMaxIdle());
consumeAndCloseStream(k1is);
}
public void testPutIfAbsentStream() throws Exception {
InputStream k1is = streamingRemoteCache.get("k1");
assertNull("expected null but received a stream", k1is);
consumeAndCloseStream(k1is);
// Write a V1 value
OutputStream k1os = streamingRemoteCache.putIfAbsent("k1");
writeDataToStream(k1os, V1_SIZE);
k1os.close();
k1is = streamingRemoteCache.get("k1");
assertEquals(V1_SIZE, readAndCheckDataFromStream(k1is));
// Attempt to overwrite it with a V2 value
k1os = streamingRemoteCache.putIfAbsent("k1");
writeDataToStream(k1os, V2_SIZE);
k1os.close();
// Check that the value was not replaced
k1is = streamingRemoteCache.get("k1");
assertEquals(V1_SIZE, readAndCheckDataFromStream(k1is));
}
public void testReplaceStream() throws Exception {
// Write a V1 value
OutputStream k1os = streamingRemoteCache.putIfAbsent("k1");
writeDataToStream(k1os, V1_SIZE);
k1os.close();
InputStream k1is = streamingRemoteCache.get("k1");
assertEquals(V1_SIZE, readAndCheckDataFromStream(k1is));
long version = ((VersionedMetadata)k1is).getVersion();
assertTrue("Expected a non-zero version: " + version, version > 0);
// Attempt to overwrite it by using a wrong version
k1os = streamingRemoteCache.replaceWithVersion("k1", version + 1);
writeDataToStream(k1os, V2_SIZE);
k1os.close();
// Check that the value was not replaced
k1is = streamingRemoteCache.get("k1");
assertEquals(V1_SIZE, readAndCheckDataFromStream(k1is));
// Attempt to overwrite it by using the correct version
k1os = streamingRemoteCache.replaceWithVersion("k1", version);
writeDataToStream(k1os, V2_SIZE);
k1os.close();
// Check that the value was replaced
k1is = streamingRemoteCache.get("k1");
assertEquals(V2_SIZE, readAndCheckDataFromStream(k1is));
}
}
| 7,686
| 34.920561
| 91
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/BulkOperationsTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
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.test.HotRodClientTestingUtil;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.commons.time.TimeService;
import org.infinispan.commons.util.CloseableIterator;
import org.infinispan.commons.util.CloseableIteratorCollection;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.ControlledTimeService;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Tests functionality related to various bulk operations in different cache modes
*
* @author William Burns
* @since 9.1
*/
@Test(groups = "functional", testName = "org.infinispan.client.hotrod.BulkOperationsTest")
public class BulkOperationsTest extends MultipleCacheManagersTest {
enum CollectionOp {
ENTRYSET(RemoteCache::entrySet) {
@Override
ProtocolVersion minimumVersionForIteration() {
return ProtocolVersion.PROTOCOL_VERSION_23;
}
},
KEYSET(RemoteCache::keySet) {
@Override
ProtocolVersion minimumVersionForIteration() {
return ProtocolVersion.PROTOCOL_VERSION_20;
}
},
VALUES(RemoteCache::values) {
@Override
ProtocolVersion minimumVersionForIteration() {
return ProtocolVersion.PROTOCOL_VERSION_23;
}
@Override
boolean isSet() {
return false;
}
};
private Function<RemoteCache<?, ?>, CloseableIteratorCollection<?>> function;
abstract ProtocolVersion minimumVersionForIteration();
boolean isSet() {
return true;
}
CollectionOp(Function<RemoteCache<?, ?>, CloseableIteratorCollection<?>> function) {
this.function = function;
}
}
enum ItemTransform {
IDENTITY(Function.identity()),
COPY_ENTRY((Function) o -> new AbstractMap.SimpleEntry<>(o, o));
private final Function<Object, Object> function;
ItemTransform(Function<Object, Object> function) {
this.function = function;
}
}
protected HotRodServer[] hotrodServers;
protected RemoteCacheManager remoteCacheManager;
protected RemoteCache<Object, Object> remoteCache;
protected ControlledTimeService timeService;
@Override
public Object[] factory() {
return new Object[] {
new BulkOperationsTest().cacheMode(CacheMode.DIST_SYNC),
new BulkOperationsTest().cacheMode(CacheMode.REPL_SYNC),
new BulkOperationsTest().cacheMode(CacheMode.LOCAL),
};
}
protected int numberOfHotRodServers() {
return cacheMode.isClustered() ? 3 : 1;
}
protected ConfigurationBuilder clusterConfig() {
return hotRodCacheConfiguration(cacheMode.isClustered() ? getDefaultClusteredCacheConfig(
cacheMode, false) : new ConfigurationBuilder());
}
@Override
protected void createCacheManagers() throws Throwable {
final int numServers = numberOfHotRodServers();
hotrodServers = new HotRodServer[numServers];
createCluster(hotRodCacheConfiguration(clusterConfig()), numberOfHotRodServers());
timeService = new ControlledTimeService();
for (int i = 0; i < numServers; i++) {
EmbeddedCacheManager cm = cacheManagers.get(i);
hotrodServers[i] = HotRodClientTestingUtil.startHotRodServer(cm);
TestingUtil.replaceComponent(cm, TimeService.class, timeService, true);
}
String servers = HotRodClientTestingUtil.getServersString(hotrodServers);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServers(servers);
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
remoteCache = remoteCacheManager.getCache();
}
@AfterMethod
public void checkNoActiveIterations() {
for (HotRodServer hotRodServer : hotrodServers) {
// The close is done async now
eventuallyEquals(0, () -> hotRodServer.getIterationManager().activeIterations());
}
}
@AfterClass(alwaysRun = true)
public void release() {
killRemoteCacheManager(remoteCacheManager);
killServers(hotrodServers);
hotrodServers = null;
}
protected void populateCacheManager() {
for (int i = 0; i < 100; i++) {
remoteCache.put(i, i);
}
}
@DataProvider(name = "collections-item")
public Object[][] collectionItemProvider() {
return new Object[][] {
{CollectionOp.KEYSET, ItemTransform.IDENTITY },
{CollectionOp.VALUES, ItemTransform.IDENTITY },
{CollectionOp.ENTRYSET, ItemTransform.COPY_ENTRY},
};
}
@Test(dataProvider = "collections-item")
public void testContains(CollectionOp op, ItemTransform transform) {
populateCacheManager();
Collection<?> collection = op.function.apply(remoteCache);
for (int i = 0; i < 100; i++) {
assertTrue(collection.contains(transform.function.apply(i)));
}
assertFalse(collection.contains(transform.function.apply(104)));
assertFalse(collection.contains(transform.function.apply(-1)));
}
@Test(dataProvider = "collections-item")
public void testContainsAll(CollectionOp op, ItemTransform transform) {
populateCacheManager();
Collection<?> collection = op.function.apply(remoteCache);
assertFalse(collection.containsAll(Arrays.asList(transform.function.apply(204), transform.function.apply(4))));
assertTrue(collection.containsAll(Arrays.asList(transform.function.apply(4), transform.function.apply(10))));
assertTrue(collection.containsAll(IntStream.range(0, 100).mapToObj(transform.function::apply).collect(Collectors.toList())));
}
@Test(dataProvider = "collections-item")
public void testRemove(CollectionOp op, ItemTransform transform) {
populateCacheManager();
Collection<?> collection = op.function.apply(remoteCache);
collection.remove(transform.function.apply(4));
collection.remove(transform.function.apply(23));
collection.remove(transform.function.apply(1001));
assertEquals(98, collection.size());
assertEquals(98, remoteCache.size());
}
@Test(dataProvider = "collections-item")
public void testRemoveAll(CollectionOp op, ItemTransform transform) {
populateCacheManager();
CloseableIteratorCollection<?> collection = op.function.apply(remoteCache);
// 105 can't be removed
collection.removeAll(Arrays.asList(transform.function.apply(5), transform.function.apply(10),
transform.function.apply(23), transform.function.apply(18),
transform.function.apply(105)));
assertEquals(96, collection.size());
collection.removeAll(Arrays.asList(transform.function.apply(5), transform.function.apply(890)));
assertEquals(96, collection.size());
assertEquals(96, remoteCache.size());
}
@Test(dataProvider = "collections-item")
public void testRetainAll(CollectionOp op, ItemTransform transform) {
populateCacheManager();
Collection<?> collection = op.function.apply(remoteCache);
collection.retainAll(Arrays.asList(transform.function.apply(1), transform.function.apply(23), transform.function.apply(102)));
assertEquals(2, collection.size());
assertEquals(2, remoteCache.size());
}
@Test(dataProvider = "collections-item", expectedExceptions = UnsupportedOperationException.class)
public void testAdd(CollectionOp op, ItemTransform transform) {
CloseableIteratorCollection collection = op.function.apply(remoteCache);
collection.add(transform.function.apply(1));
}
@Test(dataProvider = "collections-item", expectedExceptions = UnsupportedOperationException.class)
public void testAddAll(CollectionOp op, ItemTransform transform) {
CloseableIteratorCollection collection = op.function.apply(remoteCache);
collection.addAll(Arrays.asList(transform.function.apply(1), transform.function.apply(2)));
}
@Test(dataProvider = "collections-item")
public void testStreamAll(CollectionOp op, ItemTransform transform) {
populateCacheManager();
Collection<?> collection = op.function.apply(remoteCache);
// Test operator that is performed on all
// We don't try resource stream to verify iterator is closed upon full consumption
List<String> strings = collection.stream().map(transform.function).map(Object::toString).collect(Collectors.toList());
assertEquals(100, strings.size());
// Test parallel operator that is performed on all
// We don't try resource stream to verify iterator is closed upon full consumption
assertEquals(100, collection.parallelStream().count());
}
@Test(dataProvider = "collections-item")
public void testStreamShortCircuit(CollectionOp op, ItemTransform transform) {
populateCacheManager();
CloseableIteratorCollection<?> collection = op.function.apply(remoteCache);
try (Stream<?> stream = collection.stream()) {
// Test short circuit (non parallel) - it can't match all
assertEquals(false, stream.allMatch(o -> Objects.equals(o, transform.function.apply(1))));
}
try (Stream<?> stream = collection.parallelStream()) {
// Test short circuit (parallel) - should go through almost all until it finds 4
assertEquals(transform.function.apply(4),
stream.filter(o -> Objects.equals(o, transform.function.apply(4)))
.findAny()
.get());
}
}
@Test(dataProvider = "collections-item")
public void testForEach(CollectionOp op, ItemTransform transform) {
populateCacheManager();
Collection<?> collection = op.function.apply(remoteCache);
List<Object> objects = new ArrayList<>();
collection.forEach(objects::add);
assertEquals(100, objects.size());
for (int i = 0; i < 100; i++) {
assertTrue(collection.contains(transform.function.apply(i)));
}
}
@DataProvider(name = "collections")
public Object[][] collectionProvider() {
return new Object[][] {
{CollectionOp.ENTRYSET},
{CollectionOp.KEYSET},
{CollectionOp.VALUES },
};
}
@Test(dataProvider = "collections")
public void testEqualsContract(CollectionOp op) {
// Non set types don't define contract, so we don't test them
if (op.isSet()) {
Map<String, String> dataIn = new HashMap<>();
dataIn.put("aKey", "aValue");
dataIn.put("bKey", "bValue");
remoteCache.putAll(dataIn);
CloseableIteratorCollection collection1 = op.function.apply(remoteCache);
CloseableIteratorCollection collection2 = op.function.apply(remoteCache);
assertEquals(collection1, collection2);
}
}
@Test(dataProvider = "collections")
public void testSizeWithExpiration(CollectionOp op) {
Map<String, String> dataIn = new HashMap<>();
dataIn.put("aKey", "aValue");
dataIn.put("bKey", "bValue");
final long lifespan = 5000;
remoteCache.putAll(dataIn, lifespan, TimeUnit.MILLISECONDS);
assertEquals(2, op.function.apply(remoteCache).size());
timeService.advance(lifespan + 1);
assertEquals(0, op.function.apply(remoteCache).size());
}
@Test(dataProvider = "collections")
public void testIteratorRemove(CollectionOp op) {
populateCacheManager();
CloseableIteratorCollection<?> collection = op.function.apply(remoteCache);
assertEquals(100, collection.size());
try (CloseableIterator<?> iter = collection.iterator()) {
assertTrue(iter.hasNext());
assertNotNull(iter.next());
Object removed = iter.next();
assertNotNull(removed);
iter.remove();
assertTrue(iter.hasNext());
}
assertEquals(99, collection.size());
}
@Test(dataProvider = "collections")
public void testClear(CollectionOp op) {
populateCacheManager();
CloseableIteratorCollection<?> collection = op.function.apply(remoteCache);
assertEquals(100, collection.size());
collection.clear();
assertEquals(0, remoteCache.size());
}
@DataProvider(name = "collectionsAndVersion")
public Object[][] collectionAndVersionsProvider() {
return Arrays.stream(CollectionOp.values())
.flatMap(op -> Arrays.stream(ProtocolVersion.values())
.map(v -> new Object[] {op, v}))
.toArray(Object[][]::new);
}
@Test(dataProvider = "collectionsAndVersion")
public void testIteration(CollectionOp op, ProtocolVersion version) throws IOException {
Map<String, String> dataIn = new HashMap<>();
dataIn.put("aKey", "aValue");
dataIn.put("bKey", "bValue");
RemoteCache<Object, Object> cacheToUse;
RemoteCacheManager temporaryManager;
if (version != ProtocolVersion.DEFAULT_PROTOCOL_VERSION) {
String servers = HotRodClientTestingUtil.getServersString(hotrodServers);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
// Set the version on the manager to connect with
clientBuilder.version(version);
clientBuilder.addServers(servers);
temporaryManager = new RemoteCacheManager(clientBuilder.build());
cacheToUse = temporaryManager.getCache();
} else {
temporaryManager = null;
cacheToUse = remoteCache;
}
try {
// putAll doesn't work in older versions (so we use new client) - that is a different issue completely
remoteCache.putAll(dataIn);
CloseableIteratorCollection<?> collection = op.function.apply(cacheToUse);
// If we don't support it we should get an exception
if (version.compareTo(op.minimumVersionForIteration()) < 0) {
Exceptions.expectException(UnsupportedOperationException.class, () -> {
try (CloseableIterator<?> iter = collection.iterator()) {
}
});
} else {
try (CloseableIterator<?> iter = collection.iterator()) {
assertTrue(iter.hasNext());
assertNotNull(iter.next());
assertTrue(iter.hasNext());
}
}
} finally {
if (temporaryManager != null) {
temporaryManager.close();
}
}
}
}
| 15,946
| 37.612591
| 132
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/StorageRoutingTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.configuration.cache.StorageType.BINARY;
import static org.infinispan.configuration.cache.StorageType.OBJECT;
import static org.infinispan.configuration.cache.StorageType.OFF_HEAP;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.util.concurrent.atomic.AtomicInteger;
import org.infinispan.client.hotrod.test.FixedServerBalancing;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.server.hotrod.HotRodServer;
import org.testng.annotations.Test;
/**
* Tests that the Hot Rod client can correctly route requests to a server using different {@link StorageType}.
*
* @since 11.0
*/
@Test(groups = "functional", testName = "client.hotrod.StorageRoutingTest")
public class StorageRoutingTest extends MultiHotRodServersTest {
private static final int CLUSTER_SIZE = 3;
private Object key;
public Object[] factory() {
String stringKey = "key";
byte[] byteArrayKey = new byte[]{1, 2, 3};
return new Object[]{
new StorageRoutingTest().withStorageType(OBJECT).withKey(stringKey),
new StorageRoutingTest().withStorageType(OBJECT).withKey(byteArrayKey),
new StorageRoutingTest().withStorageType(OFF_HEAP).withKey(stringKey),
new StorageRoutingTest().withStorageType(OFF_HEAP).withKey(byteArrayKey),
new StorageRoutingTest().withStorageType(BINARY).withKey(stringKey),
new StorageRoutingTest().withStorageType(BINARY).withKey(byteArrayKey)
};
}
protected String[] parameterNames() {
return new String[]{null, "key"};
}
protected Object[] parameterValues() {
return new Object[]{storageType, key.getClass().getSimpleName()};
}
private StorageRoutingTest withStorageType(StorageType storageType) {
this.storageType = storageType;
return this;
}
private StorageRoutingTest withKey(Object key) {
this.key = key;
return this;
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfgBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
cfgBuilder.jmxStatistics().enable();
cfgBuilder.clustering().hash().numOwners(1);
cfgBuilder.memory().storage(storageType);
createHotRodServers(CLUSTER_SIZE, cfgBuilder);
waitForClusterToForm();
}
@Override
protected void modifyGlobalConfiguration(GlobalConfigurationBuilder builder) {
super.modifyGlobalConfiguration(builder);
builder.metrics().accurateSize(true);
}
@Override
protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(HotRodServer hotRodServer) {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder hotRodClientConfigurationBuilder = super.createHotRodClientConfigurationBuilder(hotRodServer);
hotRodClientConfigurationBuilder.balancingStrategy(() -> new FixedServerBalancing(hotRodServer));
return hotRodClientConfigurationBuilder;
}
@Test
public void shouldContactKeyOwnerForPutGet() {
String value = "value";
RemoteCache<Object, String> remoteCache = clients.get(0).getCache();
remoteCache.put(key, value);
assertEquals(remoteCache.get(key), "value");
assertCorrectServerContacted();
}
private void assertCorrectServerContacted() {
AtomicInteger storedIn = new AtomicInteger(-1);
AtomicInteger retrievedFrom = new AtomicInteger(-1);
for (int i = 0; i < clients.size(); i++) {
RemoteCacheManager rcm = client(i);
RemoteCache<?, ?> cache = rcm.getCache();
ServerStatistics statistics = cache.serverStatistics();
int retrievals = statistics.getIntStatistic("retrievals");
int dataContainerSize = statistics.getIntStatistic("currentNumberOfEntries");
if (retrievals == 1) {
if (!retrievedFrom.compareAndSet(-1, i)) fail("Retrieval happened in more than 1 server!");
}
if (dataContainerSize == 1) {
if (!storedIn.compareAndSet(-1, i)) fail("Store happened in more than 1 server!");
}
}
int storeServer = storedIn.get();
int retrieveServer = retrievedFrom.get();
assertTrue(storeServer != -1, "Entry was not stored!");
assertTrue(retrieveServer != -1, "Entry was not retrieved!");
assertEquals(storeServer, retrieveServer, String.format("Entry stored on server %d but retrieved from server %d", storeServer, retrieveServer));
}
}
| 4,906
| 39.221311
| 164
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/CacheManagerStoppedTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.test.TestingUtil.killCacheManagers;
import java.util.HashMap;
import org.infinispan.client.hotrod.exceptions.RemoteCacheManagerNotStartedException;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test (testName = "client.hotrod.CacheManagerStoppedTest", groups = "functional")
public class CacheManagerStoppedTest extends SingleCacheManagerTest {
private static final String CACHE_NAME = "someName";
EmbeddedCacheManager cacheManager = null;
HotRodServer hotrodServer = null;
RemoteCacheManager remoteCacheManager;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration());
cacheManager.defineConfiguration(CACHE_NAME, hotRodCacheConfiguration().build());
cacheManager.getCache(CACHE_NAME);
hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotrodServer.getPort());
remoteCacheManager = new RemoteCacheManager(clientBuilder.build(), true);
return cacheManager;
}
@AfterClass(alwaysRun = true)
public void release() {
killRemoteCacheManager(remoteCacheManager);
killCacheManagers(cacheManager);
killServers(hotrodServer);
hotrodServer = null;
}
public void testGetCacheOperations() {
assert remoteCacheManager.getCache() != null;
assert remoteCacheManager.getCache(CACHE_NAME) != null;
remoteCache().put("k", "v");
assert remoteCache().get("k").equals("v");
}
@Test (dependsOnMethods = "testGetCacheOperations")
public void testStopCacheManager() {
assert remoteCacheManager.isStarted();
remoteCacheManager.stop();
assert !remoteCacheManager.isStarted();
assert remoteCacheManager.getCache() != null;
assert remoteCacheManager.getCache(CACHE_NAME) != null;
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class, dependsOnMethods = "testStopCacheManager")
public void testGetCacheOperations2() {
remoteCacheManager.getCache().put("k", "v");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class, dependsOnMethods = "testStopCacheManager")
public void testGetCacheOperations3() {
remoteCacheManager.getCache(CACHE_NAME).put("k", "v");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class, dependsOnMethods = "testStopCacheManager")
public void testPut() {
remoteCache().put("k", "v");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class, dependsOnMethods = "testStopCacheManager")
public void testPutAsync() {
remoteCache().putAsync("k", "v");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class, dependsOnMethods = "testStopCacheManager")
public void testGet() {
remoteCache().get("k");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class, dependsOnMethods = "testStopCacheManager")
public void testReplace() {
remoteCache().replace("k", "v");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class, dependsOnMethods = "testStopCacheManager")
public void testReplaceAsync() {
remoteCache().replaceAsync("k", "v");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class, dependsOnMethods = "testStopCacheManager")
public void testPutAll() {
remoteCache().putAll(new HashMap<Object, Object>());
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class, dependsOnMethods = "testStopCacheManager")
public void testPutAllAsync() {
remoteCache().putAllAsync(new HashMap<Object, Object>());
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class, dependsOnMethods = "testStopCacheManager")
public void testGetWithMetadata() {
remoteCache().getWithMetadata("key");
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class, dependsOnMethods = "testStopCacheManager")
public void testVersionedRemove() {
remoteCache().removeWithVersion("key", 12312321l);
}
@Test(expectedExceptions = RemoteCacheManagerNotStartedException.class, dependsOnMethods = "testStopCacheManager")
public void testVersionedRemoveAsync() {
remoteCache().removeWithVersionAsync("key", 12312321l);
}
private RemoteCache<Object, Object> remoteCache() {
return remoteCacheManager.getCache();
}
}
| 5,378
| 39.443609
| 117
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ForceReturnValuesIdentityTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNotSame;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertSame;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
@Test(testName = "client.hotrod.ForceReturnValuesIdentityTest", groups = "functional")
@CleanupAfterMethod
public class ForceReturnValuesIdentityTest extends SingleCacheManagerTest {
private HotRodServer hotRodServer;
private RemoteCacheManager remoteCacheManager;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration());
cache = cacheManager.getCache();
hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotRodServer.getPort());
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
return cacheManager;
}
@AfterMethod
void shutdown() {
HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager);
HotRodClientTestingUtil.killServers(hotRodServer);
hotRodServer = null;
}
public void testSameInstanceForSameForceReturnValues() {
RemoteCache<String, String> rcDontForceReturn = remoteCacheManager.getCache(false);
RemoteCache<String, String> rcDontForceReturn2 = remoteCacheManager.getCache(false);
assertSame("RemoteCache instances should be the same", rcDontForceReturn, rcDontForceReturn2);
RemoteCache<String, String> rcForceReturn = remoteCacheManager.getCache(true);
RemoteCache<String, String> rcForceReturn2 = remoteCacheManager.getCache(true);
assertSame("RemoteCache instances should be the same", rcForceReturn, rcForceReturn2);
}
public void testDifferentInstancesForDifferentForceReturnValues() {
RemoteCache<String, String> rcDontForceReturn = remoteCacheManager.getCache(false);
RemoteCache<String, String> rcForceReturn = remoteCacheManager.getCache(true);
assertNotSame("RemoteCache instances should not be the same", rcDontForceReturn, rcForceReturn);
String rv = rcDontForceReturn.put("Key", "Value");
assertNull(rv);
rv = rcDontForceReturn.put("Key", "Value2");
assertNull(rv);
rv = rcForceReturn.put("Key2", "Value");
assertNull(rv);
rv = rcForceReturn.put("Key2", "Value2");
assertNotNull(rv);
assertEquals("Previous value should be 'Value'", "Value", rv);
}
}
| 3,237
| 42.756757
| 102
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/SomeCustomConsistentHashV2.java
|
package org.infinispan.client.hotrod;
import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHashV2;
public class SomeCustomConsistentHashV2 extends ConsistentHashV2 {
}
| 184
| 22.125
| 73
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/RemoteCacheManagerExtendedTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertSame;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.marshall.ProtoStreamMarshaller;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*
* Adds tests for remote cache mangaer which are not supported
* by native clients (C++ and C#). See HRCPP-189 HRCPP-190.
*/
@Test(testName = "client.hotrod.RemoteCacheManagerExtendedTest", groups = "functional" )
public class RemoteCacheManagerExtendedTest extends SingleCacheManagerTest {
HotRodServer hotrodServer;
int port;
RemoteCacheManager remoteCacheManager;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
return TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration());
}
@Override
protected void setup() throws Exception {
super.setup();
hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
port = hotrodServer.getPort();
remoteCacheManager = null;
}
@AfterClass(alwaysRun = true)
public void release() {
TestingUtil.killCacheManagers(cacheManager);
cacheManager = null;
HotRodClientTestingUtil.killServers(hotrodServer);
hotrodServer = null;
HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager);
remoteCacheManager = null;
}
public void testGetUndefinedCache() {
ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(port);
remoteCacheManager = new RemoteCacheManager(clientBuilder.build(), false);
assert !remoteCacheManager.isStarted();
remoteCacheManager.start();
assert null == remoteCacheManager.getCache("Undefined1234");
}
public void testMarshallerInstance() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(port);
Marshaller marshaller = new ProtoStreamMarshaller();
builder.marshaller(marshaller);
RemoteCacheManager newRemoteCacheManager = new RemoteCacheManager(builder.build());
assertSame(marshaller, newRemoteCacheManager.getMarshaller());
HotRodClientTestingUtil.killRemoteCacheManager(newRemoteCacheManager);
}
}
| 2,923
| 37.986667
| 93
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ServerRestartTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test(testName = "client.hotrod.ServerRestartTest", groups = "functional")
public class ServerRestartTest extends SingleCacheManagerTest {
private static final Log log = LogFactory.getLog(HotRodIntegrationTest.class);
private RemoteCache<String, String> defaultRemote;
private RemoteCacheManager remoteCacheManager;
protected HotRodServer hotrodServer;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
return TestCacheManagerFactory.createCacheManager(
hotRodCacheConfiguration());
}
@Override
protected void setup() throws Exception {
super.setup();
hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
log.info("Started server on port: " + hotrodServer.getPort());
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(hotrodServer.getPort());
remoteCacheManager = new RemoteCacheManager(builder.build());
defaultRemote = remoteCacheManager.getCache();
}
@AfterClass
public void testDestroyRemoteCacheFactory() {
killRemoteCacheManager(remoteCacheManager);
remoteCacheManager = null;
killServers(hotrodServer);
hotrodServer = null;
}
public void testServerShutdown() throws Exception {
defaultRemote.put("k","v");
assert defaultRemote.get("k").equals("v");
int port = hotrodServer.getPort();
hotrodServer.stop();
HotRodServerConfigurationBuilder builder = new HotRodServerConfigurationBuilder();
builder.name(ServerRestartTest.class.getSimpleName());
builder.host("127.0.0.1").port(port).idleTimeout(20000).tcpNoDelay(true).sendBufSize(15000).recvBufSize(25000);
hotrodServer.start(builder.build(), cacheManager);
assert defaultRemote.get("k").equals("v");
defaultRemote.put("k","v");
}
}
| 2,886
| 37.493333
| 117
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/DroppedConnectionsTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotSame;
import java.net.InetSocketAddress;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.client.hotrod.test.NoopChannelOperation;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
import io.netty.channel.Channel;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test(testName = "client.hotrod.DroppedConnectionsTest", groups = "functional")
public class DroppedConnectionsTest extends SingleCacheManagerTest {
private HotRodServer hotRodServer;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
cacheManager = TestCacheManagerFactory.createCacheManager(
hotRodCacheConfiguration(getDefaultStandaloneCacheConfig(false)));
hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
return cacheManager;
}
@AfterClass
@Override
protected void teardown() {
super.teardown();
HotRodClientTestingUtil.killServers(hotRodServer);
hotRodServer = null;
}
public void testClosedConnection() throws Exception {
ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder
.connectionPool()
.minIdle(1)
.maxActive(2)
.addServer().host(hotRodServer.getHost()).port(hotRodServer.getPort());
RemoteCacheManager remoteCacheManager = null;
try {
remoteCacheManager = new InternalRemoteCacheManager(clientBuilder.build());
RemoteCache<String, String> rc = remoteCacheManager.getCache();
ChannelFactory channelFactory = ((InternalRemoteCacheManager) remoteCacheManager).getChannelFactory();
rc.put("k", "v"); //make sure a connection is created
InetSocketAddress address = InetSocketAddress.createUnresolved("127.0.0.1", hotRodServer.getPort());
assertEquals(0, channelFactory.getNumActive(address));
assertEquals(1, channelFactory.getNumIdle(address));
Channel channel = channelFactory.fetchChannelAndInvoke(address, new NoopChannelOperation()).join();
channelFactory.releaseChannel(channel);//now we have a reference to the single connection in pool
channel.close().sync();
assertEquals("v", rc.get("k"));
assertEquals(0, channelFactory.getNumActive(address));
assertEquals(1, channelFactory.getNumIdle(address));
Channel channel2 = channelFactory.fetchChannelAndInvoke(address, new NoopChannelOperation()).join();
assertNotSame(channel.id(), channel2.id());
} finally {
HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager);
}
}
}
| 3,388
| 37.954023
| 111
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/MixedExpiryTest.java
|
package org.infinispan.client.hotrod;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.container.DataContainer;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.ControlledTimeService;
import org.infinispan.commons.time.TimeService;
import org.testng.annotations.Test;
/**
* This test verifies that an entry can be expired from the Hot Rod server
* using the default expiry lifespan or maxIdle. </p>
*
* @author William Burns
* @since 8.0
*/
@Test(groups = "functional", testName = "client.hotrod.MixedExpiryTest")
public class MixedExpiryTest extends MultiHotRodServersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false);
configure(builder);
createHotRodServers(3, builder);
ts0 = new ControlledTimeService();
TestingUtil.replaceComponent(manager(0), TimeService.class, ts0, true);
ts1 = new ControlledTimeService();
TestingUtil.replaceComponent(manager(1), TimeService.class, ts1, true);
ts2 = new ControlledTimeService();
TestingUtil.replaceComponent(manager(2), TimeService.class, ts2, true);
}
protected ControlledTimeService ts0;
protected ControlledTimeService ts1;
protected ControlledTimeService ts2;
protected void configure(ConfigurationBuilder configurationBuilder) {
}
public void testMixedExpiryLifespan() {
RemoteCacheManager client0 = client(0);
RemoteCache<String, String> remoteCache0 = client0.getCache();
String key = "someKey";
assertNull(remoteCache0.put(key, "value1", 1000, TimeUnit.SECONDS, 1000, TimeUnit.SECONDS));
assertEquals("value1", remoteCache0.get(key)); // expected "value1"
assertMetadataAndValue(remoteCache0.getWithMetadata(key), "value1", 1000, 1000);
assertEquals("value1", remoteCache0.withFlags(Flag.FORCE_RETURN_VALUE).put(key, "value2", -1, TimeUnit.SECONDS, 1000,
TimeUnit.SECONDS));
assertEquals("value2", remoteCache0.get(key)); // expected "value2"
assertMetadataAndValue(remoteCache0.getWithMetadata(key), "value2", -1, 1000);
assertEquals("value2", remoteCache0.withFlags(Flag.FORCE_RETURN_VALUE).put(key, "value3", -1, TimeUnit.SECONDS, 1000,
TimeUnit.SECONDS));
assertEquals("value3", remoteCache0.get(key)); // expected "value3"
assertMetadataAndValue(remoteCache0.getWithMetadata(key), "value3", -1, 1000);
}
public void testMixedExpiryMaxIdle() {
RemoteCacheManager client0 = client(0);
RemoteCache<String, String> remoteCache0 = client0.getCache();
String key = "someKey";
assertNull(remoteCache0.put(key, "value1", 1000, TimeUnit.SECONDS, 1000, TimeUnit.SECONDS));
assertEquals("value1", remoteCache0.get(key)); // expected "value1"
assertMetadataAndValue(remoteCache0.getWithMetadata(key), "value1", 1000, 1000);
assertEquals("value1", remoteCache0.withFlags(Flag.FORCE_RETURN_VALUE).put(key, "value2", 1000, TimeUnit.SECONDS, -1,
TimeUnit.SECONDS));
assertEquals("value2", remoteCache0.get(key)); // expected "value2"
assertMetadataAndValue(remoteCache0.getWithMetadata(key), "value2", 1000, -1);
assertEquals("value2", remoteCache0.withFlags(Flag.FORCE_RETURN_VALUE).put(key, "value3", 1000, TimeUnit.SECONDS, -1,
TimeUnit.SECONDS));
assertEquals("value3", remoteCache0.get(key)); // expected "value3"
assertMetadataAndValue(remoteCache0.getWithMetadata(key), "value3", 1000, -1);
}
public void testMaxIdleRemovedOnAccess() throws InterruptedException, IOException {
RemoteCacheManager client0 = client(0);
RemoteCache<String, String> remoteCache0 = client0.getCache();
String key = "someKey";
Object keyStorage = cache(0).getAdvancedCache().getValueDataConversion().toStorage(key);
assertNull(remoteCache0.put(key, "value1", -1, TimeUnit.MILLISECONDS, 100, TimeUnit.MILLISECONDS));
for (Cache cache : caches()) {
DataContainer dataContainer = cache.getAdvancedCache().getDataContainer();
assertNotNull(dataContainer.peek(keyStorage));
}
incrementAllTimeServices(150, TimeUnit.MILLISECONDS);
assertNull(remoteCache0.get(key));
for (Cache cache : caches()) {
DataContainer dataContainer = cache.getAdvancedCache().getDataContainer();
assertNull(dataContainer.peek(keyStorage));
}
}
private <V> void assertMetadataAndValue(MetadataValue<V> metadataValue, V value, long lifespanSeconds,
long maxIdleSeconds) {
assertEquals(value, metadataValue.getValue());
assertEquals(lifespanSeconds, metadataValue.getLifespan());
assertEquals(maxIdleSeconds, metadataValue.getMaxIdle());
}
private void incrementAllTimeServices(long time, TimeUnit unit) {
for (ControlledTimeService cts : Arrays.asList(ts0, ts1, ts2)) {
cts.advance(unit.toMillis(time));
}
}
}
| 5,450
| 41.585938
| 123
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/RoundRobinBalancingIntegrationTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.impl.protocol.HotRodConstants;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory;
import org.infinispan.client.hotrod.impl.transport.tcp.RoundRobinBalancingStrategy;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test(testName = "client.hotrod.RoundRobinBalancingIntegrationTest", groups="functional")
public class RoundRobinBalancingIntegrationTest extends MultipleCacheManagersTest {
private static final Log log = LogFactory.getLog(RoundRobinBalancingIntegrationTest.class);
Cache c1;
Cache c2;
Cache c3;
Cache c4;
HotRodServer hotRodServer1;
HotRodServer hotRodServer2;
HotRodServer hotRodServer3;
HotRodServer hotRodServer4;
RemoteCache<String, String> remoteCache;
private RemoteCacheManager remoteCacheManager;
@Override
protected void createCacheManagers() throws Throwable {
c1 = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()).getCache();
c2 = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()).getCache();
c3 = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()).getCache();
registerCacheManager(c1.getCacheManager(), c2.getCacheManager(), c3.getCacheManager());
hotRodServer1 = HotRodClientTestingUtil.startHotRodServer(c1.getCacheManager());
hotRodServer2 = HotRodClientTestingUtil.startHotRodServer(c2.getCacheManager());
hotRodServer3 = HotRodClientTestingUtil.startHotRodServer(c3.getCacheManager());
log.trace("Server 1 port: " + hotRodServer1.getPort());
log.trace("Server 2 port: " + hotRodServer2.getPort());
log.trace("Server 3 port: " + hotRodServer3.getPort());
String servers = HotRodClientTestingUtil.getServersString(hotRodServer1, hotRodServer2, hotRodServer3);
log.trace("Server list is: " + servers);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServers(servers);
remoteCacheManager = new InternalRemoteCacheManager(clientBuilder.build());
remoteCache = remoteCacheManager.getCache();
}
@AfterClass(alwaysRun = true)
public void tearDown() {
killRemoteCacheManager(remoteCacheManager);
remoteCacheManager = null;
killServers(hotRodServer1, hotRodServer2, hotRodServer3, hotRodServer4);
hotRodServer1 = null;
hotRodServer2 = null;
hotRodServer3 = null;
hotRodServer4 = null;
}
public void testRoundRobinLoadBalancing() {
remoteCache.put("k1", "v1");
remoteCache.put("k2", "v2");
remoteCache.put("k3", "v3");
assertEquals(1, c1.size());
assertEquals(1, c2.size());
assertEquals(1, c3.size());
assertEquals("v1", remoteCache.get("k1"));
assertEquals("v2", remoteCache.get("k2"));
assertEquals("v3", remoteCache.get("k3"));
remoteCache.put("k4", "v1");
remoteCache.put("k5", "v2");
remoteCache.put("k6", "v3");
remoteCache.put("k7", "v1");
remoteCache.put("k8", "v2");
remoteCache.put("k9", "v3");
assertEquals(3, c1.size());
assertEquals(3, c2.size());
assertEquals(3, c3.size());
}
@Test(dependsOnMethods = "testRoundRobinLoadBalancing")
public void testAddNewHotrodServer() {
c4 = TestCacheManagerFactory.createCacheManager(
hotRodCacheConfiguration()).getCache();
hotRodServer4 = HotRodClientTestingUtil.startHotRodServer(c4.getCacheManager());
registerCacheManager(c4.getCacheManager());
List<SocketAddress> serverAddresses = new ArrayList<>();
serverAddresses.add(InetSocketAddress.createUnresolved("localhost", hotRodServer1.getPort()));
serverAddresses.add(InetSocketAddress.createUnresolved("localhost", hotRodServer2.getPort()));
serverAddresses.add(InetSocketAddress.createUnresolved("localhost", hotRodServer3.getPort()));
serverAddresses.add(InetSocketAddress.createUnresolved("localhost", hotRodServer4.getPort()));
RoundRobinBalancingStrategy balancer = getBalancer();
balancer.setServers(serverAddresses);
remoteCache.put("k1", "v1");
remoteCache.put("k2", "v2");
remoteCache.put("k3", "v3");
remoteCache.put("k4", "v4");
assertEquals(1, c1.size());
assertEquals(1, c2.size());
assertEquals(1, c3.size());
assertEquals(1, c4.size());
assertEquals("v1", remoteCache.get("k1"));
assertEquals("v2", remoteCache.get("k2"));
assertEquals("v3", remoteCache.get("k3"));
assertEquals("v4", remoteCache.get("k4"));
remoteCache.put("k5", "v2");
remoteCache.put("k6", "v3");
remoteCache.put("k7", "v1");
remoteCache.put("k8", "v2");
remoteCache.put("k9", "v3");
remoteCache.put("k10", "v3");
remoteCache.put("k11", "v3");
remoteCache.put("k12", "v3");
assertEquals(3, c1.size());
assertEquals(3, c2.size());
assertEquals(3, c3.size());
assertEquals(3, c4.size());
}
@Test(dependsOnMethods = "testAddNewHotrodServer")
public void testStopServer() {
remoteCache.put("k1", "v1");
remoteCache.put("k2", "v2");
remoteCache.put("k3", "v3");
remoteCache.put("k4", "v4");
assertEquals(1, c1.size());
assertEquals(1, c2.size());
assertEquals(1, c3.size());
assertEquals(1, c4.size());
assertEquals("v1", remoteCache.get("k1"));
assertEquals("v2", remoteCache.get("k2"));
assertEquals("v3", remoteCache.get("k3"));
assertEquals("v4", remoteCache.get("k4"));
hotRodServer4.stop();
try {
remoteCache.put("k5", "v1");
remoteCache.put("k6", "v2");
remoteCache.put("k7", "v3");
remoteCache.put("k8", "v4");
} catch (Exception e) {
assert false : "exception should not happen even if the balancer redirects to failed node at the beggining";
}
}
@Test(dependsOnMethods = "testStopServer")
public void testRemoveServers() {
List<SocketAddress> serverAddresses = new ArrayList<>();
serverAddresses.add(InetSocketAddress.createUnresolved("localhost", hotRodServer1.getPort()));
serverAddresses.add(InetSocketAddress.createUnresolved("localhost", hotRodServer2.getPort()));
RoundRobinBalancingStrategy balancer = getBalancer();
balancer.setServers(serverAddresses);
remoteCache.put("k1", "v1");
remoteCache.put("k2", "v2");
remoteCache.put("k3", "v3");
remoteCache.put("k4", "v4");
assertEquals(2, c1.size());
assertEquals(2, c2.size());
assertEquals(0, c3.size());
assertEquals(0, c4.size());
assertEquals("v1", remoteCache.get("k1"));
assertEquals("v2", remoteCache.get("k2"));
assertEquals("v3", remoteCache.get("k3"));
assertEquals("v4", remoteCache.get("k4"));
remoteCache.put("k5", "v2");
remoteCache.put("k6", "v3");
remoteCache.put("k7", "v1");
remoteCache.put("k8", "v2");
remoteCache.put("k9", "v3");
remoteCache.put("k10", "v3");
remoteCache.put("k11", "v3");
remoteCache.put("k12", "v3");
assertEquals(6, c1.size());
assertEquals(6, c2.size());
assertEquals(0, c3.size());
assertEquals(0, c4.size());
}
private RoundRobinBalancingStrategy getBalancer() {
ChannelFactory channelFactory = ((InternalRemoteCacheManager) remoteCacheManager).getChannelFactory();
return (RoundRobinBalancingStrategy) channelFactory.getBalancer(HotRodConstants.DEFAULT_CACHE_NAME_BYTES);
}
}
| 8,631
| 36.367965
| 117
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ReplaceWithVersionConcurrencyTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
@Test(groups = "stress", testName = "client.hotrod.ReplaceWithVersionConcurrencyTest", timeOut = 15*60*1000)
public class ReplaceWithVersionConcurrencyTest extends MultiHotRodServersTest {
static final AtomicInteger globalCounter = new AtomicInteger();
static final String KEY = "A";
static final int NUM_THREADS = 20;
static final int OPS_PER_THREAD = 200;
static final int TIMEOUT_MINUTES = 5;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = hotRodCacheConfiguration(
getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false));
// .transaction()
// .lockingMode(LockingMode.PESSIMISTIC)
// .transactionMode(TransactionMode.TRANSACTIONAL);
createHotRodServers(2, builder);
}
public void testKeepingCounterWithReplaceWithVersion() throws Exception {
RemoteCache<String, Integer> cache = client(0).getCache();
assertNull(cache.get(KEY));
long timeSpent = System.currentTimeMillis();
List<Future<Integer>> results = new ArrayList<Future<Integer>>(NUM_THREADS);
ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS, getTestThreadFactory("Worker"));
for (int i = 0; i < NUM_THREADS; i++) {
CounterUpdater app = new CounterUpdater(cache, KEY, OPS_PER_THREAD);
Future<Integer> result = executor.submit(app);
results.add(result);
}
executor.shutdown();
executor.awaitTermination(TIMEOUT_MINUTES, TimeUnit.MINUTES);
timeSpent = System.currentTimeMillis() - timeSpent;
int actual = cache.get(KEY); // server-side value
int expected = 0; // client-side value
for (Future<Integer> f : results)
expected += f.get();
log.info("Time spent: " + timeSpent / 1000.0 + " secs.");
assertEquals(expected, actual);
}
static class CounterUpdater implements Callable<Integer> {
static final Log log = LogFactory.getLog(CounterUpdater.class);
final RemoteCache<String, Integer> cache;
final String key;
final int limit;
CounterUpdater(RemoteCache<String, Integer> cache, String key, int limit) {
this.cache = cache;
this.key = key;
this.limit = limit;
}
@Override
public Integer call() throws Exception {
int counter = 0;
log.info("Start to count.");
int i = 0;
while (i < limit) {
incrementCounter();
counter++;
i++;
}
log.info("Counted " + counter);
return counter;
}
private void incrementCounter() {
while (true) {
VersionedValue<Integer> versioned = cache.getWithMetadata(key);
if (versioned == null) {
if (cache.withFlags(Flag.FORCE_RETURN_VALUE).putIfAbsent(key, 1) == null) {
log.info("count=" + globalCounter.getAndIncrement() + ",prev=0,new=1 (first-put)");
return;
}
} else {
int val = versioned.getValue() + 1;
long version = versioned.getVersion();
if (cache.replaceWithVersion(key, val, version)) {
int count = globalCounter.getAndIncrement();
log.info("count=" + count +",prev=" + versioned.getValue() + ",new=" + val + ",prev-version=" + version);
// Optimistically updated, no more retries.
return;
}
}
}
}
}
}
| 4,393
| 36.237288
| 123
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ProtobufJsonScriptTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_PROTOSTREAM_TYPE;
import static org.infinispan.scripting.ScriptingManager.SCRIPT_CACHE;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.util.Collections;
import org.infinispan.client.hotrod.query.testdomain.protobuf.UserPB;
import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.query.dsl.Query;
import org.infinispan.query.dsl.embedded.testdomain.User;
import org.testng.annotations.Test;
/**
* Test for scripts with application/json data type interacting with protobuf caches.
*
* @since 9.4
*/
@Test(groups = "functional", testName = "client.hotrod.ProtobufJsonScriptTest")
public class ProtobufJsonScriptTest extends MultiHotRodServersTest {
private static final String SCRIPT_NAME = "protobuf-json-script.js";
private static final int CLUSTER_SIZE = 2;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfgBuilder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false));
cfgBuilder.encoding().key().mediaType(APPLICATION_PROTOSTREAM_TYPE);
cfgBuilder.encoding().value().mediaType(APPLICATION_PROTOSTREAM_TYPE);
createHotRodServers(CLUSTER_SIZE, cfgBuilder);
waitForClusterToForm();
}
@Override
protected SerializationContextInitializer contextInitializer() {
return TestDomainSCI.INSTANCE;
}
@Test
public void testDataAsJSONFromScript() throws IOException {
RemoteCacheManager remoteCacheManager = client(0);
RemoteCache<Integer, User> cache = remoteCacheManager.getCache();
User user1 = new UserPB();
user1.setId(1);
user1.setName("Tom");
user1.setSurname("Cat");
user1.setGender(User.Gender.MALE);
user1.setAge(33);
user1.setAccountIds(Collections.singleton(12));
User user2 = new UserPB();
user2.setId(2);
user2.setName("Jane");
user2.setSurname("Doe");
user2.setGender(User.Gender.FEMALE);
user2.setAge(39);
cache.put(1, user1);
cache.put(2, user2);
Query<User> q = Search.getQueryFactory(cache).create("FROM sample_bank_account.User WHERE name = 'Jane'");
User user = q.execute().list().iterator().next();
assertEquals("Jane", user.getName());
registerScript(remoteCacheManager, SCRIPT_NAME);
// The script will clone an existing user, change some fields and insert into a new user
User result = cache.execute(SCRIPT_NAME, Collections.emptyMap());
// Read the user as pojo
assertEquals(result.getId(), 3);
assertEquals(result.getName(), "Rex");
assertEquals((int) result.getAge(), 67);
}
private void registerScript(RemoteCacheManager remoteCacheManager, String script) throws IOException {
RemoteCache<String, String> scriptCache = remoteCacheManager.getCache(SCRIPT_CACHE);
String string = Util.getResourceAsString("/" + script, getClass().getClassLoader());
scriptCache.put(SCRIPT_NAME, string);
}
}
| 3,544
| 37.956044
| 125
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ClientSocketReadTimeoutTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.test.TestingUtil.k;
import static org.infinispan.test.TestingUtil.v;
import java.lang.reflect.Method;
import java.net.SocketTimeoutException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.exceptions.TransportException;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.distribution.BlockingInterceptor;
import org.infinispan.interceptors.impl.EntryWrappingInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* This test is used to verify that clients get a timeout when the server does
* not respond with the requested bytes.
*
* @author Galder Zamarreño
* @since 4.2
*/
@Test(testName = "client.hotrod.ClientSocketReadTimeoutTest", groups = "functional" )
public class ClientSocketReadTimeoutTest extends SingleCacheManagerTest {
HotRodServer hotrodServer;
RemoteCacheManager remoteCacheManager;
CyclicBarrier barrier;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
barrier = new CyclicBarrier(2);
cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration());
BlockingInterceptor<PutKeyValueCommand> blockingInterceptor =
new BlockingInterceptor<>(barrier, PutKeyValueCommand.class, true, true);
cacheManager.getCache().getAdvancedCache().getAsyncInterceptorChain()
.addInterceptorBefore(blockingInterceptor, EntryWrappingInterceptor.class);
// cacheManager = TestCacheManagerFactory.createLocalCacheManager();
// pass the config file to the cache
hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
log.info("Started server on port: " + hotrodServer.getPort());
remoteCacheManager = getRemoteCacheManager();
return cacheManager;
}
protected RemoteCacheManager getRemoteCacheManager() {
ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(hotrodServer)
.socketTimeout(1000).connectionTimeout(5000)
.connectionPool().maxActive(2)
.maxRetries(0);
return new RemoteCacheManager(builder.create());
}
@Override
protected void teardown() {
killRemoteCacheManager(remoteCacheManager);
killServers(hotrodServer);
hotrodServer = null;
super.teardown();
}
public void testPutTimeout(Method m) throws Throwable {
Exceptions.expectException(TransportException.class, SocketTimeoutException.class,
() -> remoteCacheManager.getCache().put(k(m), v(m)));
barrier.await(10, TimeUnit.SECONDS);
barrier.await(10, TimeUnit.SECONDS);
}
}
| 3,422
| 40.743902
| 104
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/SomeAsyncExecutorFactory.java
|
package org.infinispan.client.hotrod;
import org.infinispan.client.hotrod.impl.async.DefaultAsyncExecutorFactory;
public class SomeAsyncExecutorFactory extends DefaultAsyncExecutorFactory {
}
| 195
| 23.5
| 75
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/TransportFactoryTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import org.infinispan.client.hotrod.configuration.Configuration;
import org.infinispan.client.hotrod.impl.ConfigurationProperties;
import org.infinispan.client.hotrod.impl.transport.netty.DefaultTransportFactory;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.CleanupAfterTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.SocketChannel;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
@Test(testName = "client.hotrod.TransportFactoryTest", groups = "functional")
@CleanupAfterTest
public class TransportFactoryTest extends SingleCacheManagerTest {
private HotRodServer hotrodServer;
@Override
protected void setup() throws Exception {
super.setup();
hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
}
@Override
protected void teardown() {
killServers(hotrodServer);
super.teardown();
}
public void testTransportFactoryProgrammatic() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
TestTransportFactory transportFactory = new TestTransportFactory();
clientBuilder.addServer().host("localhost").port(hotrodServer.getPort()).transportFactory(transportFactory);
try (RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build())) {
assertEquals(0, transportFactory.socketChannelLatch.getCount());
assertEquals(0, transportFactory.createEventLoopGroupLatch.getCount());
}
}
public void testTransportFactoryDeclarative() {
Properties p = new Properties();
p.setProperty(ConfigurationProperties.TRANSPORT_FACTORY, TestTransportFactory.class.getName());
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotrodServer.getPort()).withProperties(p);
try (RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build())) {
Configuration configuration = remoteCacheManager.getConfiguration();
assertTrue(configuration.transportFactory() instanceof TestTransportFactory);
TestTransportFactory transportFactory = (TestTransportFactory) configuration.transportFactory();
assertEquals(0, transportFactory.socketChannelLatch.getCount());
assertEquals(0, transportFactory.createEventLoopGroupLatch.getCount());
}
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
return TestCacheManagerFactory.createCacheManager();
}
public static class TestTransportFactory extends DefaultTransportFactory {
CountDownLatch socketChannelLatch = new CountDownLatch(1);
CountDownLatch createEventLoopGroupLatch = new CountDownLatch(1);
@Override
public Class<? extends SocketChannel> socketChannelClass() {
socketChannelLatch.countDown();
return super.socketChannelClass();
}
@Override
public EventLoopGroup createEventLoopGroup(int maxExecutors, ExecutorService executorService) {
createEventLoopGroupLatch.countDown();
return super.createEventLoopGroup(maxExecutors, executorService);
}
}
}
| 4,011
| 41.231579
| 114
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ForceReturnValuesTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
@Test(testName = "client.hotrod.ForceReturnValuesTest", groups = "functional")
@CleanupAfterMethod
public class ForceReturnValuesTest extends SingleCacheManagerTest {
private HotRodServer hotRodServer;
private RemoteCacheManager remoteCacheManager;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration());
cache = cacheManager.getCache();
hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host(hotRodServer.getHost()).port(hotRodServer.getPort());
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
return cacheManager;
}
@AfterMethod
void shutdown() {
HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager);
HotRodClientTestingUtil.killServers(hotRodServer);
hotRodServer = null;
}
public void testDontForceReturnValues() {
RemoteCache<String, String> rc = remoteCacheManager.getCache();
String rv = rc.put("Key", "Value");
assert rv == null;
rv = rc.put("Key", "Value2");
assert rv == null;
}
public void testForceReturnValues() {
RemoteCache<String, String> rc = remoteCacheManager.getCache(true);
String rv = rc.put("Key", "Value");
assert rv == null;
rv = rc.put("Key", "Value2");
assert rv != null;
assert "Value".equals(rv);
}
}
| 2,181
| 36.62069
| 92
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/AsymmetricRoutingTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.distribution.DistributionTestHelper.isFirstOwner;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.test.TestingUtil.blockUntilCacheStatusAchieved;
import static org.infinispan.test.TestingUtil.blockUntilViewReceived;
import static org.testng.AssertJUnit.assertEquals;
import java.net.InetSocketAddress;
import java.util.Random;
import java.util.Set;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.ch.ConsistentHash;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.util.ControlledConsistentHashFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.AsymmetricRoutingTest")
public class AsymmetricRoutingTest extends HitsAwareCacheManagersTest {
private static final String DIST_ONE_CACHE_NAME = "dist-one-cache";
private static final String DIST_TWO_CACHE_NAME = "dist-two-cache";
HotRodServer server1;
HotRodServer server2;
ConfigurationBuilder defaultBuilder;
ConfigurationBuilder distOneBuilder;
ConfigurationBuilder distTwoBuilder;
RemoteCacheManager rcm;
protected ConfigurationBuilder defaultCacheConfigurationBuilder() {
return hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC));
}
@Override
protected void createCacheManagers() throws Throwable {
defaultBuilder = defaultCacheConfigurationBuilder();
distOneBuilder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC));
distOneBuilder.clustering().hash().numOwners(1).numSegments(1)
.consistentHashFactory(new ControlledConsistentHashFactory.Default(0));
distTwoBuilder = hotRodCacheConfiguration(getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC));
distTwoBuilder.clustering().hash().numOwners(1).numSegments(1)
.consistentHashFactory(new ControlledConsistentHashFactory.Default(1));
server1 = addHotRodServer();
server2 = addHotRodServer();
blockUntilViewReceived(manager(0).getCache(), 2);
blockUntilCacheStatusAchieved(manager(0).getCache(), ComponentStatus.RUNNING, 10000);
blockUntilCacheStatusAchieved(manager(1).getCache(), ComponentStatus.RUNNING, 10000);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host(server1.getHost()).port(server1.getPort())
.addServer().host(server2.getHost()).port(server2.getPort());
rcm = new RemoteCacheManager(clientBuilder.build());
}
@AfterClass
@Override
protected void destroy() {
killRemoteCacheManager(rcm);
killServers(server1, server2);
server1 = null;
server2 = null;
super.destroy();
}
private HotRodServer addHotRodServer() {
EmbeddedCacheManager cm = addClusterEnabledCacheManager(defaultBuilder);
cm.defineConfiguration(DIST_ONE_CACHE_NAME, distOneBuilder.build());
cm.defineConfiguration(DIST_TWO_CACHE_NAME, distTwoBuilder.build());
HotRodServer server = HotRodClientTestingUtil.startHotRodServer(cm);
addr2hrServer.put(new InetSocketAddress(server.getHost(), server.getPort()), server);
return server;
}
public void testRequestRouting() {
addInterceptors(DIST_ONE_CACHE_NAME);
addInterceptors(DIST_TWO_CACHE_NAME);
byte[] keyDistOne = getKeyForServer(server1, DIST_ONE_CACHE_NAME);
byte[] keyDistTwo = getKeyForServer(server2, DIST_TWO_CACHE_NAME);
assertSegments(DIST_ONE_CACHE_NAME, server1, server1.getCacheManager().getAddress());
assertSegments(DIST_ONE_CACHE_NAME, server2, server1.getCacheManager().getAddress());
assertSegments(DIST_TWO_CACHE_NAME, server1, server2.getCacheManager().getAddress());
assertSegments(DIST_TWO_CACHE_NAME, server2, server2.getCacheManager().getAddress());
assertRequestRouting(keyDistOne, DIST_ONE_CACHE_NAME, server1);
assertRequestRouting(keyDistTwo, DIST_TWO_CACHE_NAME, server2);
}
private void assertSegments(String cacheName, HotRodServer server, Address owner) {
AdvancedCache<Object, Object> cache = server.getCacheManager().getCache(cacheName).getAdvancedCache();
ConsistentHash ch = cache.getDistributionManager().getReadConsistentHash();
assertEquals(1, ch.getNumSegments());
Set<Integer> segments = ch.getSegmentsForOwner(owner);
assertEquals(1, segments.size());
assertEquals(0, segments.iterator().next().intValue());
}
private void assertRequestRouting(byte[] key, String cacheName, HotRodServer server) {
RemoteCache<Object, Object> rcOne = rcm.getCache(cacheName);
InetSocketAddress serverAddress = new InetSocketAddress(server.getHost(), server.getPort());
for (int i = 0; i < 2; i++) {
log.infof("Routing put test for key %s", Util.printArray(key, false));
rcOne.put(key, "value");
assertServerHit(serverAddress, cacheName, i + 1);
}
}
byte[] getKeyForServer(HotRodServer primaryOwner, String cacheName) {
Cache<?, ?> cache = primaryOwner.getCacheManager().getCache(cacheName);
Random r = new Random();
byte[] dummy = new byte[8];
int attemptsLeft = 1000;
do {
r.nextBytes(dummy);
attemptsLeft--;
} while (!isFirstOwner(cache, dummy) && attemptsLeft >= 0);
if (attemptsLeft < 0)
throw new IllegalStateException("Could not find any key owned by " + primaryOwner);
log.infof("Binary key %s hashes to [cluster=%s,hotrod=%s]",
Util.printArray(dummy, false), primaryOwner.getCacheManager().getAddress(),
primaryOwner.getAddress());
return dummy;
}
}
| 6,499
| 43.827586
| 108
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/DistTopologyChangeUnderLoadSingleOwnerTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.DistTopologyChangeUnderLoadSingleOwnerTest")
public class DistTopologyChangeUnderLoadSingleOwnerTest extends MultiHotRodServersTest {
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(2, getCacheConfiguration());
}
private ConfigurationBuilder getCacheConfiguration() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
builder.clustering().hash().numOwners(1);
return hotRodCacheConfiguration(builder);
}
@Override
protected int maxRetries() {
return 1;
}
public void testRestartServerWhilePutting() throws Exception {
RemoteCache<Integer, String> remote = client(0).getCache();
remote.put(1, "v1");
assertEquals("v1", remote.get(1));
PutHammer putHammer = new PutHammer();
Future<Void> putHammerFuture = fork(putHammer);
// Kill server
HotRodServer toKillServer = servers.get(0);
HotRodClientTestingUtil.killServers(toKillServer);
servers.remove(toKillServer);
EmbeddedCacheManager toKillCacheManager = cacheManagers.get(0);
TestingUtil.killCacheManagers(toKillCacheManager);
cacheManagers.remove(toKillCacheManager);
TestingUtil.waitForNoRebalance(cache(0));
// Start server
addHotRodServer(getCacheConfiguration());
putHammer.stop = true;
putHammerFuture.get();
}
private class PutHammer implements Callable<Void> {
private final Random r = new Random();
volatile boolean stop;
@Override
public Void call() throws Exception {
RemoteCache<Integer, String> remote = client(0).getCache();
while (!stop) {
int i = r.nextInt(10);
remote.put(i, "v" + i);
}
return null;
}
}
}
| 2,586
| 31.746835
| 99
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/SegmentOwnershipReplTest.java
|
package org.infinispan.client.hotrod;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.net.SocketAddress;
import java.util.Map;
import java.util.Set;
import org.infinispan.configuration.cache.CacheMode;
import org.testng.annotations.Test;
/**
* @author gustavonalle
* @since 8.0
*/
@Test(groups = "functional", testName = "client.hotrod.SegmentOwnershipReplTest")
public class SegmentOwnershipReplTest extends BaseSegmentOwnershipTest {
@Override
protected CacheMode getCacheMode() {
return CacheMode.REPL_SYNC;
}
@Test
public void testObtainSegmentOwnership() throws Exception {
RemoteCache<Object, Object> remoteCache = client(0).getCache();
Map<SocketAddress, Set<Integer>> segmentsByServer = remoteCache.getCacheTopologyInfo().getSegmentsPerServer();
assertEquals(segmentsByServer.keySet().size(), NUM_SERVERS);
assertTrue(segmentsByServer.entrySet().stream().allMatch(e -> e.getValue().size() == NUM_SEGMENTS));
}
}
| 1,033
| 28.542857
| 116
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/JsonScriptTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON;
import static org.infinispan.scripting.ScriptingManager.SCRIPT_CACHE;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.util.Collections;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.marshall.UTF8StringMarshaller;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
/**
* Test for scripts with application/json data type interacting with default caches.
*
* @since 9.4
*/
@Test(groups = "functional", testName = "client.hotrod.ProtobufJsonScriptTest")
public class JsonScriptTest extends MultiHotRodServersTest {
private static final String SCRIPT_NAME = "json-script.js";
private static final int CLUSTER_SIZE = 2;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfgBuilder = hotRodCacheConfiguration(MediaType.APPLICATION_JSON);
createHotRodServers(CLUSTER_SIZE, cfgBuilder);
waitForClusterToForm();
}
@Override
protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(String host, int serverPort) {
return super.createHotRodClientConfigurationBuilder(host, serverPort).marshaller(new UTF8StringMarshaller());
}
@Test
public void testJSONScript() throws IOException {
RemoteCacheManager remoteCacheManager = client(0);
registerScript(remoteCacheManager, SCRIPT_NAME);
RemoteCache<String, String> cache = remoteCacheManager.getCache()
.withDataFormat(DataFormat.builder().valueType(APPLICATION_JSON).build());
String result = cache.execute(SCRIPT_NAME, Collections.emptyMap());
assertEquals(result, "{\"v\":\"value2\"}");
}
private void registerScript(RemoteCacheManager remoteCacheManager, String script) throws IOException {
RemoteCache<String, String> scriptCache = remoteCacheManager.getCache(SCRIPT_CACHE);
String string = Util.getResourceAsString("/" + script, getClass().getClassLoader());
scriptCache.put(SCRIPT_NAME, string);
}
}
| 2,416
| 38.622951
| 146
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/LockingTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.InvocationContext;
import org.infinispan.interceptors.BaseCustomAsyncInterceptor;
import org.infinispan.interceptors.impl.CallInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CheckPoint;
import org.infinispan.test.fwk.CleanupAfterTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
/**
* Tests locks over HotRod.
*
* @author Pedro Ruivo
* @since 7.0
*/
@Test(testName = "client.hotrod.LockingTest", groups = "functional")
@CleanupAfterTest
public class LockingTest extends SingleCacheManagerTest {
private RemoteCacheManager remoteCacheManager;
private HotRodServer hotrodServer;
public void testPerEntryLockContainer() throws Exception {
doLockTest(CacheName.PER_ENTRY_LOCK);
}
public void testStrippedLockContainer() throws Exception {
doLockTest(CacheName.STRIPPED_LOCK);
}
@Override
protected void teardown() {
killRemoteCacheManager(remoteCacheManager);
killServers(hotrodServer);
hotrodServer = null;
super.teardown();
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder builder = hotRodCacheConfiguration();
builder.locking().lockAcquisitionTimeout(100, TimeUnit.MILLISECONDS);
EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(builder);
for (CacheName cacheName : CacheName.values()) {
cacheName.configure(builder);
cacheManager.defineConfiguration(cacheName.name(), builder.build());
cacheManager.getCache(cacheName.name());
}
return cacheManager;
}
@Override
protected void setup() throws Exception {
super.setup();
hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotrodServer.getPort()).socketTimeout(10_000);
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
}
private void doLockTest(CacheName cacheName) throws Exception {
final RemoteCache<String, String> remoteCache = remoteCacheManager.getCache(cacheName.name());
CheckPoint checkPoint = injectBlockingCommandInterceptor(cacheName.name());
Future<Void> op = fork(() -> {
remoteCache.put("key", "value1");
return null;
});
checkPoint.awaitStrict("before-block", 30, TimeUnit.SECONDS);
try {
for (int i = 0; i < 50; ++i) {
try {
remoteCache.put("key", "value" + i);
AssertJUnit.fail("It should have fail with lock timeout!");
} catch (Exception e) {
log.trace("Exception caught", e);
if (!e.getLocalizedMessage().contains("Unable to acquire lock after")) {
//we got an unexpected exception!
throw e;
}
}
}
} finally {
checkPoint.trigger("block");
}
op.get();
AssertJUnit.assertEquals("value1", remoteCache.get("key"));
}
private CheckPoint injectBlockingCommandInterceptor(String cacheName) {
final CheckPoint checkPoint = new CheckPoint();
TestingUtil.extractInterceptorChain(cache(cacheName))
.addInterceptorBefore(new BaseCustomAsyncInterceptor() {
private final AtomicBoolean first = new AtomicBoolean(false);
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) {
if (first.compareAndSet(false, true)) {
checkPoint.trigger("before-block");
return asyncInvokeNext(ctx, command,
checkPoint.future("block", 30, TimeUnit.SECONDS, testExecutor()));
}
return invokeNext(ctx, command);
}
}, CallInterceptor.class);
return checkPoint;
}
private enum CacheName {
STRIPPED_LOCK {
@Override
void configure(ConfigurationBuilder builder) {
builder.locking().useLockStriping(true);
}
},
PER_ENTRY_LOCK {
@Override
void configure(ConfigurationBuilder builder) {
builder.locking().useLockStriping(false);
}
};
abstract void configure(ConfigurationBuilder builder);
}
}
| 5,367
| 35.026846
| 104
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/GetAllObjectStorageDistTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT_TYPE;
import static org.testng.AssertJUnit.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
@Test(testName = "client.hotrod.GetAllObjectStorageDistTest", groups = "functional")
public class GetAllObjectStorageDistTest extends MultiHotRodServersTest {
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(2, getCacheConfiguration());
}
private ConfigurationBuilder getCacheConfiguration() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
builder.clustering().hash().numOwners(1)
.encoding().key().mediaType(APPLICATION_OBJECT_TYPE)
.encoding().value().mediaType(APPLICATION_OBJECT_TYPE);
return builder;
}
public void testGetAllWithObjectStorage() {
RemoteCache<String, String> cache = client(0).getCache();
HashMap<String, String> cachedValues = new HashMap<>();
for(int i=0; i<100; i++){
String key = String.format("key-%d", i);
String value = String.format("value-%d", i);
cache.put(key, value);
cachedValues.put(key, value);
}
Map<String, String> values = cache.getAll(cachedValues.keySet());
assertEquals(cachedValues.size(), values.size());
for(String key : values.keySet()){
assertEquals(cachedValues.get(key), values.get(key));
}
}
}
| 1,739
| 35.25
| 96
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/SocketTimeoutErrorTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.test.TestingUtil.k;
import static org.testng.AssertJUnit.assertEquals;
import java.lang.reflect.Method;
import java.net.SocketTimeoutException;
import java.util.concurrent.CompletableFuture;
import org.infinispan.client.hotrod.exceptions.TransportException;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commons.marshall.ProtoStreamMarshaller;
import org.infinispan.commons.marshall.WrappedByteArray;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.InvocationContext;
import org.infinispan.interceptors.BaseCustomAsyncInterceptor;
import org.infinispan.interceptors.impl.EntryWrappingInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* Tests the behaviour of the client upon a socket timeout exception and any invocation after that.
*
* @author Galder Zamarreño
* @since 4.2
*/
@Test(groups = "functional", testName = "client.hotrod.SocketTimeoutErrorTest")
public class SocketTimeoutErrorTest extends SingleHotRodServerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.customInterceptors().addInterceptor().interceptor(
new TimeoutInducingInterceptor()).after(EntryWrappingInterceptor.class);
return TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration(builder));
}
@Override
protected HotRodServer createHotRodServer() {
HotRodServerConfigurationBuilder builder = new HotRodServerConfigurationBuilder();
return HotRodClientTestingUtil.startHotRodServer(cacheManager, builder);
}
@Override
protected RemoteCacheManager getRemoteCacheManager() {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(hotrodServer.getPort());
builder.socketTimeout(2000);
builder.maxRetries(0);
return new RemoteCacheManager(builder.build());
}
public void testErrorWhileDoingPut(Method m) {
RemoteCache<String, Integer> cache = remoteCacheManager.getCache();
cache.put(k(m), 1);
assertEquals(1, cache.get(k(m)).intValue());
Exceptions.expectException(TransportException.class, SocketTimeoutException.class, () -> cache.put("FailFailFail", 2));
cache.put("dos", 2);
assertEquals(2, cache.get("dos").intValue());
TestingUtil.extractInterceptorChain(this.cache)
.findInterceptorWithClass(TimeoutInducingInterceptor.class)
.stopBlocking();
}
public static class TimeoutInducingInterceptor extends BaseCustomAsyncInterceptor {
public final CompletableFuture<Void> delay = new CompletableFuture<>();
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
if (unmarshall(command.getKey()).equals("FailFailFail")) {
return asyncValue(delay);
}
return super.visitPutKeyValueCommand(ctx, command);
}
private String unmarshall(Object key) throws Exception {
return (String) new ProtoStreamMarshaller().objectFromByteBuffer(((WrappedByteArray) key).getBytes());
}
private void stopBlocking() {
delay.complete(null);
}
}
}
| 4,021
| 40.463918
| 125
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/ExecTypedTestWithOlderClients.java
|
package org.infinispan.client.hotrod;
import org.testng.annotations.Test;
/**
* @since 9.4
*/
@Test(groups = "functional", testName = "client.hotrod.ExecTypedTestWithOlderClients")
public class ExecTypedTestWithOlderClients extends ExecTypedTest {
@Override
protected ProtocolVersion getProtocolVersion() {
return ProtocolVersion.PROTOCOL_VERSION_25;
}
}
| 375
| 22.5
| 86
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/HeavyLoadConnectionPoolingTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicLong;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.context.InvocationContext;
import org.infinispan.interceptors.BaseAsyncInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test (testName = "client.hotrod.HeavyLoadConnectionPoolingTest", groups = "functional")
public class HeavyLoadConnectionPoolingTest extends SingleCacheManagerTest {
private HotRodServer hotRodServer;
private RemoteCacheManager remoteCacheManager;
private RemoteCache<Object, Object> remoteCache;
private ChannelFactory channelFactory;
@AfterMethod
@Override
protected void clearContent() {
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration());
cache = cacheManager.getCache();
// make sure all operations take at least 100 msecs
extractInterceptorChain(cache).addInterceptor(new ConstantDelayTransportInterceptor(100), 0);
hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder
.connectionPool()
.minEvictableIdleTime(100)
.minIdle(0)
.addServer().host("localhost").port(hotRodServer.getPort());
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
remoteCache = remoteCacheManager.getCache();
channelFactory = TestingUtil.extractField(remoteCacheManager, "channelFactory");
return cacheManager;
}
@AfterClass
@Override
protected void destroyAfterClass() {
super.destroyAfterClass();
killRemoteCacheManager(remoteCacheManager);
killServers(hotRodServer);
hotRodServer = null;
}
public void testHeavyLoad() throws InterruptedException, ExecutionException {
List<WorkerThread> workers = new ArrayList<WorkerThread>();
//create 20 threads and do work with them
AtomicLong opCounter = new AtomicLong(0);
for (int i =0; i < 20; i++) {
WorkerThread workerThread = new WorkerThread(remoteCache);
workers.add(workerThread);
workerThread.stress(opCounter);
}
while (opCounter.get() < 100) {
Thread.sleep(10);
}
for (WorkerThread wt: workers) {
wt.stop();
}
for (WorkerThread wt: workers) {
wt.awaitTermination();
}
//now wait for the idle thread to wake up and clean them
eventually(new Condition() {
@Override
public boolean isSatisfied() throws Exception {
int numIdle = channelFactory.getNumIdle();
int numActive = channelFactory.getNumActive();
return numIdle == 0 && numActive == 0;
}
});
}
public static class ConstantDelayTransportInterceptor extends BaseAsyncInterceptor {
private int millis;
public ConstantDelayTransportInterceptor(int millis) {
this.millis = millis;
}
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
Thread.sleep(millis);
return invokeNext(ctx, command);
}
}
}
| 4,386
| 33.543307
| 100
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/AutomaticVersionTest.java
|
package org.infinispan.client.hotrod;
import static org.testng.AssertJUnit.assertEquals;
import org.testng.annotations.Test;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 10.0
**/
@Test(testName = "client.hotrod.AutomaticVersionTest", groups = {"unit", "functional"})
public class AutomaticVersionTest {
public void testBestProtocolSelection() {
// This should choose the highest possible version known by the client
assertEquals(ProtocolVersion.HIGHEST_PROTOCOL_VERSION, ProtocolVersion.getBestVersion(Integer.MAX_VALUE));
// This should match the exact version, as we know about it
assertEquals(ProtocolVersion.PROTOCOL_VERSION_23, ProtocolVersion.getBestVersion(23));
}
}
| 736
| 34.095238
| 112
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/BaseGetAllTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
/**
* Tests functionality related to getting multiple entries from a HotRod server
* using getAll method.
*
* @author William Burns
* @since 7.2
*/
@Test(groups = "functional")
public abstract class BaseGetAllTest extends MultipleCacheManagersTest {
protected HotRodServer[] hotrodServers;
protected RemoteCacheManager remoteCacheManager;
protected RemoteCache<Object, Object> remoteCache;
abstract protected int numberOfHotRodServers();
abstract protected ConfigurationBuilder clusterConfig();
@Override
protected void createCacheManagers() throws Throwable {
final int numServers = numberOfHotRodServers();
hotrodServers = new HotRodServer[numServers];
createCluster(hotRodCacheConfiguration(clusterConfig()), numberOfHotRodServers());
for (int i = 0; i < numServers; i++) {
EmbeddedCacheManager cm = cacheManagers.get(i);
hotrodServers[i] = HotRodClientTestingUtil.startHotRodServer(cm);
}
String servers = HotRodClientTestingUtil.getServersString(hotrodServers);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServers(servers);
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
remoteCache = remoteCacheManager.getCache();
}
@AfterClass(alwaysRun = true)
public void release() {
killRemoteCacheManager(remoteCacheManager);
killServers(hotrodServers);
hotrodServers = null;
}
protected Set<Integer> populateCacheManager() {
Map<Integer, Integer> entries = new HashMap<Integer, Integer>();
for (int i = 0; i < 100; i++) {
entries.put(i, i);
}
remoteCache.putAll(entries);
return entries.keySet();
}
public void testBulkGetKeys() {
Set<Integer> keys = populateCacheManager();
Map<Object, Object> map = remoteCache.getAll(keys);
assertEquals(100, map.size());
for (int i = 0; i < 100; i++) {
assertEquals(i, map.get(i));
}
}
public void testBulkGetAfterLifespanExpire() throws InterruptedException {
Map<String, String> dataIn = new HashMap<String, String>();
dataIn.put("aKey", "aValue");
dataIn.put("bKey", "bValue");
final long startTime = System.currentTimeMillis();
final long lifespan = 10000;
remoteCache.putAll(dataIn, lifespan, TimeUnit.MILLISECONDS);
Map<Object, Object> dataOut = new HashMap<Object, Object>();
while (true) {
dataOut = remoteCache.getAll(dataIn.keySet());
if (System.currentTimeMillis() >= startTime + lifespan)
break;
assertEquals(dataOut.size(), dataIn.size());
for (Entry<Object, Object> outEntry : dataOut.entrySet()) {
assertEquals(dataIn.get(outEntry.getKey()), outEntry.getValue());
}
Thread.sleep(100);
}
int size = dataOut.size();
// Make sure that in the next 30 secs data is removed
while (System.currentTimeMillis() < startTime + lifespan + 30000) {
dataOut = remoteCache.getAll(dataIn.keySet());
if ((size = dataOut.size()) == 0) {
break;
}
}
assertEquals("There shouldn't be any values left!", 0, size);
}
}
| 4,200
| 34.601695
| 95
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/RoundRobinBalancingStrategyTest.java
|
package org.infinispan.client.hotrod;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNotSame;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.AssertJUnit.fail;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.infinispan.client.hotrod.impl.transport.tcp.RoundRobinBalancingStrategy;
import org.infinispan.test.AbstractInfinispanTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
@Test (groups = "unit", testName = "client.hotrod.RoundRobinBalancingStrategyTest")
public class RoundRobinBalancingStrategyTest extends AbstractInfinispanTest {
SocketAddress addr1 = new InetSocketAddress("localhost",1111);
SocketAddress addr2 = new InetSocketAddress("localhost",2222);
SocketAddress addr3 = new InetSocketAddress("localhost",3333);
SocketAddress addr4 = new InetSocketAddress("localhost",4444);
private List<SocketAddress> defaultServers;
private RoundRobinBalancingStrategy strategy;
@BeforeMethod
public void setUp() {
strategy = new RoundRobinBalancingStrategy();
defaultServers = new ArrayList<SocketAddress>();
defaultServers.add(addr1);
defaultServers.add(addr2);
defaultServers.add(addr3);
strategy.setServers(defaultServers);
}
public void simpleTest() {
// Starts with a random server
expectServerEventually(addr1, defaultServers, null);
assertEquals(addr2, strategy.nextServer(null));
assertEquals(addr3, strategy.nextServer(null));
assertEquals(addr1, strategy.nextServer(null));
assertEquals(addr2, strategy.nextServer(null));
assertEquals(addr3, strategy.nextServer(null));
assertEquals(addr1, strategy.nextServer(null));
assertEquals(addr2, strategy.nextServer(null));
assertEquals(addr3, strategy.nextServer(null));
}
public void testAddServer() {
List<SocketAddress> newServers = new ArrayList<SocketAddress>(defaultServers);
newServers.add(addr4);
strategy.setServers(newServers);
// Starts with a random server
expectServerEventually(addr1, newServers, null);
assertEquals(addr2, strategy.nextServer(null));
assertEquals(addr3, strategy.nextServer(null));
assertEquals(addr4, strategy.nextServer(null));
assertEquals(addr1, strategy.nextServer(null));
assertEquals(addr2, strategy.nextServer(null));
assertEquals(addr3, strategy.nextServer(null));
assertEquals(addr4, strategy.nextServer(null));
assertEquals(addr1, strategy.nextServer(null));
assertEquals(addr2, strategy.nextServer(null));
assertEquals(addr3, strategy.nextServer(null));
}
public void testRemoveServer() {
List<SocketAddress> newServers = new ArrayList<SocketAddress>(defaultServers);
newServers.remove(addr3);
strategy.setServers(newServers);
// Starts with a random server
expectServerEventually(addr1, newServers, null);
assertEquals(addr2, strategy.nextServer(null));
assertEquals(addr1, strategy.nextServer(null));
assertEquals(addr2, strategy.nextServer(null));
assertEquals(addr1, strategy.nextServer(null));
assertEquals(addr2, strategy.nextServer(null));
}
public void testRemoveServerAfterActivity() {
// Starts with a random server
expectServerEventually(addr1, defaultServers, null);
assertEquals(addr2, strategy.nextServer(null));
assertEquals(addr3, strategy.nextServer(null));
assertEquals(addr1, strategy.nextServer(null));
assertEquals(addr2, strategy.nextServer(null));
List<SocketAddress> newServers = new ArrayList<SocketAddress>(defaultServers);
newServers.remove(addr3);
strategy.setServers(newServers);
// Selects a new random server
expectServerEventually(addr1, newServers, null);
assertEquals(addr2, strategy.nextServer(null));
assertEquals(addr1, strategy.nextServer(null));
assertEquals(addr2, strategy.nextServer(null));
assertEquals(addr1, strategy.nextServer(null));
assertEquals(addr2, strategy.nextServer(null));
}
public void testAddServerAfterActivity() {
// Starts with a random server
expectServerEventually(addr1, defaultServers, null);
assertEquals(addr2, strategy.nextServer(null));
assertEquals(addr3, strategy.nextServer(null));
assertEquals(addr1, strategy.nextServer(null));
assertEquals(addr2, strategy.nextServer(null));
List<SocketAddress> newServers = new ArrayList<SocketAddress>(defaultServers);
newServers.add(addr4);
strategy.setServers(newServers);
// Selects a new random server
expectServerEventually(addr3, newServers, null);
assertEquals(addr4, strategy.nextServer(null));
assertEquals(addr1, strategy.nextServer(null));
assertEquals(addr2, strategy.nextServer(null));
assertEquals(addr3, strategy.nextServer(null));
assertEquals(addr4, strategy.nextServer(null));
assertEquals(addr1, strategy.nextServer(null));
assertEquals(addr2, strategy.nextServer(null));
assertEquals(addr3, strategy.nextServer(null));
assertEquals(addr4, strategy.nextServer(null));
}
public void testFailedServers1() {
strategy.setServers(defaultServers);
Set<SocketAddress> failedServers = Collections.singleton(addr1);
// other servers should be available
final int LOOPS = 10;
int c1 = 0, c2 = 0;
for (int i = 0; i < LOOPS; ++i) {
SocketAddress server = strategy.nextServer(failedServers);
assertNotNull(server);
assertNotSame(addr1, server);
if (server.equals(addr2)) {
c1++;
} else if (server.equals(addr3)) {
c2++;
}
}
assertEquals(LOOPS, c1 + c2);
assertTrue(Math.abs(c1 - c2) <= 1);
}
public void testFailedServers2() {
strategy.setServers(defaultServers);
Set<SocketAddress> failedServers = new HashSet<SocketAddress>(defaultServers);
// with all servers failed, the behaviour should be the same
expectServerEventually(addr1, defaultServers, failedServers);
assertEquals(addr2, strategy.nextServer(failedServers));
assertEquals(addr3, strategy.nextServer(failedServers));
assertEquals(addr1, strategy.nextServer(failedServers));
}
private void expectServerEventually(SocketAddress addr, List<SocketAddress> servers,
Set<SocketAddress> failedServers) {
for (int i = 0; i < servers.size(); i++) {
if (addr.equals(strategy.nextServer(failedServers)))
return;
}
fail("Did not get server " + addr + " after " + servers.size() + " attempts");
}
}
| 7,043
| 39.953488
| 87
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/HotRodIntegrationTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.assertHotRodEquals;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.infinispan.test.TestingUtil.k;
import static org.infinispan.test.TestingUtil.v;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
/**
* @author mmarkus
* @since 4.1
*/
@Test (testName = "client.hotrod.HotRodIntegrationTest", groups = {"functional", "smoke"} )
public class HotRodIntegrationTest extends SingleCacheManagerTest {
private static final Log log = LogFactory.getLog(HotRodIntegrationTest.class);
private static final String CACHE_NAME = "replSync";
RemoteCache<String, String> defaultRemote;
RemoteCache<Object, String> remoteCache;
private RemoteCacheManager remoteCacheManager;
protected HotRodServer hotrodServer;
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder builder = hotRodCacheConfiguration(
getDefaultStandaloneCacheConfig(false));
EmbeddedCacheManager cm = TestCacheManagerFactory
.createCacheManager(hotRodCacheConfiguration());
cm.defineConfiguration(CACHE_NAME, builder.build());
cm.getCache(CACHE_NAME);
return cm;
}
@Override
protected void setup() throws Exception {
super.setup();
//pass the config file to the cache
hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
log.info("Started server on port: " + hotrodServer.getPort());
remoteCacheManager = getRemoteCacheManager();
defaultRemote = remoteCacheManager.getCache();
remoteCache = remoteCacheManager.getCache(CACHE_NAME);
}
protected RemoteCacheManager getRemoteCacheManager() {
Properties config = new Properties();
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("localhost").port(hotrodServer.getPort());
return new RemoteCacheManager(clientBuilder.build());
}
@AfterClass
public void testDestroyRemoteCacheFactory() {
HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager);
HotRodClientTestingUtil.killServers(hotrodServer);
hotrodServer = null;
}
public void testPut() throws Exception {
assert null == remoteCache.put("aKey", "aValue");
assertHotRodEquals(cacheManager, CACHE_NAME, "aKey", "aValue");
assert null == defaultRemote.put("otherKey", "otherValue");
assertHotRodEquals(cacheManager, "otherKey", "otherValue");
assert remoteCache.containsKey("aKey");
assert defaultRemote.containsKey("otherKey");
assert remoteCache.get("aKey").equals("aValue");
assert defaultRemote.get("otherKey").equals("otherValue");
}
public void testRemove() throws Exception {
assert null == remoteCache.put("aKey", "aValue");
assertHotRodEquals(cacheManager, CACHE_NAME, "aKey", "aValue");
assert remoteCache.get("aKey").equals("aValue");
assert null == remoteCache.remove("aKey");
assertHotRodEquals(cacheManager, CACHE_NAME, "aKey", null);
assert !remoteCache.containsKey("aKey");
}
public void testContains() {
assert !remoteCache.containsKey("aKey");
remoteCache.put("aKey", "aValue");
assert remoteCache.containsKey("aKey");
}
public void testGetWithMetadata() {
MetadataValue<?> value = remoteCache.getWithMetadata("aKey");
assertNull("expected null but received: " + value, value);
remoteCache.put("aKey", "aValue");
assert remoteCache.get("aKey").equals("aValue");
MetadataValue<?> immortalValue = remoteCache.getWithMetadata("aKey");
assertNotNull(immortalValue);
assertEquals("aValue", immortalValue.getValue());
assertEquals(-1, immortalValue.getLifespan());
assertEquals(-1, immortalValue.getMaxIdle());
remoteCache.put("bKey", "bValue", 60, TimeUnit.SECONDS);
MetadataValue<?> mortalValueWithLifespan = remoteCache.getWithMetadata("bKey");
assertNotNull(mortalValueWithLifespan);
assertEquals("bValue", mortalValueWithLifespan.getValue());
assertEquals(60, mortalValueWithLifespan.getLifespan());
assertEquals(-1, mortalValueWithLifespan.getMaxIdle());
remoteCache.put("cKey", "cValue", 60, TimeUnit.SECONDS, 30, TimeUnit.SECONDS);
MetadataValue<?> mortalValueWithMaxIdle = remoteCache.getWithMetadata("cKey");
assertNotNull(mortalValueWithMaxIdle);
assertEquals("cValue", mortalValueWithMaxIdle.getValue());
assertEquals(60, mortalValueWithMaxIdle.getLifespan());
assertEquals(30, mortalValueWithMaxIdle.getMaxIdle());
}
public void testReplace() {
assert null == remoteCache.replace("aKey", "anotherValue");
remoteCache.put("aKey", "aValue");
assert null == remoteCache.replace("aKey", "anotherValue");
assert remoteCache.get("aKey").equals("anotherValue");
}
public void testReplaceIfUnmodified() {
assert null == remoteCache.replace("aKey", "aValue");
remoteCache.put("aKey", "aValue");
VersionedValue valueBinary = remoteCache.getWithMetadata("aKey");
assert remoteCache.replaceWithVersion("aKey", "aNewValue", valueBinary.getVersion());
VersionedValue entry2 = remoteCache.getWithMetadata("aKey");
assert entry2.getVersion() != valueBinary.getVersion();
assertEquals(entry2.getValue(), "aNewValue");
assert !remoteCache.replaceWithVersion("aKey", "aNewValue", valueBinary.getVersion());
}
public void testPutAllAndReplaceWithVersion(Method m ) {
String key = k(m);
remoteCache.putAll(Map.of(key, "A"));
MetadataValue<String> existingMetaDataValue = remoteCache.getWithMetadata(key);
assertEquals(existingMetaDataValue.getValue(), "A");
assertTrue(remoteCache.replaceWithVersion(key, "B", existingMetaDataValue.getVersion()));
assertEquals("B", remoteCache.get(key));
}
public void testPutAllUpdatingVersions(Method m) {
String key = k(m);
remoteCache.putAll(Map.of(key, "A"));
MetadataValue<String> prevMetadata = remoteCache.getWithMetadata(key);
assertEquals("A", prevMetadata.getValue());
String anotherKey = key + k(m);
remoteCache.putAll(Map.of(key, "B", anotherKey, "C"));
MetadataValue<String> currMetadata = remoteCache.getWithMetadata(key);
assertTrue(currMetadata.getVersion() > prevMetadata.getVersion());
assertEquals("B", currMetadata.getValue());
// Created entries receive the same version, no way to set version per entry w/ put all.
MetadataValue<String> anotherMetadata = remoteCache.getWithMetadata(anotherKey);
assertEquals(currMetadata.getVersion(), anotherMetadata.getVersion());
assertEquals("C", anotherMetadata.getValue());
}
public void testPutAllAndRemoveWithVersion(Method m) {
String key = k(m);
remoteCache.putAll(Map.of(key, "A"));
MetadataValue<String> prevMetadata = remoteCache.getWithMetadata(key);
assertEquals("A", prevMetadata.getValue());
String anotherKey = key + k(m);
remoteCache.putAll(Map.of(key, "B", anotherKey, "C"));
MetadataValue<String> currMetadata = remoteCache.getWithMetadata(key);
assertTrue(currMetadata.getVersion() > prevMetadata.getVersion());
assertFalse(remoteCache.removeWithVersion(key, prevMetadata.getVersion()));
assertEquals("B", remoteCache.get(key));
MetadataValue<String> anotherMetadata = remoteCache.getWithMetadata(anotherKey);
assertEquals(currMetadata.getVersion(), anotherMetadata.getVersion());
assertTrue(remoteCache.removeWithVersion(anotherKey, anotherMetadata.getVersion()));
}
public void testReplaceIfUnmodifiedWithExpiry(Method m) throws InterruptedException {
final int key = 1;
remoteCache.put(key, v(m));
VersionedValue valueBinary = remoteCache.getWithMetadata(key);
int lifespanSecs = 3; // seconds
long lifespan = TimeUnit.SECONDS.toMillis(lifespanSecs);
long startTime = System.currentTimeMillis();
String newValue = v(m, 2);
assert remoteCache.replaceWithVersion(key, newValue, valueBinary.getVersion(), lifespanSecs);
while (true) {
Object value = remoteCache.get(key);
if (System.currentTimeMillis() >= startTime + lifespan)
break;
assertEquals(v(m, 2), value);
Thread.sleep(100);
}
while (System.currentTimeMillis() < startTime + lifespan + 2000) {
if (remoteCache.get(key) == null) break;
Thread.sleep(50);
}
assertNull(remoteCache.get(key));
}
public void testReplaceWithVersionWithLifespanAsync(Method m) throws Exception {
int lifespanInSecs = 1; //seconds
final String k = k(m), v = v(m), newV = v(m, 2);
assertNull(remoteCache.replace(k, v));
remoteCache.put(k, v);
VersionedValue valueBinary = remoteCache.getWithMetadata(k);
long lifespan = TimeUnit.SECONDS.toMillis(lifespanInSecs);
long startTime = System.currentTimeMillis();
CompletableFuture<Boolean> future = remoteCache.replaceWithVersionAsync(
k, newV, valueBinary.getVersion(), lifespanInSecs);
assert future.get();
while (true) {
VersionedValue entry2 = remoteCache.getWithMetadata(k);
if (System.currentTimeMillis() >= startTime + lifespan)
break;
// version should have changed; value should have changed
assert entry2.getVersion() != valueBinary.getVersion();
assertEquals(newV, entry2.getValue());
Thread.sleep(100);
}
while (System.currentTimeMillis() < startTime + lifespan + 2000) {
if (remoteCache.get(k) == null) break;
Thread.sleep(50);
}
assertNull(remoteCache.getWithMetadata(k));
}
public void testRemoveIfUnmodified() {
assert !remoteCache.removeWithVersion("aKey", 12321212l);
remoteCache.put("aKey", "aValue");
VersionedValue valueBinary = remoteCache.getWithMetadata("aKey");
assert remoteCache.removeWithVersion("aKey", valueBinary.getVersion());
assertHotRodEquals(cacheManager, CACHE_NAME, "aKey", null);
remoteCache.put("aKey", "aNewValue");
VersionedValue entry2 = remoteCache.getWithMetadata("aKey");
assert entry2.getVersion() != valueBinary.getVersion();
assertEquals(entry2.getValue(), "aNewValue");
assert !remoteCache.removeWithVersion("aKey", valueBinary.getVersion());
}
public void testPutIfAbsent() {
remoteCache.put("aKey", "aValue");
assert null == remoteCache.putIfAbsent("aKey", "anotherValue");
assertEquals(remoteCache.get("aKey"),"aValue");
assertEquals(remoteCache.get("aKey"),"aValue");
assert remoteCache.containsKey("aKey");
assert true : remoteCache.replace("aKey", "anotherValue");
}
public void testClear() {
remoteCache.put("aKey", "aValue");
remoteCache.put("aKey2", "aValue");
remoteCache.clear();
assert !remoteCache.containsKey("aKey");
assert !remoteCache.containsKey("aKey2");
assert cache.isEmpty();
}
public void testPutWithPrevious() {
assert null == remoteCache.put("aKey", "aValue");
assert "aValue".equals(remoteCache.withFlags(Flag.FORCE_RETURN_VALUE).put("aKey", "otherValue"));
assert remoteCache.containsKey("aKey");
assert remoteCache.get("aKey").equals("otherValue");
}
public void testRemoveWithPrevious() {
assert null == remoteCache.put("aKey", "aValue");
assert remoteCache.get("aKey").equals("aValue");
assert "aValue".equals(remoteCache.withFlags(Flag.FORCE_RETURN_VALUE).remove("aKey"));
assert !remoteCache.containsKey("aKey");
}
public void testRemoveNonExistForceReturnPrevious() {
assertNull(remoteCache.withFlags(Flag.FORCE_RETURN_VALUE).remove("aKey"));
remoteCache.put("k", "v");
}
public void testReplaceWithPrevious() {
assert null == remoteCache.replace("aKey", "anotherValue");
remoteCache.put("aKey", "aValue");
assert "aValue".equals(remoteCache.withFlags(Flag.FORCE_RETURN_VALUE).replace("aKey", "anotherValue"));
assert remoteCache.get("aKey").equals("anotherValue");
}
public void testPutIfAbsentWithPrevious() {
remoteCache.put("aKey", "aValue");
assert null == remoteCache.putIfAbsent("aKey", "anotherValue");
Object existingValue = remoteCache.withFlags(Flag.FORCE_RETURN_VALUE).putIfAbsent("aKey", "anotherValue");
assert "aValue".equals(existingValue) : "Existing value was:" + existingValue;
}
public void testPutSerializableByteArray() {
RemoteCache<Object, byte[]> binaryRemote = remoteCacheManager.getCache();
byte[] bytes = serializeObject(new MyValue<>("aValue"));
binaryRemote.put("aKey", bytes);
assertArrayEquals(bytes, binaryRemote.get("aKey"));
}
private byte[] serializeObject(Object obj) {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
try {
ObjectOutputStream os = new ObjectOutputStream(bs);
os.writeObject(obj);
os.close();
return bs.toByteArray();
} catch (IOException ioe) {
throw new AssertionError(ioe);
}
}
static class MyValue<V> implements Serializable {
final V value;
MyValue(V value) {
this.value = value;
}
}
}
| 14,698
| 38.197333
| 112
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/GetAllLocalTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
/**
* Tests functionality related to getting getting multiple entries using a local
* cache
*
* @author William Burns
* @since 7.2
*/
@Test(testName = "client.hotrod.GetAllLocalTest", groups = "functional")
public class GetAllLocalTest extends BaseGetAllTest {
@Override
protected int numberOfHotRodServers() {
return 1;
}
@Override
protected ConfigurationBuilder clusterConfig() {
return hotRodCacheConfiguration(getDefaultClusteredCacheConfig(
CacheMode.LOCAL, false));
}
}
| 812
| 26.1
| 91
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/HitsAwareCacheManagersTest.java
|
package org.infinispan.client.hotrod;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.test.TestingUtil.blockUntilCacheStatusAchieved;
import static org.infinispan.test.TestingUtil.blockUntilViewReceived;
import static org.infinispan.test.TestingUtil.killCacheManagers;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commands.read.AbstractDataCommand;
import org.infinispan.commands.read.EntrySetCommand;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.FlagBitSets;
import org.infinispan.interceptors.BaseAsyncInterceptor;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.manager.CacheContainer;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder;
import org.infinispan.server.hotrod.test.HotRodTestingUtil;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeMethod;
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
public abstract class HitsAwareCacheManagersTest extends MultipleCacheManagersTest {
protected Map<SocketAddress, HotRodServer> addr2hrServer = new LinkedHashMap<>();
protected List<RemoteCacheManager> clients = new ArrayList<>();
protected void createHotRodServers(int num, ConfigurationBuilder defaultBuilder) {
// Start Hot Rod servers
for (int i = 0; i < num; i++) addHotRodServer(defaultBuilder);
// Verify that default caches should be started
for (int i = 0; i < num; i++) assert manager(i).getCache() != null;
// Block until views have been received
blockUntilViewReceived(manager(0).getCache(), num);
// Verify that caches running
for (int i = 0; i < num; i++) {
blockUntilCacheStatusAchieved(
manager(i).getCache(), ComponentStatus.RUNNING, 10000);
}
// Add hits tracking interceptors
addInterceptors();
for (int i = 0; i < num; i++) {
clients.add(createClient());
}
}
protected RemoteCacheManager client(int i) {
return clients.get(i);
}
protected RemoteCacheManager createClient() {
return new RemoteCacheManager(createHotRodClientConfigurationBuilder(
addr2hrServer.values().iterator().next().getPort()).build());
}
protected org.infinispan.client.hotrod.configuration.ConfigurationBuilder createHotRodClientConfigurationBuilder(int serverPort) {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer()
.host("localhost")
.port(serverPort);
clientBuilder.maxRetries(2);
return clientBuilder;
}
protected HotRodServer addHotRodServer(ConfigurationBuilder builder) {
EmbeddedCacheManager cm = addClusterEnabledCacheManager(builder);
HotRodServer server = HotRodClientTestingUtil.startHotRodServer(cm);
InetSocketAddress addr = new InetSocketAddress(server.getHost(), server.getPort());
addr2hrServer.put(addr, server);
return server;
}
protected HotRodServer addHotRodServer(ConfigurationBuilder builder, int port) {
EmbeddedCacheManager cm = addClusterEnabledCacheManager(builder);
HotRodServer server = HotRodTestingUtil.startHotRodServer(
cm, port, new HotRodServerConfigurationBuilder());
InetSocketAddress addr = new InetSocketAddress(server.getHost(), server.getPort());
addr2hrServer.put(addr, server);
return server;
}
protected void killServer() {
Iterator<HotRodServer> it = addr2hrServer.values().iterator();
HotRodServer server = it.next();
EmbeddedCacheManager cm = server.getCacheManager();
it.remove();
killServers(server);
killCacheManagers(cm);
cacheManagers.remove(cm);
}
@Override
@BeforeMethod(alwaysRun=true)
public void createBeforeMethod() throws Throwable {
if (cleanupAfterMethod()) {
addr2hrServer.clear();
}
super.createBeforeMethod();
}
protected HitCountInterceptor getHitCountInterceptor(Cache<?, ?> cache) {
return cache.getAdvancedCache().getAsyncInterceptorChain().findInterceptorWithClass(HitCountInterceptor.class);
}
protected void assertOnlyServerHit(SocketAddress serverAddress) {
assertServerHit(serverAddress, null, 1);
}
protected void assertServerHit(SocketAddress serverAddress, String cacheName, int expectedHits) {
CacheContainer cacheContainer = addr2hrServer.get(serverAddress).getCacheManager();
HitCountInterceptor interceptor = getHitCountInterceptor(namedCache(cacheName, cacheContainer));
assert interceptor.getHits() == expectedHits :
"Expected " + expectedHits + " hit(s) for " + serverAddress + " but received " + interceptor.getHits();
for (HotRodServer server : addr2hrServer.values()) {
if (server.getCacheManager() != cacheContainer) {
interceptor = getHitCountInterceptor(namedCache(cacheName, server.getCacheManager()));
assert interceptor.getHits() == 0 :
"Expected 0 hits in " + serverAddress + " but got " + interceptor.getHits();
}
}
}
private Cache<?, ?> namedCache(String cacheName, CacheContainer cacheContainer) {
return cacheName == null ? cacheContainer.getCache() : cacheContainer.getCache(cacheName);
}
protected void assertNoHits() {
for (HotRodServer server : addr2hrServer.values()) {
HitCountInterceptor interceptor = getHitCountInterceptor(server.getCacheManager().getCache());
assert interceptor.getHits() == 0 : "Expected 0 hits but got " + interceptor.getHits();
}
}
protected InetSocketAddress getAddress(HotRodServer hotRodServer) {
InetSocketAddress socketAddress = InetSocketAddress.createUnresolved(hotRodServer.getHost(), hotRodServer.getPort());
addr2hrServer.put(socketAddress, hotRodServer);
return socketAddress;
}
protected void resetStats() {
for (EmbeddedCacheManager manager : cacheManagers) {
HitCountInterceptor cmi = getHitCountInterceptor(manager.getCache());
cmi.reset();
}
}
protected void addInterceptors() {
addInterceptors((String)null);
}
protected void addInterceptors(String cacheName) {
for (EmbeddedCacheManager manager : cacheManagers) {
Cache<?, ?> cache = namedCache(cacheName, manager);
addInterceptors(cache);
}
}
protected void addInterceptors(Cache<?, ?> cache) {
addHitCountInterceptor(cache);
}
private void addHitCountInterceptor(Cache<?, ?> cache) {
HitCountInterceptor interceptor = new HitCountInterceptor();
cache.getAdvancedCache().getAsyncInterceptorChain().addInterceptor(interceptor, 1);
}
@AfterClass(alwaysRun = true)
protected void destroy() {
clients.forEach(HotRodClientTestingUtil::killRemoteCacheManager);
addr2hrServer.values().forEach(HotRodClientTestingUtil::killServers);
addr2hrServer.clear();
super.destroy();
}
/**
* @author Mircea.Markus@jboss.com
* @since 4.1
*/
public static class HitCountInterceptor extends BaseAsyncInterceptor {
private static final Log log = LogFactory.getLog(HitCountInterceptor.class);
private final AtomicInteger localSiteInvocationCount = new AtomicInteger(0);
private final AtomicInteger backupSiteInvocationCount = new AtomicInteger(0);
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) {
if (command instanceof EntrySetCommand) {
return invokeNext(ctx, command);
}
if (ctx.isOriginLocal()) {
if ((command instanceof AbstractDataCommand) && ((AbstractDataCommand)command).hasAnyFlag(FlagBitSets.SKIP_XSITE_BACKUP)) {
int count = backupSiteInvocationCount.incrementAndGet();
log.debugf("Backup Hit %d for %s", count, command);
} else {
int count = localSiteInvocationCount.incrementAndGet();
log.debugf("Local Hit %d for %s", count, command);
}
}
return invokeNext(ctx, command);
}
public int getHits() {
return localSiteInvocationCount.get();
}
public void reset() {
localSiteInvocationCount.set(0);
backupSiteInvocationCount.set(0);
}
}
}
| 9,160
| 38.149573
| 142
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/stress/ClusterClientEventStressTest.java
|
package org.infinispan.client.hotrod.stress;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.toBytes;
import static org.infinispan.distribution.DistributionTestHelper.isFirstOwner;
import static org.infinispan.distribution.DistributionTestHelper.isOwner;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.event.ClientEvent;
import org.infinispan.client.hotrod.logging.Log;
import org.infinispan.client.hotrod.logging.LogFactory;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.InternalRemoteCacheManager;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.commons.test.TestResourceTracker;
import org.testng.annotations.Test;
@Test(groups = "stress", testName = "client.hotrod.event.ClusterClientEventStressTest", timeOut = 15*60*1000)
public class ClusterClientEventStressTest extends MultiHotRodServersTest {
private static final Log log = LogFactory.getLog(ClusterClientEventStressTest.class);
static final int NUM_SERVERS = 3;
static final int NUM_OWNERS = 2;
static final int NUM_CLIENTS = 1;
static final int NUM_THREADS_PER_CLIENT = 6;
// static final int NUM_THREADS_PER_CLIENT = 36;
static final int NUM_OPERATIONS = 1_000; // per thread, per client
// static final int NUM_OPERATIONS = 300; // per thread, per client
// static final int NUM_OPERATIONS = 600; // per thread, per client
static final int NUM_EVENTS = NUM_OPERATIONS * NUM_THREADS_PER_CLIENT * NUM_CLIENTS * NUM_CLIENTS;
// public static final int NUM_STORES = NUM_OPERATIONS * NUM_CLIENTS * NUM_THREADS_PER_CLIENT;
// public static final int NUM_STORES_PER_SERVER = NUM_STORES / NUM_SERVERS;
// public static final int NUM_ENTRIES_PER_SERVER = (NUM_STORES * NUM_OWNERS) / NUM_SERVERS;
static Set<String> ALL_KEYS = ConcurrentHashMap.newKeySet();
static ExecutorService EXEC = Executors.newCachedThreadPool();
static ClientEntryListener listener;
@Override
protected void createCacheManagers() throws Throwable {
createHotRodServers(NUM_SERVERS, getCacheConfiguration());
}
private ConfigurationBuilder getCacheConfiguration() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
builder.clustering().hash().numOwners(NUM_OWNERS)
// .expiration().lifespan(1000).maxIdle(1000).wakeUpInterval(5000)
.expiration().maxIdle(1000).wakeUpInterval(5000)
.statistics().enable();
return hotRodCacheConfiguration(builder);
}
RemoteCacheManager getRemoteCacheManager(int port) {
org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(port);
RemoteCacheManager rcm = new InternalRemoteCacheManager(builder.build());
rcm.getCache();
return rcm;
}
Map<String, RemoteCacheManager> createClients() {
Map<String, RemoteCacheManager> remotecms = new HashMap<>(NUM_CLIENTS);
for (int i = 0; i < NUM_CLIENTS; i++)
remotecms.put("c" + i, getRemoteCacheManager(server(0).getPort()));
return remotecms;
}
public void testAddClientListenerDuringOperations() {
TestResourceTracker.testThreadStarted(this.getTestName());
CyclicBarrier barrier = new CyclicBarrier((NUM_CLIENTS * NUM_THREADS_PER_CLIENT) + 1);
List<Future<Void>> futures = new ArrayList<>(NUM_CLIENTS * NUM_THREADS_PER_CLIENT);
List<ClientEntryListener> listeners = new ArrayList<>(NUM_CLIENTS);
Map<String, RemoteCacheManager> remotecms = createClients();
// assertStatsBefore(remotecms);
for (Entry<String, RemoteCacheManager> e : remotecms.entrySet()) {
RemoteCache<String, String> remote = e.getValue().getCache();
ClientEntryListener listener = new ClientEntryListener();
listeners.add(listener);
remote.addClientListener(listener);
for (int i = 0; i < NUM_THREADS_PER_CLIENT; i++) {
String prefix = String.format("%s-t%d-", e.getKey(), i);
Callable<Void> call = new Put(prefix, barrier, remote, servers);
futures.add(EXEC.submit(call));
}
}
barrierAwait(barrier); // wait for all threads to be ready
barrierAwait(barrier); // wait for all threads to finish
for (Future<Void> f : futures)
futureGet(f);
// log.debugf("Put operations completed, assert statistics");
// assertStatsAfter(remotecms);
log.debugf("Stats asserted, wait for events...");
eventuallyEquals(NUM_EVENTS, () -> countEvents(listeners));
}
int countEvents(List<ClientEntryListener> listeners) {
Integer count = listeners.stream().reduce(0, (acc, l) -> acc + l.count.get(), (x, y) -> x + y);
log.infof("Event count is %d, target %d%n", (int) count, NUM_EVENTS);
return count;
}
// void assertStatsBefore(Map<String, RemoteCacheManager> remotecms) {
// RemoteCacheManager client = remotecms.values().iterator().next();
// IntStream.range(0, NUM_SERVERS)
// .forEach(x -> {
// ServerStatistics stat = client.getCache().stats();
// assertEquals(0, stat.getIntStatistic(STORES).intValue());
// assertEquals(0, stat.getIntStatistic(CURRENT_NR_OF_ENTRIES).intValue());
// });
// }
//
// void assertStatsAfter(Map<String, RemoteCacheManager> remotecms) {
// RemoteCacheManager client = remotecms.values().iterator().next();
// IntStream.range(0, NUM_SERVERS)
// .forEach(x -> {
// ServerStatistics stat = client.getCache().stats();
// int stores = stat.getIntStatistic(STORES);
// System.out.println("Number of stores: " + stores);
// assertEquals(NUM_STORES_PER_SERVER, stores);
// int entries = stat.getIntStatistic(CURRENT_NR_OF_ENTRIES);
// assertEquals(NUM_ENTRIES_PER_SERVER, entries);
// });
// }
static class Put implements Callable<Void> {
static final ThreadLocalRandom R = ThreadLocalRandom.current();
final CyclicBarrier barrier;
final RemoteCache<String, String> remote;
final List<HotRodServer> servers;
final List<String> keys;
public Put(String prefix, CyclicBarrier barrier,
RemoteCache<String, String> remote, List<HotRodServer> servers) {
this.barrier = barrier;
this.remote = remote;
this.servers = servers;
this.keys = generateKeys(prefix, servers, R);
Collections.shuffle(this.keys);
}
@Override
public Void call() throws Exception {
barrierAwait(barrier);
try {
for (int i = 0; i < NUM_OPERATIONS; i++) {
String value = keys.get(i);
remote.put(value, value);
if (value.startsWith("c0-t0") && i == (NUM_OPERATIONS / 2)) {
listener = new ClientEntryListener();
remote.addClientListener(listener);
}
}
return null;
} finally {
barrierAwait(barrier);
}
}
}
static List<String> generateKeys(String prefix, List<HotRodServer> servers, ThreadLocalRandom r) {
List<String> keys = new ArrayList<>();
List<HotRodServer[]> combos = Arrays.asList(
new HotRodServer[]{servers.get(0), servers.get(1)},
new HotRodServer[]{servers.get(1), servers.get(0)},
new HotRodServer[]{servers.get(1), servers.get(2)},
new HotRodServer[]{servers.get(2), servers.get(1)},
new HotRodServer[]{servers.get(2), servers.get(0)},
new HotRodServer[]{servers.get(0), servers.get(2)}
);
for (int i = 0; i < NUM_OPERATIONS; i++) {
HotRodServer[] owners = combos.get(i % combos.size());
String key = getStringKey(prefix, owners, r);
if (ALL_KEYS.contains(key))
throw new AssertionError("Key already in use: " + key);
keys.add(key);
ALL_KEYS.add(key);
}
return keys;
}
static String getStringKey(String prefix, HotRodServer[] owners, ThreadLocalRandom r) {
Cache<?, ?> firstOwnerCache = owners[0].getCacheManager().getCache();
Cache<?, ?> otherOwnerCache = owners[1].getCacheManager().getCache();
// Random r = new Random();
byte[] dummy;
String dummyKey;
int attemptsLeft = 1000;
do {
Integer dummyInt = r.nextInt();
dummyKey = prefix + dummyInt;
dummy = toBytes(dummyKey);
attemptsLeft--;
} while (!(isFirstOwner(firstOwnerCache, dummy) && isOwner(otherOwnerCache, dummy))
&& attemptsLeft >= 0);
if (attemptsLeft < 0)
throw new IllegalStateException("Could not find any key owned by "
+ firstOwnerCache + " as primary owner and "
+ otherOwnerCache + " as secondary owner");
log.infof("Integer key %s hashes to primary [cluster=%s,hotrod=%s] and secondary [cluster=%s,hotrod=%s]",
dummyKey,
firstOwnerCache.getCacheManager().getAddress(), owners[0].getAddress(),
otherOwnerCache.getCacheManager().getAddress(), owners[1].getAddress());
return dummyKey;
}
static int barrierAwait(CyclicBarrier barrier) {
try {
return barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
throw new AssertionError(e);
}
}
static <T> T futureGet(Future<T> future) {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
throw new AssertionError(e);
}
}
@ClientListener
static class ClientEntryListener {
final AtomicInteger count = new AtomicInteger();
@ClientCacheEntryCreated
@ClientCacheEntryModified
@SuppressWarnings("unused")
public void handleClientEvent(ClientEvent event) {
int countSoFar;
if ((countSoFar = count.incrementAndGet()) % 100 == 0) {
log.debugf("Reached %s", countSoFar);
}
}
}
}
| 11,502
| 38.802768
| 111
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/stress/RemoteQueryDslPerfTest.java
|
package org.infinispan.client.hotrod.stress;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT_TYPE;
import static org.infinispan.configuration.cache.IndexStorage.LOCAL_HEAP;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.query.testdomain.protobuf.marshallers.TestDomainSCI;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.query.Search;
import org.infinispan.query.dsl.Query;
import org.infinispan.query.dsl.QueryFactory;
import org.infinispan.query.dsl.embedded.testdomain.User;
import org.infinispan.query.dsl.embedded.testdomain.hsearch.UserHS;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Perf test for remote query. This test runs storing objects so we can also run queries with lucene directly and
* compare the performance.
*
* @author anistor@redhat.com
* @since 7.2
*/
@Test(groups = "stress", testName = "client.hotrod.stress.RemoteQueryDslPerfTest", timeOut = 15 * 60 * 1000)
public class RemoteQueryDslPerfTest extends MultipleCacheManagersTest {
protected HotRodServer hotRodServer;
protected RemoteCacheManager remoteCacheManager;
protected RemoteCache<Object, Object> remoteCache;
protected Cache<Object, Object> cache;
private static final int WRITE_LOOPS = 10000;
private static final int QUERY_LOOPS = 100000;
@Override
protected void clearContent() {
// Don't clear, this is destroying the index
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = hotRodCacheConfiguration();
builder.encoding().key().mediaType(APPLICATION_OBJECT_TYPE);
builder.encoding().value().mediaType(APPLICATION_OBJECT_TYPE);
builder.indexing().enable()
.storage(LOCAL_HEAP)
.addIndexedEntity(UserHS.class);
createClusteredCaches(1, TestDomainSCI.INSTANCE, builder);
cache = manager(0).getCache();
hotRodServer = HotRodClientTestingUtil.startHotRodServer(manager(0));
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServer().host("127.0.0.1").port(hotRodServer.getPort()).addContextInitializer(TestDomainSCI.INSTANCE);
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
remoteCache = remoteCacheManager.getCache();
}
@AfterClass(alwaysRun = true)
public void release() {
killRemoteCacheManager(remoteCacheManager);
remoteCacheManager = null;
killServers(hotRodServer);
hotRodServer = null;
}
@BeforeClass(alwaysRun = true)
protected void populateCache() {
for (int i = 0; i < WRITE_LOOPS; i++) {
// create the test objects
User user1 = new UserHS();
int id1 = i * 10 + 1;
user1.setId(id1);
user1.setName("John" + id1);
user1.setSurname("Doe" + id1);
user1.setAge(22);
user1.setAccountIds(new HashSet<>(Arrays.asList(1, 2)));
user1.setNotes("Lorem ipsum dolor sit amet");
User user2 = new UserHS();
int id2 = i * 10 + 2;
user2.setId(id2);
user2.setName("Spider" + id2);
user2.setSurname("Man" + id2);
user2.setAccountIds(Collections.singleton(3));
User user3 = new UserHS();
int id3 = i * 10 + 3;
user3.setId(id3);
user3.setName("Spider" + id3);
user3.setSurname("Woman" + id3);
cache.put("user_" + user1.getId(), user1);
cache.put("user_" + user2.getId(), user2);
cache.put("user_" + user3.getId(), user3);
}
}
public void testRemoteQueryDslExecution() {
QueryFactory qf = org.infinispan.client.hotrod.Search.getQueryFactory(remoteCache);
String queryString = "FROM sample_bank_account.User WHERE name = 'John1'";
final long startTs = System.nanoTime();
for (int i = 0; i < QUERY_LOOPS; i++) {
Query<User> q = qf.create(queryString);
List<User> list = q.execute().list();
assertEquals(1, list.size());
assertEquals("John1", list.get(0).getName());
}
final long duration = (System.nanoTime() - startTs) / QUERY_LOOPS;
// this is around 600 us
System.out.printf("Remote execution took %d us per query\n", TimeUnit.NANOSECONDS.toMicros(duration));
}
public void testEmbeddedQueryDslExecution() {
QueryFactory qf = Search.getQueryFactory(cache);
String queryString = String.format("FROM %s WHERE name = 'John1'", UserHS.class.getName());
final long startTs = System.nanoTime();
for (int i = 0; i < QUERY_LOOPS; i++) {
Query<User> q = qf.create(queryString);
List<User> list = q.execute().list();
assertEquals(1, list.size());
assertEquals("John1", list.get(0).getName());
}
final long duration = (System.nanoTime() - startTs) / QUERY_LOOPS;
// this is around 300 us
System.out.printf("Embedded execution took %d us per query\n", TimeUnit.NANOSECONDS.toMicros(duration));
}
}
| 5,945
| 38.64
| 142
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/stress/AbstractPutAllPerfTest.java
|
package org.infinispan.client.hotrod.stress;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
/**
* Tests putAll performance with large and small data sets
*
* @author William Burns
* @since 7.2
*/
@Test(groups = "stress")
public abstract class AbstractPutAllPerfTest extends MultipleCacheManagersTest {
protected HotRodServer[] hotrodServers;
protected RemoteCacheManager remoteCacheManager;
protected RemoteCache<Object, Object> remoteCache;
abstract protected int numberOfHotRodServers();
abstract protected ConfigurationBuilder clusterConfig();
protected final long millisecondsToRun = TimeUnit.MINUTES.toMillis(1);
@Override
protected void createCacheManagers() throws Throwable {
final int numServers = numberOfHotRodServers();
hotrodServers = new HotRodServer[numServers];
createCluster(hotRodCacheConfiguration(clusterConfig()), numberOfHotRodServers());
for (int i = 0; i < numServers; i++) {
EmbeddedCacheManager cm = cacheManagers.get(i);
hotrodServers[i] = HotRodClientTestingUtil.startHotRodServer(cm);
}
String servers = HotRodClientTestingUtil.getServersString(hotrodServers);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServers(servers);
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
remoteCache = remoteCacheManager.getCache();
}
@AfterClass(alwaysRun = true)
public void release() {
killRemoteCacheManager(remoteCacheManager);
remoteCacheManager = null;
killServers(hotrodServers);
hotrodServers = null;
}
protected void runTest(int size, String name) {
long begin = System.currentTimeMillis();
int iterations = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Random random = new Random();
long currentTime;
while (millisecondsToRun + begin > (currentTime = System.currentTimeMillis())) {
map.clear();
for (int i = 0; i < size; ++i) {
int value = random.nextInt(Integer.MAX_VALUE);
map.put(value, value);
}
remoteCache.putAll(map);
iterations++;
}
long totalTime = currentTime - begin;
System.out.println(name + " - Performed " + iterations + " in " + totalTime + " ms generating " +
iterations / (totalTime / 1000) + " ops/sec");
}
public void test5Input() {
runTest(5, "test5Input");
}
public void test500Input() {
runTest(500, "test500Input");
}
public void test50000Input() {
runTest(50000, "test50000Input");
}
}
| 3,538
| 34.039604
| 103
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/stress/DistGetAllPerfTest.java
|
package org.infinispan.client.hotrod.stress;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
@Test(groups = "stress", testName="org.infinispan.client.hotrod.stress.DistGetAllPerfTest", timeOut = 15*60*1000)
public class DistGetAllPerfTest extends AbstractGetAllPerfTest {
@Override
protected int numberOfHotRodServers() {
return 5;
}
@Override
protected ConfigurationBuilder clusterConfig() {
return hotRodCacheConfiguration(getDefaultClusteredCacheConfig(
CacheMode.DIST_SYNC, false));
}
}
| 735
| 31
| 113
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/stress/ReplGetAllPerfTest.java
|
package org.infinispan.client.hotrod.stress;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
@Test(groups = "stress", testName="org.infinispan.client.hotrod.stress.ReplGetAllPerfTest", timeOut = 15*60*1000)
public class ReplGetAllPerfTest extends AbstractGetAllPerfTest {
@Override
protected int numberOfHotRodServers() {
return 5;
}
@Override
protected ConfigurationBuilder clusterConfig() {
return hotRodCacheConfiguration(getDefaultClusteredCacheConfig(
CacheMode.REPL_SYNC, false));
}
}
| 735
| 31
| 113
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/stress/DistPutAllPerfTest.java
|
package org.infinispan.client.hotrod.stress;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
@Test(groups = "stress", testName="org.infinispan.client.hotrod.stress.DistPutAllPerfTest", timeOut = 15*60*1000)
public class DistPutAllPerfTest extends AbstractPutAllPerfTest {
@Override
protected int numberOfHotRodServers() {
return 5;
}
@Override
protected ConfigurationBuilder clusterConfig() {
return hotRodCacheConfiguration(getDefaultClusteredCacheConfig(
CacheMode.DIST_SYNC, false));
}
}
| 735
| 31
| 113
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/stress/ClientConsistentHashPerfTest.java
|
package org.infinispan.client.hotrod.stress;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.net.SocketAddress;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.impl.consistenthash.ConsistentHash;
import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory;
import org.infinispan.client.hotrod.test.MultiHotRodServersTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
/**
* Test the performance of ConsistentHashV1/V2.
*
* @author Dan Berindei
* @since 5.3
*/
@Test(groups = "profiling", testName = "client.hotrod.stress.ClientConsistentHashPerfTest")
public class ClientConsistentHashPerfTest extends MultiHotRodServersTest {
private static final int NUM_SERVERS = 64;
private static final int ITERATIONS = 10000000;
private static final int NUM_KEYS = 100000;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder config = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
createHotRodServers(NUM_SERVERS, config);
}
public void testConsistentHashPerf() throws Exception {
RemoteCacheManager rcm = client(0);
RemoteCache<Object, Object> cache = rcm.getCache();
// This will initialize the consistent hash
cache.put("k", "v");
ChannelFactory channelFactory = TestingUtil.extractField(rcm, "channelFactory");
ConsistentHash ch = channelFactory.getConsistentHash(RemoteCacheManager.cacheNameBytes());
byte[][] keys = new byte[NUM_KEYS][];
for (int i = 0; i < NUM_KEYS; i++) {
keys[i] = String.valueOf(i).getBytes(UTF_8);
}
SocketAddress aServer = null;
// warm-up
for (int i = 0; i < ITERATIONS/10; i++) {
SocketAddress server = ch.getServer(keys[i % keys.length]);
if (server != null) aServer = server;
}
long startNanos = System.nanoTime();
for (int i = 0; i < ITERATIONS; i++) {
SocketAddress server = ch.getServer(keys[i % keys.length]);
if (server != null) aServer = server;
}
double duration = System.nanoTime() - startNanos;
log.infof("Test took %.3f s, average CH lookup was %.3f ns", duration / 1000000000L, duration / ITERATIONS);
}
}
| 2,463
| 36.333333
| 114
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/stress/HotRodLocalProfilingTest.java
|
package org.infinispan.client.hotrod.stress;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
/**
* A simple test that stresses a local HotRod server.
*
* @author Dan Berindei
* @since 8.1
*/
@Test(groups = "profiling", testName = "client.hotrod.profiling.HotRodLocalProfilingTest")
public class HotRodLocalProfilingTest extends SingleCacheManagerTest {
public void testPutBigSizeValue() {
System.out.println("Starting test");
long nanos = System.nanoTime();
HotRodServer hotRodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager);
String servers = HotRodClientTestingUtil.getServersString(hotRodServer);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServers(servers);
RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
RemoteCache<Object, Object> remoteCache = remoteCacheManager.getCache();
for (int i = 0; i < 10000000; i++) {
byte[] key = ("key" + i).getBytes();
byte[] value = ("value" + i).getBytes();
remoteCache.put(key, value);
if ((i & 0xFFFF) == 0xFFFF) {
System.out.println("Written " + i + " entries.");
}
}
System.out.println("Test took " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - nanos) + "ms.");
}
@AfterMethod
@Override
protected void clearContent() {
// Do nothing
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder configuration = new ConfigurationBuilder();
configuration.clustering().cacheMode(CacheMode.REPL_SYNC);
return TestCacheManagerFactory.createClusteredCacheManager(configuration);
}
}
| 2,397
| 38.966667
| 106
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/stress/AbstractGetAllPerfTest.java
|
package org.infinispan.client.hotrod.stress;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killRemoteCacheManager;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.killServers;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
/**
* Tests getAll performance with large and small data sets
*
* @author William Burns
* @since 7.2
*/
@Test(groups = "stress")
public abstract class AbstractGetAllPerfTest extends MultipleCacheManagersTest {
protected HotRodServer[] hotrodServers;
protected RemoteCacheManager remoteCacheManager;
protected RemoteCache<Object, Object> remoteCache;
abstract protected int numberOfHotRodServers();
abstract protected ConfigurationBuilder clusterConfig();
protected final long millisecondsToRun = TimeUnit.MINUTES.toMillis(1);
@Override
protected void createCacheManagers() throws Throwable {
final int numServers = numberOfHotRodServers();
hotrodServers = new HotRodServer[numServers];
createCluster(hotRodCacheConfiguration(clusterConfig()), numberOfHotRodServers());
for (int i = 0; i < numServers; i++) {
EmbeddedCacheManager cm = cacheManagers.get(i);
hotrodServers[i] = HotRodClientTestingUtil.startHotRodServer(cm);
}
String servers = HotRodClientTestingUtil.getServersString(hotrodServers);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
clientBuilder.addServers(servers);
remoteCacheManager = new RemoteCacheManager(clientBuilder.build());
remoteCache = remoteCacheManager.getCache();
}
@AfterClass(alwaysRun = true)
public void release() {
killRemoteCacheManager(remoteCacheManager);
remoteCacheManager = null;
killServers(hotrodServers);
hotrodServers = null;
}
protected void runTest(int size, int possibilities, String name) {
assertTrue(possibilities > size);
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < size; ++i) {
map.put(i, i);
}
remoteCache.putAll(map);
long begin = System.currentTimeMillis();
int iterations = 0;
Set<Integer> set = new HashSet<Integer>();
Random random = new Random();
long currentTime;
while (millisecondsToRun + begin > (currentTime = System.currentTimeMillis())) {
int count = 0;
set.clear();
for (int i = 0; i < size;) {
int value = random.nextInt(possibilities);
if (set.add(value)) {
i++;
if (value < size) {
count++;
}
}
}
assertEquals(count, remoteCache.getAll(set).size());
iterations++;
}
long totalTime = currentTime - begin;
System.out.println(name + " - Performed " + iterations + " in " + totalTime + " ms generating " +
iterations / (totalTime / 1000) + " ops/sec");
}
public void test5Input() {
runTest(5, 8, "test5Input");
}
public void test500Input() {
runTest(500, 800, "test500Input");
}
public void test50000Input() {
runTest(50000, 80000, "test50000Input");
}
}
| 4,067
| 33.769231
| 103
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/stress/ReplPutAllPerfTest.java
|
package org.infinispan.client.hotrod.stress;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
@Test(groups = "stress", testName="org.infinispan.client.hotrod.stress.ReplPutAllPerfTest", timeOut = 15*60*1000)
public class ReplPutAllPerfTest extends AbstractPutAllPerfTest {
@Override
protected int numberOfHotRodServers() {
return 5;
}
@Override
protected ConfigurationBuilder clusterConfig() {
return hotRodCacheConfiguration(getDefaultClusteredCacheConfig(
CacheMode.REPL_SYNC, false));
}
}
| 735
| 31
| 113
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/stress/RemoteClientPutGetTest.java
|
package org.infinispan.client.hotrod.stress;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.commons.test.TestResourceTracker;
import org.infinispan.commons.util.Util;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Simple PUTs/GETs test to verify performance regressions. Requires an external running server.
*/
@Test(groups = "stress", testName = "org.infinispan.client.hotrod.stress.RemoteClientPutGetTest", timeOut = 15*60*1000)
public class RemoteClientPutGetTest {
private RemoteCache<String, Object> cache;
private static final int NUMBER_OF_ENTRIES = 100_000;
private static final int THREAD_COUNT = 10;
private static final int GET_OPERATIONS = 100_000;
public static void main(String[] args) throws Exception {
RemoteClientPutGetTest testCase = new RemoteClientPutGetTest();
testCase.prepare();
testCase.putTest();
testCase.getTest();
}
@BeforeClass
public void prepare() {
TestResourceTracker.testStarted(RemoteClientPutGetTest.class.getName());
RemoteCacheManager cacheManager = new RemoteCacheManager(
HotRodClientTestingUtil.newRemoteConfigurationBuilder()
.addServer().host("localhost").port(11222)
.build());
cache = cacheManager.getCache();
cache.clear();
}
@AfterClass(alwaysRun = true)
public void afterClass() throws IOException {
cache.getRemoteCacheContainer().stop();
}
public void putTest() throws Exception {
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
final int thread_index = i;
threads[i] = new Thread(() -> {
for (int j = 0; j < NUMBER_OF_ENTRIES; j++) {
cache.put("key_" + thread_index + "_" + j, Util.threadLocalRandomUUID().toString());
if (j % 2 == 0) {
cache.remove("key_" + thread_index + "_" + (j / 2));
}
}
});
}
long start = System.nanoTime();
for (int i = 0; i < THREAD_COUNT; i++) {
threads[i].start();
}
for (int i = 0; i < THREAD_COUNT; i++) {
threads[i].join();
}
long elapsed = System.nanoTime() - start;
System.out.format("Puts took: %,d s", TimeUnit.NANOSECONDS.toSeconds(elapsed));
}
public void getTest() throws Exception {
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
final int thread_index = i;
threads[i] = new Thread(() -> {
Random r = new Random(thread_index);
for (int j = 0; j < GET_OPERATIONS; j++) {
int key_id = r.nextInt(NUMBER_OF_ENTRIES);
cache.get("key_" + thread_index + "_" + key_id);
}
});
}
long start = System.nanoTime();
for (int i = 0; i < THREAD_COUNT; i++) {
threads[i].start();
}
for (int i = 0; i < THREAD_COUNT; i++) {
threads[i].join();
}
long elapsed = System.nanoTime() - start;
System.out.format("\nGets took: %,d s", TimeUnit.NANOSECONDS.toSeconds(elapsed));
}
}
| 3,490
| 34.622449
| 119
|
java
|
null |
infinispan-main/client/hotrod-client/src/test/java/org/infinispan/client/hotrod/stress/IterationStressTest.java
|
package org.infinispan.client.hotrod.stress;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.commons.util.CloseableIterator;
import org.infinispan.commons.util.ProcessorInfo;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration;
/**
* Simple stress test for remote iteration of entries.
* By default, it runs the server and the client in the same VM; when the sys prop -DserverHost=server
* is present it will connect to that server instead.
*/
@Test(groups = "stress", testName = "org.infinispan.client.hotrod.stress.IterationStressTest")
public class IterationStressTest extends SingleHotRodServerTest {
private static final int NUM_ENTRIES = 500_000;
private static final String SERVER_HOST = "serverHost";
public static final int THREADS = ProcessorInfo.availableProcessors();
private RemoteCache<Object, Object> remoteCache;
@Override
protected void setup() throws Exception {
String serverHost = System.getProperty(SERVER_HOST);
org.infinispan.client.hotrod.configuration.ConfigurationBuilder builder =
HotRodClientTestingUtil.newRemoteConfigurationBuilder();
if (serverHost == null) {
cacheManager = createCacheManager();
hotrodServer = createHotRodServer();
builder.addServer().host("127.0.0.1").port(hotrodServer.getPort());
} else {
builder.addServer().host(serverHost);
}
remoteCacheManager = new RemoteCacheManager(builder.build());
remoteCacheManager.getCache();
remoteCache = remoteCacheManager.getCache();
AtomicInteger counter = new AtomicInteger();
ExecutorService executorService = Executors.newFixedThreadPool(THREADS);
CompletableFuture[] futures = new CompletableFuture[THREADS];
timedExecution("Data ingestion", () -> {
for (int i = 0; i < THREADS; i++) {
futures[i] = CompletableFuture.supplyAsync(() -> {
for (int c = counter.getAndIncrement(); c < NUM_ENTRIES; c = counter.getAndIncrement()) {
remoteCache.put(c, c);
}
return null;
}, executorService);
}
CompletableFuture.allOf(futures).join();
});
timedExecution("Size", () -> {
int size = remoteCache.size();
System.out.printf("Ingested %d entries\n", size);
});
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder builder = new ConfigurationBuilder();
return TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration(builder));
}
private void warmup() {
IntStream.range(0, 10).forEach(i -> iterate());
}
private void iterate() {
AtomicInteger count = new AtomicInteger();
CloseableIterator<Map.Entry<Object, Object>> iterator = remoteCache.retrieveEntries(null, 1000);
iterator.forEachRemaining(o -> count.getAndIncrement());
iterator.close();
}
@Test
public void testIteration() {
timedExecution("warmup", this::warmup);
timedExecution("iteration", this::iterate);
timedExecution("close cache manager", () -> remoteCacheManager.stop());
}
private static void timedExecution(String label, Runnable code) {
long start = System.currentTimeMillis();
code.run();
System.out.format("Run %s in %d ms\n", label, System.currentTimeMillis() - start);
}
}
| 4,244
| 37.944954
| 109
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.