diff --git a/src/main/java/redis/clients/jedis/ClusterPipeline.java b/src/main/java/redis/clients/jedis/ClusterPipeline.java index 9b8dd68f00..37751d386a 100644 --- a/src/main/java/redis/clients/jedis/ClusterPipeline.java +++ b/src/main/java/redis/clients/jedis/ClusterPipeline.java @@ -2859,4 +2859,9 @@ public Response ftSearch(byte[] indexName, Query query) { throw new UnsupportedOperationException("Not supported yet."); //return appendCommand(provider.getNode(key), commandObjects.ftCreate(indexName, query)); } + + @Override + public Response waitReplicas(int replicas, long timeout) { + throw new UnsupportedOperationException("Not supported yet."); + } } diff --git a/src/main/java/redis/clients/jedis/Connection.java b/src/main/java/redis/clients/jedis/Connection.java index e859abb58f..b70dc3db3d 100644 --- a/src/main/java/redis/clients/jedis/Connection.java +++ b/src/main/java/redis/clients/jedis/Connection.java @@ -28,6 +28,7 @@ public class Connection implements Closeable { private Socket socket; private RedisOutputStream outputStream; private RedisInputStream inputStream; + private int soTimeout = 0; private int infiniteSoTimeout = 0; private boolean broken = false; @@ -40,7 +41,7 @@ public Connection(final String host, final int port) { } public Connection(final HostAndPort hostAndPort) { - this(hostAndPort, DefaultJedisClientConfig.builder().build()); + this(new DefaultJedisSocketFactory(hostAndPort)); } public Connection(final HostAndPort hostAndPort, final JedisClientConfig clientConfig) { @@ -55,6 +56,7 @@ public Connection(final JedisSocketFactory socketFactory, JedisClientConfig clie public Connection(final JedisSocketFactory socketFactory, JedisClientConfig clientConfig, Pool pool) { this.socketFactory = socketFactory; + this.soTimeout = clientConfig.getSocketTimeoutMillis(); this.infiniteSoTimeout = clientConfig.getBlockingSocketTimeoutMillis(); initializeFromClientConfig(clientConfig); this.memberOf = pool; @@ -70,8 +72,13 @@ public String toString() { return "Connection{" + socketFactory + "}"; } + public int getSoTimeout() { + return soTimeout; + } + public void setSoTimeout(int soTimeout) { - socketFactory.setSocketTimeout(soTimeout); +// socketFactory.setSocketTimeout(soTimeout); + this.soTimeout = soTimeout; if (this.socket != null) { try { this.socket.setSoTimeout(soTimeout); @@ -96,7 +103,8 @@ public void setTimeoutInfinite() { public void rollbackTimeout() { try { - socket.setSoTimeout(socketFactory.getSocketTimeout()); +// socket.setSoTimeout(socketFactory.getSocketTimeout()); + socket.setSoTimeout(this.soTimeout); } catch (SocketException ex) { broken = true; throw new JedisConnectionException(ex); @@ -202,6 +210,7 @@ public void connect() throws JedisConnectionException { if (!isConnected()) { try { socket = socketFactory.createSocket(); + soTimeout = socket.getSoTimeout(); //? outputStream = new RedisOutputStream(socket.getOutputStream()); inputStream = new RedisInputStream(socket.getInputStream()); @@ -317,6 +326,10 @@ public Object getOne() { return readProtocolWithCheckingBroken(); } + public void setBroken() { + broken = true; + } + public boolean isBroken() { return broken; } diff --git a/src/main/java/redis/clients/jedis/DefaultJedisSocketFactory.java b/src/main/java/redis/clients/jedis/DefaultJedisSocketFactory.java index a20e2af445..c8c045dab5 100644 --- a/src/main/java/redis/clients/jedis/DefaultJedisSocketFactory.java +++ b/src/main/java/redis/clients/jedis/DefaultJedisSocketFactory.java @@ -122,16 +122,16 @@ protected HostAndPort getSocketHostAndPort() { } return hap; } - - @Override - public void setSocketTimeout(int socketTimeout) { - this.socketTimeout = socketTimeout; - } - - @Override - public int getSocketTimeout() { - return socketTimeout; - } +// +// @Override +// public void setSocketTimeout(int socketTimeout) { +// this.socketTimeout = socketTimeout; +// } +// +// @Override +// public int getSocketTimeout() { +// return socketTimeout; +// } @Override public String toString() { diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 3b6b732635..4a8647ffab 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -7,7 +7,6 @@ import java.io.Closeable; import java.net.URI; -import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; @@ -40,6 +39,8 @@ public class Jedis implements ServerCommands, DatabaseCommands, JedisCommands, J private final RedisCommandObjects commandObjects = new RedisCommandObjects(); private int db = 0; private Transaction transaction = null; + private boolean isInMulti = false; + private boolean isInWatch = false; private Pipeline pipeline = null; protected static final byte[][] DUMMY_ARRAY = new byte[0][]; @@ -69,7 +70,7 @@ public Jedis(final String uriString) { } public Jedis(final HostAndPort hp) { - this(hp, DefaultJedisClientConfig.builder().build()); + connection = new Connection(hp); } public Jedis(final String host, final int port) { @@ -302,7 +303,26 @@ public Jedis(final Connection connection) { @Override public String toString() { - return "BinaryJedis{" + connection + '}'; + return "Jedis{" + connection + '}'; + } + + // Legacy + public Connection getClient() { + return getConnection(); + } + + public Connection getConnection() { + return connection; + } + + // Legacy + public void connect() { + connection.connect(); + } + + // Legacy + public void disconnect() { + connection.disconnect(); } public boolean isConnected() { @@ -324,6 +344,11 @@ public void resetState() { } // // connection.resetState(); + if (isInWatch) { + connection.sendCommand(UNWATCH); + connection.getStatusCodeReply(); + isInWatch = false; + } } transaction = null; @@ -349,12 +374,33 @@ public void close() { } } - public Connection getConnection() { - return connection; + // Legacy + public Transaction multi() { +// client.multi(); +// client.getOne(); // expected OK +// transaction = new Transaction(client); + transaction = new Transaction(this); + return transaction; } - public Connection getClient() { - return getConnection(); + // Legacy + public Pipeline pipelined() { +// pipeline = new Pipeline(); +// pipeline.setClient(connection); + pipeline = new Pipeline(this); + return pipeline; + } + + // Legacy + protected void checkIsInMultiOrPipeline() { +// if (connection.isInMulti()) { + if (transaction != null) { + throw new IllegalStateException( + "Cannot use Jedis when in Multi. Please use Transaction or reset jedis state."); + } else if (pipeline != null && pipeline.hasPipelinedResponse()) { + throw new IllegalStateException( + "Cannot use Jedis when in Pipeline. Please use Pipeline or reset jedis state."); + } } public int getDB() { @@ -483,6 +529,7 @@ public String quit() { connection.sendCommand(QUIT); String quitReturn = connection.getStatusCodeReply(); connection.disconnect(); + connection.setBroken(); return quitReturn; } @@ -2189,35 +2236,13 @@ public Set zpopmin(final byte[] key, final int count) { return connection.executeCommand(commandObjects.zpopmin(key, count)); } - public Pipeline pipelined() { -// pipeline = new Pipeline(); -// pipeline.setClient(connection); - pipeline = new Pipeline(connection); - return pipeline; - } - - public Transaction multi() { - connection.sendCommand(MULTI); - connection.getOne(); // expected OK - transaction = new Transaction(connection); - return transaction; - } - - protected void checkIsInMultiOrPipeline() { -// if (connection.isInMulti()) { - if (transaction != null) { - throw new IllegalStateException( - "Cannot use Jedis when in Multi. Please use Transaction or reset jedis state."); - } else if (pipeline != null && pipeline.hasPipelinedResponse()) { - throw new IllegalStateException( - "Cannot use Jedis when in Pipeline. Please use Pipeline or reset jedis state."); - } - } - public String watch(final byte[]... keys) { checkIsInMultiOrPipeline(); connection.sendCommand(WATCH, keys); - return connection.getStatusCodeReply(); +// return connection.getStatusCodeReply(); + String status = connection.getStatusCodeReply(); + isInWatch = true; + return status; } public String unwatch() { @@ -3260,6 +3285,7 @@ public String shutdown() throws JedisException { } catch (JedisConnectionException jce) { // expected status = null; + connection.setBroken(); } return status; } @@ -3271,6 +3297,7 @@ public void shutdown(final SaveMode saveMode) throws JedisException { throw new JedisException(connection.getStatusCodeReply()); } catch (JedisConnectionException jce) { // expected + connection.setBroken(); } } @@ -3751,19 +3778,19 @@ public List slowlogGetBinary(final long entries) { @Override public Long objectRefcount(final byte[] key) { - connection.sendCommand(OBJECT, REFCOUNT); + connection.sendCommand(OBJECT, REFCOUNT.getRaw(), key); return connection.getIntegerReply(); } @Override public byte[] objectEncoding(final byte[] key) { - connection.sendCommand(OBJECT, ENCODING); + connection.sendCommand(OBJECT, ENCODING.getRaw(), key); return connection.getBinaryBulkReply(); } @Override public Long objectIdletime(final byte[] key) { - connection.sendCommand(OBJECT, IDLETIME); + connection.sendCommand(OBJECT, IDLETIME.getRaw(), key); return connection.getIntegerReply(); } @@ -3775,7 +3802,7 @@ public List objectHelpBinary() { @Override public Long objectFreq(final byte[] key) { - connection.sendCommand(OBJECT, FREQ); + connection.sendCommand(OBJECT, FREQ.getRaw(), key); return connection.getIntegerReply(); } @@ -3886,13 +3913,20 @@ public Long memoryUsage(final byte[] key) { @Override public Long memoryUsage(final byte[] key, final int samples) { checkIsInMultiOrPipeline(); - connection.sendCommand(MEMORY, USAGE.getRaw(), key, toByteArray(samples)); + connection.sendCommand(MEMORY, USAGE.getRaw(), key, SAMPLES.getRaw(), toByteArray(samples)); return connection.getIntegerReply(); } @Override public String failover() { - return failover(null); + checkIsInMultiOrPipeline(); + connection.sendCommand(FAILOVER); + connection.setTimeoutInfinite(); + try { + return connection.getStatusCodeReply(); + } finally { + connection.rollbackTimeout(); + } } @Override @@ -4142,7 +4176,7 @@ public String migrate(final String host, final int port, final int destinationDB final int timeout, final MigrateParams params, final byte[]... keys) { checkIsInMultiOrPipeline(); CommandArguments args = new CommandArguments(MIGRATE).add(host).add(port).add(new byte[0]).add(destinationDB) - .add(timeout).addParams(params).keys((Object[]) keys); + .add(timeout).addParams(params).add(Keyword.KEYS).keys((Object[]) keys); connection.sendCommand(args); return connection.getStatusCodeReply(); } @@ -6250,7 +6284,10 @@ public Set zpopmin(final String key, final int count) { public String watch(final String... keys) { checkIsInMultiOrPipeline(); connection.sendCommand(WATCH, keys); - return connection.getStatusCodeReply(); +// return connection.getStatusCodeReply(); + String status = connection.getStatusCodeReply(); + isInWatch = true; + return status; } /** @@ -7490,19 +7527,19 @@ public List slowlogGet(final long entries) { @Override public Long objectRefcount(final String key) { - connection.sendCommand(OBJECT, REFCOUNT); + connection.sendCommand(OBJECT, REFCOUNT.name(), key); return connection.getIntegerReply(); } @Override public String objectEncoding(final String key) { - connection.sendCommand(OBJECT, ENCODING); + connection.sendCommand(OBJECT, ENCODING.name(), key); return connection.getBulkReply(); } @Override public Long objectIdletime(final String key) { - connection.sendCommand(OBJECT, IDLETIME); + connection.sendCommand(OBJECT, IDLETIME.name(), key); return connection.getIntegerReply(); } @@ -7514,7 +7551,7 @@ public List objectHelp() { @Override public Long objectFreq(final String key) { - connection.sendCommand(OBJECT, FREQ); + connection.sendCommand(OBJECT, FREQ.name(), key); return connection.getIntegerReply(); } @@ -7900,7 +7937,7 @@ public String clientList() { @Override public String clientList(ClientType type) { checkIsInMultiOrPipeline(); - connection.sendCommand(CLIENT, LIST.getRaw(), type.getRaw()); + connection.sendCommand(CLIENT, LIST.getRaw(), Keyword.TYPE.getRaw(), type.getRaw()); return connection.getBulkReply(); } @@ -7939,7 +7976,7 @@ public String migrate(final String host, final int port, final int destinationDB final int timeout, final MigrateParams params, final String... keys) { checkIsInMultiOrPipeline(); CommandArguments args = new CommandArguments(MIGRATE).add(host).add(port).add(new byte[0]).add(destinationDB) - .add(timeout).addParams(params).keys((Object[]) keys); + .add(timeout).addParams(params).add(Keyword.KEYS).keys((Object[]) keys); connection.sendCommand(args); return connection.getStatusCodeReply(); } diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java new file mode 100644 index 0000000000..e9df0162a6 --- /dev/null +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -0,0 +1,209 @@ +package redis.clients.jedis; + +import java.time.Duration; +import java.util.Collections; +import java.util.Map; +import java.util.Set; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import redis.clients.jedis.util.Pool; + +public class JedisCluster extends UnifiedJedis { + + /** + * Default timeout in milliseconds. + */ + public static final int DEFAULT_TIMEOUT = 2000; + public static final int DEFAULT_MAX_ATTEMPTS = 5; + + public JedisCluster(HostAndPort node) { + this(Collections.singleton(node)); + } + + public JedisCluster(HostAndPort node, int timeout) { + this(Collections.singleton(node), timeout); + } + + public JedisCluster(HostAndPort node, int timeout, int maxAttempts) { + this(Collections.singleton(node), timeout, maxAttempts); + } + + public JedisCluster(HostAndPort node, final GenericObjectPoolConfig poolConfig) { + this(Collections.singleton(node), poolConfig); + } + + public JedisCluster(HostAndPort node, int timeout, final GenericObjectPoolConfig poolConfig) { + this(Collections.singleton(node), timeout, poolConfig); + } + + public JedisCluster(HostAndPort node, int timeout, int maxAttempts, + final GenericObjectPoolConfig poolConfig) { + this(Collections.singleton(node), timeout, maxAttempts, poolConfig); + } + + public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, + final GenericObjectPoolConfig poolConfig) { + this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, poolConfig); + } + + public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, + String password, final GenericObjectPoolConfig poolConfig) { + this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, password, + poolConfig); + } + + public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, + String password, String clientName, final GenericObjectPoolConfig poolConfig) { + this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, password, + clientName, poolConfig); + } + + public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, + String user, String password, String clientName, + final GenericObjectPoolConfig poolConfig) { + this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, user, password, + clientName, poolConfig); + } + + public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, + String password, String clientName, final GenericObjectPoolConfig poolConfig, + boolean ssl) { + this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, password, + clientName, poolConfig, ssl); + } + + public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, + String user, String password, String clientName, + final GenericObjectPoolConfig poolConfig, boolean ssl) { + this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, user, password, + clientName, poolConfig, ssl); + } + + public JedisCluster(HostAndPort node, final JedisClientConfig clientConfig, int maxAttempts, + final GenericObjectPoolConfig poolConfig) { + this(Collections.singleton(node), clientConfig, maxAttempts, poolConfig); + } + + public JedisCluster(Set nodes) { + this(nodes, DEFAULT_TIMEOUT); + } + + public JedisCluster(Set nodes, int timeout) { + this(nodes, timeout, DEFAULT_MAX_ATTEMPTS); + } + + public JedisCluster(Set nodes, int timeout, int maxAttempts) { + super(nodes, timeout, maxAttempts); + } + + public JedisCluster(Set nodes, final GenericObjectPoolConfig poolConfig) { + this(nodes, DEFAULT_TIMEOUT, DEFAULT_MAX_ATTEMPTS, poolConfig); + } + + public JedisCluster(Set nodes, int timeout, + final GenericObjectPoolConfig poolConfig) { + this(nodes, timeout, DEFAULT_MAX_ATTEMPTS, poolConfig); + } + + public JedisCluster(Set jedisClusterNode, int timeout, int maxAttempts, + final GenericObjectPoolConfig poolConfig) { + this(jedisClusterNode, timeout, timeout, maxAttempts, poolConfig); + } + + public JedisCluster(Set jedisClusterNode, int connectionTimeout, + int soTimeout, int maxAttempts, final GenericObjectPoolConfig poolConfig) { + this(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, null, poolConfig); + } + + public JedisCluster(Set jedisClusterNode, int connectionTimeout, + int soTimeout, int maxAttempts, String password, GenericObjectPoolConfig poolConfig) { + this(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, null, poolConfig); + } + + public JedisCluster(Set jedisClusterNode, int connectionTimeout, + int soTimeout, int maxAttempts, String password, String clientName, + GenericObjectPoolConfig poolConfig) { + this(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, null, password, clientName, + poolConfig); + } + + public JedisCluster(Set jedisClusterNode, int connectionTimeout, + int soTimeout, int maxAttempts, String user, String password, String clientName, + GenericObjectPoolConfig poolConfig) { + this(jedisClusterNode, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) + .socketTimeoutMillis(soTimeout).user(user).password(password).clientName(clientName).build(), + maxAttempts, poolConfig); + } + + public JedisCluster(Set jedisClusterNode, int connectionTimeout, + int soTimeout, int infiniteSoTimeout, int maxAttempts, String user, String password, + String clientName, GenericObjectPoolConfig poolConfig) { + this(jedisClusterNode, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) + .socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout) + .user(user).password(password).clientName(clientName).build(), maxAttempts, poolConfig); + } + + public JedisCluster(Set jedisClusterNode, int connectionTimeout, + int soTimeout, int maxAttempts, String password, String clientName, + GenericObjectPoolConfig poolConfig, boolean ssl) { + this(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, null, password, clientName, + poolConfig, ssl); + } + + public JedisCluster(Set jedisClusterNode, int connectionTimeout, + int soTimeout, int maxAttempts, String user, String password, String clientName, + GenericObjectPoolConfig poolConfig, boolean ssl) { + this(jedisClusterNode, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) + .socketTimeoutMillis(soTimeout).user(user).password(password).clientName(clientName).ssl(ssl).build(), + maxAttempts, poolConfig); + } + + public JedisCluster(Set jedisClusterNode, JedisClientConfig clientConfig, + int maxAttempts, GenericObjectPoolConfig poolConfig) { + this(jedisClusterNode, clientConfig, maxAttempts, + Duration.ofMillis((long) clientConfig.getSocketTimeoutMillis() * maxAttempts), poolConfig); + } + + public JedisCluster(Set jedisClusterNode, JedisClientConfig clientConfig, + int maxAttempts, Duration maxTotalRetriesDuration, GenericObjectPoolConfig poolConfig) { + super(jedisClusterNode, clientConfig, convertPoolConfig(poolConfig), maxAttempts, maxTotalRetriesDuration); + } +// +// private static GenericObjectPoolConfig convertPoolConfig(GenericObjectPoolConfig jedis) { +// GenericObjectPoolConfig conn = new GenericObjectPoolConfig<>(); +// conn.setBlockWhenExhausted(jedis.getBlockWhenExhausted()); +// conn.setEvictorShutdownTimeout(jedis.getEvictorShutdownTimeoutDuration()); +// conn.setFairness(jedis.getFairness()); +// conn.setJmxEnabled(jedis.getJmxEnabled()); +// conn.setJmxNameBase(jedis.getJmxNameBase()); +// conn.setJmxNamePrefix(jedis.getJmxNamePrefix()); +// conn.setLifo(jedis.getLifo()); +// conn.setMaxIdle(jedis.getMaxIdle()); +// conn.setMaxTotal(jedis.getMaxTotal()); +// conn.setMaxWait(jedis.getMaxWaitDuration()); +// conn.setMinIdle(jedis.getMinIdle()); +// conn.setTestOnBorrow(jedis.getTestOnBorrow()); +// conn.setTestOnCreate(jedis.getTestOnCreate()); +// conn.setTestOnReturn(jedis.getTestOnReturn()); +// conn.setTestWhileIdle(jedis.getTestWhileIdle()); +// return conn; +// } + private static GenericObjectPoolConfig convertPoolConfig(GenericObjectPoolConfig jedis) { + GenericObjectPoolConfig config = jedis; + return (GenericObjectPoolConfig) config; + } +// private static GenericObjectPoolConfig convertPoolConfig(GenericObjectPoolConfig jedis) { +// return new GenericObjectPoolConfig<>(); +// } + + public JedisCluster(Set jedisClusterNodes, JedisClientConfig clientConfig, int maxAttempts) { + super(jedisClusterNodes, clientConfig, maxAttempts); + } + + public JedisCluster(Set jedisClusterNodes, JedisClientConfig clientConfig, int maxAttempts, Duration maxTotalRetriesDuration) { + super(jedisClusterNodes, clientConfig, maxAttempts, maxTotalRetriesDuration); + } + + public Map> getClusterNodes() { + return ((RetryableClusterCommandExecutor) executor).provider.getNodes(); + } +} diff --git a/src/main/java/redis/clients/jedis/JedisConnectionExecutor.java b/src/main/java/redis/clients/jedis/JedisConnectionExecutor.java index ea829b6de1..e8f32f6434 100644 --- a/src/main/java/redis/clients/jedis/JedisConnectionExecutor.java +++ b/src/main/java/redis/clients/jedis/JedisConnectionExecutor.java @@ -4,7 +4,7 @@ public class JedisConnectionExecutor implements JedisCommandExecutor { - private final Connection connection; + protected final Connection connection; public JedisConnectionExecutor(Connection connection) { this.connection = connection; diff --git a/src/main/java/redis/clients/jedis/JedisFactory.java b/src/main/java/redis/clients/jedis/JedisFactory.java new file mode 100644 index 0000000000..7472c8b076 --- /dev/null +++ b/src/main/java/redis/clients/jedis/JedisFactory.java @@ -0,0 +1,223 @@ +package redis.clients.jedis; + +import java.net.URI; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocketFactory; + +import org.apache.commons.pool2.PooledObject; +import org.apache.commons.pool2.PooledObjectFactory; +import org.apache.commons.pool2.impl.DefaultPooledObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import redis.clients.jedis.exceptions.InvalidURIException; +import redis.clients.jedis.exceptions.JedisException; +import redis.clients.jedis.util.JedisURIHelper; + +/** + * PoolableObjectFactory custom impl. + */ +// Legacy +public class JedisFactory implements PooledObjectFactory { + + private static final Logger logger = LoggerFactory.getLogger(JedisFactory.class); + + private final JedisSocketFactory jedisSocketFactory; + + private final JedisClientConfig clientConfig; + + protected JedisFactory(final String host, final int port, final int connectionTimeout, + final int soTimeout, final String password, final int database, final String clientName) { + this(host, port, connectionTimeout, soTimeout, password, database, clientName, false, null, null, null); + } + + protected JedisFactory(final String host, final int port, final int connectionTimeout, + final int soTimeout, final String user, final String password, final int database, final String clientName) { + this(host, port, connectionTimeout, soTimeout, 0, user, password, database, clientName); + } + + protected JedisFactory(final String host, final int port, final int connectionTimeout, final int soTimeout, + final int infiniteSoTimeout, final String user, final String password, final int database, final String clientName) { + this(host, port, connectionTimeout, soTimeout, infiniteSoTimeout, user, password, database, clientName, false, null, null, null); + } +// +// /** +// * {@link #setHostAndPort(redis.clients.jedis.HostAndPort) setHostAndPort} must be called later. +// */ +// protected JedisFactory(final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, +// final String user, final String password, final int database, final String clientName) { +// this(connectionTimeout, soTimeout, infiniteSoTimeout, user, password, database, clientName, false, null, null, null); +// } + + protected JedisFactory(final String host, final int port, final int connectionTimeout, + final int soTimeout, final String password, final int database, final String clientName, + final boolean ssl, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(host, port, connectionTimeout, soTimeout, null, password, database, clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier); + } + + protected JedisFactory(final String host, final int port, final int connectionTimeout, + final int soTimeout, final String user, final String password, final int database, final String clientName, + final boolean ssl, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(host, port, connectionTimeout, soTimeout, 0, user, password, database, clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier); + } + + protected JedisFactory(final HostAndPort hostAndPort, final JedisClientConfig clientConfig) { + this.clientConfig = DefaultJedisClientConfig.copyConfig(clientConfig); + this.jedisSocketFactory = new DefaultJedisSocketFactory(hostAndPort, this.clientConfig); + } + + protected JedisFactory(final String host, final int port, final int connectionTimeout, final int soTimeout, + final int infiniteSoTimeout, final String user, final String password, final int database, + final String clientName, final boolean ssl, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this.clientConfig = DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) + .socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout).user(user) + .password(password).database(database).clientName(clientName) + .ssl(ssl).sslSocketFactory(sslSocketFactory) + .sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build(); + this.jedisSocketFactory = new DefaultJedisSocketFactory(new HostAndPort(host, port), this.clientConfig); + } + + protected JedisFactory(final JedisSocketFactory jedisSocketFactory, final JedisClientConfig clientConfig) { + this.clientConfig = DefaultJedisClientConfig.copyConfig(clientConfig); + this.jedisSocketFactory = jedisSocketFactory; + } +// +// /** +// * {@link #setHostAndPort(redis.clients.jedis.HostAndPort) setHostAndPort} must be called later. +// */ +// protected JedisFactory(final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, +// final String user, final String password, final int database, final String clientName, final boolean ssl, +// final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { +// this(DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) +// .socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout).user(user) +// .password(password).database(database).clientName(clientName) +// .ssl(ssl).sslSocketFactory(sslSocketFactory) +// .sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build()); +// } +// +// /** +// * {@link #setHostAndPort(redis.clients.jedis.HostAndPort) setHostAndPort} must be called later. +// */ +// protected JedisFactory(final JedisClientConfig clientConfig) { +// this.clientConfig = clientConfig; +// this.jedisSocketFactory = new DefaultJedisSocketFactory(clientConfig); +// } + + protected JedisFactory(final URI uri, final int connectionTimeout, final int soTimeout, + final String clientName) { + this(uri, connectionTimeout, soTimeout, clientName, null, null, null); + } + + protected JedisFactory(final URI uri, final int connectionTimeout, final int soTimeout, + final String clientName, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(uri, connectionTimeout, soTimeout, 0, clientName, sslSocketFactory, sslParameters, hostnameVerifier); + } + + protected JedisFactory(final URI uri, final int connectionTimeout, final int soTimeout, + final int infiniteSoTimeout, final String clientName, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + if (!JedisURIHelper.isValid(uri)) { + throw new InvalidURIException(String.format( + "Cannot open Redis connection due invalid URI. %s", uri.toString())); + } + this.clientConfig = DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) + .socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout) + .user(JedisURIHelper.getUser(uri)).password(JedisURIHelper.getPassword(uri)) + .database(JedisURIHelper.getDBIndex(uri)).clientName(clientName) + .ssl(JedisURIHelper.isRedisSSLScheme(uri)).sslSocketFactory(sslSocketFactory) + .sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build(); + this.jedisSocketFactory = new DefaultJedisSocketFactory(new HostAndPort(uri.getHost(), uri.getPort()), this.clientConfig); + } +// +// public void setHostAndPort(final HostAndPort hostAndPort) { +// jedisSocketFactory.updateHostAndPort(hostAndPort); +// } + + public void setPassword(final String password) { + this.clientConfig.updatePassword(password); + } + + @Override + public void activateObject(PooledObject pooledJedis) throws Exception { + final Jedis jedis = pooledJedis.getObject(); + if (jedis.getDB() != clientConfig.getDatabase()) { + jedis.select(clientConfig.getDatabase()); + } + } + + @Override + public void destroyObject(PooledObject pooledJedis) throws Exception { + final Jedis jedis = pooledJedis.getObject(); + if (jedis.isConnected()) { + try { + // need a proper test, probably with mock + if (!jedis.isBroken()) { + jedis.quit(); + } + } catch (RuntimeException e) { + logger.warn("Error while QUIT", e); + } + try { + jedis.close(); + } catch (RuntimeException e) { + logger.warn("Error while close", e); + } + } + } + + @Override + public PooledObject makeObject() throws Exception { + Jedis jedis = null; + try { + jedis = new Jedis(jedisSocketFactory, clientConfig); + jedis.connect(); + return new DefaultPooledObject<>(jedis); + } catch (JedisException je) { + if (jedis != null) { + try { + jedis.quit(); + } catch (RuntimeException e) { + logger.warn("Error while QUIT", e); + } + try { + jedis.close(); + } catch (RuntimeException e) { + logger.warn("Error while close", e); + } + } + throw je; + } + } + + @Override + public void passivateObject(PooledObject pooledJedis) throws Exception { + // TODO maybe should select db 0? Not sure right now. + } + + @Override + public boolean validateObject(PooledObject pooledJedis) { + final Jedis jedis = pooledJedis.getObject(); + try { +// String host = jedisSocketFactory.getHost(); +// int port = jedisSocketFactory.getPort(); +// +// +// String connectionHost = jedis.getClient().getHost(); +// int connectionPort = jedis.getClient().getPort(); +// +// return host.equals(connectionHost) +// && port == connectionPort && jedis.isConnected() +// && jedis.ping().equals("PONG"); + return jedis.getConnection().isConnected() && jedis.ping().equals("PONG"); + } catch (final Exception e) { + logger.error("Error while validating pooled Jedis object.", e); + return false; + } + } +} diff --git a/src/main/java/redis/clients/jedis/JedisPool.java b/src/main/java/redis/clients/jedis/JedisPool.java new file mode 100644 index 0000000000..18228169ae --- /dev/null +++ b/src/main/java/redis/clients/jedis/JedisPool.java @@ -0,0 +1,382 @@ +package redis.clients.jedis; + +import java.net.URI; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocketFactory; + +import org.apache.commons.pool2.PooledObjectFactory; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import redis.clients.jedis.util.JedisURIHelper; +import redis.clients.jedis.util.Pool; + +// Legacy +public class JedisPool extends Pool { + + private static final Logger log = LoggerFactory.getLogger(JedisPool.class); + + public JedisPool() { + this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) { + this(poolConfig, host, Protocol.DEFAULT_PORT); + } + + public JedisPool(String host, int port) { + this(new GenericObjectPoolConfig(), host, port); + } + + /** + * WARNING: This constructor only accepts a uri string as {@code url}. + * {@link JedisURIHelper#isValid(java.net.URI)} can be used before this. + *

+ * To use a host string, {@link #JedisPool(java.lang.String, int)} can be used with + * {@link Protocol#DEFAULT_PORT}. + * + * @param url + */ + public JedisPool(final String url) { + this(new GenericObjectPoolConfig(), new JedisFactory(URI.create(url), Protocol.DEFAULT_TIMEOUT, + Protocol.DEFAULT_TIMEOUT, null)); + } + + /** + * WARNING: This constructor only accepts a uri string as {@code url}. + * {@link JedisURIHelper#isValid(java.net.URI)} can be used before this. + *

+ * To use a host string, + * {@link #JedisPool(java.lang.String, int, boolean, javax.net.ssl.SSLSocketFactory, javax.net.ssl.SSLParameters, javax.net.ssl.HostnameVerifier)} + * can be used with {@link Protocol#DEFAULT_PORT} and {@code ssl=true}. + * + * @param url + * @param sslSocketFactory + * @param sslParameters + * @param hostnameVerifier + */ + public JedisPool(final String url, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(new GenericObjectPoolConfig(), new JedisFactory(URI.create(url), Protocol.DEFAULT_TIMEOUT, + Protocol.DEFAULT_TIMEOUT, null, sslSocketFactory, sslParameters, hostnameVerifier)); + } + + public JedisPool(final URI uri) { + this(new GenericObjectPoolConfig(), uri); + } + + public JedisPool(final URI uri, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(new GenericObjectPoolConfig(), uri, sslSocketFactory, sslParameters, + hostnameVerifier); + } + + public JedisPool(final URI uri, final int timeout) { + this(new GenericObjectPoolConfig(), uri, timeout); + } + + public JedisPool(final URI uri, final int timeout, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(new GenericObjectPoolConfig(), uri, timeout, sslSocketFactory, sslParameters, + hostnameVerifier); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password) { + this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE); + } + + public JedisPool(final String host, int port, String user, final String password) { + this(new GenericObjectPoolConfig(), host, port, user, password); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + String user, final String password) { + this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, user, password, + Protocol.DEFAULT_DATABASE); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String user, final String password) { + this(poolConfig, host, port, timeout, user, password, Protocol.DEFAULT_DATABASE); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final boolean ssl) { + this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE, ssl); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String user, final String password, final boolean ssl) { + this(poolConfig, host, port, timeout, user, password, Protocol.DEFAULT_DATABASE, ssl); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE, ssl, + sslSocketFactory, sslParameters, hostnameVerifier); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, + final int port) { + this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, + final int port, final boolean ssl) { + this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, ssl); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, + final int port, final boolean ssl, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, ssl, sslSocketFactory, sslParameters, + hostnameVerifier); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, + final int port, final int timeout) { + this(poolConfig, host, port, timeout, null); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, + final int port, final int timeout, final boolean ssl) { + this(poolConfig, host, port, timeout, null, ssl); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, + final int port, final int timeout, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(poolConfig, host, port, timeout, null, ssl, sslSocketFactory, sslParameters, + hostnameVerifier); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final int database) { + this(poolConfig, host, port, timeout, password, database, null); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String user, final String password, final int database) { + this(poolConfig, host, port, timeout, user, password, database, null); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final int database, final boolean ssl) { + this(poolConfig, host, port, timeout, password, database, null, ssl); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String user, final String password, final int database, final boolean ssl) { + this(poolConfig, host, port, timeout, user, password, database, null, ssl); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final int database, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(poolConfig, host, port, timeout, password, database, null, ssl, sslSocketFactory, + sslParameters, hostnameVerifier); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final int database, final String clientName) { + this(poolConfig, host, port, timeout, timeout, password, database, clientName); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String user, final String password, final int database, + final String clientName) { + this(poolConfig, host, port, timeout, timeout, user, password, database, clientName); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final int database, final String clientName, + final boolean ssl) { + this(poolConfig, host, port, timeout, timeout, password, database, clientName, ssl); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String user, final String password, final int database, + final String clientName, final boolean ssl) { + this(poolConfig, host, port, timeout, timeout, user, password, database, clientName, ssl); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final int database, final String clientName, + final boolean ssl, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(poolConfig, host, port, timeout, timeout, password, database, clientName, ssl, + sslSocketFactory, sslParameters, hostnameVerifier); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + final int connectionTimeout, final int soTimeout, final String password, final int database, + final String clientName, final boolean ssl, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(poolConfig, new JedisFactory(host, port, connectionTimeout, soTimeout, password, + database, clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier)); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, + final String password, final int database, final String clientName, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(poolConfig, host, port, connectionTimeout, soTimeout, infiniteSoTimeout, null, password, + database, clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + final int connectionTimeout, final int soTimeout, final String user, final String password, + final int database, final String clientName, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(poolConfig, host, port, connectionTimeout, soTimeout, 0, user, password, database, + clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, + final String user, final String password, final int database, final String clientName, + final boolean ssl, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(poolConfig, new JedisFactory(host, port, connectionTimeout, soTimeout, infiniteSoTimeout, + user, password, database, clientName, ssl, sslSocketFactory, sslParameters, + hostnameVerifier)); + } + + public JedisPool(final HostAndPort hostAndPort, final JedisClientConfig clientConfig) { + this(new GenericObjectPoolConfig(), hostAndPort, clientConfig); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final HostAndPort hostAndPort, + final JedisClientConfig clientConfig) { + this(poolConfig, new JedisFactory(hostAndPort, clientConfig)); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final JedisSocketFactory jedisSocketFactory, + final JedisClientConfig clientConfig) { + this(poolConfig, new JedisFactory(jedisSocketFactory, clientConfig)); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig) { + this(poolConfig, Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT); + } + + public JedisPool(final String host, final int port, final boolean ssl) { + this(new GenericObjectPoolConfig(), host, port, ssl); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + final int connectionTimeout, final int soTimeout, final String password, final int database, + final String clientName) { + this(poolConfig, new JedisFactory(host, port, connectionTimeout, soTimeout, password, + database, clientName)); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + final int connectionTimeout, final int soTimeout, final String user, final String password, + final int database, final String clientName) { + this(poolConfig, new JedisFactory(host, port, connectionTimeout, soTimeout, user, password, + database, clientName)); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, + final String user, final String password, final int database, final String clientName) { + this(poolConfig, new JedisFactory(host, port, connectionTimeout, soTimeout, infiniteSoTimeout, + user, password, database, clientName)); + } + + public JedisPool(final String host, final int port, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(new GenericObjectPoolConfig(), host, port, ssl, sslSocketFactory, sslParameters, + hostnameVerifier); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, + final int port, final int connectionTimeout, final int soTimeout, final String password, + final int database, final String clientName, final boolean ssl) { + this(poolConfig, host, port, connectionTimeout, soTimeout, password, database, clientName, ssl, + null, null, null); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, + final int port, final int connectionTimeout, final int soTimeout, final String user, + final String password, final int database, final String clientName, final boolean ssl) { + this(poolConfig, host, port, connectionTimeout, soTimeout, user, password, database, + clientName, ssl, null, null, null); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri) { + this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT, sslSocketFactory, sslParameters, + hostnameVerifier); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int timeout) { + this(poolConfig, uri, timeout, timeout); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, + final int timeout, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(poolConfig, uri, timeout, timeout, sslSocketFactory, sslParameters, hostnameVerifier); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, + final int connectionTimeout, final int soTimeout) { + this(poolConfig, uri, connectionTimeout, soTimeout, null, null, null); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, + final int connectionTimeout, final int soTimeout, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(poolConfig, new JedisFactory(uri, connectionTimeout, soTimeout, null, sslSocketFactory, + sslParameters, hostnameVerifier)); + } + + public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, + final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(poolConfig, new JedisFactory(uri, connectionTimeout, soTimeout, infiniteSoTimeout, null, + sslSocketFactory, sslParameters, hostnameVerifier)); + } + + public JedisPool(GenericObjectPoolConfig poolConfig, PooledObjectFactory factory) { + super(poolConfig, factory); + } + + @Override + public Jedis getResource() { + Jedis jedis = super.getResource(); + jedis.setDataSource(this); + return jedis; + } + + @Override + public void returnResource(final Jedis resource) { + if (resource != null) { + try { + resource.resetState(); + super.returnResource(resource); + } catch (RuntimeException e) { + super.returnBrokenResource(resource); + log.warn("Resource is returned to the pool as broken", e); + } + } + } +} diff --git a/src/main/java/redis/clients/jedis/JedisPoolConfig.java b/src/main/java/redis/clients/jedis/JedisPoolConfig.java new file mode 100644 index 0000000000..c88364bf4f --- /dev/null +++ b/src/main/java/redis/clients/jedis/JedisPoolConfig.java @@ -0,0 +1,14 @@ +package redis.clients.jedis; + +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; + +public class JedisPoolConfig extends GenericObjectPoolConfig { + + public JedisPoolConfig() { + // defaults to make your life with connection pool easier :) + setTestWhileIdle(true); + setMinEvictableIdleTimeMillis(60000); + setTimeBetweenEvictionRunsMillis(30000); + setNumTestsPerEvictionRun(-1); + } +} diff --git a/src/main/java/redis/clients/jedis/JedisSocketFactory.java b/src/main/java/redis/clients/jedis/JedisSocketFactory.java index 8d73df00af..473fad3625 100644 --- a/src/main/java/redis/clients/jedis/JedisSocketFactory.java +++ b/src/main/java/redis/clients/jedis/JedisSocketFactory.java @@ -16,8 +16,8 @@ public interface JedisSocketFactory { Socket createSocket() throws JedisConnectionException; - - void setSocketTimeout(int soTimeout); - - int getSocketTimeout(); +// +// void setSocketTimeout(int soTimeout); +// +// int getSocketTimeout(); } diff --git a/src/main/java/redis/clients/jedis/Pipeline.java b/src/main/java/redis/clients/jedis/Pipeline.java index 36638cb496..fd416048a1 100644 --- a/src/main/java/redis/clients/jedis/Pipeline.java +++ b/src/main/java/redis/clients/jedis/Pipeline.java @@ -21,13 +21,29 @@ public class Pipeline extends PipelineBase implements PipelineCommands, PipelineBinaryCommands, RedisModulePipelineCommands { + private final Jedis jedis; private final RedisCommandObjects commandObjects; public Pipeline(Connection connection) { super(connection); + this.jedis = null; this.commandObjects = new RedisCommandObjects(); } + public Pipeline(Jedis jedis) { + super(jedis.getConnection()); + this.jedis = jedis; + this.commandObjects = new RedisCommandObjects(); + } +// +// @Override +// public void sync() { +// super.sync(); +// if (jedis != null) { +// jedis.resetState(); +// } +// } + @Override public Response exists(String key) { return appendCommand(commandObjects.exists(key)); @@ -1177,12 +1193,12 @@ public Response> xrange(String key, StreamEntryID start, Strea @Override public Response> xrevrange(String key, StreamEntryID end, StreamEntryID start) { - return appendCommand(commandObjects.xrevrange(key, start, end)); + return appendCommand(commandObjects.xrevrange(key, end, start)); } @Override public Response> xrevrange(String key, StreamEntryID end, StreamEntryID start, int count) { - return appendCommand(commandObjects.xrevrange(key, start, end, count)); + return appendCommand(commandObjects.xrevrange(key, end, start, count)); } @Override @@ -2214,7 +2230,7 @@ public Response> zrangeByScore(byte[] key, byte[] min, byte[] max) { @Override public Response> zrevrangeByScore(byte[] key, double max, double min) { - return appendCommand(commandObjects.zrevrangeByScore(key, min, max)); + return appendCommand(commandObjects.zrevrangeByScore(key, max, min)); } @Override @@ -2224,7 +2240,7 @@ public Response> zrangeByScore(byte[] key, double min, double max, i @Override public Response> zrevrangeByScore(byte[] key, byte[] max, byte[] min) { - return appendCommand(commandObjects.zrevrangeByScore(key, min, max)); + return appendCommand(commandObjects.zrevrangeByScore(key, max, min)); } @Override @@ -2234,7 +2250,7 @@ public Response> zrangeByScore(byte[] key, byte[] min, byte[] max, i @Override public Response> zrevrangeByScore(byte[] key, double max, double min, int offset, int count) { - return appendCommand(commandObjects.zrevrangeByScore(key, min, max, offset, count)); + return appendCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); } @Override @@ -2244,7 +2260,7 @@ public Response> zrangeByScoreWithScores(byte[] key, double min, doub @Override public Response> zrevrangeByScoreWithScores(byte[] key, double max, double min) { - return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, min, max)); + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); } @Override @@ -2254,7 +2270,7 @@ public Response> zrangeByScoreWithScores(byte[] key, double min, doub @Override public Response> zrevrangeByScore(byte[] key, byte[] max, byte[] min, int offset, int count) { - return appendCommand(commandObjects.zrevrangeByScore(key, min, max, offset, count)); + return appendCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); } @Override @@ -2264,7 +2280,7 @@ public Response> zrangeByScoreWithScores(byte[] key, byte[] min, byte @Override public Response> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min) { - return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, min, max)); + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); } @Override @@ -2274,12 +2290,12 @@ public Response> zrangeByScoreWithScores(byte[] key, byte[] min, byte @Override public Response> zrevrangeByScoreWithScores(byte[] key, double max, double min, int offset, int count) { - return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, min, max, offset, count)); + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); } @Override public Response> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, int offset, int count) { - return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, min, max, offset, count)); + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); } @Override @@ -2314,12 +2330,12 @@ public Response> zrangeByLex(byte[] key, byte[] min, byte[] max, int @Override public Response> zrevrangeByLex(byte[] key, byte[] max, byte[] min) { - return appendCommand(commandObjects.zrevrangeByLex(key, min, max)); + return appendCommand(commandObjects.zrevrangeByLex(key, max, min)); } @Override public Response> zrevrangeByLex(byte[] key, byte[] max, byte[] min, int offset, int count) { - return appendCommand(commandObjects.zrevrangeByLex(key, min, max, offset, count)); + return appendCommand(commandObjects.zrevrangeByLex(key, max, min, offset, count)); } @Override @@ -2820,4 +2836,9 @@ public Response ftSearch(String indexName, Query query) { public Response ftSearch(byte[] indexName, Query query) { return appendCommand(commandObjects.ftSearch(indexName, query)); } + + @Override + public Response waitReplicas(int replicas, long timeout) { + return appendCommand(commandObjects.waitReplicas(replicas, timeout)); + } } diff --git a/src/main/java/redis/clients/jedis/PipelineBase.java b/src/main/java/redis/clients/jedis/PipelineBase.java index 88e720ec0f..518ae1c0d8 100644 --- a/src/main/java/redis/clients/jedis/PipelineBase.java +++ b/src/main/java/redis/clients/jedis/PipelineBase.java @@ -30,7 +30,8 @@ public void close() { * get return values from pipelined commands, capture the different Response<?> of the * commands you execute. */ - public final void sync() { + public void sync() { + if (!hasPipelinedResponse()) return; List unformatted = connection.getMany(getPipelinedResponseLength()); for (Object o : unformatted) { generateResponse(o); diff --git a/src/main/java/redis/clients/jedis/PipelinedTransactionBase.java b/src/main/java/redis/clients/jedis/PipelinedTransactionBase.java index 30351e5a10..386055777f 100644 --- a/src/main/java/redis/clients/jedis/PipelinedTransactionBase.java +++ b/src/main/java/redis/clients/jedis/PipelinedTransactionBase.java @@ -1,7 +1,9 @@ package redis.clients.jedis; import java.io.Closeable; +import java.util.ArrayList; import java.util.List; +import redis.clients.jedis.exceptions.JedisDataException; /** * Transaction is nearly identical to Pipeline, only differences are the multi/discard behaviors @@ -33,22 +35,55 @@ public void clear() { } } - public final void exec() { + public Response unwatch() { + return appendCommand(new CommandObject<>(new CommandArguments(Protocol.Command.UNWATCH), BuilderFactory.STRING)); + } + +// public final void exec() { +// // ignore QUEUED or ERROR +// connection.getMany(1 + getPipelinedResponseLength()); +// connection.sendCommand(Protocol.Command.EXEC); +// inTransaction = false; +// +// List unformatted = connection.getObjectMultiBulkReply(); +// unformatted.stream().forEachOrdered(u -> generateResponse(u)); +// } + public List exec() { + if (!inTransaction) throw new IllegalStateException("EXEC without MULTI"); // ignore QUEUED or ERROR connection.getMany(1 + getPipelinedResponseLength()); connection.sendCommand(Protocol.Command.EXEC); inTransaction = false; List unformatted = connection.getObjectMultiBulkReply(); - unformatted.stream().forEachOrdered(u -> generateResponse(u)); + if (unformatted == null) return null; + List formatted = new ArrayList<>(unformatted.size()); + for (Object o : unformatted) { + try { + formatted.add(generateResponse(o).get()); + } catch (JedisDataException e) { + formatted.add(e); + } + } + return formatted; } - public void discard() { +// public final void discard() { +// // ignore QUEUED or ERROR +// connection.getMany(1 + getPipelinedResponseLength()); +// connection.sendCommand(Protocol.Command.DISCARD); +// connection.getStatusCodeReply(); // OK +// inTransaction = false; +// clean(); +// } + public String discard() { + if (!inTransaction) throw new IllegalStateException("DISCARD without MULTI"); // ignore QUEUED or ERROR connection.getMany(1 + getPipelinedResponseLength()); connection.sendCommand(Protocol.Command.DISCARD); - connection.getStatusCodeReply(); // OK + String status = connection.getStatusCodeReply(); // OK inTransaction = false; clean(); + return status; } } diff --git a/src/main/java/redis/clients/jedis/Queable.java b/src/main/java/redis/clients/jedis/Queable.java index 095e690065..d25ffa3d69 100644 --- a/src/main/java/redis/clients/jedis/Queable.java +++ b/src/main/java/redis/clients/jedis/Queable.java @@ -11,8 +11,12 @@ protected void clean() { pipelinedResponses.clear(); } - protected final void generateResponse(Object data) { - pipelinedResponses.poll().set(data); +// protected final void generateResponse(Object data) { +// pipelinedResponses.poll().set(data); + protected final Response generateResponse(Object data) { + Response response = pipelinedResponses.poll(); + response.set(data); + return response; } protected final Response enqueResponse(Builder builder) { diff --git a/src/main/java/redis/clients/jedis/RedisClusterCommandObjects.java b/src/main/java/redis/clients/jedis/RedisClusterCommandObjects.java index 58abbbd144..5f2f4592bf 100644 --- a/src/main/java/redis/clients/jedis/RedisClusterCommandObjects.java +++ b/src/main/java/redis/clients/jedis/RedisClusterCommandObjects.java @@ -2,6 +2,7 @@ import static redis.clients.jedis.Protocol.Command.KEYS; import static redis.clients.jedis.Protocol.Command.SCAN; +import static redis.clients.jedis.Protocol.Command.WAIT; import static redis.clients.jedis.Protocol.Keyword.TYPE; import java.util.Set; @@ -22,6 +23,8 @@ protected ClusterCommandArguments commandArguments(ProtocolCommand command) { return new ClusterCommandArguments(command); } + private static final String CLUSTER_UNSUPPORTED_MESSAGE = "Not supported in cluster mode."; + private static final String KEYS_PATTERN_MESSAGE = "Cluster mode only supports KEYS command" + " with pattern containing hash-tag ( curly-brackets enclosed string )"; @@ -90,6 +93,11 @@ public final CommandObject> scan(byte[] cursor, ScanParams pa return new CommandObject<>(commandArguments(SCAN).addParams(params).processKey(match).add(TYPE).add(type), BuilderFactory.SCAN_BINARY_RESPONSE); } + @Override + public final CommandObject waitReplicas(int replicas, long timeout) { + throw new UnsupportedOperationException(CLUSTER_UNSUPPORTED_MESSAGE); + } + boolean searchLite = false; private CommandObject processSearchCommand(String indexName, CommandObject command) { diff --git a/src/main/java/redis/clients/jedis/RedisCommandObjects.java b/src/main/java/redis/clients/jedis/RedisCommandObjects.java index aa2f2d1cf9..0664b0368e 100644 --- a/src/main/java/redis/clients/jedis/RedisCommandObjects.java +++ b/src/main/java/redis/clients/jedis/RedisCommandObjects.java @@ -4,8 +4,10 @@ import static redis.clients.jedis.Protocol.Keyword.*; import com.google.gson.Gson; - -import java.util.*; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.stream.Collectors; import redis.clients.jedis.Protocol.Command; @@ -17,12 +19,9 @@ import redis.clients.jedis.json.JsonSetParams; import redis.clients.jedis.params.*; import redis.clients.jedis.resps.*; -import redis.clients.jedis.search.IndexOptions; -import redis.clients.jedis.search.Query; -import redis.clients.jedis.search.Schema; +import redis.clients.jedis.search.*; import redis.clients.jedis.search.SearchProtocol.SearchCommand; import redis.clients.jedis.search.SearchProtocol.SearchKeyword; -import redis.clients.jedis.search.SearchResult; import redis.clients.jedis.search.SearchResult.SearchResultBuilder; import redis.clients.jedis.stream.*; @@ -2397,6 +2396,10 @@ public final CommandObject objectFreq(byte[] key) { return new CommandObject<>(commandArguments(OBJECT).add(FREQ).key(key), BuilderFactory.LONG); } + public CommandObject waitReplicas(int replicas, long timeout) { + return new CommandObject<>(commandArguments(WAIT).add(replicas).add(timeout), BuilderFactory.LONG); + } + public final CommandObject waitReplicas(String sampleKey, int replicas, long timeout) { return new CommandObject<>(commandArguments(WAIT).add(replicas).add(timeout).processKey(sampleKey), BuilderFactory.LONG); } @@ -2411,7 +2414,7 @@ public final CommandObject migrate(String host, int port, String key, in public final CommandObject migrate(String host, int port, int timeout, MigrateParams params, String... keys) { return new CommandObject<>(commandArguments(MIGRATE).add(host).add(port).add(new byte[0]).add(0) - .add(timeout).addParams(params).keys((Object[]) keys), BuilderFactory.STRING); + .add(timeout).addParams(params).add(Keyword.KEYS).keys((Object[]) keys), BuilderFactory.STRING); } public final CommandObject migrate(String host, int port, byte[] key, int timeout) { @@ -2420,7 +2423,7 @@ public final CommandObject migrate(String host, int port, byte[] key, in public final CommandObject migrate(String host, int port, int timeout, MigrateParams params, byte[]... keys) { return new CommandObject<>(commandArguments(MIGRATE).add(host).add(port).add(new byte[0]).add(0) - .add(timeout).addParams(params).keys((Object[]) keys), BuilderFactory.STRING); + .add(timeout).addParams(params).add(Keyword.KEYS).keys((Object[]) keys), BuilderFactory.STRING); } public final CommandObject publish(String channel, String message) { diff --git a/src/main/java/redis/clients/jedis/ReliableTransaction.java b/src/main/java/redis/clients/jedis/ReliableTransaction.java index ba16b9cb7e..a33e89bd6d 100644 --- a/src/main/java/redis/clients/jedis/ReliableTransaction.java +++ b/src/main/java/redis/clients/jedis/ReliableTransaction.java @@ -2821,4 +2821,9 @@ public Response ftSearch(String indexName, Query query) { public Response ftSearch(byte[] indexName, Query query) { return appendCommand(commandObjects.ftSearch(indexName, query)); } + + @Override + public Response waitReplicas(int replicas, long timeout) { + throw new UnsupportedOperationException("Not supported yet."); + } } diff --git a/src/main/java/redis/clients/jedis/RetryableClusterCommandExecutor.java b/src/main/java/redis/clients/jedis/RetryableClusterCommandExecutor.java index 69c08bc275..d1ccc8a021 100644 --- a/src/main/java/redis/clients/jedis/RetryableClusterCommandExecutor.java +++ b/src/main/java/redis/clients/jedis/RetryableClusterCommandExecutor.java @@ -12,9 +12,9 @@ public class RetryableClusterCommandExecutor implements JedisCommandExecutor { private static final Logger LOG = LoggerFactory.getLogger(RetryableClusterCommandExecutor.class); - private final JedisClusterConnectionProvider provider; - private final int maxAttempts; - private final Duration maxTotalRetriesDuration; + protected final JedisClusterConnectionProvider provider; + protected final int maxAttempts; + protected final Duration maxTotalRetriesDuration; public RetryableClusterCommandExecutor(JedisClusterConnectionProvider provider, int maxAttempts, Duration maxTotalRetriesDuration) { diff --git a/src/main/java/redis/clients/jedis/RetryableCommandExecutor.java b/src/main/java/redis/clients/jedis/RetryableCommandExecutor.java index 5ddcc9712b..91cfe4618f 100644 --- a/src/main/java/redis/clients/jedis/RetryableCommandExecutor.java +++ b/src/main/java/redis/clients/jedis/RetryableCommandExecutor.java @@ -15,9 +15,9 @@ public class RetryableCommandExecutor implements JedisCommandExecutor { private static final Logger LOG = LoggerFactory.getLogger(RetryableCommandExecutor.class); - private final JedisConnectionProvider provider; - private final int maxAttempts; - private final Duration maxTotalRetriesDuration; + protected final JedisConnectionProvider provider; + protected final int maxAttempts; + protected final Duration maxTotalRetriesDuration; public RetryableCommandExecutor(JedisConnectionProvider provider, int maxAttempts, Duration maxTotalRetriesDuration) { diff --git a/src/main/java/redis/clients/jedis/SimpleJedisExecutor.java b/src/main/java/redis/clients/jedis/SimpleJedisExecutor.java index 2952019242..4260e52289 100644 --- a/src/main/java/redis/clients/jedis/SimpleJedisExecutor.java +++ b/src/main/java/redis/clients/jedis/SimpleJedisExecutor.java @@ -5,7 +5,7 @@ public class SimpleJedisExecutor implements JedisCommandExecutor { - private final JedisConnectionProvider provider; + protected final JedisConnectionProvider provider; public SimpleJedisExecutor(JedisConnectionProvider provider) { this.provider = provider; diff --git a/src/main/java/redis/clients/jedis/Transaction.java b/src/main/java/redis/clients/jedis/Transaction.java index 071bd06086..40e275422d 100644 --- a/src/main/java/redis/clients/jedis/Transaction.java +++ b/src/main/java/redis/clients/jedis/Transaction.java @@ -21,13 +21,47 @@ public class Transaction extends PipelinedTransactionBase implements PipelineCommands, PipelineBinaryCommands, RedisModulePipelineCommands { + private final Jedis jedis; private final RedisCommandObjects commandObjects; + public Transaction(Jedis jedis) { + super(jedis.getConnection()); + this.jedis = jedis; + this.commandObjects = new RedisCommandObjects(); + } + public Transaction(Connection connection) { super(connection); + this.jedis = null; this.commandObjects = new RedisCommandObjects(); } + @Override + public List exec() { + List ret; + try { + ret = super.exec(); + } finally { + if (jedis != null) { + jedis.resetState(); + } + } + return ret; + } + + @Override + public String discard() { + String ret; + try { + ret = super.discard(); + } finally { + if (jedis != null) { + jedis.resetState(); + } + } + return ret; + } + @Override public Response exists(String key) { return appendCommand(commandObjects.exists(key)); @@ -2820,4 +2854,9 @@ public Response ftSearch(String indexName, Query query) { public Response ftSearch(byte[] indexName, Query query) { return appendCommand(commandObjects.ftSearch(indexName, query)); } + + @Override + public Response waitReplicas(int replicas, long timeout) { + throw new UnsupportedOperationException("Not supported yet."); + } } diff --git a/src/main/java/redis/clients/jedis/UnifiedJedis.java b/src/main/java/redis/clients/jedis/UnifiedJedis.java index 3f21b39e91..b7e92c80fd 100644 --- a/src/main/java/redis/clients/jedis/UnifiedJedis.java +++ b/src/main/java/redis/clients/jedis/UnifiedJedis.java @@ -59,6 +59,10 @@ public UnifiedJedis(JedisConnectionProvider provider) { ? new RedisClusterCommandObjects() : new RedisCommandObjects(); } + public UnifiedJedis(Set nodes, int timeout, int maxAttempts) { + this(nodes, DefaultJedisClientConfig.builder().timeoutMillis(timeout).build(), maxAttempts); + } + public UnifiedJedis(Set jedisClusterNodes, JedisClientConfig clientConfig, int maxAttempts) { this(new JedisClusterConnectionProvider(jedisClusterNodes, clientConfig), maxAttempts, Duration.ofMillis(maxAttempts * clientConfig.getSocketTimeoutMillis())); diff --git a/src/main/java/redis/clients/jedis/args/FlushMode.java b/src/main/java/redis/clients/jedis/args/FlushMode.java index 4be513066f..92bc3b528e 100644 --- a/src/main/java/redis/clients/jedis/args/FlushMode.java +++ b/src/main/java/redis/clients/jedis/args/FlushMode.java @@ -19,7 +19,7 @@ public enum FlushMode implements Rawable { private final byte[] raw; - FlushMode() { + private FlushMode() { raw = SafeEncoder.encode(this.name()); } diff --git a/src/main/java/redis/clients/jedis/args/ListPosition.java b/src/main/java/redis/clients/jedis/args/ListPosition.java index bcc546a26e..04cfdc35e9 100644 --- a/src/main/java/redis/clients/jedis/args/ListPosition.java +++ b/src/main/java/redis/clients/jedis/args/ListPosition.java @@ -3,6 +3,7 @@ import redis.clients.jedis.util.SafeEncoder; public enum ListPosition implements Rawable { + BEFORE, AFTER; private final byte[] raw; diff --git a/src/main/java/redis/clients/jedis/args/UnblockType.java b/src/main/java/redis/clients/jedis/args/UnblockType.java index a69dd4105d..9a6217a8a4 100644 --- a/src/main/java/redis/clients/jedis/args/UnblockType.java +++ b/src/main/java/redis/clients/jedis/args/UnblockType.java @@ -6,11 +6,12 @@ * Unblock type for {@code CLIENT UNBLOCK} command. */ public enum UnblockType implements Rawable { + TIMEOUT, ERROR; private final byte[] raw; - UnblockType() { + private UnblockType() { raw = SafeEncoder.encode(this.name()); } diff --git a/src/main/java/redis/clients/jedis/commands/MiscellaneousPipelineBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/MiscellaneousPipelineBinaryCommands.java index 17c2d253b8..166c597eb2 100644 --- a/src/main/java/redis/clients/jedis/commands/MiscellaneousPipelineBinaryCommands.java +++ b/src/main/java/redis/clients/jedis/commands/MiscellaneousPipelineBinaryCommands.java @@ -9,4 +9,6 @@ public interface MiscellaneousPipelineBinaryCommands { Response publish(byte[] channel, byte[] message); Response strAlgoLCSStrings(final byte[] strA, final byte[] strB, final StrAlgoLCSParams params); + + Response waitReplicas(int replicas, long timeout); } diff --git a/src/main/java/redis/clients/jedis/commands/MiscellaneousPipelineCommands.java b/src/main/java/redis/clients/jedis/commands/MiscellaneousPipelineCommands.java index 6e5e95995a..f4c7a93ddd 100644 --- a/src/main/java/redis/clients/jedis/commands/MiscellaneousPipelineCommands.java +++ b/src/main/java/redis/clients/jedis/commands/MiscellaneousPipelineCommands.java @@ -9,4 +9,6 @@ public interface MiscellaneousPipelineCommands { Response publish(final String channel, final String message); Response strAlgoLCSStrings(final String strA, final String strB, final StrAlgoLCSParams params); + + Response waitReplicas(int replicas, long timeout); } diff --git a/src/main/java/redis/clients/jedis/commands/StringBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/StringBinaryCommands.java index e24c5dc747..b733403601 100644 --- a/src/main/java/redis/clients/jedis/commands/StringBinaryCommands.java +++ b/src/main/java/redis/clients/jedis/commands/StringBinaryCommands.java @@ -3,7 +3,7 @@ import java.util.List; import redis.clients.jedis.args.BitOP; -import redis.clients.jedis.args.BitPosParams; +import redis.clients.jedis.params.BitPosParams; import redis.clients.jedis.params.GetExParams; import redis.clients.jedis.params.SetParams; import redis.clients.jedis.params.StrAlgoLCSParams; diff --git a/src/main/java/redis/clients/jedis/commands/StringCommands.java b/src/main/java/redis/clients/jedis/commands/StringCommands.java index 0ca2ca22e8..1c82960e73 100644 --- a/src/main/java/redis/clients/jedis/commands/StringCommands.java +++ b/src/main/java/redis/clients/jedis/commands/StringCommands.java @@ -3,7 +3,7 @@ import java.util.List; import redis.clients.jedis.args.BitOP; -import redis.clients.jedis.args.BitPosParams; +import redis.clients.jedis.params.BitPosParams; import redis.clients.jedis.params.GetExParams; import redis.clients.jedis.params.SetParams; import redis.clients.jedis.params.StrAlgoLCSParams; diff --git a/src/main/java/redis/clients/jedis/commands/StringPipelineBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/StringPipelineBinaryCommands.java index 85c784a1b1..667f6c94c2 100644 --- a/src/main/java/redis/clients/jedis/commands/StringPipelineBinaryCommands.java +++ b/src/main/java/redis/clients/jedis/commands/StringPipelineBinaryCommands.java @@ -2,7 +2,7 @@ import redis.clients.jedis.Response; import redis.clients.jedis.args.BitOP; -import redis.clients.jedis.args.BitPosParams; +import redis.clients.jedis.params.BitPosParams; import redis.clients.jedis.params.GetExParams; import redis.clients.jedis.params.SetParams; import redis.clients.jedis.params.StrAlgoLCSParams; diff --git a/src/main/java/redis/clients/jedis/commands/StringPipelineCommands.java b/src/main/java/redis/clients/jedis/commands/StringPipelineCommands.java index 3cf0c567d2..1243d51d4e 100644 --- a/src/main/java/redis/clients/jedis/commands/StringPipelineCommands.java +++ b/src/main/java/redis/clients/jedis/commands/StringPipelineCommands.java @@ -2,7 +2,7 @@ import redis.clients.jedis.Response; import redis.clients.jedis.args.BitOP; -import redis.clients.jedis.args.BitPosParams; +import redis.clients.jedis.params.BitPosParams; import redis.clients.jedis.params.GetExParams; import redis.clients.jedis.params.SetParams; import redis.clients.jedis.params.StrAlgoLCSParams; diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxAttemptsException.java b/src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxAttemptsException.java index 35c8a142ad..0373708274 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxAttemptsException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxAttemptsException.java @@ -1,23 +1,23 @@ -package redis.clients.jedis.exceptions; - -/** - * @deprecated This exception class will be removed in future. Use - * {@link JedisClusterOperationException} instead. - */ -@Deprecated -public class JedisClusterMaxAttemptsException extends JedisClusterOperationException { - - private static final long serialVersionUID = 167600616259092761L; - - public JedisClusterMaxAttemptsException(String message) { - super(message); - } - - public JedisClusterMaxAttemptsException(Throwable cause) { - super(cause); - } - - public JedisClusterMaxAttemptsException(String message, Throwable cause) { - super(message, cause); - } -} +//package redis.clients.jedis.exceptions; +// +///** +// * @deprecated This exception class will be removed in future. Use +// * {@link JedisClusterOperationException} instead. +// */ +//@Deprecated +//public class JedisClusterMaxAttemptsException extends JedisClusterOperationException { +// +// private static final long serialVersionUID = 167600616259092761L; +// +// public JedisClusterMaxAttemptsException(String message) { +// super(message); +// } +// +// public JedisClusterMaxAttemptsException(Throwable cause) { +// super(cause); +// } +// +// public JedisClusterMaxAttemptsException(String message, Throwable cause) { +// super(message, cause); +// } +//} diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisExhaustedPoolException.java b/src/main/java/redis/clients/jedis/exceptions/JedisExhaustedPoolException.java index e37e598653..f4aa3bfa15 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisExhaustedPoolException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisExhaustedPoolException.java @@ -1,20 +1,20 @@ -package redis.clients.jedis.exceptions; - -/** - * This exception will be thrown when the Jedis client isn't able to retrieve a connection from the - * pool, since all the connections are being used (a.k.a. an "exhausted" pool). - */ -public class JedisExhaustedPoolException extends JedisException { - - public JedisExhaustedPoolException(String message) { - super(message); - } - - public JedisExhaustedPoolException(Throwable e) { - super(e); - } - - public JedisExhaustedPoolException(String message, Throwable cause) { - super(message, cause); - } -} +//package redis.clients.jedis.exceptions; +// +///** +// * This exception will be thrown when the Jedis client isn't able to retrieve a connection from the +// * pool, since all the connections are being used (a.k.a. an "exhausted" pool). +// */ +//public class JedisExhaustedPoolException extends JedisException { +// +// public JedisExhaustedPoolException(String message) { +// super(message); +// } +// +// public JedisExhaustedPoolException(Throwable e) { +// super(e); +// } +// +// public JedisExhaustedPoolException(String message, Throwable cause) { +// super(message, cause); +// } +//} diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisNoReachableClusterNodeException.java b/src/main/java/redis/clients/jedis/exceptions/JedisNoReachableClusterNodeException.java index cc4495a44e..426bcd7e7a 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisNoReachableClusterNodeException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisNoReachableClusterNodeException.java @@ -1,22 +1,23 @@ -package redis.clients.jedis.exceptions; - -/** - * @deprecated This exception class will be removed in future. Use - * {@link JedisClusterOperationException} instead. - */ -public class JedisNoReachableClusterNodeException extends JedisClusterOperationException { - - private static final long serialVersionUID = 3878122572474110407L; - - public JedisNoReachableClusterNodeException(String message) { - super(message); - } - - public JedisNoReachableClusterNodeException(Throwable cause) { - super(cause); - } - - public JedisNoReachableClusterNodeException(String message, Throwable cause) { - super(message, cause); - } -} +//package redis.clients.jedis.exceptions; +// +///** +// * @deprecated This exception class will be removed in future. Use +// * {@link JedisClusterOperationException} instead. +// */ +//@Deprecated +//public class JedisNoReachableClusterNodeException extends JedisClusterOperationException { +// +// private static final long serialVersionUID = 3878122572474110407L; +// +// public JedisNoReachableClusterNodeException(String message) { +// super(message); +// } +// +// public JedisNoReachableClusterNodeException(Throwable cause) { +// super(cause); +// } +// +// public JedisNoReachableClusterNodeException(String message, Throwable cause) { +// super(message, cause); +// } +//} diff --git a/src/main/java/redis/clients/jedis/args/BitPosParams.java b/src/main/java/redis/clients/jedis/params/BitPosParams.java similarity index 94% rename from src/main/java/redis/clients/jedis/args/BitPosParams.java rename to src/main/java/redis/clients/jedis/params/BitPosParams.java index 412accf548..e07583ba7c 100644 --- a/src/main/java/redis/clients/jedis/args/BitPosParams.java +++ b/src/main/java/redis/clients/jedis/params/BitPosParams.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.args; +package redis.clients.jedis.params; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/redis/clients/jedis/providers/JedisClusterConnectionProvider.java b/src/main/java/redis/clients/jedis/providers/JedisClusterConnectionProvider.java index a9f11daafc..dbed23ed2a 100644 --- a/src/main/java/redis/clients/jedis/providers/JedisClusterConnectionProvider.java +++ b/src/main/java/redis/clients/jedis/providers/JedisClusterConnectionProvider.java @@ -1,5 +1,12 @@ package redis.clients.jedis.providers; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; + import redis.clients.jedis.ClusterCommandArguments; import redis.clients.jedis.CommandArguments; import redis.clients.jedis.HostAndPort; @@ -12,13 +19,6 @@ import redis.clients.jedis.exceptions.JedisException; import redis.clients.jedis.util.Pool; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; - public class JedisClusterConnectionProvider implements JedisConnectionProvider { protected final JedisClusterInfoCache cache; @@ -70,7 +70,7 @@ public HostAndPort getNode(String key) { } public HostAndPort getNode(byte[] key) { - return getNode(key.toString()); + return cache.getSlotNode(JedisClusterCRC16.getSlot(key)); } public Connection getConnection(HostAndPort node) { diff --git a/src/test/java/redis/clients/jedis/tests/ExceptionsTest.java b/src/test/java/redis/clients/jedis/tests/ExceptionsTest.java index 83650c03a3..a1bfe560a7 100644 --- a/src/test/java/redis/clients/jedis/tests/ExceptionsTest.java +++ b/src/test/java/redis/clients/jedis/tests/ExceptionsTest.java @@ -185,33 +185,33 @@ public void cluster() { assertEquals(CAUSE, e.getCause()); } } - - @Test - public void maxAttempts() { - try { - throw new JedisClusterMaxAttemptsException(MESSAGE); - } catch (Exception e) { - assertSame(JedisClusterMaxAttemptsException.class, e.getClass()); - assertEquals(MESSAGE, e.getMessage()); - assertNull(e.getCause()); - } - - try { - throw new JedisClusterMaxAttemptsException(CAUSE); - } catch (Exception e) { - assertSame(JedisClusterMaxAttemptsException.class, e.getClass()); - assertEquals(CAUSE, e.getCause()); - assertEquals(CAUSE.toString(), e.getMessage()); - } - - try { - throw new JedisClusterMaxAttemptsException(MESSAGE, CAUSE); - } catch (Exception e) { - assertSame(JedisClusterMaxAttemptsException.class, e.getClass()); - assertEquals(MESSAGE, e.getMessage()); - assertEquals(CAUSE, e.getCause()); - } - } +// +// @Test +// public void maxAttempts() { +// try { +// throw new JedisClusterMaxAttemptsException(MESSAGE); +// } catch (Exception e) { +// assertSame(JedisClusterMaxAttemptsException.class, e.getClass()); +// assertEquals(MESSAGE, e.getMessage()); +// assertNull(e.getCause()); +// } +// +// try { +// throw new JedisClusterMaxAttemptsException(CAUSE); +// } catch (Exception e) { +// assertSame(JedisClusterMaxAttemptsException.class, e.getClass()); +// assertEquals(CAUSE, e.getCause()); +// assertEquals(CAUSE.toString(), e.getMessage()); +// } +// +// try { +// throw new JedisClusterMaxAttemptsException(MESSAGE, CAUSE); +// } catch (Exception e) { +// assertSame(JedisClusterMaxAttemptsException.class, e.getClass()); +// assertEquals(MESSAGE, e.getMessage()); +// assertEquals(CAUSE, e.getCause()); +// } +// } @Test public void clusterOperation() { @@ -320,33 +320,33 @@ public void jedis() { assertEquals(CAUSE, e.getCause()); } } - - @Test - public void exhaustedPool() { - try { - throw new JedisExhaustedPoolException(MESSAGE); - } catch (Exception e) { - assertSame(JedisExhaustedPoolException.class, e.getClass()); - assertEquals(MESSAGE, e.getMessage()); - assertNull(e.getCause()); - } - - try { - throw new JedisExhaustedPoolException(CAUSE); - } catch (Exception e) { - assertSame(JedisExhaustedPoolException.class, e.getClass()); - assertEquals(CAUSE, e.getCause()); - assertEquals(CAUSE.toString(), e.getMessage()); - } - - try { - throw new JedisExhaustedPoolException(MESSAGE, CAUSE); - } catch (Exception e) { - assertSame(JedisExhaustedPoolException.class, e.getClass()); - assertEquals(MESSAGE, e.getMessage()); - assertEquals(CAUSE, e.getCause()); - } - } +// +// @Test +// public void exhaustedPool() { +// try { +// throw new JedisExhaustedPoolException(MESSAGE); +// } catch (Exception e) { +// assertSame(JedisExhaustedPoolException.class, e.getClass()); +// assertEquals(MESSAGE, e.getMessage()); +// assertNull(e.getCause()); +// } +// +// try { +// throw new JedisExhaustedPoolException(CAUSE); +// } catch (Exception e) { +// assertSame(JedisExhaustedPoolException.class, e.getClass()); +// assertEquals(CAUSE, e.getCause()); +// assertEquals(CAUSE.toString(), e.getMessage()); +// } +// +// try { +// throw new JedisExhaustedPoolException(MESSAGE, CAUSE); +// } catch (Exception e) { +// assertSame(JedisExhaustedPoolException.class, e.getClass()); +// assertEquals(MESSAGE, e.getMessage()); +// assertEquals(CAUSE, e.getCause()); +// } +// } @Test public void movedData() { @@ -377,33 +377,33 @@ public void movedData() { assertEquals(CAUSE, e.getCause()); } } - - @Test - public void noReachableNode() { - try { - throw new JedisNoReachableClusterNodeException(MESSAGE); - } catch (Exception e) { - assertSame(JedisNoReachableClusterNodeException.class, e.getClass()); - assertEquals(MESSAGE, e.getMessage()); - assertNull(e.getCause()); - } - - try { - throw new JedisNoReachableClusterNodeException(CAUSE); - } catch (Exception e) { - assertSame(JedisNoReachableClusterNodeException.class, e.getClass()); - assertEquals(CAUSE, e.getCause()); - assertEquals(CAUSE.toString(), e.getMessage()); - } - - try { - throw new JedisNoReachableClusterNodeException(MESSAGE, CAUSE); - } catch (Exception e) { - assertSame(JedisNoReachableClusterNodeException.class, e.getClass()); - assertEquals(MESSAGE, e.getMessage()); - assertEquals(CAUSE, e.getCause()); - } - } +// +// @Test +// public void noReachableNode() { +// try { +// throw new JedisNoReachableClusterNodeException(MESSAGE); +// } catch (Exception e) { +// assertSame(JedisNoReachableClusterNodeException.class, e.getClass()); +// assertEquals(MESSAGE, e.getMessage()); +// assertNull(e.getCause()); +// } +// +// try { +// throw new JedisNoReachableClusterNodeException(CAUSE); +// } catch (Exception e) { +// assertSame(JedisNoReachableClusterNodeException.class, e.getClass()); +// assertEquals(CAUSE, e.getCause()); +// assertEquals(CAUSE.toString(), e.getMessage()); +// } +// +// try { +// throw new JedisNoReachableClusterNodeException(MESSAGE, CAUSE); +// } catch (Exception e) { +// assertSame(JedisNoReachableClusterNodeException.class, e.getClass()); +// assertEquals(MESSAGE, e.getMessage()); +// assertEquals(CAUSE, e.getCause()); +// } +// } @Test public void noScript() { diff --git a/src/test/java/redis/clients/jedis/tests/HostAndPortTest.java b/src/test/java/redis/clients/jedis/tests/HostAndPortTest.java index 98b4f586ad..c7aebf3753 100644 --- a/src/test/java/redis/clients/jedis/tests/HostAndPortTest.java +++ b/src/test/java/redis/clients/jedis/tests/HostAndPortTest.java @@ -1,15 +1,16 @@ -//package redis.clients.jedis.tests; +package redis.clients.jedis.tests; + +import org.junit.Test; + +import java.util.Arrays; + +import redis.clients.jedis.HostAndPort; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +public class HostAndPortTest { // -//import org.junit.Test; -// -//import java.util.Arrays; -// -//import redis.clients.jedis.HostAndPort; -// -//import static org.junit.Assert.assertArrayEquals; -//import static org.junit.Assert.assertEquals; -// -//public class HostAndPortTest { // @Test // public void checkExtractParts() throws Exception { // String host = "2a11:1b1:0:111:e111:1f11:1111:1f1e:1999"; @@ -42,16 +43,31 @@ // assertEquals(host, hp.getHost()); // assertEquals(port, hp.getPort()); // } + + @Test + public void checkFrom() throws Exception { + String host = "2a11:1b1:0:111:e111:1f11:1111:1f1e:1999"; + int port = 6379; + HostAndPort hp = HostAndPort.from(host + ":" + Integer.toString(port)); + assertEquals(host, hp.getHost()); + assertEquals(port, hp.getPort()); + } // // @Test(expected = IllegalArgumentException.class) // public void checkParseStringWithoutPort() throws Exception { // String host = "localhost"; // HostAndPort.parseString(host + ":"); // } + + @Test(expected = IllegalArgumentException.class) + public void checkFromWithoutPort() throws Exception { + String host = "localhost"; + HostAndPort.from(host + ":"); + } // // @Test // public void checkConvertHost() { // String host = "2a11:1b1:0:111:e111:1f11:1111:1f1e"; // assertEquals(host, HostAndPort.convertHost(host)); // } -//} \ No newline at end of file +} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index 44a44120cf..7f7c7286f6 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -1,204 +1,209 @@ -//package redis.clients.jedis.tests; -// -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertFalse; -//import static org.junit.Assert.assertNotNull; -//import static org.junit.Assert.assertNull; -//import static org.junit.Assert.assertTrue; -//import static org.junit.Assert.fail; -// -//import static redis.clients.jedis.Protocol.CLUSTER_HASHSLOTS; -//import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArraySetEquals; -// -//import java.io.IOException; -//import java.util.ArrayList; -//import java.util.Collection; -//import java.util.Collections; -//import java.util.HashMap; -//import java.util.HashSet; -//import java.util.LinkedHashSet; -//import java.util.List; -//import java.util.Map; -//import java.util.Set; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.Callable; -//import java.util.concurrent.ExecutionException; -//import java.util.concurrent.Future; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//import org.apache.commons.pool2.impl.GenericObjectPoolConfig; -//import org.junit.After; -//import org.junit.AfterClass; -//import org.junit.Before; -//import org.junit.Test; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -// -//import redis.clients.jedis.GeoCoordinate; -//import redis.clients.jedis.HostAndPort; -//import redis.clients.jedis.Jedis; -//import redis.clients.jedis.DefaultJedisClientConfig; -//import redis.clients.jedis.JedisClusterInfoCache; -//import redis.clients.jedis.args.ClusterResetType; -//import redis.clients.jedis.args.GeoUnit; -//import redis.clients.jedis.exceptions.*; -//import redis.clients.jedis.params.GeoRadiusParam; -//import redis.clients.jedis.params.GeoRadiusStoreParam; -//import redis.clients.jedis.tests.utils.JedisClusterTestUtil; -//import redis.clients.jedis.util.JedisClusterCRC16; -// -//public class JedisClusterTest { -// private static Jedis node1; -// private static Jedis node2; -// private static Jedis node3; -// private static Jedis node4; -// private static Jedis nodeSlave2; -// private static final String LOCAL_IP = "127.0.0.1"; -// -// private static final int DEFAULT_TIMEOUT = 2000; -// private static final int DEFAULT_REDIRECTIONS = 5; -// private static final JedisPoolConfig DEFAULT_POOL_CONFIG = new JedisPoolConfig(); -// private static final DefaultJedisClientConfig DEFAULT_CLIENT_CONFIG -// = DefaultJedisClientConfig.builder().password("cluster").build(); -// -// private HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0); -// private HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1); -// private HostAndPort nodeInfo3 = HostAndPortUtil.getClusterServers().get(2); -// private HostAndPort nodeInfo4 = HostAndPortUtil.getClusterServers().get(3); -// private HostAndPort nodeInfoSlave2 = HostAndPortUtil.getClusterServers().get(4); -// protected Logger log = LoggerFactory.getLogger(getClass().getName()); -// -// @Before -// public void setUp() throws InterruptedException { -// node1 = new Jedis(nodeInfo1); -// node1.auth("cluster"); -// node1.flushAll(); -// -// node2 = new Jedis(nodeInfo2); -// node2.auth("cluster"); -// node2.flushAll(); -// -// node3 = new Jedis(nodeInfo3); -// node3.auth("cluster"); -// node3.flushAll(); -// -// node4 = new Jedis(nodeInfo4); -// node4.auth("cluster"); -// node4.flushAll(); -// -// nodeSlave2 = new Jedis(nodeInfoSlave2); -// nodeSlave2.auth("cluster"); -// nodeSlave2.flushAll(); -// // ---- configure cluster -// -// // add nodes to cluster -// node1.clusterMeet(LOCAL_IP, nodeInfo2.getPort()); -// node1.clusterMeet(LOCAL_IP, nodeInfo3.getPort()); -// -// // split available slots across the three nodes -// int slotsPerNode = CLUSTER_HASHSLOTS / 3; -// int[] node1Slots = new int[slotsPerNode]; -// int[] node2Slots = new int[slotsPerNode + 1]; -// int[] node3Slots = new int[slotsPerNode]; -// for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < CLUSTER_HASHSLOTS; i++) { -// if (i < slotsPerNode) { -// node1Slots[slot1++] = i; -// } else if (i > slotsPerNode * 2) { -// node3Slots[slot3++] = i; -// } else { -// node2Slots[slot2++] = i; -// } -// } -// -// node1.clusterAddSlots(node1Slots); -// node2.clusterAddSlots(node2Slots); -// node3.clusterAddSlots(node3Slots); -// -// JedisClusterTestUtil.waitForClusterReady(node1, node2, node3); -// } -// -// @AfterClass -// public static void cleanUp() { -// node1.flushDB(); -// node2.flushDB(); -// node3.flushDB(); -// node4.flushDB(); -// node1.clusterReset(ClusterResetType.SOFT); -// node2.clusterReset(ClusterResetType.SOFT); -// node3.clusterReset(ClusterResetType.SOFT); -// node4.clusterReset(ClusterResetType.SOFT); -// } -// -// @After -// public void tearDown() throws InterruptedException { -// cleanUp(); -// } -// -// @Test(expected = JedisMovedDataException.class) -// public void testThrowMovedException() { -// node1.set("foo", "bar"); -// } -// -// @Test -// public void testMovedExceptionParameters() { -// try { -// node1.set("foo", "bar"); -// } catch (JedisMovedDataException jme) { -// assertEquals(12182, jme.getSlot()); -// assertEquals(new HostAndPort("127.0.0.1", 7381), jme.getTargetNode()); -// return; -// } -// fail(); -// } -// -// @Test(expected = JedisAskDataException.class) -// public void testThrowAskException() { -// int keySlot = JedisClusterCRC16.getSlot("test"); -// String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes()); -// node2.clusterSetSlotMigrating(keySlot, node3Id); -// node2.get("test"); -// } -// -// @Test -// public void testDiscoverNodesAutomatically() { -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); -// -// try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, -// DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { -// assertEquals(3, jc.getClusterNodes().size()); -// } -// -// try (JedisCluster jc2 = new JedisCluster(new HostAndPort("127.0.0.1", 7379), DEFAULT_TIMEOUT, -// DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { -// assertEquals(3, jc2.getClusterNodes().size()); -// } -// } -// -// @Test -// public void testDiscoverNodesAutomaticallyWithSocketConfig() { -// HostAndPort hp = new HostAndPort("127.0.0.1", 7379); -// -// try (JedisCluster jc = new JedisCluster(hp, DEFAULT_CLIENT_CONFIG, DEFAULT_REDIRECTIONS, -// DEFAULT_POOL_CONFIG)) { -// assertEquals(3, jc.getClusterNodes().size()); -// } -// -// try (JedisCluster jc = new JedisCluster(Collections.singleton(hp), DEFAULT_CLIENT_CONFIG, -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// assertEquals(3, jc.getClusterNodes().size()); -// } -// } -// -// @Test -// public void testSetClientName() { -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); -// String clientName = "myAppName"; -// -// try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, -// DEFAULT_REDIRECTIONS, "cluster", clientName, DEFAULT_POOL_CONFIG)) { +package redis.clients.jedis.tests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import static redis.clients.jedis.Protocol.CLUSTER_HASHSLOTS; +import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArraySetEquals; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import redis.clients.jedis.Connection; + +import redis.clients.jedis.GeoCoordinate; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.DefaultJedisClientConfig; +import redis.clients.jedis.JedisCluster; +import redis.clients.jedis.JedisClusterInfoCache; +import redis.clients.jedis.JedisPoolConfig; +import redis.clients.jedis.args.ClusterResetType; +import redis.clients.jedis.args.GeoUnit; +import redis.clients.jedis.exceptions.*; +import redis.clients.jedis.params.GeoRadiusParam; +import redis.clients.jedis.params.GeoRadiusStoreParam; +import redis.clients.jedis.tests.utils.ClientKillerUtil; +import redis.clients.jedis.tests.utils.JedisClusterTestUtil; +import redis.clients.jedis.util.JedisClusterCRC16; +import redis.clients.jedis.util.Pool; + +public class JedisClusterTest { + private static Jedis node1; + private static Jedis node2; + private static Jedis node3; + private static Jedis node4; + private static Jedis nodeSlave2; + private static final String LOCAL_IP = "127.0.0.1"; + + private static final int DEFAULT_TIMEOUT = 2000; + private static final int DEFAULT_REDIRECTIONS = 5; + private static final JedisPoolConfig DEFAULT_POOL_CONFIG = new JedisPoolConfig(); + private static final DefaultJedisClientConfig DEFAULT_CLIENT_CONFIG + = DefaultJedisClientConfig.builder().password("cluster").build(); + + private HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0); + private HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1); + private HostAndPort nodeInfo3 = HostAndPortUtil.getClusterServers().get(2); + private HostAndPort nodeInfo4 = HostAndPortUtil.getClusterServers().get(3); + private HostAndPort nodeInfoSlave2 = HostAndPortUtil.getClusterServers().get(4); + protected Logger log = LoggerFactory.getLogger(getClass().getName()); + + @Before + public void setUp() throws InterruptedException { + node1 = new Jedis(nodeInfo1); + node1.auth("cluster"); + node1.flushAll(); + + node2 = new Jedis(nodeInfo2); + node2.auth("cluster"); + node2.flushAll(); + + node3 = new Jedis(nodeInfo3); + node3.auth("cluster"); + node3.flushAll(); + + node4 = new Jedis(nodeInfo4); + node4.auth("cluster"); + node4.flushAll(); + + nodeSlave2 = new Jedis(nodeInfoSlave2); + nodeSlave2.auth("cluster"); + nodeSlave2.flushAll(); + // ---- configure cluster + + // add nodes to cluster + node1.clusterMeet(LOCAL_IP, nodeInfo2.getPort()); + node1.clusterMeet(LOCAL_IP, nodeInfo3.getPort()); + + // split available slots across the three nodes + int slotsPerNode = CLUSTER_HASHSLOTS / 3; + int[] node1Slots = new int[slotsPerNode]; + int[] node2Slots = new int[slotsPerNode + 1]; + int[] node3Slots = new int[slotsPerNode]; + for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < CLUSTER_HASHSLOTS; i++) { + if (i < slotsPerNode) { + node1Slots[slot1++] = i; + } else if (i > slotsPerNode * 2) { + node3Slots[slot3++] = i; + } else { + node2Slots[slot2++] = i; + } + } + + node1.clusterAddSlots(node1Slots); + node2.clusterAddSlots(node2Slots); + node3.clusterAddSlots(node3Slots); + + JedisClusterTestUtil.waitForClusterReady(node1, node2, node3); + } + + @AfterClass + public static void cleanUp() { + node1.flushDB(); + node2.flushDB(); + node3.flushDB(); + node4.flushDB(); + node1.clusterReset(ClusterResetType.SOFT); + node2.clusterReset(ClusterResetType.SOFT); + node3.clusterReset(ClusterResetType.SOFT); + node4.clusterReset(ClusterResetType.SOFT); + } + + @After + public void tearDown() throws InterruptedException { + cleanUp(); + } + + @Test(expected = JedisMovedDataException.class) + public void testThrowMovedException() { + node1.set("foo", "bar"); + } + + @Test + public void testMovedExceptionParameters() { + try { + node1.set("foo", "bar"); + } catch (JedisMovedDataException jme) { + assertEquals(12182, jme.getSlot()); + assertEquals(new HostAndPort("127.0.0.1", 7381), jme.getTargetNode()); + return; + } + fail(); + } + + @Test(expected = JedisAskDataException.class) + public void testThrowAskException() { + int keySlot = JedisClusterCRC16.getSlot("test"); + String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes()); + node2.clusterSetSlotMigrating(keySlot, node3Id); + node2.get("test"); + } + + @Test + public void testDiscoverNodesAutomatically() { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + + try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + assertEquals(3, jc.getClusterNodes().size()); + } + + try (JedisCluster jc2 = new JedisCluster(new HostAndPort("127.0.0.1", 7379), DEFAULT_TIMEOUT, + DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + assertEquals(3, jc2.getClusterNodes().size()); + } + } + + @Test + public void testDiscoverNodesAutomaticallyWithSocketConfig() { + HostAndPort hp = new HostAndPort("127.0.0.1", 7379); + + try (JedisCluster jc = new JedisCluster(hp, DEFAULT_CLIENT_CONFIG, DEFAULT_REDIRECTIONS, + DEFAULT_POOL_CONFIG)) { + assertEquals(3, jc.getClusterNodes().size()); + } + + try (JedisCluster jc = new JedisCluster(Collections.singleton(hp), DEFAULT_CLIENT_CONFIG, + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + assertEquals(3, jc.getClusterNodes().size()); + } + } + + @Test + public void testSetClientName() { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + String clientName = "myAppName"; + + try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", clientName, DEFAULT_POOL_CONFIG)) { // Map clusterNodes = jc.getClusterNodes(); // Collection values = clusterNodes.values(); // for (JedisPool jedisPool : values) { @@ -209,480 +214,501 @@ // jedis.close(); // } // } -// } -// } -// -// @Test -// public void testSetClientNameWithConfig() { -// HostAndPort hp = new HostAndPort("127.0.0.1", 7379); -// String clientName = "config-pattern-app"; -// try (JedisCluster jc = new JedisCluster(Collections.singleton(hp), -// DefaultJedisClientConfig.builder().password("cluster").clientName(clientName).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + for (Pool pool : jc.getClusterNodes().values()) { + try (Jedis jedis = new Jedis(pool.getResource())) { + assertEquals(clientName, jedis.clientGetname()); + } + } + } + } + + @Test + public void testSetClientNameWithConfig() { + HostAndPort hp = new HostAndPort("127.0.0.1", 7379); + String clientName = "config-pattern-app"; + try (JedisCluster jc = new JedisCluster(Collections.singleton(hp), + DefaultJedisClientConfig.builder().password("cluster").clientName(clientName).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { // jc.getClusterNodes().values().forEach(jedisPool -> { // try (Jedis jedis = jedisPool.getResource()) { // assertEquals(clientName, jedis.clientGetname()); // } // }); -// } -// } -// -// @Test -// public void testCalculateConnectionPerSlot() { -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); -// -// try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, -// DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { -// jc.set("foo", "bar"); -// jc.set("test", "test"); -// assertEquals("bar", node3.get("foo")); -// assertEquals("test", node2.get("test")); -// } -// -// try (JedisCluster jc2 = new JedisCluster(new HostAndPort("127.0.0.1", 7379), DEFAULT_TIMEOUT, -// DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { -// jc2.set("foo", "bar"); -// jc2.set("test", "test"); -// assertEquals("bar", node3.get("foo")); -// assertEquals("test", node2.get("test")); -// } -// } -// -// @Test -// public void testReadonlyAndReadwrite() throws Exception { -// node1.clusterMeet(LOCAL_IP, nodeInfoSlave2.getPort()); -// JedisClusterTestUtil.waitForClusterReady(node1, node2, node3, nodeSlave2); -// -// for (String nodeInfo : node2.clusterNodes().split("\n")) { -// if (nodeInfo.contains("myself")) { -// nodeSlave2.clusterReplicate(nodeInfo.split(" ")[0]); -// break; -// } -// } -// -// try { -// nodeSlave2.get("test"); -// fail(); -// } catch (JedisMovedDataException e) { -// } -// nodeSlave2.readonly(); -// nodeSlave2.get("test"); -// -// nodeSlave2.readwrite(); -// try { -// nodeSlave2.get("test"); -// fail(); -// } catch (JedisMovedDataException e) { -// } -// -// nodeSlave2.clusterReset(ClusterResetType.SOFT); -// nodeSlave2.flushDB(); -// } -// -// /** -// * slot->nodes 15363 node3 e -// */ -// @Test -// public void testMigrate() { -// log.info("test migrate slot"); -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(nodeInfo1); -// try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, -// DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { -// String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes()); -// String node2Id = JedisClusterTestUtil.getNodeId(node2.clusterNodes()); -// node3.clusterSetSlotMigrating(15363, node2Id); -// node2.clusterSetSlotImporting(15363, node3Id); -// try { -// node2.set("e", "e"); -// } catch (JedisMovedDataException jme) { -// assertEquals(15363, jme.getSlot()); -// assertEquals(new HostAndPort(LOCAL_IP, nodeInfo3.getPort()), jme.getTargetNode()); -// } -// -// try { -// node3.set("e", "e"); -// } catch (JedisAskDataException jae) { -// assertEquals(15363, jae.getSlot()); -// assertEquals(new HostAndPort(LOCAL_IP, nodeInfo2.getPort()), jae.getTargetNode()); -// } -// -// jc.set("e", "e"); -// -// try { -// node2.get("e"); -// } catch (JedisMovedDataException jme) { -// assertEquals(15363, jme.getSlot()); -// assertEquals(new HostAndPort(LOCAL_IP, nodeInfo3.getPort()), jme.getTargetNode()); -// } -// try { -// node3.get("e"); -// } catch (JedisAskDataException jae) { -// assertEquals(15363, jae.getSlot()); -// assertEquals(new HostAndPort(LOCAL_IP, nodeInfo2.getPort()), jae.getTargetNode()); -// } -// -// assertEquals("e", jc.get("e")); -// -// node2.clusterSetSlotNode(15363, node2Id); -// node3.clusterSetSlotNode(15363, node2Id); -// // assertEquals("e", jc.get("e")); -// assertEquals("e", node2.get("e")); -// -// // assertEquals("e", node3.get("e")); -// } -// } -// -// @Test -// public void testMigrateToNewNode() throws InterruptedException { -// log.info("test migrate slot to new node"); -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(nodeInfo1); -// try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, -// DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { -// node3.clusterMeet(LOCAL_IP, nodeInfo4.getPort()); -// -// String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes()); -// String node4Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes()); -// JedisClusterTestUtil.waitForClusterReady(node4); -// node3.clusterSetSlotMigrating(15363, node4Id); -// node4.clusterSetSlotImporting(15363, node3Id); -// try { -// node4.set("e", "e"); -// } catch (JedisMovedDataException jme) { -// assertEquals(15363, jme.getSlot()); -// assertEquals(new HostAndPort(LOCAL_IP, nodeInfo3.getPort()), jme.getTargetNode()); -// } -// -// try { -// node3.set("e", "e"); -// } catch (JedisAskDataException jae) { -// assertEquals(15363, jae.getSlot()); -// assertEquals(new HostAndPort(LOCAL_IP, nodeInfo4.getPort()), jae.getTargetNode()); -// } -// -// try { -// node3.set("e", "e"); -// } catch (JedisAskDataException jae) { -// assertEquals(15363, jae.getSlot()); -// assertEquals(new HostAndPort(LOCAL_IP, nodeInfo4.getPort()), jae.getTargetNode()); -// } -// -// jc.set("e", "e"); -// -// try { -// node4.get("e"); -// } catch (JedisMovedDataException jme) { -// assertEquals(15363, jme.getSlot()); -// assertEquals(new HostAndPort(LOCAL_IP, nodeInfo3.getPort()), jme.getTargetNode()); -// } -// try { -// node3.get("e"); -// } catch (JedisAskDataException jae) { -// assertEquals(15363, jae.getSlot()); -// assertEquals(new HostAndPort(LOCAL_IP, nodeInfo4.getPort()), jae.getTargetNode()); -// } -// -// assertEquals("e", jc.get("e")); -// -// node4.clusterSetSlotNode(15363, node4Id); -// node3.clusterSetSlotNode(15363, node4Id); -// // assertEquals("e", jc.get("e")); -// assertEquals("e", node4.get("e")); -// -// // assertEquals("e", node3.get("e")); -// } -// } -// -// @Test -// public void testRecalculateSlotsWhenMoved() throws InterruptedException { -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); -// -// try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, -// DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { -// int slot51 = JedisClusterCRC16.getSlot("51"); -// node2.clusterDelSlots(slot51); -// node3.clusterDelSlots(slot51); -// node3.clusterAddSlots(slot51); -// -// JedisClusterTestUtil.waitForClusterReady(node1, node2, node3); -// jc.set("51", "foo"); -// assertEquals("foo", jc.get("51")); -// } -// } -// -// @Test -// public void testAskResponse() { -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); -// -// try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, -// DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { -// int slot51 = JedisClusterCRC16.getSlot("51"); -// node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes())); -// node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); -// jc.set("51", "foo"); -// assertEquals("foo", jc.get("51")); -// } -// } -// -// @Test -// public void testAskResponseWithConfig() { -// HostAndPort hp = new HostAndPort("127.0.0.1", 7379); -// try (JedisCluster jc = new JedisCluster(Collections.singleton(hp), DEFAULT_CLIENT_CONFIG, -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// int slot51 = JedisClusterCRC16.getSlot("51"); -// node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes())); -// node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); -// jc.set("51", "foo"); -// assertEquals("foo", jc.get("51")); -// } -// } -// + jc.getClusterNodes().values().forEach(pool -> { + try (Jedis jedis = new Jedis(pool.getResource())) { + assertEquals(clientName, jedis.clientGetname()); + } + }); + } + } + + @Test + public void testCalculateConnectionPerSlot() { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + + try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + jc.set("foo", "bar"); + jc.set("test", "test"); + assertEquals("bar", node3.get("foo")); + assertEquals("test", node2.get("test")); + } + + try (JedisCluster jc2 = new JedisCluster(new HostAndPort("127.0.0.1", 7379), DEFAULT_TIMEOUT, + DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + jc2.set("foo", "bar"); + jc2.set("test", "test"); + assertEquals("bar", node3.get("foo")); + assertEquals("test", node2.get("test")); + } + } + + @Test + public void testReadonlyAndReadwrite() throws Exception { + node1.clusterMeet(LOCAL_IP, nodeInfoSlave2.getPort()); + JedisClusterTestUtil.waitForClusterReady(node1, node2, node3, nodeSlave2); + + for (String nodeInfo : node2.clusterNodes().split("\n")) { + if (nodeInfo.contains("myself")) { + nodeSlave2.clusterReplicate(nodeInfo.split(" ")[0]); + break; + } + } + + try { + nodeSlave2.get("test"); + fail(); + } catch (JedisMovedDataException e) { + } + nodeSlave2.readonly(); + nodeSlave2.get("test"); + + nodeSlave2.readwrite(); + try { + nodeSlave2.get("test"); + fail(); + } catch (JedisMovedDataException e) { + } + + nodeSlave2.clusterReset(ClusterResetType.SOFT); + nodeSlave2.flushDB(); + } + + /** + * slot->nodes 15363 node3 e + */ + @Test + public void testMigrate() { + log.info("test migrate slot"); + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(nodeInfo1); + try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes()); + String node2Id = JedisClusterTestUtil.getNodeId(node2.clusterNodes()); + node3.clusterSetSlotMigrating(15363, node2Id); + node2.clusterSetSlotImporting(15363, node3Id); + try { + node2.set("e", "e"); + } catch (JedisMovedDataException jme) { + assertEquals(15363, jme.getSlot()); + assertEquals(new HostAndPort(LOCAL_IP, nodeInfo3.getPort()), jme.getTargetNode()); + } + + try { + node3.set("e", "e"); + } catch (JedisAskDataException jae) { + assertEquals(15363, jae.getSlot()); + assertEquals(new HostAndPort(LOCAL_IP, nodeInfo2.getPort()), jae.getTargetNode()); + } + + jc.set("e", "e"); + + try { + node2.get("e"); + } catch (JedisMovedDataException jme) { + assertEquals(15363, jme.getSlot()); + assertEquals(new HostAndPort(LOCAL_IP, nodeInfo3.getPort()), jme.getTargetNode()); + } + try { + node3.get("e"); + } catch (JedisAskDataException jae) { + assertEquals(15363, jae.getSlot()); + assertEquals(new HostAndPort(LOCAL_IP, nodeInfo2.getPort()), jae.getTargetNode()); + } + + assertEquals("e", jc.get("e")); + + node2.clusterSetSlotNode(15363, node2Id); + node3.clusterSetSlotNode(15363, node2Id); + // assertEquals("e", jc.get("e")); + assertEquals("e", node2.get("e")); + + // assertEquals("e", node3.get("e")); + } + } + + @Test + public void testMigrateToNewNode() throws InterruptedException { + log.info("test migrate slot to new node"); + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(nodeInfo1); + try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + node3.clusterMeet(LOCAL_IP, nodeInfo4.getPort()); + + String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes()); + String node4Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes()); + JedisClusterTestUtil.waitForClusterReady(node4); + node3.clusterSetSlotMigrating(15363, node4Id); + node4.clusterSetSlotImporting(15363, node3Id); + try { + node4.set("e", "e"); + } catch (JedisMovedDataException jme) { + assertEquals(15363, jme.getSlot()); + assertEquals(new HostAndPort(LOCAL_IP, nodeInfo3.getPort()), jme.getTargetNode()); + } + + try { + node3.set("e", "e"); + } catch (JedisAskDataException jae) { + assertEquals(15363, jae.getSlot()); + assertEquals(new HostAndPort(LOCAL_IP, nodeInfo4.getPort()), jae.getTargetNode()); + } + + try { + node3.set("e", "e"); + } catch (JedisAskDataException jae) { + assertEquals(15363, jae.getSlot()); + assertEquals(new HostAndPort(LOCAL_IP, nodeInfo4.getPort()), jae.getTargetNode()); + } + + jc.set("e", "e"); + + try { + node4.get("e"); + } catch (JedisMovedDataException jme) { + assertEquals(15363, jme.getSlot()); + assertEquals(new HostAndPort(LOCAL_IP, nodeInfo3.getPort()), jme.getTargetNode()); + } + try { + node3.get("e"); + } catch (JedisAskDataException jae) { + assertEquals(15363, jae.getSlot()); + assertEquals(new HostAndPort(LOCAL_IP, nodeInfo4.getPort()), jae.getTargetNode()); + } + + assertEquals("e", jc.get("e")); + + node4.clusterSetSlotNode(15363, node4Id); + node3.clusterSetSlotNode(15363, node4Id); + // assertEquals("e", jc.get("e")); + assertEquals("e", node4.get("e")); + + // assertEquals("e", node3.get("e")); + } + } + + @Test + public void testRecalculateSlotsWhenMoved() throws InterruptedException { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + + try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + int slot51 = JedisClusterCRC16.getSlot("51"); + node2.clusterDelSlots(slot51); + node3.clusterDelSlots(slot51); + node3.clusterAddSlots(slot51); + + JedisClusterTestUtil.waitForClusterReady(node1, node2, node3); + jc.set("51", "foo"); + assertEquals("foo", jc.get("51")); + } + } + + @Test + public void testAskResponse() { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + + try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + int slot51 = JedisClusterCRC16.getSlot("51"); + node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes())); + node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); + jc.set("51", "foo"); + assertEquals("foo", jc.get("51")); + } + } + + @Test + public void testAskResponseWithConfig() { + HostAndPort hp = new HostAndPort("127.0.0.1", 7379); + try (JedisCluster jc = new JedisCluster(Collections.singleton(hp), DEFAULT_CLIENT_CONFIG, + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + int slot51 = JedisClusterCRC16.getSlot("51"); + node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes())); + node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); + jc.set("51", "foo"); + assertEquals("foo", jc.get("51")); + } + } + // @Test(expected = JedisClusterMaxAttemptsException.class) -// public void testRedisClusterMaxRedirections() { -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); -// -// try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, -// DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { -// int slot51 = JedisClusterCRC16.getSlot("51"); -// // This will cause an infinite redirection loop -// node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); -// jc.set("51", "foo"); -// } -// } -// + @Test(expected = JedisClusterOperationException.class) + public void testRedisClusterMaxRedirections() { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + + try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + int slot51 = JedisClusterCRC16.getSlot("51"); + // This will cause an infinite redirection loop + node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); + jc.set("51", "foo"); + } + } + // @Test(expected = JedisClusterMaxAttemptsException.class) -// public void testRedisClusterMaxRedirectionsWithConfig() { -// HostAndPort hp = new HostAndPort("127.0.0.1", 7379); -// try (JedisCluster jc = new JedisCluster(Collections.singleton(hp), DEFAULT_CLIENT_CONFIG, -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// int slot51 = JedisClusterCRC16.getSlot("51"); -// // This will cause an infinite redirection loop -// node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); -// jc.set("51", "foo"); -// } -// } -// -// @Test -// public void testClusterForgetNode() throws InterruptedException { -// // at first, join node4 to cluster -// node1.clusterMeet("127.0.0.1", nodeInfo4.getPort()); -// node2.clusterMeet("127.0.0.1", nodeInfo4.getPort()); -// node3.clusterMeet("127.0.0.1", nodeInfo4.getPort()); -// -// String node4Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes()); -// -// JedisClusterTestUtil.assertNodeIsKnown(node1, node4Id, 1000); -// JedisClusterTestUtil.assertNodeIsKnown(node2, node4Id, 1000); -// JedisClusterTestUtil.assertNodeIsKnown(node3, node4Id, 1000); -// -// assertNodeHandshakeEnded(node1, 1000); -// assertNodeHandshakeEnded(node2, 1000); -// assertNodeHandshakeEnded(node3, 1000); -// -// assertEquals(4, node1.clusterNodes().split("\n").length); -// assertEquals(4, node2.clusterNodes().split("\n").length); -// assertEquals(4, node3.clusterNodes().split("\n").length); -// -// // do cluster forget -// node1.clusterForget(node4Id); -// node2.clusterForget(node4Id); -// node3.clusterForget(node4Id); -// -// JedisClusterTestUtil.assertNodeIsUnknown(node1, node4Id, 1000); -// JedisClusterTestUtil.assertNodeIsUnknown(node2, node4Id, 1000); -// JedisClusterTestUtil.assertNodeIsUnknown(node3, node4Id, 1000); -// -// assertEquals(3, node1.clusterNodes().split("\n").length); -// assertEquals(3, node2.clusterNodes().split("\n").length); -// assertEquals(3, node3.clusterNodes().split("\n").length); -// } -// -// @Test -// public void testClusterFlushSlots() { -// String slotRange = getNodeServingSlotRange(node1.clusterNodes()); -// assertNotNull(slotRange); -// -// try { -// node1.clusterFlushSlots(); -// assertNull(getNodeServingSlotRange(node1.clusterNodes())); -// } finally { -// // rollback -// String[] rangeInfo = slotRange.split("-"); -// int lower = Integer.parseInt(rangeInfo[0]); -// int upper = Integer.parseInt(rangeInfo[1]); -// -// int[] node1Slots = new int[upper - lower + 1]; -// for (int i = 0; lower <= upper;) { -// node1Slots[i++] = lower++; -// } -// node1.clusterAddSlots(node1Slots); -// } -// } -// -// @Test -// public void testClusterKeySlot() { -// // It assumes JedisClusterCRC16 is correctly implemented -// assertEquals(JedisClusterCRC16.getSlot("{user1000}.following"), -// node1.clusterKeySlot("{user1000}.following")); -// assertEquals(JedisClusterCRC16.getSlot("foo{bar}{zap}"), -// node1.clusterKeySlot("foo{bar}{zap}")); -// assertEquals(JedisClusterCRC16.getSlot("foo{}{bar}"), -// node1.clusterKeySlot("foo{}{bar}")); -// assertEquals(JedisClusterCRC16.getSlot("foo{{bar}}zap"), -// node1.clusterKeySlot("foo{{bar}}zap")); -// } -// -// @Test -// public void testClusterCountKeysInSlot() { -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); -// -// try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, -// DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { -// -// int count = 5; -// for (int index = 0; index < count; index++) { -// jc.set("foo{bar}" + index, "hello"); -// } -// -// int slot = JedisClusterCRC16.getSlot("foo{bar}"); -// assertEquals(count, node1.clusterCountKeysInSlot(slot)); -// } -// } -// -// @Test -// public void testStableSlotWhenMigratingNodeOrImportingNodeIsNotSpecified() -// throws InterruptedException { -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); -// -// try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, -// DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { -// -// int slot51 = JedisClusterCRC16.getSlot("51"); -// jc.set("51", "foo"); -// // node2 is responsible of taking care of slot51 (7186) -// -// node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes())); -// assertEquals("foo", jc.get("51")); -// node3.clusterSetSlotStable(slot51); -// assertEquals("foo", jc.get("51")); -// -// node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); -// // assertEquals("foo", jc.get("51")); // it leads Max Redirections -// node2.clusterSetSlotStable(slot51); -// assertEquals("foo", jc.get("51")); -// } -// } -// + @Test(expected = JedisClusterOperationException.class) + public void testRedisClusterMaxRedirectionsWithConfig() { + HostAndPort hp = new HostAndPort("127.0.0.1", 7379); + try (JedisCluster jc = new JedisCluster(Collections.singleton(hp), DEFAULT_CLIENT_CONFIG, + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + int slot51 = JedisClusterCRC16.getSlot("51"); + // This will cause an infinite redirection loop + node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); + jc.set("51", "foo"); + } + } + + @Test + public void testClusterForgetNode() throws InterruptedException { + // at first, join node4 to cluster + node1.clusterMeet("127.0.0.1", nodeInfo4.getPort()); + node2.clusterMeet("127.0.0.1", nodeInfo4.getPort()); + node3.clusterMeet("127.0.0.1", nodeInfo4.getPort()); + + String node4Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes()); + + JedisClusterTestUtil.assertNodeIsKnown(node1, node4Id, 1000); + JedisClusterTestUtil.assertNodeIsKnown(node2, node4Id, 1000); + JedisClusterTestUtil.assertNodeIsKnown(node3, node4Id, 1000); + + assertNodeHandshakeEnded(node1, 1000); + assertNodeHandshakeEnded(node2, 1000); + assertNodeHandshakeEnded(node3, 1000); + + assertEquals(4, node1.clusterNodes().split("\n").length); + assertEquals(4, node2.clusterNodes().split("\n").length); + assertEquals(4, node3.clusterNodes().split("\n").length); + + // do cluster forget + node1.clusterForget(node4Id); + node2.clusterForget(node4Id); + node3.clusterForget(node4Id); + + JedisClusterTestUtil.assertNodeIsUnknown(node1, node4Id, 1000); + JedisClusterTestUtil.assertNodeIsUnknown(node2, node4Id, 1000); + JedisClusterTestUtil.assertNodeIsUnknown(node3, node4Id, 1000); + + assertEquals(3, node1.clusterNodes().split("\n").length); + assertEquals(3, node2.clusterNodes().split("\n").length); + assertEquals(3, node3.clusterNodes().split("\n").length); + } + + @Test + public void testClusterFlushSlots() { + String slotRange = getNodeServingSlotRange(node1.clusterNodes()); + assertNotNull(slotRange); + + try { + node1.clusterFlushSlots(); + assertNull(getNodeServingSlotRange(node1.clusterNodes())); + } finally { + // rollback + String[] rangeInfo = slotRange.split("-"); + int lower = Integer.parseInt(rangeInfo[0]); + int upper = Integer.parseInt(rangeInfo[1]); + + int[] node1Slots = new int[upper - lower + 1]; + for (int i = 0; lower <= upper;) { + node1Slots[i++] = lower++; + } + node1.clusterAddSlots(node1Slots); + } + } + + @Test + public void testClusterKeySlot() { + // It assumes JedisClusterCRC16 is correctly implemented + assertEquals(JedisClusterCRC16.getSlot("{user1000}.following"), + node1.clusterKeySlot("{user1000}.following")); + assertEquals(JedisClusterCRC16.getSlot("foo{bar}{zap}"), + node1.clusterKeySlot("foo{bar}{zap}")); + assertEquals(JedisClusterCRC16.getSlot("foo{}{bar}"), + node1.clusterKeySlot("foo{}{bar}")); + assertEquals(JedisClusterCRC16.getSlot("foo{{bar}}zap"), + node1.clusterKeySlot("foo{{bar}}zap")); + } + + @Test + public void testClusterCountKeysInSlot() { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); + + try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + + int count = 5; + for (int index = 0; index < count; index++) { + jc.set("foo{bar}" + index, "hello"); + } + + int slot = JedisClusterCRC16.getSlot("foo{bar}"); + assertEquals(count, node1.clusterCountKeysInSlot(slot)); + } + } + + @Test + public void testStableSlotWhenMigratingNodeOrImportingNodeIsNotSpecified() + throws InterruptedException { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); + + try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + + int slot51 = JedisClusterCRC16.getSlot("51"); + jc.set("51", "foo"); + // node2 is responsible of taking care of slot51 (7186) + + node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes())); + assertEquals("foo", jc.get("51")); + node3.clusterSetSlotStable(slot51); + assertEquals("foo", jc.get("51")); + + node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); + // assertEquals("foo", jc.get("51")); // it leads Max Redirections + node2.clusterSetSlotStable(slot51); + assertEquals("foo", jc.get("51")); + } + } + // @Test(expected = JedisExhaustedPoolException.class) -// public void testIfPoolConfigAppliesToClusterPools() { -// GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); -// config.setMaxTotal(0); -// config.setMaxWaitMillis(DEFAULT_TIMEOUT); -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); -// try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, -// DEFAULT_REDIRECTIONS, "cluster", config)) { -// jc.set("52", "poolTestValue"); -// } -// } -// -// @Test -// public void testCloseable() throws IOException { -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); -// -// JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, -// DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG); -// jc.set("51", "foo"); -// jc.close(); -// -// assertEquals(0, jc.getClusterNodes().size()); -// } -// -// @Test -// public void testCloseableWithConfig() { -// HostAndPort hp = nodeInfo1; -// try (JedisCluster jc = new JedisCluster(hp, DEFAULT_CLIENT_CONFIG, DEFAULT_REDIRECTIONS, -// DEFAULT_POOL_CONFIG)) { -// jc.set("51", "foo"); -// jc.close(); -// -// assertEquals(0, jc.getClusterNodes().size()); -// } -// } -// -// @Test -// public void testJedisClusterTimeout() { -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); -// -// try (JedisCluster jc = new JedisCluster(jedisClusterNode, 4000, 4000, DEFAULT_REDIRECTIONS, -// "cluster", DEFAULT_POOL_CONFIG)) { -// + @Test(expected = JedisException.class) + public void testIfPoolConfigAppliesToClusterPools() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); + config.setMaxTotal(0); + config.setMaxWaitMillis(DEFAULT_TIMEOUT); + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", config)) { + jc.set("52", "poolTestValue"); + } + } + + @Test + public void testCloseable() throws IOException { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); + + JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG); + jc.set("51", "foo"); + jc.close(); + + assertEquals(0, jc.getClusterNodes().size()); + } + + @Test + public void testCloseableWithConfig() { + HostAndPort hp = nodeInfo1; + try (JedisCluster jc = new JedisCluster(hp, DEFAULT_CLIENT_CONFIG, DEFAULT_REDIRECTIONS, + DEFAULT_POOL_CONFIG)) { + jc.set("51", "foo"); + jc.close(); + + assertEquals(0, jc.getClusterNodes().size()); + } + } + + @Test + public void testJedisClusterTimeout() { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); + + try (JedisCluster jc = new JedisCluster(jedisClusterNode, 4000, 4000, DEFAULT_REDIRECTIONS, + "cluster", DEFAULT_POOL_CONFIG)) { + // for (JedisPool pool : jc.getClusterNodes().values()) { // Jedis jedis = pool.getResource(); // assertEquals(4000, jedis.getClient().getConnectionTimeout()); // assertEquals(4000, jedis.getClient().getSoTimeout()); // jedis.close(); // } -// } -// } -// -// @Test -// public void testJedisClusterTimeoutWithConfig() { -// HostAndPort hp = nodeInfo1; -// try (JedisCluster jc = new JedisCluster(hp, DefaultJedisClientConfig.builder() -// .connectionTimeoutMillis(4000).socketTimeoutMillis(4000).password("cluster").build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// -// jc.getClusterNodes().values().forEach(pool -> { + for (Pool pool : jc.getClusterNodes().values()) { + try (Connection conn = pool.getResource()) { + assertEquals(4000, conn.getSoTimeout()); + } + } + } + } + + @Test + public void testJedisClusterTimeoutWithConfig() { + HostAndPort hp = nodeInfo1; + try (JedisCluster jc = new JedisCluster(hp, DefaultJedisClientConfig.builder() + .connectionTimeoutMillis(4000).socketTimeoutMillis(4000).password("cluster").build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + + jc.getClusterNodes().values().forEach(pool -> { // try (Jedis jedis = pool.getResource()) { // assertEquals(4000, jedis.getClient().getConnectionTimeout()); // assertEquals(4000, jedis.getClient().getSoTimeout()); // } -// }); -// } -// } -// -// @Test -// public void testJedisClusterRunsWithMultithreaded() throws InterruptedException, -// ExecutionException, IOException { -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); -// final JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, -// DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG); -// jc.set("foo", "bar"); -// -// ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 0, TimeUnit.SECONDS, -// new ArrayBlockingQueue(10)); -// List> futures = new ArrayList>(); -// for (int i = 0; i < 50; i++) { -// executor.submit(new Callable() { -// @Override -// public String call() throws Exception { -// // FIXME : invalidate slot cache from JedisCluster to test -// // random connection also does work -// return jc.get("foo"); -// } -// }); -// } -// -// for (Future future : futures) { -// String value = future.get(); -// assertEquals("bar", value); -// } -// -// jc.close(); -// } -// -// @Test(timeout = DEFAULT_TIMEOUT) + try (Connection conn = pool.getResource()) { + assertEquals(4000, conn.getSoTimeout()); + } + }); + } + } + + @Test + public void testJedisClusterRunsWithMultithreaded() throws InterruptedException, + ExecutionException, IOException { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + final JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG); + jc.set("foo", "bar"); + + ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 0, TimeUnit.SECONDS, + new ArrayBlockingQueue(10)); + List> futures = new ArrayList>(); + for (int i = 0; i < 50; i++) { + executor.submit(new Callable() { + @Override + public String call() throws Exception { + // FIXME : invalidate slot cache from JedisCluster to test + // random connection also does work + return jc.get("foo"); + } + }); + } + + for (Future future : futures) { + String value = future.get(); + assertEquals("bar", value); + } + + jc.close(); + } +// +// @Test(timeout = DEFAULT_TIMEOUT * 2) // public void testReturnConnectionOnJedisConnectionException() throws InterruptedException { // Set jedisClusterNode = new HashSet(); // jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); @@ -691,7 +717,16 @@ // try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, // DEFAULT_REDIRECTIONS, "cluster", config)) { // -// try (Jedis j = jc.getClusterNodes().get("127.0.0.1:7380").getResource()) { +//// try (Jedis j = jc.getClusterNodes().get("127.0.0.1:7380").getResource()) { +//// ClientKillerUtil.tagClient(j, "DEAD"); +//// ClientKillerUtil.killClient(j, "DEAD"); +//// } +//// try (Connection c = jc.getClusterNodes().get("127.0.0.1:7380").getResource()) { +//// ClientKillerUtil.tagClient(c, "DEAD"); +//// ClientKillerUtil.killClient(c, "DEAD"); +//// } +// try (Connection c = jc.getClusterNodes().get("127.0.0.1:7380").getResource()) { +// Jedis j = new Jedis(c); // ClientKillerUtil.tagClient(j, "DEAD"); // ClientKillerUtil.killClient(j, "DEAD"); // } @@ -714,244 +749,252 @@ // jc.get("e"); // } // } -// -// @Test -// public void testLocalhostNodeNotAddedWhen127Present() { -// HostAndPort localhost = new HostAndPort("localhost", 7379); -// Set jedisClusterNode = new HashSet(); -// // cluster node is defined as 127.0.0.1; adding localhost should work, -// // but shouldn't show up. -// jedisClusterNode.add(localhost); -// JedisPoolConfig config = new JedisPoolConfig(); -// config.setMaxTotal(1); -// -// try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, -// DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + + @Test + public void testLocalhostNodeNotAddedWhen127Present() { + HostAndPort localhost = new HostAndPort("localhost", 7379); + Set jedisClusterNode = new HashSet(); + // cluster node is defined as 127.0.0.1; adding localhost should work, + // but shouldn't show up. + jedisClusterNode.add(localhost); + JedisPoolConfig config = new JedisPoolConfig(); + config.setMaxTotal(1); + + try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { // Map clusterNodes = jc.getClusterNodes(); -// assertEquals(3, clusterNodes.size()); -// assertFalse(clusterNodes.containsKey(JedisClusterInfoCache.getNodeKey(localhost))); -// } -// } -// -// @Test -// public void testInvalidStartNodeNotAdded() { -// HostAndPort invalidHost = new HostAndPort("not-a-real-host", 7379); -// Set jedisClusterNode = new LinkedHashSet(); -// jedisClusterNode.add(invalidHost); -// jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); -// JedisPoolConfig config = new JedisPoolConfig(); -// config.setMaxTotal(1); -// try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, -// DEFAULT_REDIRECTIONS, "cluster", config)) { + Map clusterNodes = jc.getClusterNodes(); + assertEquals(3, clusterNodes.size()); + assertFalse(clusterNodes.containsKey(JedisClusterInfoCache.getNodeKey(localhost))); + } + } + + @Test + public void testInvalidStartNodeNotAdded() { + HostAndPort invalidHost = new HostAndPort("not-a-real-host", 7379); + Set jedisClusterNode = new LinkedHashSet(); + jedisClusterNode.add(invalidHost); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + JedisPoolConfig config = new JedisPoolConfig(); + config.setMaxTotal(1); + try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", config)) { // Map clusterNodes = jc.getClusterNodes(); -// assertEquals(3, clusterNodes.size()); -// assertFalse(clusterNodes.containsKey(JedisClusterInfoCache.getNodeKey(invalidHost))); -// } -// } -// -// @Test -// public void nullKeys() { -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); -// -// try (JedisCluster cluster = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, -// DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { -// -// String foo = "foo"; -// byte[] bfoo = new byte[] { 0x0b, 0x0f, 0x00, 0x00 }; -// -// try { -// cluster.exists((String) null); -// fail(); + Map clusterNodes = jc.getClusterNodes(); + assertEquals(3, clusterNodes.size()); + assertFalse(clusterNodes.containsKey(JedisClusterInfoCache.getNodeKey(invalidHost))); + } + } + + @Test + public void nullKeys() { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); + + try (JedisCluster cluster = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, + DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + + String foo = "foo"; + byte[] bfoo = new byte[] { 0x0b, 0x0f, 0x00, 0x00 }; + + try { + cluster.exists((String) null); + fail(); // } catch (JedisClusterOperationException coe) { -// // expected -// } -// -// try { -// cluster.exists(foo, null); -// fail(); + } catch (NullPointerException coe) { + // expected + } + + try { + cluster.exists(foo, null); + fail(); // } catch (JedisClusterOperationException coe) { -// // expected -// } -// -// try { -// cluster.exists(null, foo); -// fail(); + } catch (NullPointerException coe) { + // expected + } + + try { + cluster.exists(null, foo); + fail(); // } catch (JedisClusterOperationException coe) { -// // expected -// } -// -// try { -// cluster.exists((byte[]) null); -// fail(); + } catch (NullPointerException coe) { + // expected + } + + try { + cluster.exists((byte[]) null); + fail(); // } catch (JedisClusterOperationException coe) { -// // expected -// } -// -// try { -// cluster.exists(bfoo, null); -// fail(); + } catch (NullPointerException coe) { + // expected + } + + try { + cluster.exists(bfoo, null); + fail(); // } catch (JedisClusterOperationException coe) { -// // expected -// } -// -// try { -// cluster.exists(null, bfoo); -// fail(); + } catch (NullPointerException coe) { + // expected + } + + try { + cluster.exists(null, bfoo); + fail(); // } catch (JedisClusterOperationException coe) { -// // expected -// } -// } -// } -// -// -// @Test -// public void clusterRefreshNodes() throws Exception { -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(nodeInfo1); -// jedisClusterNode.add(nodeInfo2); -// jedisClusterNode.add(nodeInfo3); -// -// try (JedisCluster cluster = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, -// DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { -// assertEquals(3, cluster.getClusterNodes().size()); -// cleanUp(); // cleanup and add node4 -// -// // at first, join node4 to cluster -// node1.clusterMeet(LOCAL_IP, nodeInfo2.getPort()); -// node1.clusterMeet(LOCAL_IP, nodeInfo3.getPort()); -// node1.clusterMeet(LOCAL_IP, nodeInfo4.getPort()); -// // split available slots across the three nodes -// int slotsPerNode = CLUSTER_HASHSLOTS / 4; -// int[] node1Slots = new int[slotsPerNode]; -// int[] node2Slots = new int[slotsPerNode]; -// int[] node3Slots = new int[slotsPerNode]; -// int[] node4Slots = new int[slotsPerNode]; -// for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0, slot4 = 0; i < CLUSTER_HASHSLOTS; i++) { -// if (i < slotsPerNode) { -// node1Slots[slot1++] = i; -// } else if (i >= slotsPerNode && i < slotsPerNode*2) { -// node2Slots[slot2++] = i; -// } else if (i >= slotsPerNode*2 && i < slotsPerNode*3) { -// node3Slots[slot3++] = i; -// } else { -// node4Slots[slot4++] = i; -// } -// } -// -// node1.clusterAddSlots(node1Slots); -// node2.clusterAddSlots(node2Slots); -// node3.clusterAddSlots(node3Slots); -// node4.clusterAddSlots(node4Slots); -// JedisClusterTestUtil.waitForClusterReady(node1, node2, node3, node4); -// -// // cluster.set("key", "value"); will get JedisMovedDataException and renewSlotCache -// cluster.set("key", "value"); -// -// assertEquals(4, cluster.getClusterNodes().size()); -// String nodeKey4 = LOCAL_IP + ":" + nodeInfo4.getPort(); -// assertTrue(cluster.getClusterNodes().keySet().contains(nodeKey4)); -// -// // make 4 nodes to 3 nodes -// cleanUp(); -// setUp(); -// // cluster.set("bar", "foo") will get JedisMovedDataException and renewSlotCache -// cluster.set("bar", "foo"); -// assertEquals(3, cluster.getClusterNodes().size()); -// } -// } -// -// @Test -// public void georadiusStore() { -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(nodeInfo1); -// jedisClusterNode.add(nodeInfo2); -// jedisClusterNode.add(nodeInfo3); -// -// try (JedisCluster cluster = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, -// DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { -// -// // prepare datas -// Map coordinateMap = new HashMap(); -// coordinateMap.put("Palermo", new GeoCoordinate(13.361389, 38.115556)); -// coordinateMap.put("Catania", new GeoCoordinate(15.087269, 37.502669)); -// cluster.geoadd("{Sicily}", coordinateMap); -// -// long size = cluster.georadiusStore("{Sicily}", 15, 37, 200, GeoUnit.KM, -// GeoRadiusParam.geoRadiusParam(), -// GeoRadiusStoreParam.geoRadiusStoreParam().store("{Sicily}Store")); -// assertEquals(2, size); -// Set expected = new LinkedHashSet(); -// expected.add("Palermo"); -// expected.add("Catania"); -// assertEquals(expected, cluster.zrange("{Sicily}Store", 0, -1)); -// } -// } -// -// @Test -// public void georadiusStoreBinary() { -// Set jedisClusterNode = new HashSet(); -// jedisClusterNode.add(nodeInfo1); -// jedisClusterNode.add(nodeInfo2); -// jedisClusterNode.add(nodeInfo3); -// -// try (JedisCluster cluster = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, -// DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { -// -// // prepare datas -// Map bcoordinateMap = new HashMap(); -// bcoordinateMap.put("Palermo".getBytes(), new GeoCoordinate(13.361389, 38.115556)); -// bcoordinateMap.put("Catania".getBytes(), new GeoCoordinate(15.087269, 37.502669)); -// cluster.geoadd("{Sicily}".getBytes(), bcoordinateMap); -// -// long size = cluster.georadiusStore("{Sicily}".getBytes(), 15, 37, 200, GeoUnit.KM, -// GeoRadiusParam.geoRadiusParam(), -// GeoRadiusStoreParam.geoRadiusStoreParam().store("{Sicily}Store")); -// assertEquals(2, size); -// Set bexpected = new LinkedHashSet(); -// bexpected.add("Palermo".getBytes()); -// bexpected.add("Palermo".getBytes()); -// assertByteArraySetEquals(bexpected, cluster.zrange("{Sicily}Store".getBytes(), 0, -1)); -// } -// } -// -// private static String getNodeServingSlotRange(String infoOutput) { -// // f4f3dc4befda352a4e0beccf29f5e8828438705d 127.0.0.1:7380 master - 0 -// // 1394372400827 0 connected 5461-10922 -// for (String infoLine : infoOutput.split("\n")) { -// if (infoLine.contains("myself")) { -// try { -// return infoLine.split(" ")[8]; -// } catch (ArrayIndexOutOfBoundsException e) { -// return null; -// } -// } -// } -// return null; -// } -// -// private void assertNodeHandshakeEnded(Jedis node, int timeoutMs) { -// int sleepInterval = 100; -// for (int sleepTime = 0; sleepTime <= timeoutMs; sleepTime += sleepInterval) { -// boolean isHandshaking = isAnyNodeHandshaking(node); -// if (!isHandshaking) return; -// -// try { -// Thread.sleep(sleepInterval); -// } catch (InterruptedException e) { -// } -// } -// -// throw new JedisException("Node handshaking is not ended"); -// } -// -// private boolean isAnyNodeHandshaking(Jedis node) { -// String infoOutput = node.clusterNodes(); -// for (String infoLine : infoOutput.split("\n")) { -// if (infoLine.contains("handshake")) { -// return true; -// } -// } -// return false; -// } -//} + } catch (NullPointerException coe) { + // expected + } + } + } + + + @Test + public void clusterRefreshNodes() throws Exception { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(nodeInfo1); + jedisClusterNode.add(nodeInfo2); + jedisClusterNode.add(nodeInfo3); + + try (JedisCluster cluster = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, + DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + assertEquals(3, cluster.getClusterNodes().size()); + cleanUp(); // cleanup and add node4 + + // at first, join node4 to cluster + node1.clusterMeet(LOCAL_IP, nodeInfo2.getPort()); + node1.clusterMeet(LOCAL_IP, nodeInfo3.getPort()); + node1.clusterMeet(LOCAL_IP, nodeInfo4.getPort()); + // split available slots across the three nodes + int slotsPerNode = CLUSTER_HASHSLOTS / 4; + int[] node1Slots = new int[slotsPerNode]; + int[] node2Slots = new int[slotsPerNode]; + int[] node3Slots = new int[slotsPerNode]; + int[] node4Slots = new int[slotsPerNode]; + for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0, slot4 = 0; i < CLUSTER_HASHSLOTS; i++) { + if (i < slotsPerNode) { + node1Slots[slot1++] = i; + } else if (i >= slotsPerNode && i < slotsPerNode*2) { + node2Slots[slot2++] = i; + } else if (i >= slotsPerNode*2 && i < slotsPerNode*3) { + node3Slots[slot3++] = i; + } else { + node4Slots[slot4++] = i; + } + } + + node1.clusterAddSlots(node1Slots); + node2.clusterAddSlots(node2Slots); + node3.clusterAddSlots(node3Slots); + node4.clusterAddSlots(node4Slots); + JedisClusterTestUtil.waitForClusterReady(node1, node2, node3, node4); + + // cluster.set("key", "value"); will get JedisMovedDataException and renewSlotCache + cluster.set("key", "value"); + + assertEquals(4, cluster.getClusterNodes().size()); + String nodeKey4 = LOCAL_IP + ":" + nodeInfo4.getPort(); + assertTrue(cluster.getClusterNodes().keySet().contains(nodeKey4)); + + // make 4 nodes to 3 nodes + cleanUp(); + setUp(); + // cluster.set("bar", "foo") will get JedisMovedDataException and renewSlotCache + cluster.set("bar", "foo"); + assertEquals(3, cluster.getClusterNodes().size()); + } + } + + @Test + public void georadiusStore() { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(nodeInfo1); + jedisClusterNode.add(nodeInfo2); + jedisClusterNode.add(nodeInfo3); + + try (JedisCluster cluster = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, + DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + + // prepare datas + Map coordinateMap = new HashMap(); + coordinateMap.put("Palermo", new GeoCoordinate(13.361389, 38.115556)); + coordinateMap.put("Catania", new GeoCoordinate(15.087269, 37.502669)); + cluster.geoadd("{Sicily}", coordinateMap); + + long size = cluster.georadiusStore("{Sicily}", 15, 37, 200, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam(), + GeoRadiusStoreParam.geoRadiusStoreParam().store("{Sicily}Store")); + assertEquals(2, size); + Set expected = new LinkedHashSet(); + expected.add("Palermo"); + expected.add("Catania"); + assertEquals(expected, cluster.zrange("{Sicily}Store", 0, -1)); + } + } + + @Test + public void georadiusStoreBinary() { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(nodeInfo1); + jedisClusterNode.add(nodeInfo2); + jedisClusterNode.add(nodeInfo3); + + try (JedisCluster cluster = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, + DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + + // prepare datas + Map bcoordinateMap = new HashMap(); + bcoordinateMap.put("Palermo".getBytes(), new GeoCoordinate(13.361389, 38.115556)); + bcoordinateMap.put("Catania".getBytes(), new GeoCoordinate(15.087269, 37.502669)); + cluster.geoadd("{Sicily}".getBytes(), bcoordinateMap); + + long size = cluster.georadiusStore("{Sicily}".getBytes(), 15, 37, 200, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam(), + GeoRadiusStoreParam.geoRadiusStoreParam().store("{Sicily}Store")); + assertEquals(2, size); + Set bexpected = new LinkedHashSet(); + bexpected.add("Palermo".getBytes()); + bexpected.add("Palermo".getBytes()); + assertByteArraySetEquals(bexpected, cluster.zrange("{Sicily}Store".getBytes(), 0, -1)); + } + } + + private static String getNodeServingSlotRange(String infoOutput) { + // f4f3dc4befda352a4e0beccf29f5e8828438705d 127.0.0.1:7380 master - 0 + // 1394372400827 0 connected 5461-10922 + for (String infoLine : infoOutput.split("\n")) { + if (infoLine.contains("myself")) { + try { + return infoLine.split(" ")[8]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + } + return null; + } + + private void assertNodeHandshakeEnded(Jedis node, int timeoutMs) { + int sleepInterval = 100; + for (int sleepTime = 0; sleepTime <= timeoutMs; sleepTime += sleepInterval) { + boolean isHandshaking = isAnyNodeHandshaking(node); + if (!isHandshaking) return; + + try { + Thread.sleep(sleepInterval); + } catch (InterruptedException e) { + } + } + + throw new JedisException("Node handshaking is not ended"); + } + + private boolean isAnyNodeHandshaking(Jedis node) { + String infoOutput = node.clusterNodes(); + for (String infoLine : infoOutput.split("\n")) { + if (infoLine.contains("handshake")) { + return true; + } + } + return false; + } +} diff --git a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java index a81469684e..aacb16700a 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java @@ -1,447 +1,450 @@ -//package redis.clients.jedis.tests; -// -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertNull; -//import static org.junit.Assert.assertSame; -//import static org.junit.Assert.assertTrue; -//import static org.junit.Assert.fail; -// -//import java.net.URI; -//import java.net.URISyntaxException; -//import java.util.concurrent.atomic.AtomicInteger; -//import org.apache.commons.pool2.PooledObject; -//import org.apache.commons.pool2.PooledObjectFactory; -//import org.apache.commons.pool2.impl.DefaultPooledObject; -//import org.apache.commons.pool2.impl.GenericObjectPoolConfig; -//import org.junit.Test; -// -//import redis.clients.jedis.DefaultJedisClientConfig; -//import redis.clients.jedis.HostAndPort; -//import redis.clients.jedis.Jedis; -//import redis.clients.jedis.JedisFactory; -//import redis.clients.jedis.JedisPool; -//import redis.clients.jedis.JedisPoolConfig; -//import redis.clients.jedis.Transaction; -//import redis.clients.jedis.exceptions.InvalidURIException; -//import redis.clients.jedis.exceptions.JedisConnectionException; -//import redis.clients.jedis.exceptions.JedisException; +package redis.clients.jedis.tests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.commons.pool2.PooledObject; +import org.apache.commons.pool2.PooledObjectFactory; +import org.apache.commons.pool2.impl.DefaultPooledObject; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import org.junit.Test; + +import redis.clients.jedis.DefaultJedisClientConfig; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisFactory; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; +import redis.clients.jedis.Transaction; +import redis.clients.jedis.exceptions.InvalidURIException; +import redis.clients.jedis.exceptions.JedisConnectionException; +import redis.clients.jedis.exceptions.JedisException; //import redis.clients.jedis.exceptions.JedisExhaustedPoolException; -// -//public class JedisPoolTest { -// private static final HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); -// -// @Test -// public void checkConnections() { -// JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000); -// try (Jedis jedis = pool.getResource()) { -// jedis.auth("foobared"); -// jedis.set("foo", "bar"); -// assertEquals("bar", jedis.get("foo")); -// } -// pool.close(); -// assertTrue(pool.isClosed()); -// } -// -// @Test -// public void checkResourceWithConfig() { -// try (JedisPool pool = new JedisPool(HostAndPortUtil.getRedisServers().get(7), -// DefaultJedisClientConfig.builder().socketTimeoutMillis(5000).build())) { -// -// try (Jedis jedis = pool.getResource()) { -// assertEquals("PONG", jedis.ping()); + +public class JedisPoolTest { + + private static final HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); + + @Test + public void checkConnections() { + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000); + try (Jedis jedis = pool.getResource()) { + jedis.auth("foobared"); + jedis.set("foo", "bar"); + assertEquals("bar", jedis.get("foo")); + } + pool.close(); + assertTrue(pool.isClosed()); + } + + @Test + public void checkResourceWithConfig() { + try (JedisPool pool = new JedisPool(HostAndPortUtil.getRedisServers().get(7), + DefaultJedisClientConfig.builder().socketTimeoutMillis(5000).build())) { + + try (Jedis jedis = pool.getResource()) { + assertEquals("PONG", jedis.ping()); // assertEquals(5000, jedis.getClient().getSoTimeout()); -// jedis.close(); -// } -// } -// } -// -// @Test -// public void checkCloseableConnections() throws Exception { -// JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000); -// try (Jedis jedis = pool.getResource()) { -// jedis.auth("foobared"); -// jedis.set("foo", "bar"); -// assertEquals("bar", jedis.get("foo")); -// } -// pool.close(); -// assertTrue(pool.isClosed()); -// } -// -// @Test -// public void checkConnectionWithDefaultPort() { -// JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost()); -// try (Jedis jedis = pool.getResource()) { -// jedis.auth("foobared"); -// jedis.set("foo", "bar"); -// assertEquals("bar", jedis.get("foo")); -// } -// pool.close(); -// assertTrue(pool.isClosed()); -// } -// -// @Test -// public void checkResourceIsClosableAndReusable() { -// GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); -// config.setMaxTotal(1); -// config.setBlockWhenExhausted(false); -// try (JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, "foobared", 0, -// "closable-resuable-pool", false, null, null, null)) { -// -// Jedis jedis = pool.getResource(); -// jedis.set("hello", "jedis"); -// jedis.close(); -// -// Jedis jedis2 = pool.getResource(); -// assertEquals(jedis, jedis2); -// assertEquals("jedis", jedis2.get("hello")); -// jedis2.close(); -// } -// } -// -// @Test -// public void checkPoolRepairedWhenJedisIsBroken() { -// JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort()); -// try (Jedis jedis = pool.getResource()) { -// jedis.auth("foobared"); -// jedis.set("foo", "0"); -// jedis.quit(); -// } -// -// try (Jedis jedis = pool.getResource()) { -// jedis.auth("foobared"); -// jedis.incr("foo"); -// } -// pool.close(); -// assertTrue(pool.isClosed()); -// } -// + assertEquals(5000, jedis.getClient().getSoTimeout()); + jedis.close(); + } + } + } + + @Test + public void checkCloseableConnections() throws Exception { + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000); + try (Jedis jedis = pool.getResource()) { + jedis.auth("foobared"); + jedis.set("foo", "bar"); + assertEquals("bar", jedis.get("foo")); + } + pool.close(); + assertTrue(pool.isClosed()); + } + + @Test + public void checkConnectionWithDefaultPort() { + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost()); + try (Jedis jedis = pool.getResource()) { + jedis.auth("foobared"); + jedis.set("foo", "bar"); + assertEquals("bar", jedis.get("foo")); + } + pool.close(); + assertTrue(pool.isClosed()); + } + + @Test + public void checkResourceIsClosableAndReusable() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + try (JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, "foobared", 0, + "closable-resuable-pool", false, null, null, null)) { + + Jedis jedis = pool.getResource(); + jedis.set("hello", "jedis"); + jedis.close(); + + Jedis jedis2 = pool.getResource(); + assertEquals(jedis, jedis2); + assertEquals("jedis", jedis2.get("hello")); + jedis2.close(); + } + } + + @Test + public void checkPoolRepairedWhenJedisIsBroken() { + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort()); + try (Jedis jedis = pool.getResource()) { + jedis.auth("foobared"); + jedis.set("foo", "0"); + jedis.quit(); + } + + try (Jedis jedis = pool.getResource()) { + jedis.auth("foobared"); + jedis.incr("foo"); + } + pool.close(); + assertTrue(pool.isClosed()); + } + // @Test(expected = JedisExhaustedPoolException.class) -// public void checkPoolOverflow() { -// GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); -// config.setMaxTotal(1); -// config.setBlockWhenExhausted(false); -// try (JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort()); -// Jedis jedis = pool.getResource()) { -// jedis.auth("foobared"); -// -// try (Jedis jedis2 = pool.getResource()) { -// jedis2.auth("foobared"); -// } -// } -// } -// -// @Test -// public void securePool() { -// JedisPoolConfig config = new JedisPoolConfig(); -// config.setTestOnBorrow(true); -// JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, "foobared"); -// try (Jedis jedis = pool.getResource()) { -// jedis.set("foo", "bar"); -// } -// pool.close(); -// assertTrue(pool.isClosed()); -// } -// -// @Test -// public void nonDefaultDatabase() { -// try (JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, -// "foobared"); Jedis jedis0 = pool0.getResource()) { -// jedis0.set("foo", "bar"); -// assertEquals("bar", jedis0.get("foo")); -// } -// -// try (JedisPool pool1 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, -// "foobared", 1); Jedis jedis1 = pool1.getResource()) { -// assertNull(jedis1.get("foo")); -// } -// } -// -// @Test -// public void startWithUrlString() { -// try (Jedis j = new Jedis("localhost", 6380)) { -// j.auth("foobared"); -// j.select(2); -// j.set("foo", "bar"); -// } -// -// try (JedisPool pool = new JedisPool("redis://:foobared@localhost:6380/2"); -// Jedis jedis = pool.getResource()) { -// assertEquals("PONG", jedis.ping()); -// assertEquals("bar", jedis.get("foo")); -// } -// } -// -// @Test -// public void startWithUrl() throws URISyntaxException { -// try (Jedis j = new Jedis("localhost", 6380)) { -// j.auth("foobared"); -// j.select(2); -// j.set("foo", "bar"); -// } -// -// try (JedisPool pool = new JedisPool(new URI("redis://:foobared@localhost:6380/2")); -// Jedis jedis = pool.getResource()) { -// assertEquals("bar", jedis.get("foo")); -// } -// } -// -// @Test(expected = InvalidURIException.class) -// public void shouldThrowInvalidURIExceptionForInvalidURI() throws URISyntaxException { -// new JedisPool(new URI("localhost:6380")).close(); -// } -// -// @Test -// public void allowUrlWithNoDBAndNoPassword() throws URISyntaxException { -// new JedisPool("redis://localhost:6380").close(); -// new JedisPool(new URI("redis://localhost:6380")).close(); -// } -// -// @Test -// public void selectDatabaseOnActivation() { -// try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, -// "foobared")) { -// -// Jedis jedis0 = pool.getResource(); -// assertEquals(0, jedis0.getDB()); -// -// jedis0.select(1); -// assertEquals(1, jedis0.getDB()); -// -// jedis0.close(); -// -// Jedis jedis1 = pool.getResource(); -// assertTrue("Jedis instance was not reused", jedis1 == jedis0); -// assertEquals(0, jedis1.getDB()); -// -// jedis1.close(); -// } -// } -// -// @Test -// public void customClientName() { -// try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, -// "foobared", 0, "my_shiny_client_name"); Jedis jedis = pool.getResource()) { -// -// assertEquals("my_shiny_client_name", jedis.clientGetname()); -// } -// } -// -// @Test -// public void returnResourceDestroysResourceOnException() { -// -// class CrashingJedis extends Jedis { -// @Override -// public void resetState() { -// throw new RuntimeException(); -// } -// } -// -// final AtomicInteger destroyed = new AtomicInteger(0); -// -// class CrashingJedisPooledObjectFactory implements PooledObjectFactory { -// -// @Override -// public PooledObject makeObject() throws Exception { -// return new DefaultPooledObject(new CrashingJedis()); -// } -// -// @Override -// public void destroyObject(PooledObject p) throws Exception { -// destroyed.incrementAndGet(); -// } -// -// @Override -// public boolean validateObject(PooledObject p) { -// return true; -// } -// -// @Override -// public void activateObject(PooledObject p) throws Exception { -// } -// -// @Override -// public void passivateObject(PooledObject p) throws Exception { -// } -// } -// -// GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); -// config.setMaxTotal(1); -// JedisPool pool = new JedisPool(config, new CrashingJedisPooledObjectFactory()); -// Jedis crashingJedis = pool.getResource(); -// -// try { -// crashingJedis.close(); -// } catch (Exception ignored) { -// } -// -// assertEquals(1, destroyed.get()); -// } -// -// @Test -// public void returnResourceShouldResetState() { -// GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); -// config.setMaxTotal(1); -// config.setBlockWhenExhausted(false); -// JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, "foobared"); -// -// Jedis jedis = pool.getResource(); -// try { -// jedis.set("hello", "jedis"); -// Transaction t = jedis.multi(); -// t.set("hello", "world"); -// } finally { -// jedis.close(); -// } -// -// Jedis jedis2 = pool.getResource(); -// try { -// assertTrue(jedis == jedis2); -// assertEquals("jedis", jedis2.get("hello")); -// } finally { -// jedis2.close(); -// } -// -// pool.close(); -// assertTrue(pool.isClosed()); -// } -// -// @Test -// public void getNumActiveWhenPoolIsClosed() { -// JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, -// "foobared", 0, "my_shiny_client_name"); -// -// try (Jedis j = pool.getResource()) { -// j.ping(); -// } -// -// pool.close(); -// assertEquals(0, pool.getNumActive()); -// } -// -// @Test -// public void getNumActiveReturnsTheCorrectNumber() { -// try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000)) { -// Jedis jedis = pool.getResource(); -// jedis.auth("foobared"); -// jedis.set("foo", "bar"); -// assertEquals("bar", jedis.get("foo")); -// -// assertEquals(1, pool.getNumActive()); -// -// Jedis jedis2 = pool.getResource(); -// jedis.auth("foobared"); -// jedis.set("foo", "bar"); -// -// assertEquals(2, pool.getNumActive()); -// -// jedis.close(); -// assertEquals(1, pool.getNumActive()); -// -// jedis2.close(); -// -// assertEquals(0, pool.getNumActive()); -// } -// } -// -// @Test -// public void testAddObject() { -// try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000)) { -// pool.addObjects(1); -// assertEquals(1, pool.getNumIdle()); -// } -// } -// -// @Test -// public void closeResourceTwice() { -// try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000)) { -// Jedis j = pool.getResource(); -// j.auth("foobared"); -// j.ping(); -// j.close(); -// j.close(); -// } -// } -// -// @Test -// public void closeBrokenResourceTwice() { -// try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000)) { -// Jedis j = pool.getResource(); -// try { -// // make connection broken -// j.getClient().getOne(); -// fail(); -// } catch (Exception e) { -// assertTrue(e instanceof JedisConnectionException); -// } -// assertTrue(j.isBroken()); -// j.close(); -// j.close(); -// } -// } -// -// @Test -// public void testCloseConnectionOnMakeObject() { -// JedisPoolConfig config = new JedisPoolConfig(); -// config.setTestOnBorrow(true); -// try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, -// "wrong pass"); Jedis jedis = new Jedis("redis://:foobared@localhost:6379/")) { -// int currentClientCount = getClientCount(jedis.clientList()); -// try { -// pool.getResource(); -// fail("Should throw exception as password is incorrect."); -// } catch (Exception e) { -// assertEquals(currentClientCount, getClientCount(jedis.clientList())); -// } -// } -// } -// -// private int getClientCount(final String clientList) { -// return clientList.split("\n").length; -// } -// -// @Test -// public void testResetInvalidPassword() { -// JedisFactory factory = new JedisFactory(hnp.getHost(), hnp.getPort(), 2000, 2000, -// "foobared", 0, "my_shiny_client_name") { }; -// -// try (JedisPool pool = new JedisPool(new JedisPoolConfig(), factory)) { -// Jedis obj1_ref; -// try (Jedis obj1_1 = pool.getResource()) { -// obj1_ref = obj1_1; -// obj1_1.set("foo", "bar"); -// assertEquals("bar", obj1_1.get("foo")); -// assertEquals(1, pool.getNumActive()); -// } -// assertEquals(0, pool.getNumActive()); -// try (Jedis obj1_2 = pool.getResource()) { -// assertSame(obj1_ref, obj1_2); -// assertEquals(1, pool.getNumActive()); -// factory.setPassword("wrong password"); -// try (Jedis obj2 = pool.getResource()) { -// fail("Should not get resource from pool"); -// } catch (JedisException e) { } -// assertEquals(1, pool.getNumActive()); -// } -// assertEquals(0, pool.getNumActive()); -// } -// } -// -// @Test -// public void testResetValidPassword() { -// JedisFactory factory = new JedisFactory(hnp.getHost(), hnp.getPort(), 2000, 2000, -// "bad password", 0, "my_shiny_client_name") { }; -// -// try (JedisPool pool = new JedisPool(new JedisPoolConfig(), factory)) { -// try (Jedis obj1 = pool.getResource()) { -// fail("Should not get resource from pool"); -// } catch (JedisException e) { } -// assertEquals(0, pool.getNumActive()); -// -// factory.setPassword("foobared"); -// try (Jedis obj2 = pool.getResource()) { -// obj2.set("foo", "bar"); -// assertEquals("bar", obj2.get("foo")); -// } -// } -// } -//} + @Test(expected = JedisException.class) + public void checkPoolOverflow() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + try (JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort()); + Jedis jedis = pool.getResource()) { + jedis.auth("foobared"); + + try (Jedis jedis2 = pool.getResource()) { + jedis2.auth("foobared"); + } + } + } + + @Test + public void securePool() { + JedisPoolConfig config = new JedisPoolConfig(); + config.setTestOnBorrow(true); + JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, "foobared"); + try (Jedis jedis = pool.getResource()) { + jedis.set("foo", "bar"); + } + pool.close(); + assertTrue(pool.isClosed()); + } + + @Test + public void nonDefaultDatabase() { + try (JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, + "foobared"); Jedis jedis0 = pool0.getResource()) { + jedis0.set("foo", "bar"); + assertEquals("bar", jedis0.get("foo")); + } + + try (JedisPool pool1 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, + "foobared", 1); Jedis jedis1 = pool1.getResource()) { + assertNull(jedis1.get("foo")); + } + } + + @Test + public void startWithUrlString() { + try (Jedis j = new Jedis("localhost", 6380)) { + j.auth("foobared"); + j.select(2); + j.set("foo", "bar"); + } + + try (JedisPool pool = new JedisPool("redis://:foobared@localhost:6380/2"); + Jedis jedis = pool.getResource()) { + assertEquals("PONG", jedis.ping()); + assertEquals("bar", jedis.get("foo")); + } + } + + @Test + public void startWithUrl() throws URISyntaxException { + try (Jedis j = new Jedis("localhost", 6380)) { + j.auth("foobared"); + j.select(2); + j.set("foo", "bar"); + } + + try (JedisPool pool = new JedisPool(new URI("redis://:foobared@localhost:6380/2")); + Jedis jedis = pool.getResource()) { + assertEquals("bar", jedis.get("foo")); + } + } + + @Test(expected = InvalidURIException.class) + public void shouldThrowInvalidURIExceptionForInvalidURI() throws URISyntaxException { + new JedisPool(new URI("localhost:6380")).close(); + } + + @Test + public void allowUrlWithNoDBAndNoPassword() throws URISyntaxException { + new JedisPool("redis://localhost:6380").close(); + new JedisPool(new URI("redis://localhost:6380")).close(); + } + + @Test + public void selectDatabaseOnActivation() { + try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, + "foobared")) { + + Jedis jedis0 = pool.getResource(); + assertEquals(0, jedis0.getDB()); + + jedis0.select(1); + assertEquals(1, jedis0.getDB()); + + jedis0.close(); + + Jedis jedis1 = pool.getResource(); + assertTrue("Jedis instance was not reused", jedis1 == jedis0); + assertEquals(0, jedis1.getDB()); + + jedis1.close(); + } + } + + @Test + public void customClientName() { + try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, + "foobared", 0, "my_shiny_client_name"); Jedis jedis = pool.getResource()) { + + assertEquals("my_shiny_client_name", jedis.clientGetname()); + } + } + + @Test + public void returnResourceDestroysResourceOnException() { + + class CrashingJedis extends Jedis { + @Override + public void resetState() { + throw new RuntimeException(); + } + } + + final AtomicInteger destroyed = new AtomicInteger(0); + + class CrashingJedisPooledObjectFactory implements PooledObjectFactory { + + @Override + public PooledObject makeObject() throws Exception { + return new DefaultPooledObject(new CrashingJedis()); + } + + @Override + public void destroyObject(PooledObject p) throws Exception { + destroyed.incrementAndGet(); + } + + @Override + public boolean validateObject(PooledObject p) { + return true; + } + + @Override + public void activateObject(PooledObject p) throws Exception { + } + + @Override + public void passivateObject(PooledObject p) throws Exception { + } + } + + GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); + config.setMaxTotal(1); + JedisPool pool = new JedisPool(config, new CrashingJedisPooledObjectFactory()); + Jedis crashingJedis = pool.getResource(); + + try { + crashingJedis.close(); + } catch (Exception ignored) { + } + + assertEquals(1, destroyed.get()); + } + + @Test + public void returnResourceShouldResetState() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, "foobared"); + + Jedis jedis = pool.getResource(); + try { + jedis.set("hello", "jedis"); + Transaction t = jedis.multi(); + t.set("hello", "world"); + } finally { + jedis.close(); + } + + Jedis jedis2 = pool.getResource(); + try { + assertTrue(jedis == jedis2); + assertEquals("jedis", jedis2.get("hello")); + } finally { + jedis2.close(); + } + + pool.close(); + assertTrue(pool.isClosed()); + } + + @Test + public void getNumActiveWhenPoolIsClosed() { + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, + "foobared", 0, "my_shiny_client_name"); + + try (Jedis j = pool.getResource()) { + j.ping(); + } + + pool.close(); + assertEquals(0, pool.getNumActive()); + } + + @Test + public void getNumActiveReturnsTheCorrectNumber() { + try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000)) { + Jedis jedis = pool.getResource(); + jedis.auth("foobared"); + jedis.set("foo", "bar"); + assertEquals("bar", jedis.get("foo")); + + assertEquals(1, pool.getNumActive()); + + Jedis jedis2 = pool.getResource(); + jedis.auth("foobared"); + jedis.set("foo", "bar"); + + assertEquals(2, pool.getNumActive()); + + jedis.close(); + assertEquals(1, pool.getNumActive()); + + jedis2.close(); + + assertEquals(0, pool.getNumActive()); + } + } + + @Test + public void testAddObject() { + try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000)) { + pool.addObjects(1); + assertEquals(1, pool.getNumIdle()); + } + } + + @Test + public void closeResourceTwice() { + try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000)) { + Jedis j = pool.getResource(); + j.auth("foobared"); + j.ping(); + j.close(); + j.close(); + } + } + + @Test + public void closeBrokenResourceTwice() { + try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000)) { + Jedis j = pool.getResource(); + try { + // make connection broken + j.getClient().getOne(); + fail(); + } catch (Exception e) { + assertTrue(e instanceof JedisConnectionException); + } + assertTrue(j.isBroken()); + j.close(); + j.close(); + } + } + + @Test + public void testCloseConnectionOnMakeObject() { + JedisPoolConfig config = new JedisPoolConfig(); + config.setTestOnBorrow(true); + try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, + "wrong pass"); Jedis jedis = new Jedis("redis://:foobared@localhost:6379/")) { + int currentClientCount = getClientCount(jedis.clientList()); + try { + pool.getResource(); + fail("Should throw exception as password is incorrect."); + } catch (Exception e) { + assertEquals(currentClientCount, getClientCount(jedis.clientList())); + } + } + } + + private int getClientCount(final String clientList) { + return clientList.split("\n").length; + } + + @Test + public void testResetInvalidPassword() { + JedisFactory factory = new JedisFactory(hnp.getHost(), hnp.getPort(), 2000, 2000, + "foobared", 0, "my_shiny_client_name") { }; + + try (JedisPool pool = new JedisPool(new JedisPoolConfig(), factory)) { + Jedis obj1_ref; + try (Jedis obj1_1 = pool.getResource()) { + obj1_ref = obj1_1; + obj1_1.set("foo", "bar"); + assertEquals("bar", obj1_1.get("foo")); + assertEquals(1, pool.getNumActive()); + } + assertEquals(0, pool.getNumActive()); + try (Jedis obj1_2 = pool.getResource()) { + assertSame(obj1_ref, obj1_2); + assertEquals(1, pool.getNumActive()); + factory.setPassword("wrong password"); + try (Jedis obj2 = pool.getResource()) { + fail("Should not get resource from pool"); + } catch (JedisException e) { } + assertEquals(1, pool.getNumActive()); + } + assertEquals(0, pool.getNumActive()); + } + } + + @Test + public void testResetValidPassword() { + JedisFactory factory = new JedisFactory(hnp.getHost(), hnp.getPort(), 2000, 2000, + "bad password", 0, "my_shiny_client_name") { }; + + try (JedisPool pool = new JedisPool(new JedisPoolConfig(), factory)) { + try (Jedis obj1 = pool.getResource()) { + fail("Should not get resource from pool"); + } catch (JedisException e) { } + assertEquals(0, pool.getNumActive()); + + factory.setPassword("foobared"); + try (Jedis obj2 = pool.getResource()) { + obj2.set("foo", "bar"); + assertEquals("bar", obj2.get("foo")); + } + } + } +} diff --git a/src/test/java/redis/clients/jedis/tests/JedisPoolWithCompleteCredentialsTest.java b/src/test/java/redis/clients/jedis/tests/JedisPoolWithCompleteCredentialsTest.java index 08343b2b5c..652da4657d 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisPoolWithCompleteCredentialsTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisPoolWithCompleteCredentialsTest.java @@ -1,327 +1,328 @@ -//package redis.clients.jedis.tests; -// -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertNull; -//import static org.junit.Assert.assertSame; -//import static org.junit.Assert.assertTrue; -//import static org.junit.Assert.fail; -// -//import java.net.URI; -//import java.net.URISyntaxException; -//import org.apache.commons.pool2.impl.GenericObjectPoolConfig; -//import org.junit.BeforeClass; -//import org.junit.Test; -// -//import redis.clients.jedis.DefaultJedisClientConfig; -//import redis.clients.jedis.HostAndPort; -//import redis.clients.jedis.Jedis; -//import redis.clients.jedis.JedisFactory; -//import redis.clients.jedis.JedisPool; -//import redis.clients.jedis.JedisPoolConfig; -//import redis.clients.jedis.Protocol; -//import redis.clients.jedis.exceptions.InvalidURIException; -//import redis.clients.jedis.exceptions.JedisException; +package redis.clients.jedis.tests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.net.URI; +import java.net.URISyntaxException; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.DefaultJedisClientConfig; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisFactory; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; +import redis.clients.jedis.Protocol; +import redis.clients.jedis.exceptions.InvalidURIException; +import redis.clients.jedis.exceptions.JedisException; //import redis.clients.jedis.exceptions.JedisExhaustedPoolException; -//import redis.clients.jedis.tests.utils.RedisVersionUtil; -// -///** -// * This test class is a copy of {@link JedisPoolTest}. -// *

-// * This test is only executed when the server/cluster is Redis 6. or more. -// */ -//public class JedisPoolWithCompleteCredentialsTest { -// private static final HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); -// -// @BeforeClass -// public static void prepare() throws Exception { -// // Use to check if the ACL test should be ran. ACL are available only in 6.0 and later -// org.junit.Assume.assumeTrue("Not running ACL test on this version of Redis", -// RedisVersionUtil.checkRedisMajorVersionNumber(6)); -// } -// -// @Test -// public void checkConnections() { -// JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), "acljedis", -// "fizzbuzz"); -// try (Jedis jedis = pool.getResource()) { -// jedis.set("foo", "bar"); -// assertEquals("bar", jedis.get("foo")); -// } -// pool.close(); -// assertTrue(pool.isClosed()); -// } -// -// @Test -// public void checkCloseableConnections() throws Exception { -// JedisPool pool = new JedisPool(hnp.getHost(), hnp.getPort(), "acljedis", "fizzbuzz"); -// try (Jedis jedis = pool.getResource()) { -// jedis.set("foo", "bar"); -// assertEquals("bar", jedis.get("foo")); -// } -// pool.close(); -// assertTrue(pool.isClosed()); -// } -// -// @Test -// public void checkResourceIsClosableAndReusable() { -// GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); -// config.setMaxTotal(1); -// config.setBlockWhenExhausted(false); -// try (JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), -// Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, 0 /* infinite */, "acljedis", -// "fizzbuzz", Protocol.DEFAULT_DATABASE, "closable-resuable-pool", false, null, null, null)) { -// -// Jedis jedis = pool.getResource(); -// jedis.set("hello", "jedis"); -// jedis.close(); -// -// Jedis jedis2 = pool.getResource(); -// assertEquals(jedis, jedis2); -// assertEquals("jedis", jedis2.get("hello")); -// jedis2.close(); -// } -// } -// -// @Test -// public void checkResourceWithConfigIsClosableAndReusable() { -// GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); -// config.setMaxTotal(1); -// config.setBlockWhenExhausted(false); -// try (JedisPool pool = new JedisPool(config, hnp, DefaultJedisClientConfig.builder() -// .user("acljedis").password("fizzbuzz").clientName("closable-resuable-pool") -// .build())) { -// -// Jedis jedis = pool.getResource(); -// jedis.set("hello", "jedis"); -// jedis.close(); -// -// Jedis jedis2 = pool.getResource(); -// assertEquals(jedis, jedis2); -// assertEquals("jedis", jedis2.get("hello")); -// assertEquals("closable-resuable-pool", jedis2.clientGetname()); -// jedis2.close(); -// } -// } -// -// @Test -// public void checkPoolRepairedWhenJedisIsBroken() { -// JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), -// Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, 0 /* infinite */, "acljedis", -// "fizzbuzz", Protocol.DEFAULT_DATABASE, "repairable-pool"); -// try (Jedis jedis = pool.getResource()) { -// jedis.set("foo", "0"); -// jedis.quit(); -// } -// -// try (Jedis jedis = pool.getResource()) { -// jedis.incr("foo"); -// } -// pool.close(); -// assertTrue(pool.isClosed()); -// } -// +import redis.clients.jedis.tests.utils.RedisVersionUtil; + +/** + * This test class is a copy of {@link JedisPoolTest}. + *

+ * This test is only executed when the server/cluster is Redis 6. or more. + */ +public class JedisPoolWithCompleteCredentialsTest { + private static final HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); + + @BeforeClass + public static void prepare() throws Exception { + // Use to check if the ACL test should be ran. ACL are available only in 6.0 and later + org.junit.Assume.assumeTrue("Not running ACL test on this version of Redis", + RedisVersionUtil.checkRedisMajorVersionNumber(6)); + } + + @Test + public void checkConnections() { + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), "acljedis", + "fizzbuzz"); + try (Jedis jedis = pool.getResource()) { + jedis.set("foo", "bar"); + assertEquals("bar", jedis.get("foo")); + } + pool.close(); + assertTrue(pool.isClosed()); + } + + @Test + public void checkCloseableConnections() throws Exception { + JedisPool pool = new JedisPool(hnp.getHost(), hnp.getPort(), "acljedis", "fizzbuzz"); + try (Jedis jedis = pool.getResource()) { + jedis.set("foo", "bar"); + assertEquals("bar", jedis.get("foo")); + } + pool.close(); + assertTrue(pool.isClosed()); + } + + @Test + public void checkResourceIsClosableAndReusable() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + try (JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), + Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, 0 /* infinite */, "acljedis", + "fizzbuzz", Protocol.DEFAULT_DATABASE, "closable-resuable-pool", false, null, null, null)) { + + Jedis jedis = pool.getResource(); + jedis.set("hello", "jedis"); + jedis.close(); + + Jedis jedis2 = pool.getResource(); + assertEquals(jedis, jedis2); + assertEquals("jedis", jedis2.get("hello")); + jedis2.close(); + } + } + + @Test + public void checkResourceWithConfigIsClosableAndReusable() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + try (JedisPool pool = new JedisPool(config, hnp, DefaultJedisClientConfig.builder() + .user("acljedis").password("fizzbuzz").clientName("closable-resuable-pool") + .build())) { + + Jedis jedis = pool.getResource(); + jedis.set("hello", "jedis"); + jedis.close(); + + Jedis jedis2 = pool.getResource(); + assertEquals(jedis, jedis2); + assertEquals("jedis", jedis2.get("hello")); + assertEquals("closable-resuable-pool", jedis2.clientGetname()); + jedis2.close(); + } + } + + @Test + public void checkPoolRepairedWhenJedisIsBroken() { + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), + Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, 0 /* infinite */, "acljedis", + "fizzbuzz", Protocol.DEFAULT_DATABASE, "repairable-pool"); + try (Jedis jedis = pool.getResource()) { + jedis.set("foo", "0"); + jedis.quit(); + } + + try (Jedis jedis = pool.getResource()) { + jedis.incr("foo"); + } + pool.close(); + assertTrue(pool.isClosed()); + } + // @Test(expected = JedisExhaustedPoolException.class) -// public void checkPoolOverflow() { -// GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); -// config.setMaxTotal(1); -// config.setBlockWhenExhausted(false); -// try (JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort()); -// Jedis jedis = pool.getResource()) { -// jedis.auth("acljedis", "fizzbuzz"); -// -// try (Jedis jedis2 = pool.getResource()) { -// jedis2.auth("acljedis", "fizzbuzz"); -// } -// } -// } -// -// @Test -// public void securePool() { -// JedisPoolConfig config = new JedisPoolConfig(); -// config.setTestOnBorrow(true); -// JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, "acljedis", -// "fizzbuzz"); -// try (Jedis jedis = pool.getResource()) { -// jedis.set("foo", "bar"); -// } -// pool.close(); -// assertTrue(pool.isClosed()); -// } -// -// @Test -// public void securePoolNonSSL() { -// JedisPoolConfig config = new JedisPoolConfig(); -// config.setTestOnBorrow(true); -// JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, "acljedis", -// "fizzbuzz", false); -// try (Jedis jedis = pool.getResource()) { -// jedis.set("foo", "bar"); -// } -// pool.close(); -// assertTrue(pool.isClosed()); -// } -// -// @Test -// public void nonDefaultDatabase() { -// try (JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, -// "acljedis", "fizzbuzz"); Jedis jedis0 = pool0.getResource()) { -// jedis0.set("foo", "bar"); -// assertEquals("bar", jedis0.get("foo")); -// } -// -// try (JedisPool pool1 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, -// "acljedis", "fizzbuzz", 1); Jedis jedis1 = pool1.getResource()) { -// assertNull(jedis1.get("foo")); -// } -// } -// -// @Test -// public void startWithUrlString() { -// try (Jedis j = new Jedis("localhost", 6379)) { -// j.auth("acljedis", "fizzbuzz"); -// j.select(2); -// j.set("foo", "bar"); -// } -// -// try (JedisPool pool = new JedisPool("redis://acljedis:fizzbuzz@localhost:6379/2"); -// Jedis jedis = pool.getResource()) { -// assertEquals("bar", jedis.get("foo")); -// } -// } -// -// @Test -// public void startWithUrl() throws URISyntaxException { -// try (Jedis j = new Jedis("localhost", 6379)) { -// j.auth("acljedis", "fizzbuzz"); -// j.select(2); -// j.set("foo", "bar"); -// } -// -// try (JedisPool pool = new JedisPool(new URI("redis://acljedis:fizzbuzz@localhost:6379/2")); -// Jedis jedis = pool.getResource()) { -// assertEquals("bar", jedis.get("foo")); -// } -// -// try (JedisPool pool = new JedisPool(new URI("redis://default:foobared@localhost:6379/2")); -// Jedis jedis = pool.getResource()) { -// assertEquals("bar", jedis.get("foo")); -// } -// } -// -// @Test(expected = InvalidURIException.class) -// public void shouldThrowInvalidURIExceptionForInvalidURI() throws URISyntaxException { -// new JedisPool(new URI("localhost:6379")).close(); -// } -// -// @Test -// public void allowUrlWithNoDBAndNoPassword() throws URISyntaxException { -// new JedisPool("redis://localhost:6379").close(); -// new JedisPool(new URI("redis://localhost:6379")).close(); -// } -// -// @Test -// public void selectDatabaseOnActivation() { -// try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, -// "acljedis", "fizzbuzz")) { -// -// Jedis jedis0 = pool.getResource(); -// assertEquals(0, jedis0.getDB()); -// -// jedis0.select(1); -// assertEquals(1, jedis0.getDB()); -// -// jedis0.close(); -// -// Jedis jedis1 = pool.getResource(); -// assertTrue("Jedis instance was not reused", jedis1 == jedis0); -// assertEquals(0, jedis1.getDB()); -// -// jedis1.close(); -// } -// } -// -// @Test -// public void customClientName() { -// try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, -// "acljedis", "fizzbuzz", 0, "my_shiny_client_name"); Jedis jedis = pool.getResource()) { -// -// assertEquals("my_shiny_client_name", jedis.clientGetname()); -// } -// } -// -// @Test -// public void customClientNameNoSSL() { -// try (JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, -// "acljedis", "fizzbuzz", 0, "my_shiny_client_name_no_ssl", false); -// Jedis jedis = pool0.getResource()) { -// -// assertEquals("my_shiny_client_name_no_ssl", jedis.clientGetname()); -// } -// } -// -// @Test -// public void testCloseConnectionOnMakeObject() { -// JedisPoolConfig config = new JedisPoolConfig(); -// config.setTestOnBorrow(true); -// try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, -// "acljedis", "foobared"); Jedis jedis = new Jedis("redis://:foobared@localhost:6379/")) { -// int currentClientCount = getClientCount(jedis.clientList()); -// try { -// pool.getResource(); -// fail("Should throw exception as password is incorrect."); -// } catch (Exception e) { -// assertEquals(currentClientCount, getClientCount(jedis.clientList())); -// } -// } -// } -// -// private int getClientCount(final String clientList) { -// return clientList.split("\n").length; -// } -// -// @Test -// public void testResetInvalidPassword() { -// JedisFactory factory = new JedisFactory(hnp.getHost(), hnp.getPort(), 2000, 2000, -// "acljedis", "fizzbuzz", 0, "my_shiny_client_name") { }; -// -// try (JedisPool pool = new JedisPool(new JedisPoolConfig(), factory)) { -// Jedis obj1_ref; -// try (Jedis obj1_1 = pool.getResource()) { -// obj1_ref = obj1_1; -// obj1_1.set("foo", "bar"); -// assertEquals("bar", obj1_1.get("foo")); -// assertEquals(1, pool.getNumActive()); -// } -// assertEquals(0, pool.getNumActive()); -// try (Jedis obj1_2 = pool.getResource()) { -// assertSame(obj1_ref, obj1_2); -// assertEquals(1, pool.getNumActive()); -// factory.setPassword("wrong password"); -// try (Jedis obj2 = pool.getResource()) { -// fail("Should not get resource from pool"); -// } catch (JedisException e) { } -// assertEquals(1, pool.getNumActive()); -// } -// assertEquals(0, pool.getNumActive()); -// } -// } -// -// @Test -// public void testResetValidPassword() { -// JedisFactory factory = new JedisFactory(hnp.getHost(), hnp.getPort(), 2000, 2000, -// "acljedis", "bad password", 0, "my_shiny_client_name") { }; -// -// try (JedisPool pool = new JedisPool(new JedisPoolConfig(), factory)) { -// try (Jedis obj1 = pool.getResource()) { -// fail("Should not get resource from pool"); -// } catch (JedisException e) { } -// assertEquals(0, pool.getNumActive()); -// -// factory.setPassword("fizzbuzz"); -// try (Jedis obj2 = pool.getResource()) { -// obj2.set("foo", "bar"); -// assertEquals("bar", obj2.get("foo")); -// } -// } -// } -//} + @Test(expected = JedisException.class) + public void checkPoolOverflow() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + try (JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort()); + Jedis jedis = pool.getResource()) { + jedis.auth("acljedis", "fizzbuzz"); + + try (Jedis jedis2 = pool.getResource()) { + jedis2.auth("acljedis", "fizzbuzz"); + } + } + } + + @Test + public void securePool() { + JedisPoolConfig config = new JedisPoolConfig(); + config.setTestOnBorrow(true); + JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, "acljedis", + "fizzbuzz"); + try (Jedis jedis = pool.getResource()) { + jedis.set("foo", "bar"); + } + pool.close(); + assertTrue(pool.isClosed()); + } + + @Test + public void securePoolNonSSL() { + JedisPoolConfig config = new JedisPoolConfig(); + config.setTestOnBorrow(true); + JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, "acljedis", + "fizzbuzz", false); + try (Jedis jedis = pool.getResource()) { + jedis.set("foo", "bar"); + } + pool.close(); + assertTrue(pool.isClosed()); + } + + @Test + public void nonDefaultDatabase() { + try (JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, + "acljedis", "fizzbuzz"); Jedis jedis0 = pool0.getResource()) { + jedis0.set("foo", "bar"); + assertEquals("bar", jedis0.get("foo")); + } + + try (JedisPool pool1 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, + "acljedis", "fizzbuzz", 1); Jedis jedis1 = pool1.getResource()) { + assertNull(jedis1.get("foo")); + } + } + + @Test + public void startWithUrlString() { + try (Jedis j = new Jedis("localhost", 6379)) { + j.auth("acljedis", "fizzbuzz"); + j.select(2); + j.set("foo", "bar"); + } + + try (JedisPool pool = new JedisPool("redis://acljedis:fizzbuzz@localhost:6379/2"); + Jedis jedis = pool.getResource()) { + assertEquals("bar", jedis.get("foo")); + } + } + + @Test + public void startWithUrl() throws URISyntaxException { + try (Jedis j = new Jedis("localhost", 6379)) { + j.auth("acljedis", "fizzbuzz"); + j.select(2); + j.set("foo", "bar"); + } + + try (JedisPool pool = new JedisPool(new URI("redis://acljedis:fizzbuzz@localhost:6379/2")); + Jedis jedis = pool.getResource()) { + assertEquals("bar", jedis.get("foo")); + } + + try (JedisPool pool = new JedisPool(new URI("redis://default:foobared@localhost:6379/2")); + Jedis jedis = pool.getResource()) { + assertEquals("bar", jedis.get("foo")); + } + } + + @Test(expected = InvalidURIException.class) + public void shouldThrowInvalidURIExceptionForInvalidURI() throws URISyntaxException { + new JedisPool(new URI("localhost:6379")).close(); + } + + @Test + public void allowUrlWithNoDBAndNoPassword() throws URISyntaxException { + new JedisPool("redis://localhost:6379").close(); + new JedisPool(new URI("redis://localhost:6379")).close(); + } + + @Test + public void selectDatabaseOnActivation() { + try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, + "acljedis", "fizzbuzz")) { + + Jedis jedis0 = pool.getResource(); + assertEquals(0, jedis0.getDB()); + + jedis0.select(1); + assertEquals(1, jedis0.getDB()); + + jedis0.close(); + + Jedis jedis1 = pool.getResource(); + assertTrue("Jedis instance was not reused", jedis1 == jedis0); + assertEquals(0, jedis1.getDB()); + + jedis1.close(); + } + } + + @Test + public void customClientName() { + try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, + "acljedis", "fizzbuzz", 0, "my_shiny_client_name"); Jedis jedis = pool.getResource()) { + + assertEquals("my_shiny_client_name", jedis.clientGetname()); + } + } + + @Test + public void customClientNameNoSSL() { + try (JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, + "acljedis", "fizzbuzz", 0, "my_shiny_client_name_no_ssl", false); + Jedis jedis = pool0.getResource()) { + + assertEquals("my_shiny_client_name_no_ssl", jedis.clientGetname()); + } + } + + @Test + public void testCloseConnectionOnMakeObject() { + JedisPoolConfig config = new JedisPoolConfig(); + config.setTestOnBorrow(true); + try (JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000, + "acljedis", "foobared"); Jedis jedis = new Jedis("redis://:foobared@localhost:6379/")) { + int currentClientCount = getClientCount(jedis.clientList()); + try { + pool.getResource(); + fail("Should throw exception as password is incorrect."); + } catch (Exception e) { + assertEquals(currentClientCount, getClientCount(jedis.clientList())); + } + } + } + + private int getClientCount(final String clientList) { + return clientList.split("\n").length; + } + + @Test + public void testResetInvalidPassword() { + JedisFactory factory = new JedisFactory(hnp.getHost(), hnp.getPort(), 2000, 2000, + "acljedis", "fizzbuzz", 0, "my_shiny_client_name") { }; + + try (JedisPool pool = new JedisPool(new JedisPoolConfig(), factory)) { + Jedis obj1_ref; + try (Jedis obj1_1 = pool.getResource()) { + obj1_ref = obj1_1; + obj1_1.set("foo", "bar"); + assertEquals("bar", obj1_1.get("foo")); + assertEquals(1, pool.getNumActive()); + } + assertEquals(0, pool.getNumActive()); + try (Jedis obj1_2 = pool.getResource()) { + assertSame(obj1_ref, obj1_2); + assertEquals(1, pool.getNumActive()); + factory.setPassword("wrong password"); + try (Jedis obj2 = pool.getResource()) { + fail("Should not get resource from pool"); + } catch (JedisException e) { } + assertEquals(1, pool.getNumActive()); + } + assertEquals(0, pool.getNumActive()); + } + } + + @Test + public void testResetValidPassword() { + JedisFactory factory = new JedisFactory(hnp.getHost(), hnp.getPort(), 2000, 2000, + "acljedis", "bad password", 0, "my_shiny_client_name") { }; + + try (JedisPool pool = new JedisPool(new JedisPoolConfig(), factory)) { + try (Jedis obj1 = pool.getResource()) { + fail("Should not get resource from pool"); + } catch (JedisException e) { } + assertEquals(0, pool.getNumActive()); + + factory.setPassword("fizzbuzz"); + try (Jedis obj2 = pool.getResource()) { + obj2.set("foo", "bar"); + assertEquals("bar", obj2.get("foo")); + } + } + } +} diff --git a/src/test/java/redis/clients/jedis/tests/JedisTest.java b/src/test/java/redis/clients/jedis/tests/JedisTest.java index dd25eca80a..36f5fe120c 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisTest.java @@ -1,57 +1,57 @@ -//package redis.clients.jedis.tests; -// -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertFalse; -//import static org.junit.Assert.assertSame; -//import static org.junit.Assert.assertTrue; -//import static org.junit.Assert.fail; -// -//import java.io.IOException; -//import java.net.ServerSocket; -//import java.net.SocketTimeoutException; -//import java.net.URI; -//import java.net.URISyntaxException; -//import java.time.Duration; -//import java.time.Instant; -//import java.util.HashMap; -//import java.util.Map; -// -//import org.junit.Test; -// +package redis.clients.jedis.tests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.ServerSocket; +import java.net.SocketTimeoutException; +import java.net.URI; +import java.net.URISyntaxException; +import java.time.Duration; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + //import redis.clients.jedis.BinaryJedis; -//import redis.clients.jedis.DefaultJedisClientConfig; -//import redis.clients.jedis.Jedis; -//import redis.clients.jedis.JedisClientConfig; +import redis.clients.jedis.DefaultJedisClientConfig; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisClientConfig; //import redis.clients.jedis.JedisShardInfo; -//import redis.clients.jedis.Protocol; -//import redis.clients.jedis.exceptions.InvalidURIException; -//import redis.clients.jedis.exceptions.JedisConnectionException; -//import redis.clients.jedis.exceptions.JedisException; -//import redis.clients.jedis.tests.commands.JedisCommandTestBase; -//import redis.clients.jedis.util.SafeEncoder; -// -//public class JedisTest extends JedisCommandTestBase { -// -// @Test -// public void useWithoutConnecting() { -// try (Jedis j = new Jedis()) { -// j.auth("foobared"); -// j.dbSize(); -// } -// } -// -// @Test -// public void checkBinaryData() { -// byte[] bigdata = new byte[1777]; -// for (int b = 0; b < bigdata.length; b++) { -// bigdata[b] = (byte) ((byte) b % 255); -// } -// Map hash = new HashMap<>(); -// hash.put("data", SafeEncoder.encode(bigdata)); -// -// assertEquals("OK", jedis.hmset("foo", hash)); -// assertEquals(hash, jedis.hgetAll("foo")); -// } +import redis.clients.jedis.Protocol; +import redis.clients.jedis.exceptions.InvalidURIException; +import redis.clients.jedis.exceptions.JedisConnectionException; +import redis.clients.jedis.exceptions.JedisException; +import redis.clients.jedis.tests.commands.JedisCommandTestBase; +import redis.clients.jedis.util.SafeEncoder; + +public class JedisTest extends JedisCommandTestBase { + + @Test + public void useWithoutConnecting() { + try (Jedis j = new Jedis()) { + j.auth("foobared"); + j.dbSize(); + } + } + + @Test + public void checkBinaryData() { + byte[] bigdata = new byte[1777]; + for (int b = 0; b < bigdata.length; b++) { + bigdata[b] = (byte) ((byte) b % 255); + } + Map hash = new HashMap<>(); + hash.put("data", SafeEncoder.encode(bigdata)); + + assertEquals("OK", jedis.hmset("foo", hash)); + assertEquals(hash, jedis.hgetAll("foo")); + } // // @Test // public void connectWithShardInfo() { @@ -61,82 +61,82 @@ // jedis.get("foo"); // } // } -// -// @Test -// public void connectWithConfig() { -// try (Jedis jedis = new Jedis(hnp, DefaultJedisClientConfig.builder().build())) { -// jedis.auth("foobared"); -// assertEquals("PONG", jedis.ping()); -// } -// try (Jedis jedis = new Jedis(hnp, DefaultJedisClientConfig.builder().password("foobared") -// .build())) { -// assertEquals("PONG", jedis.ping()); -// } -// } -// -// @Test -// public void connectWithConfigInterface() { -// try (Jedis jedis = new Jedis(hnp, new JedisClientConfig() { -// })) { -// jedis.auth("foobared"); -// assertEquals("PONG", jedis.ping()); -// } -// try (Jedis jedis = new Jedis(hnp, new JedisClientConfig() { -// @Override -// public String getPassword() { -// return "foobared"; -// } -// })) { -// assertEquals("PONG", jedis.ping()); -// } -// } -// -// @Test -// public void timeoutConnection() throws Exception { -// Jedis jedis = new Jedis("localhost", 6379, 15000); -// jedis.auth("foobared"); -// String timeout = jedis.configGet("timeout").get(1); -// jedis.configSet("timeout", "1"); -// Thread.sleep(2000); -// try { -// jedis.hmget("foobar", "foo"); -// fail("Operation should throw JedisConnectionException"); -// } catch (JedisConnectionException jce) { -// // expected -// } -// jedis.close(); -// -// // reset config -// jedis = new Jedis("localhost", 6379); -// jedis.auth("foobared"); -// jedis.configSet("timeout", timeout); -// jedis.close(); -// } -// -// @Test -// public void infiniteTimeout() throws Exception { -// try (Jedis timeoutJedis = new Jedis("localhost", 6379, 350, 350, 350)) { -// timeoutJedis.auth("foobared"); -// try { -// timeoutJedis.blpop(0, "foo"); -// fail("SocketTimeoutException should occur"); -// } catch (JedisConnectionException jce) { -// assertSame(java.net.SocketTimeoutException.class, jce.getCause().getClass()); -// assertEquals("Read timed out", jce.getCause().getMessage()); -// assertTrue(timeoutJedis.isBroken()); -// } -// } -// } -// -// @Test(expected = IllegalArgumentException.class) -// public void failWhenSendingNullValues() { -// jedis.set("foo", null); -// } -// -// @Test(expected = InvalidURIException.class) -// public void shouldThrowInvalidURIExceptionForInvalidURI() throws URISyntaxException { -// Jedis j = new Jedis(new URI("localhost:6380")); -// } + + @Test + public void connectWithConfig() { + try (Jedis jedis = new Jedis(hnp, DefaultJedisClientConfig.builder().build())) { + jedis.auth("foobared"); + assertEquals("PONG", jedis.ping()); + } + try (Jedis jedis = new Jedis(hnp, DefaultJedisClientConfig.builder().password("foobared") + .build())) { + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void connectWithConfigInterface() { + try (Jedis jedis = new Jedis(hnp, new JedisClientConfig() { + })) { + jedis.auth("foobared"); + assertEquals("PONG", jedis.ping()); + } + try (Jedis jedis = new Jedis(hnp, new JedisClientConfig() { + @Override + public String getPassword() { + return "foobared"; + } + })) { + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void timeoutConnection() throws Exception { + Jedis jedis = new Jedis("localhost", 6379, 15000); + jedis.auth("foobared"); + String timeout = jedis.configGet("timeout").get(1); + jedis.configSet("timeout", "1"); + Thread.sleep(2000); + try { + jedis.hmget("foobar", "foo"); + fail("Operation should throw JedisConnectionException"); + } catch (JedisConnectionException jce) { + // expected + } + jedis.close(); + + // reset config + jedis = new Jedis("localhost", 6379); + jedis.auth("foobared"); + jedis.configSet("timeout", timeout); + jedis.close(); + } + + @Test + public void infiniteTimeout() throws Exception { + try (Jedis timeoutJedis = new Jedis("localhost", 6379, 350, 350, 350)) { + timeoutJedis.auth("foobared"); + try { + timeoutJedis.blpop(0, "foo"); + fail("SocketTimeoutException should occur"); + } catch (JedisConnectionException jce) { + assertSame(java.net.SocketTimeoutException.class, jce.getCause().getClass()); + assertEquals("Read timed out", jce.getCause().getMessage()); + assertTrue(timeoutJedis.isBroken()); + } + } + } + + @Test(expected = IllegalArgumentException.class) + public void failWhenSendingNullValues() { + jedis.set("foo", null); + } + + @Test(expected = InvalidURIException.class) + public void shouldThrowInvalidURIExceptionForInvalidURI() throws URISyntaxException { + Jedis j = new Jedis(new URI("localhost:6380")); + } // // @Test // public void shouldReconnectToSameDB() throws IOException { @@ -146,47 +146,47 @@ // jedis.getClient().getSocket().shutdownOutput(); // assertEquals("bar", jedis.get("foo")); // } -// -// @Test -// public void startWithUrl() { -// try (Jedis j = new Jedis("localhost", 6380)) { -// j.auth("foobared"); -// j.select(2); -// j.set("foo", "bar"); -// } -// -// try (Jedis j2 = new Jedis("redis://:foobared@localhost:6380/2")) { -// assertEquals("PONG", j2.ping()); -// assertEquals("bar", j2.get("foo")); -// } -// } -// -// @Test -// public void startWithUri() throws URISyntaxException { -// try (Jedis j = new Jedis("localhost", 6380)) { -// j.auth("foobared"); -// j.select(2); -// j.set("foo", "bar"); -// } -// -// try (Jedis jedis = new Jedis(new URI("redis://:foobared@localhost:6380/2"))) { -// assertEquals("PONG", jedis.ping()); -// assertEquals("bar", jedis.get("foo")); -// } -// } -// -// @Test -// public void shouldNotUpdateDbIndexIfSelectFails() { -// int currentDb = jedis.getDB(); -// try { -// int invalidDb = -1; -// jedis.select(invalidDb); -// -// fail("Should throw an exception if tried to select invalid db"); -// } catch (JedisException e) { -// assertEquals(currentDb, jedis.getDB()); -// } -// } + + @Test + public void startWithUrl() { + try (Jedis j = new Jedis("localhost", 6380)) { + j.auth("foobared"); + j.select(2); + j.set("foo", "bar"); + } + + try (Jedis j2 = new Jedis("redis://:foobared@localhost:6380/2")) { + assertEquals("PONG", j2.ping()); + assertEquals("bar", j2.get("foo")); + } + } + + @Test + public void startWithUri() throws URISyntaxException { + try (Jedis j = new Jedis("localhost", 6380)) { + j.auth("foobared"); + j.select(2); + j.set("foo", "bar"); + } + + try (Jedis jedis = new Jedis(new URI("redis://:foobared@localhost:6380/2"))) { + assertEquals("PONG", jedis.ping()); + assertEquals("bar", jedis.get("foo")); + } + } + + @Test + public void shouldNotUpdateDbIndexIfSelectFails() { + int currentDb = jedis.getDB(); + try { + int invalidDb = -1; + jedis.select(invalidDb); + + fail("Should throw an exception if tried to select invalid db"); + } catch (JedisException e) { + assertEquals(currentDb, jedis.getDB()); + } + } // // @Test // public void allowUrlWithNoDBAndNoPassword() { @@ -204,48 +204,51 @@ // assertEquals(0, j2.getDB()); // } // } -// -// @Test -// public void uriWithDBindexShouldUseTimeout() throws URISyntaxException, IOException { -// int fakePort = 6378; -// int timeoutMillis = 3250; -// int deltaMillis = 500; -// URI uri = new URI(String.format("redis://localhost:%d/1", fakePort)); -// Instant start = Instant.now(); -// -// try (ServerSocket server = new ServerSocket(fakePort); -// Jedis jedis = new Jedis(uri, timeoutMillis)) { -// fail("Jedis should fail to connect to a fake port"); -// } catch (JedisConnectionException ex) { -// assertSame(SocketTimeoutException.class, ex.getCause().getClass()); -// assertEquals(timeoutMillis, Duration.between(start, Instant.now()).toMillis(), deltaMillis); -// } -// } -// -// @Test -// public void checkCloseable() { + + @Test + public void uriWithDBindexShouldUseTimeout() throws URISyntaxException, IOException { + int fakePort = 6378; + int timeoutMillis = 3250; + int deltaMillis = 500; + URI uri = new URI(String.format("redis://localhost:%d/1", fakePort)); + Instant start = Instant.now(); + + try (ServerSocket server = new ServerSocket(fakePort); + Jedis jedis = new Jedis(uri, timeoutMillis)) { + fail("Jedis should fail to connect to a fake port"); + } catch (JedisConnectionException ex) { + assertSame(SocketTimeoutException.class, ex.getCause().getClass()); + assertEquals(timeoutMillis, Duration.between(start, Instant.now()).toMillis(), deltaMillis); + } + } + + @Test + public void checkCloseable() { // BinaryJedis bj = new BinaryJedis(); -// bj.close(); -// } -// -// @Test -// public void checkCloseableAfterConnect() { + Jedis bj = new Jedis(); + bj.close(); + } + + @Test + public void checkCloseableAfterConnect() { // BinaryJedis bj = new BinaryJedis(); -// bj.connect(); -// bj.close(); -// } -// -// @Test -// public void checkCloseableAfterCommand() { + Jedis bj = new Jedis(); + bj.connect(); + bj.close(); + } + + @Test + public void checkCloseableAfterCommand() { // BinaryJedis bj = new BinaryJedis(); -// bj.auth("foobared"); -// bj.close(); -// } -// -// @Test -// public void checkDisconnectOnQuit() { -// jedis.quit(); -// assertFalse(jedis.isConnected()); -// } -// -//} + Jedis bj = new Jedis(); + bj.auth("foobared"); + bj.close(); + } + + @Test + public void checkDisconnectOnQuit() { + jedis.quit(); + assertFalse(jedis.isConnected()); + } + +} diff --git a/src/test/java/redis/clients/jedis/tests/ModuleTest.java b/src/test/java/redis/clients/jedis/tests/ModuleTest.java index f580e18e53..7195faeb1f 100644 --- a/src/test/java/redis/clients/jedis/tests/ModuleTest.java +++ b/src/test/java/redis/clients/jedis/tests/ModuleTest.java @@ -1,49 +1,49 @@ -//package redis.clients.jedis.tests; -// -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertTrue; -// -//import java.util.List; -// -//import org.junit.Test; -// -//import redis.clients.jedis.Module; -//import redis.clients.jedis.commands.ProtocolCommand; -//import redis.clients.jedis.tests.commands.JedisCommandTestBase; -//import redis.clients.jedis.util.SafeEncoder; -// -//public class ModuleTest extends JedisCommandTestBase { -// -// static enum ModuleCommand implements ProtocolCommand { -// SIMPLE("testmodule.simple"); -// -// private final byte[] raw; -// -// ModuleCommand(String alt) { -// raw = SafeEncoder.encode(alt); -// } -// -// @Override -// public byte[] getRaw() { -// return raw; -// } -// } -// -// @Test -// public void testModules() { -// String res = jedis.moduleLoad("/tmp/testmodule.so"); -// assertEquals("OK", res); -// -// List modules = jedis.moduleList(); -// -// assertEquals("testmodule", modules.get(0).getName()); -// -// jedis.getClient().sendCommand(ModuleCommand.SIMPLE); -// Long out = jedis.getClient().getIntegerReply(); -// assertTrue(out > 0); -// -// res = jedis.moduleUnload("testmodule"); -// assertEquals("OK", res); -// } -// -//} \ No newline at end of file +package redis.clients.jedis.tests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.Test; + +import redis.clients.jedis.Module; +import redis.clients.jedis.commands.ProtocolCommand; +import redis.clients.jedis.tests.commands.JedisCommandTestBase; +import redis.clients.jedis.util.SafeEncoder; + +public class ModuleTest extends JedisCommandTestBase { + + static enum ModuleCommand implements ProtocolCommand { + SIMPLE("testmodule.simple"); + + private final byte[] raw; + + ModuleCommand(String alt) { + raw = SafeEncoder.encode(alt); + } + + @Override + public byte[] getRaw() { + return raw; + } + } + + @Test + public void testModules() { + String res = jedis.moduleLoad("/tmp/testmodule.so"); + assertEquals("OK", res); + + List modules = jedis.moduleList(); + + assertEquals("testmodule", modules.get(0).getName()); + + jedis.getClient().sendCommand(ModuleCommand.SIMPLE); + Long out = jedis.getClient().getIntegerReply(); + assertTrue(out > 0); + + res = jedis.moduleUnload("testmodule"); + assertEquals("OK", res); + } + +} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/PipeliningTest.java b/src/test/java/redis/clients/jedis/tests/PipeliningTest.java index 3ddade716e..7439fc05a5 100644 --- a/src/test/java/redis/clients/jedis/tests/PipeliningTest.java +++ b/src/test/java/redis/clients/jedis/tests/PipeliningTest.java @@ -1,41 +1,41 @@ -//package redis.clients.jedis.tests; -// -//import static org.hamcrest.CoreMatchers.equalTo; -//import static org.junit.Assert.assertArrayEquals; -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertFalse; -//import static org.junit.Assert.assertNotNull; -//import static org.junit.Assert.assertNull; -//import static org.junit.Assert.assertSame; -//import static org.junit.Assert.assertThat; -//import static org.junit.Assert.assertTrue; -//import static org.junit.Assert.fail; -// -//import java.io.IOException; -//import java.util.ArrayList; -//import java.util.Arrays; -//import java.util.HashMap; -//import java.util.Iterator; -//import java.util.List; -//import java.util.Map; -//import java.util.Set; -//import java.util.UUID; -// -//import org.hamcrest.CoreMatchers; -//import org.hamcrest.Matcher; -//import org.junit.Test; -// -//import redis.clients.jedis.Jedis; -//import redis.clients.jedis.Pipeline; -//import redis.clients.jedis.Response; -//import redis.clients.jedis.Tuple; -//import redis.clients.jedis.exceptions.AbortedTransactionException; -//import redis.clients.jedis.exceptions.JedisBusyException; -//import redis.clients.jedis.exceptions.JedisDataException; -//import redis.clients.jedis.tests.commands.JedisCommandTestBase; -//import redis.clients.jedis.util.SafeEncoder; -// -//public class PipeliningTest extends JedisCommandTestBase { +package redis.clients.jedis.tests; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import org.hamcrest.CoreMatchers; +import org.hamcrest.Matcher; +import org.junit.Test; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.Pipeline; +import redis.clients.jedis.Response; +import redis.clients.jedis.exceptions.AbortedTransactionException; +import redis.clients.jedis.exceptions.JedisBusyException; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.resps.Tuple; +import redis.clients.jedis.tests.commands.JedisCommandTestBase; +import redis.clients.jedis.util.SafeEncoder; + +public class PipeliningTest extends JedisCommandTestBase { // // @Test // public void pipeline() { @@ -48,119 +48,119 @@ // assertEquals("OK", results.get(0)); // assertEquals("bar", results.get(1)); // } -// -// @Test -// public void pipelineResponse() { -// jedis.set("string", "foo"); -// jedis.lpush("list", "foo"); -// jedis.hset("hash", "foo", "bar"); -// jedis.zadd("zset", 1, "foo"); -// jedis.sadd("set", "foo"); -// jedis.setrange("setrange", 0, "0123456789"); -// byte[] bytesForSetRange = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; -// jedis.setrange("setrangebytes".getBytes(), 0, bytesForSetRange); -// -// Pipeline p = jedis.pipelined(); -// Response string = p.get("string"); -// Response list = p.lpop("list"); -// Response hash = p.hget("hash", "foo"); -// Response> zset = p.zrange("zset", 0, -1); -// Response set = p.spop("set"); -// Response blist = p.exists("list"); -// Response zincrby = p.zincrby("zset", 1, "foo"); -// Response zcard = p.zcard("zset"); -// p.lpush("list", "bar"); -// Response> lrange = p.lrange("list", 0, -1); -// Response> hgetAll = p.hgetAll("hash"); -// p.sadd("set", "foo"); -// Response> smembers = p.smembers("set"); -// Response> zrangeWithScores = p.zrangeWithScores("zset", 0, -1); -// Response getrange = p.getrange("setrange", 1, 3); -// Response getrangeBytes = p.getrange("setrangebytes".getBytes(), 6, 8); -// p.sync(); -// -// assertEquals("foo", string.get()); -// assertEquals("foo", list.get()); -// assertEquals("bar", hash.get()); -// assertEquals("foo", zset.get().iterator().next()); -// assertEquals("foo", set.get()); -// assertEquals(false, blist.get()); -// assertEquals(Double.valueOf(2), zincrby.get()); -// assertEquals(Long.valueOf(1), zcard.get()); -// assertEquals(1, lrange.get().size()); -// assertNotNull(hgetAll.get().get("foo")); -// assertEquals(1, smembers.get().size()); -// assertEquals(1, zrangeWithScores.get().size()); -// assertEquals("123", getrange.get()); -// byte[] expectedGetRangeBytes = { 6, 7, 8 }; -// assertArrayEquals(expectedGetRangeBytes, getrangeBytes.get()); -// } -// -// @Test -// public void pipelineResponseWithData() { -// jedis.zadd("zset", 1, "foo"); -// -// Pipeline p = jedis.pipelined(); -// Response score = p.zscore("zset", "foo"); -// p.sync(); -// -// assertNotNull(score.get()); -// } -// -// @Test -// public void pipelineBinarySafeHashCommands() { -// jedis.hset("key".getBytes(), "f1".getBytes(), "v111".getBytes()); -// jedis.hset("key".getBytes(), "f22".getBytes(), "v2222".getBytes()); -// -// Pipeline p = jedis.pipelined(); -// Response> fmap = p.hgetAll("key".getBytes()); -// Response> fkeys = p.hkeys("key".getBytes()); -// Response> fordered = p.hmget("key".getBytes(), "f22".getBytes(), "f1".getBytes()); -// Response> fvals = p.hvals("key".getBytes()); -// p.sync(); -// -// assertNotNull(fmap.get()); -// // we have to do these strange contortions because byte[] is not a very -// // good key -// // for a java Map. It only works with equality (you need the exact key -// // object to retrieve -// // the value) I recommend we switch to using ByteBuffer or something -// // similar: -// // http://stackoverflow.com/questions/1058149/using-a-byte-array-as-hashmap-key-java -// Map map = fmap.get(); -// Set mapKeys = map.keySet(); -// Iterator iterMap = mapKeys.iterator(); -// byte[] firstMapKey = iterMap.next(); -// byte[] secondMapKey = iterMap.next(); -// assertFalse(iterMap.hasNext()); -// verifyHasBothValues(firstMapKey, secondMapKey, "f1".getBytes(), "f22".getBytes()); -// byte[] firstMapValue = map.get(firstMapKey); -// byte[] secondMapValue = map.get(secondMapKey); -// verifyHasBothValues(firstMapValue, secondMapValue, "v111".getBytes(), "v2222".getBytes()); -// -// assertNotNull(fkeys.get()); -// Iterator iter = fkeys.get().iterator(); -// byte[] firstKey = iter.next(); -// byte[] secondKey = iter.next(); -// assertFalse(iter.hasNext()); -// verifyHasBothValues(firstKey, secondKey, "f1".getBytes(), "f22".getBytes()); -// -// assertNotNull(fordered.get()); -// assertArrayEquals("v2222".getBytes(), fordered.get().get(0)); -// assertArrayEquals("v111".getBytes(), fordered.get().get(1)); -// -// assertNotNull(fvals.get()); -// assertEquals(2, fvals.get().size()); -// byte[] firstValue = fvals.get().get(0); -// byte[] secondValue = fvals.get().get(1); -// verifyHasBothValues(firstValue, secondValue, "v111".getBytes(), "v2222".getBytes()); -// } -// -// private void verifyHasBothValues(byte[] firstKey, byte[] secondKey, byte[] value1, byte[] value2) { -// assertFalse(Arrays.equals(firstKey, secondKey)); -// assertTrue(Arrays.equals(firstKey, value1) || Arrays.equals(firstKey, value2)); -// assertTrue(Arrays.equals(secondKey, value1) || Arrays.equals(secondKey, value2)); -// } + + @Test + public void pipelineResponse() { + jedis.set("string", "foo"); + jedis.lpush("list", "foo"); + jedis.hset("hash", "foo", "bar"); + jedis.zadd("zset", 1, "foo"); + jedis.sadd("set", "foo"); + jedis.setrange("setrange", 0, "0123456789"); + byte[] bytesForSetRange = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + jedis.setrange("setrangebytes".getBytes(), 0, bytesForSetRange); + + Pipeline p = jedis.pipelined(); + Response string = p.get("string"); + Response list = p.lpop("list"); + Response hash = p.hget("hash", "foo"); + Response> zset = p.zrange("zset", 0, -1); + Response set = p.spop("set"); + Response blist = p.exists("list"); + Response zincrby = p.zincrby("zset", 1, "foo"); + Response zcard = p.zcard("zset"); + p.lpush("list", "bar"); + Response> lrange = p.lrange("list", 0, -1); + Response> hgetAll = p.hgetAll("hash"); + p.sadd("set", "foo"); + Response> smembers = p.smembers("set"); + Response> zrangeWithScores = p.zrangeWithScores("zset", 0, -1); + Response getrange = p.getrange("setrange", 1, 3); + Response getrangeBytes = p.getrange("setrangebytes".getBytes(), 6, 8); + p.sync(); + + assertEquals("foo", string.get()); + assertEquals("foo", list.get()); + assertEquals("bar", hash.get()); + assertEquals("foo", zset.get().iterator().next()); + assertEquals("foo", set.get()); + assertEquals(false, blist.get()); + assertEquals(Double.valueOf(2), zincrby.get()); + assertEquals(Long.valueOf(1), zcard.get()); + assertEquals(1, lrange.get().size()); + assertNotNull(hgetAll.get().get("foo")); + assertEquals(1, smembers.get().size()); + assertEquals(1, zrangeWithScores.get().size()); + assertEquals("123", getrange.get()); + byte[] expectedGetRangeBytes = { 6, 7, 8 }; + assertArrayEquals(expectedGetRangeBytes, getrangeBytes.get()); + } + + @Test + public void pipelineResponseWithData() { + jedis.zadd("zset", 1, "foo"); + + Pipeline p = jedis.pipelined(); + Response score = p.zscore("zset", "foo"); + p.sync(); + + assertNotNull(score.get()); + } + + @Test + public void pipelineBinarySafeHashCommands() { + jedis.hset("key".getBytes(), "f1".getBytes(), "v111".getBytes()); + jedis.hset("key".getBytes(), "f22".getBytes(), "v2222".getBytes()); + + Pipeline p = jedis.pipelined(); + Response> fmap = p.hgetAll("key".getBytes()); + Response> fkeys = p.hkeys("key".getBytes()); + Response> fordered = p.hmget("key".getBytes(), "f22".getBytes(), "f1".getBytes()); + Response> fvals = p.hvals("key".getBytes()); + p.sync(); + + assertNotNull(fmap.get()); + // we have to do these strange contortions because byte[] is not a very + // good key + // for a java Map. It only works with equality (you need the exact key + // object to retrieve + // the value) I recommend we switch to using ByteBuffer or something + // similar: + // http://stackoverflow.com/questions/1058149/using-a-byte-array-as-hashmap-key-java + Map map = fmap.get(); + Set mapKeys = map.keySet(); + Iterator iterMap = mapKeys.iterator(); + byte[] firstMapKey = iterMap.next(); + byte[] secondMapKey = iterMap.next(); + assertFalse(iterMap.hasNext()); + verifyHasBothValues(firstMapKey, secondMapKey, "f1".getBytes(), "f22".getBytes()); + byte[] firstMapValue = map.get(firstMapKey); + byte[] secondMapValue = map.get(secondMapKey); + verifyHasBothValues(firstMapValue, secondMapValue, "v111".getBytes(), "v2222".getBytes()); + + assertNotNull(fkeys.get()); + Iterator iter = fkeys.get().iterator(); + byte[] firstKey = iter.next(); + byte[] secondKey = iter.next(); + assertFalse(iter.hasNext()); + verifyHasBothValues(firstKey, secondKey, "f1".getBytes(), "f22".getBytes()); + + assertNotNull(fordered.get()); + assertArrayEquals("v2222".getBytes(), fordered.get().get(0)); + assertArrayEquals("v111".getBytes(), fordered.get().get(1)); + + assertNotNull(fvals.get()); + assertEquals(2, fvals.get().size()); + byte[] firstValue = fvals.get().get(0); + byte[] secondValue = fvals.get().get(1); + verifyHasBothValues(firstValue, secondValue, "v111".getBytes(), "v2222".getBytes()); + } + + private void verifyHasBothValues(byte[] firstKey, byte[] secondKey, byte[] value1, byte[] value2) { + assertFalse(Arrays.equals(firstKey, secondKey)); + assertTrue(Arrays.equals(firstKey, value1) || Arrays.equals(firstKey, value2)); + assertTrue(Arrays.equals(secondKey, value1) || Arrays.equals(secondKey, value2)); + } // // @Test // public void pipelineSelect() { @@ -168,61 +168,61 @@ // p.select(1); // p.sync(); // } -// -// @Test -// public void pipelineResponseWithoutData() { -// jedis.zadd("zset", 1, "foo"); -// -// Pipeline p = jedis.pipelined(); -// Response score = p.zscore("zset", "bar"); -// p.sync(); -// -// assertNull(score.get()); -// } -// -// @Test(expected = IllegalStateException.class) -// public void pipelineResponseWithinPipeline() { -// jedis.set("string", "foo"); -// -// Pipeline p = jedis.pipelined(); -// Response string = p.get("string"); -// string.get(); -// p.sync(); -// } -// -// @Test -// public void pipelineWithPubSub() { -// Pipeline pipelined = jedis.pipelined(); -// Response p1 = pipelined.publish("foo", "bar"); -// Response p2 = pipelined.publish("foo".getBytes(), "bar".getBytes()); -// pipelined.sync(); -// assertEquals(0, p1.get().longValue()); -// assertEquals(0, p2.get().longValue()); -// } -// -// @Test -// public void canRetrieveUnsetKey() { -// Pipeline p = jedis.pipelined(); -// Response shouldNotExist = p.get(UUID.randomUUID().toString()); -// p.sync(); -// assertNull(shouldNotExist.get()); -// } -// -// @Test -// public void piplineWithError() { -// Pipeline p = jedis.pipelined(); -// p.set("foo", "bar"); -// Response> error = p.smembers("foo"); -// Response r = p.get("foo"); -// p.sync(); -// try { -// error.get(); -// fail(); -// } catch (JedisDataException e) { -// // that is fine we should be here -// } -// assertEquals(r.get(), "bar"); -// } + + @Test + public void pipelineResponseWithoutData() { + jedis.zadd("zset", 1, "foo"); + + Pipeline p = jedis.pipelined(); + Response score = p.zscore("zset", "bar"); + p.sync(); + + assertNull(score.get()); + } + + @Test(expected = IllegalStateException.class) + public void pipelineResponseWithinPipeline() { + jedis.set("string", "foo"); + + Pipeline p = jedis.pipelined(); + Response string = p.get("string"); + string.get(); + p.sync(); + } + + @Test + public void pipelineWithPubSub() { + Pipeline pipelined = jedis.pipelined(); + Response p1 = pipelined.publish("foo", "bar"); + Response p2 = pipelined.publish("foo".getBytes(), "bar".getBytes()); + pipelined.sync(); + assertEquals(0, p1.get().longValue()); + assertEquals(0, p2.get().longValue()); + } + + @Test + public void canRetrieveUnsetKey() { + Pipeline p = jedis.pipelined(); + Response shouldNotExist = p.get(UUID.randomUUID().toString()); + p.sync(); + assertNull(shouldNotExist.get()); + } + + @Test + public void piplineWithError() { + Pipeline p = jedis.pipelined(); + p.set("foo", "bar"); + Response> error = p.smembers("foo"); + Response r = p.get("foo"); + p.sync(); + try { + error.get(); + fail(); + } catch (JedisDataException e) { + // that is fine we should be here + } + assertEquals(r.get(), "bar"); + } // // @Test // public void multi() { @@ -367,32 +367,32 @@ // pipeline.set("foo", "3"); // pipeline.multi(); // } -// -// @Test(expected = IllegalStateException.class) -// public void testJedisThrowExceptionWhenInPipeline() { -// Pipeline pipeline = jedis.pipelined(); -// pipeline.set("foo", "3"); -// jedis.get("somekey"); -// fail("Can't use jedis instance when in Pipeline"); -// } -// -// @Test -// public void testReuseJedisWhenPipelineIsEmpty() { -// Pipeline pipeline = jedis.pipelined(); -// pipeline.set("foo", "3"); -// pipeline.sync(); -// String result = jedis.get("foo"); -// assertEquals(result, "3"); -// } -// -// @Test -// public void testResetStateWhenInPipeline() { -// Pipeline pipeline = jedis.pipelined(); -// pipeline.set("foo", "3"); -// jedis.resetState(); -// String result = jedis.get("foo"); -// assertEquals(result, "3"); -// } + + @Test(expected = IllegalStateException.class) + public void testJedisThrowExceptionWhenInPipeline() { + Pipeline pipeline = jedis.pipelined(); + pipeline.set("foo", "3"); + jedis.get("somekey"); + fail("Can't use jedis instance when in Pipeline"); + } + + @Test + public void testReuseJedisWhenPipelineIsEmpty() { + Pipeline pipeline = jedis.pipelined(); + pipeline.set("foo", "3"); + pipeline.sync(); + String result = jedis.get("foo"); + assertEquals(result, "3"); + } + + @Test + public void testResetStateWhenInPipeline() { + Pipeline pipeline = jedis.pipelined(); + pipeline.set("foo", "3"); + jedis.resetState(); + String result = jedis.get("foo"); + assertEquals(result, "3"); + } // // @Test // public void testDiscardInPipeline() { @@ -405,167 +405,167 @@ // discard.get(); // get.get(); // } -// -// @Test -// public void waitReplicas() { -// Pipeline p = jedis.pipelined(); -// p.set("wait", "replicas"); -// p.waitReplicas(1, 10); -// p.sync(); -// -// try (Jedis j = new Jedis(HostAndPortUtil.getRedisServers().get(4))) { -// j.auth("foobared"); -// assertEquals("replicas", j.get("wait")); -// } -// } -// -// @Test -// public void testEval() { -// String script = "return 'success!'"; -// -// Pipeline p = jedis.pipelined(); -// Response result = p.eval(script); -// p.sync(); -// -// assertEquals("success!", result.get()); -// } -// -// @Test -// public void testEvalWithBinary() { -// String script = "return 'success!'"; -// -// Pipeline p = jedis.pipelined(); -// Response result = p.eval(SafeEncoder.encode(script)); -// p.sync(); -// -// assertArrayEquals(SafeEncoder.encode("success!"), (byte[]) result.get()); -// } -// -// @Test -// public void testEvalKeyAndArg() { -// String key = "test"; -// String arg = "3"; -// String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"; -// -// Pipeline p = jedis.pipelined(); -// p.set(key, "0"); -// Response result0 = p.eval(script, Arrays.asList(key), Arrays.asList(arg)); -// p.incr(key); -// Response result1 = p.eval(script, Arrays.asList(key), Arrays.asList(arg)); -// Response result2 = p.get(key); -// p.sync(); -// -// assertNull(result0.get()); -// assertNull(result1.get()); -// assertEquals("13", result2.get()); -// } -// -// @Test -// public void testEvalKeyAndArgWithBinary() { -// // binary -// byte[] bKey = SafeEncoder.encode("test"); -// byte[] bArg = SafeEncoder.encode("3"); -// byte[] bScript = SafeEncoder -// .encode("redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"); -// -// Pipeline bP = jedis.pipelined(); -// bP.set(bKey, SafeEncoder.encode("0")); -// Response bResult0 = bP.eval(bScript, Arrays.asList(bKey), Arrays.asList(bArg)); -// bP.incr(bKey); -// Response bResult1 = bP.eval(bScript, Arrays.asList(bKey), Arrays.asList(bArg)); -// Response bResult2 = bP.get(bKey); -// bP.sync(); -// -// assertNull(bResult0.get()); -// assertNull(bResult1.get()); -// assertArrayEquals(SafeEncoder.encode("13"), bResult2.get()); -// } -// -// @Test -// public void testEvalNestedLists() { -// String script = "return { {KEYS[1]} , {2} }"; -// -// Pipeline p = jedis.pipelined(); -// Response result = p.eval(script, 1, "key1"); -// p.sync(); -// -// List results = (List) result.get(); -// assertThat((List) results.get(0), listWithItem("key1")); -// assertThat((List) results.get(1), listWithItem(2L)); -// } -// -// @Test -// public void testEvalNestedListsWithBinary() { -// byte[] bScript = SafeEncoder.encode("return { {KEYS[1]} , {2} }"); -// byte[] bKey = SafeEncoder.encode("key1"); -// -// Pipeline p = jedis.pipelined(); -// Response result = p.eval(bScript, 1, bKey); -// p.sync(); -// -// List results = (List) result.get(); -// assertThat((List) results.get(0), listWithItem(bKey)); -// assertThat((List) results.get(1), listWithItem(2L)); -// } -// -// @Test -// public void testEvalsha() { -// String script = "return 'success!'"; -// String sha1 = jedis.scriptLoad(script); -// -// assertTrue(jedis.scriptExists(sha1)); -// -// Pipeline p = jedis.pipelined(); -// Response result = p.evalsha(sha1); -// p.sync(); -// -// assertEquals("success!", result.get()); -// } -// -// @Test -// public void testEvalshaKeyAndArg() { -// String key = "test"; -// String arg = "3"; -// String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"; -// String sha1 = jedis.scriptLoad(script); -// -// assertTrue(jedis.scriptExists(sha1)); -// -// Pipeline p = jedis.pipelined(); -// p.set(key, "0"); -// Response result0 = p.evalsha(sha1, Arrays.asList(key), Arrays.asList(arg)); -// p.incr(key); -// Response result1 = p.evalsha(sha1, Arrays.asList(key), Arrays.asList(arg)); -// Response result2 = p.get(key); -// p.sync(); -// -// assertNull(result0.get()); -// assertNull(result1.get()); -// assertEquals("13", result2.get()); -// } -// -// @Test -// public void testEvalshaKeyAndArgWithBinary() { -// byte[] bKey = SafeEncoder.encode("test"); -// byte[] bArg = SafeEncoder.encode("3"); -// String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"; -// byte[] bScript = SafeEncoder.encode(script); -// byte[] bSha1 = jedis.scriptLoad(bScript); -// -// assertTrue(jedis.scriptExists(bSha1) == 1); -// -// Pipeline p = jedis.pipelined(); -// p.set(bKey, SafeEncoder.encode("0")); -// Response result0 = p.evalsha(bSha1, Arrays.asList(bKey), Arrays.asList(bArg)); -// p.incr(bKey); -// Response result1 = p.evalsha(bSha1, Arrays.asList(bKey), Arrays.asList(bArg)); -// Response result2 = p.get(bKey); -// p.sync(); -// -// assertNull(result0.get()); -// assertNull(result1.get()); -// assertArrayEquals(SafeEncoder.encode("13"), result2.get()); -// } + + @Test + public void waitReplicas() { + Pipeline p = jedis.pipelined(); + p.set("wait", "replicas"); + p.waitReplicas(1, 10); + p.sync(); + + try (Jedis j = new Jedis(HostAndPortUtil.getRedisServers().get(4))) { + j.auth("foobared"); + assertEquals("replicas", j.get("wait")); + } + } + + @Test + public void testEval() { + String script = "return 'success!'"; + + Pipeline p = jedis.pipelined(); + Response result = p.eval(script); + p.sync(); + + assertEquals("success!", result.get()); + } + + @Test + public void testEvalWithBinary() { + String script = "return 'success!'"; + + Pipeline p = jedis.pipelined(); + Response result = p.eval(SafeEncoder.encode(script)); + p.sync(); + + assertArrayEquals(SafeEncoder.encode("success!"), (byte[]) result.get()); + } + + @Test + public void testEvalKeyAndArg() { + String key = "test"; + String arg = "3"; + String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"; + + Pipeline p = jedis.pipelined(); + p.set(key, "0"); + Response result0 = p.eval(script, Arrays.asList(key), Arrays.asList(arg)); + p.incr(key); + Response result1 = p.eval(script, Arrays.asList(key), Arrays.asList(arg)); + Response result2 = p.get(key); + p.sync(); + + assertNull(result0.get()); + assertNull(result1.get()); + assertEquals("13", result2.get()); + } + + @Test + public void testEvalKeyAndArgWithBinary() { + // binary + byte[] bKey = SafeEncoder.encode("test"); + byte[] bArg = SafeEncoder.encode("3"); + byte[] bScript = SafeEncoder + .encode("redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"); + + Pipeline bP = jedis.pipelined(); + bP.set(bKey, SafeEncoder.encode("0")); + Response bResult0 = bP.eval(bScript, Arrays.asList(bKey), Arrays.asList(bArg)); + bP.incr(bKey); + Response bResult1 = bP.eval(bScript, Arrays.asList(bKey), Arrays.asList(bArg)); + Response bResult2 = bP.get(bKey); + bP.sync(); + + assertNull(bResult0.get()); + assertNull(bResult1.get()); + assertArrayEquals(SafeEncoder.encode("13"), bResult2.get()); + } + + @Test + public void testEvalNestedLists() { + String script = "return { {KEYS[1]} , {2} }"; + + Pipeline p = jedis.pipelined(); + Response result = p.eval(script, 1, "key1"); + p.sync(); + + List results = (List) result.get(); + assertThat((List) results.get(0), listWithItem("key1")); + assertThat((List) results.get(1), listWithItem(2L)); + } + + @Test + public void testEvalNestedListsWithBinary() { + byte[] bScript = SafeEncoder.encode("return { {KEYS[1]} , {2} }"); + byte[] bKey = SafeEncoder.encode("key1"); + + Pipeline p = jedis.pipelined(); + Response result = p.eval(bScript, 1, bKey); + p.sync(); + + List results = (List) result.get(); + assertThat((List) results.get(0), listWithItem(bKey)); + assertThat((List) results.get(1), listWithItem(2L)); + } + + @Test + public void testEvalsha() { + String script = "return 'success!'"; + String sha1 = jedis.scriptLoad(script); + + assertTrue(jedis.scriptExists(sha1)); + + Pipeline p = jedis.pipelined(); + Response result = p.evalsha(sha1); + p.sync(); + + assertEquals("success!", result.get()); + } + + @Test + public void testEvalshaKeyAndArg() { + String key = "test"; + String arg = "3"; + String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"; + String sha1 = jedis.scriptLoad(script); + + assertTrue(jedis.scriptExists(sha1)); + + Pipeline p = jedis.pipelined(); + p.set(key, "0"); + Response result0 = p.evalsha(sha1, Arrays.asList(key), Arrays.asList(arg)); + p.incr(key); + Response result1 = p.evalsha(sha1, Arrays.asList(key), Arrays.asList(arg)); + Response result2 = p.get(key); + p.sync(); + + assertNull(result0.get()); + assertNull(result1.get()); + assertEquals("13", result2.get()); + } + + @Test + public void testEvalshaKeyAndArgWithBinary() { + byte[] bKey = SafeEncoder.encode("test"); + byte[] bArg = SafeEncoder.encode("3"); + String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"; + byte[] bScript = SafeEncoder.encode(script); + byte[] bSha1 = jedis.scriptLoad(bScript); + + assertTrue(jedis.scriptExists(bSha1)); + + Pipeline p = jedis.pipelined(); + p.set(bKey, SafeEncoder.encode("0")); + Response result0 = p.evalsha(bSha1, Arrays.asList(bKey), Arrays.asList(bArg)); + p.incr(bKey); + Response result1 = p.evalsha(bSha1, Arrays.asList(bKey), Arrays.asList(bArg)); + Response result2 = p.get(bKey); + p.sync(); + + assertNull(result0.get()); + assertNull(result1.get()); + assertArrayEquals(SafeEncoder.encode("13"), result2.get()); + } // // @Test // public void testPipelinedTransactionResponse() { @@ -651,24 +651,24 @@ // // jedis2.close(); // } -// -// @Test -// public void testCloseable() throws IOException { -// // we need to test with fresh instance of Jedis -// Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); -// jedis2.auth("foobared"); -// -// Pipeline pipeline = jedis2.pipelined(); -// Response retFuture1 = pipeline.set("a", "1"); -// Response retFuture2 = pipeline.set("b", "2"); -// -// pipeline.close(); -// -// // it shouldn't meet any exception -// retFuture1.get(); -// retFuture2.get(); -// jedis2.close(); -// } + + @Test + public void testCloseable() throws IOException { + // we need to test with fresh instance of Jedis + Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); + jedis2.auth("foobared"); + + Pipeline pipeline = jedis2.pipelined(); + Response retFuture1 = pipeline.set("a", "1"); + Response retFuture2 = pipeline.set("b", "2"); + + pipeline.close(); + + // it shouldn't meet any exception + retFuture1.get(); + retFuture2.get(); + jedis2.close(); + } // // @Test // public void testCloseableWithMulti() throws IOException { @@ -776,8 +776,8 @@ // assertTrue(firstKey.equals(value1) || firstKey.equals(value2)); // assertTrue(secondKey.equals(value1) || secondKey.equals(value2)); // } -// -// private Matcher> listWithItem(T expected) { -// return CoreMatchers. hasItem(equalTo(expected)); -// } -//} + + private Matcher> listWithItem(T expected) { + return CoreMatchers. hasItem(equalTo(expected)); + } +} diff --git a/src/test/java/redis/clients/jedis/tests/SSLJedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/SSLJedisClusterTest.java index de825ac426..106b053cd4 100644 --- a/src/test/java/redis/clients/jedis/tests/SSLJedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/SSLJedisClusterTest.java @@ -1,239 +1,249 @@ -//package redis.clients.jedis.tests; -// -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertTrue; -// -//import java.util.Collections; -//import java.util.Map; -//import javax.net.ssl.HostnameVerifier; -//import javax.net.ssl.SSLParameters; -//import javax.net.ssl.SSLSession; -//import javax.net.ssl.SSLSocketFactory; -// -//import org.junit.Assert; -//import org.junit.BeforeClass; -//import org.junit.Test; -// -//import redis.clients.jedis.DefaultJedisClientConfig; -//import redis.clients.jedis.HostAndPort; -//import redis.clients.jedis.HostAndPortMapper; -//import redis.clients.jedis.JedisCluster; -//import redis.clients.jedis.JedisPool; -//import redis.clients.jedis.JedisPoolConfig; +package redis.clients.jedis.tests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Collections; +import java.util.Map; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocketFactory; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.DefaultJedisClientConfig; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.HostAndPortMapper; +import redis.clients.jedis.JedisCluster; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; //import redis.clients.jedis.exceptions.JedisClusterMaxAttemptsException; +import redis.clients.jedis.exceptions.JedisClusterOperationException; //import redis.clients.jedis.exceptions.JedisNoReachableClusterNodeException; -//import redis.clients.jedis.tests.SSLJedisTest.BasicHostnameVerifier; -// -//public class SSLJedisClusterTest extends JedisClusterTest { -// -// private static final int DEFAULT_REDIRECTIONS = 5; -// private static final JedisPoolConfig DEFAULT_POOL_CONFIG = new JedisPoolConfig(); -// -// private final HostAndPortMapper hostAndPortMap = (HostAndPort hostAndPort) -> { -// String host = hostAndPort.getHost(); -// int port = hostAndPort.getPort(); -// if (host.equals("127.0.0.1")) { -// host = "localhost"; -// port = port + 1000; -// } -// return new HostAndPort(host, port); -// }; -// -// // don't map IP addresses so that we try to connect with host 127.0.0.1 -// private final HostAndPortMapper portMap = (HostAndPort hostAndPort) -> { -// if ("localhost".equals(hostAndPort.getHost())) { -// return hostAndPort; -// } -// return new HostAndPort(hostAndPort.getHost(), hostAndPort.getPort() + 1000); -// }; -// -// @BeforeClass -// public static void prepare() { -// SSLJedisTest.setupTrustStore(); // set up trust store for SSL tests -// } -// -// @Test -// public void testSSLDiscoverNodesAutomatically() { -// try (JedisCluster jc = new JedisCluster(Collections.singleton(new HostAndPort("localhost", 8379)), -// DefaultJedisClientConfig.builder().password("cluster").ssl(true) -// .hostAndPortMapper(hostAndPortMap).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { +import redis.clients.jedis.tests.SSLJedisTest.BasicHostnameVerifier; + +public class SSLJedisClusterTest extends JedisClusterTest { + + private static final int DEFAULT_REDIRECTIONS = 5; + private static final JedisPoolConfig DEFAULT_POOL_CONFIG = new JedisPoolConfig(); + + private final HostAndPortMapper hostAndPortMap = (HostAndPort hostAndPort) -> { + String host = hostAndPort.getHost(); + int port = hostAndPort.getPort(); + if (host.equals("127.0.0.1")) { + host = "localhost"; + port = port + 1000; + } + return new HostAndPort(host, port); + }; + + // don't map IP addresses so that we try to connect with host 127.0.0.1 + private final HostAndPortMapper portMap = (HostAndPort hostAndPort) -> { + if ("localhost".equals(hostAndPort.getHost())) { + return hostAndPort; + } + return new HostAndPort(hostAndPort.getHost(), hostAndPort.getPort() + 1000); + }; + + @BeforeClass + public static void prepare() { + SSLJedisTest.setupTrustStore(); // set up trust store for SSL tests + } + + @Test + public void testSSLDiscoverNodesAutomatically() { + try (JedisCluster jc = new JedisCluster(Collections.singleton(new HostAndPort("localhost", 8379)), + DefaultJedisClientConfig.builder().password("cluster").ssl(true) + .hostAndPortMapper(hostAndPortMap).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { // Map clusterNodes = jc.getClusterNodes(); -// assertEquals(3, clusterNodes.size()); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); -// -// jc.get("foo"); -// } -// -// try (JedisCluster jc2 = new JedisCluster(new HostAndPort("localhost", 8379), -// DefaultJedisClientConfig.builder().password("cluster").ssl(true) -// .hostAndPortMapper(hostAndPortMap).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + Map clusterNodes = jc.getClusterNodes(); + assertEquals(3, clusterNodes.size()); + assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); + + jc.get("foo"); + } + + try (JedisCluster jc2 = new JedisCluster(new HostAndPort("localhost", 8379), + DefaultJedisClientConfig.builder().password("cluster").ssl(true) + .hostAndPortMapper(hostAndPortMap).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { // Map clusterNodes = jc2.getClusterNodes(); -// assertEquals(3, clusterNodes.size()); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); -// jc2.get("foo"); -// } -// } -// -// @Test -// public void testSSLWithoutPortMap() { -// try (JedisCluster jc = new JedisCluster(Collections.singleton(new HostAndPort("localhost", 8379)), -// DefaultJedisClientConfig.builder().password("cluster").ssl(true).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + Map clusterNodes = jc2.getClusterNodes(); + assertEquals(3, clusterNodes.size()); + assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); + jc2.get("foo"); + } + } + + @Test + public void testSSLWithoutPortMap() { + try (JedisCluster jc = new JedisCluster(Collections.singleton(new HostAndPort("localhost", 8379)), + DefaultJedisClientConfig.builder().password("cluster").ssl(true).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { // Map clusterNodes = jc.getClusterNodes(); -// assertEquals(3, clusterNodes.size()); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); -// } -// } -// -// @Test -// public void connectByIpAddress() { -// try (JedisCluster jc = new JedisCluster(new HostAndPort("127.0.0.1", 7379), -// DefaultJedisClientConfig.builder().password("cluster").ssl(true) -// .hostAndPortMapper(hostAndPortMap).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// jc.get("foo"); -// } -// } -// -// @Test -// public void connectToNodesFailsWithSSLParametersAndNoHostMapping() { -// final SSLParameters sslParameters = new SSLParameters(); -// sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); -// -// try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), -// DefaultJedisClientConfig.builder().password("cluster").ssl(true) -// .sslParameters(sslParameters).hostAndPortMapper(portMap).build(), DEFAULT_REDIRECTIONS, -// DEFAULT_POOL_CONFIG)) { -// jc.get("foo"); -// Assert.fail("It should fail after all cluster attempts."); + Map clusterNodes = jc.getClusterNodes(); + assertEquals(3, clusterNodes.size()); + assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); + } + } + + @Test + public void connectByIpAddress() { + try (JedisCluster jc = new JedisCluster(new HostAndPort("127.0.0.1", 7379), + DefaultJedisClientConfig.builder().password("cluster").ssl(true) + .hostAndPortMapper(hostAndPortMap).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + jc.get("foo"); + } + } + + @Test + public void connectToNodesFailsWithSSLParametersAndNoHostMapping() { + final SSLParameters sslParameters = new SSLParameters(); + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); + + try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), + DefaultJedisClientConfig.builder().password("cluster").ssl(true) + .sslParameters(sslParameters).hostAndPortMapper(portMap).build(), DEFAULT_REDIRECTIONS, + DEFAULT_POOL_CONFIG)) { + jc.get("foo"); + Assert.fail("It should fail after all cluster attempts."); // } catch (JedisClusterMaxAttemptsException e) { -// // initial connection to localhost works, but subsequent connections to nodes use 127.0.0.1 -// // and fail hostname verification -// assertEquals("No more cluster attempts left.", e.getMessage()); -// } -// } -// -// @Test -// public void connectToNodesSucceedsWithSSLParametersAndHostMapping() { -// final SSLParameters sslParameters = new SSLParameters(); -// sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); -// -// try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), -// DefaultJedisClientConfig.builder().password("cluster").ssl(true) -// .sslParameters(sslParameters).hostAndPortMapper(hostAndPortMap).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// jc.get("foo"); -// } -// } -// -// @Test -// public void connectByIpAddressFailsWithSSLParameters() { -// final SSLParameters sslParameters = new SSLParameters(); -// sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); -// -// try (JedisCluster jc = new JedisCluster(new HostAndPort("127.0.0.1", 8379), -// DefaultJedisClientConfig.builder().password("cluster").ssl(true) -// .sslParameters(sslParameters).hostAndPortMapper(hostAndPortMap).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// jc.get("key"); -// Assert.fail("There should be no reachable node in cluster."); + } catch (JedisClusterOperationException e) { + // initial connection to localhost works, but subsequent connections to nodes use 127.0.0.1 + // and fail hostname verification + assertEquals("No more cluster attempts left.", e.getMessage()); + } + } + + @Test + public void connectToNodesSucceedsWithSSLParametersAndHostMapping() { + final SSLParameters sslParameters = new SSLParameters(); + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); + + try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), + DefaultJedisClientConfig.builder().password("cluster").ssl(true) + .sslParameters(sslParameters).hostAndPortMapper(hostAndPortMap).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + jc.get("foo"); + } + } + + @Test + public void connectByIpAddressFailsWithSSLParameters() { + final SSLParameters sslParameters = new SSLParameters(); + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); + + try (JedisCluster jc = new JedisCluster(new HostAndPort("127.0.0.1", 8379), + DefaultJedisClientConfig.builder().password("cluster").ssl(true) + .sslParameters(sslParameters).hostAndPortMapper(hostAndPortMap).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + jc.get("key"); + Assert.fail("There should be no reachable node in cluster."); // } catch (JedisNoReachableClusterNodeException e) { -// assertEquals("No reachable node in cluster.", e.getMessage()); -// } -// } -// -// @Test -// public void connectWithCustomHostNameVerifier() { -// HostnameVerifier hostnameVerifier = new BasicHostnameVerifier(); -// HostnameVerifier localhostVerifier = new LocalhostVerifier(); -// -// try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), -// DefaultJedisClientConfig.builder().password("cluster").ssl(true) -// .hostnameVerifier(hostnameVerifier).hostAndPortMapper(portMap).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// jc.get("foo"); -// Assert.fail("It should fail after all cluster attempts."); + } catch (JedisClusterOperationException e) { + assertEquals("No reachable node in cluster.", e.getMessage()); + } + } + + @Test + public void connectWithCustomHostNameVerifier() { + HostnameVerifier hostnameVerifier = new BasicHostnameVerifier(); + HostnameVerifier localhostVerifier = new LocalhostVerifier(); + + try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), + DefaultJedisClientConfig.builder().password("cluster").ssl(true) + .hostnameVerifier(hostnameVerifier).hostAndPortMapper(portMap).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + jc.get("foo"); + Assert.fail("It should fail after all cluster attempts."); // } catch (JedisClusterMaxAttemptsException e) { -// // initial connection made with 'localhost' but subsequent connections to nodes use 127.0.0.1 -// // which causes custom hostname verification to fail -// assertEquals("No more cluster attempts left.", e.getMessage()); -// } -// -// try (JedisCluster jc2 = new JedisCluster(new HostAndPort("127.0.0.1", 8379), -// DefaultJedisClientConfig.builder().password("cluster").ssl(true) -// .hostnameVerifier(hostnameVerifier).hostAndPortMapper(portMap).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// jc2.get("foo"); -// Assert.fail("There should be no reachable node in cluster."); + } catch (JedisClusterOperationException e) { + // initial connection made with 'localhost' but subsequent connections to nodes use 127.0.0.1 + // which causes custom hostname verification to fail + assertEquals("No more cluster attempts left.", e.getMessage()); + } + + try (JedisCluster jc2 = new JedisCluster(new HostAndPort("127.0.0.1", 8379), + DefaultJedisClientConfig.builder().password("cluster").ssl(true) + .hostnameVerifier(hostnameVerifier).hostAndPortMapper(portMap).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + jc2.get("foo"); + Assert.fail("There should be no reachable node in cluster."); // } catch (JedisNoReachableClusterNodeException e) { -// // JedisNoReachableClusterNodeException exception occurs from not being able to connect -// // since the socket factory fails the hostname verification -// assertEquals("No reachable node in cluster.", e.getMessage()); -// } -// -// try (JedisCluster jc3 = new JedisCluster(new HostAndPort("localhost", 8379), -// DefaultJedisClientConfig.builder().password("cluster").ssl(true) -// .hostnameVerifier(localhostVerifier).hostAndPortMapper(portMap).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// jc3.get("foo"); -// } -// } -// -// @Test -// public void connectWithCustomSocketFactory() throws Exception { -// final SSLSocketFactory sslSocketFactory = SSLJedisTest.createTrustStoreSslSocketFactory(); -// -// try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), -// DefaultJedisClientConfig.builder().password("cluster").ssl(true) -// .sslSocketFactory(sslSocketFactory).hostAndPortMapper(portMap).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// assertEquals(3, jc.getClusterNodes().size()); -// } -// } -// -// @Test -// public void connectWithEmptyTrustStore() throws Exception { -// final SSLSocketFactory sslSocketFactory = SSLJedisTest.createTrustNoOneSslSocketFactory(); -// -// try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), -// DefaultJedisClientConfig.builder().password("cluster").ssl(true) -// .sslSocketFactory(sslSocketFactory).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// jc.get("key"); -// Assert.fail("There should be no reachable node in cluster."); + } catch (JedisClusterOperationException e) { + // JedisNoReachableClusterNodeException exception occurs from not being able to connect + // since the socket factory fails the hostname verification + assertEquals("No reachable node in cluster.", e.getMessage()); + } + + try (JedisCluster jc3 = new JedisCluster(new HostAndPort("localhost", 8379), + DefaultJedisClientConfig.builder().password("cluster").ssl(true) + .hostnameVerifier(localhostVerifier).hostAndPortMapper(portMap).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + jc3.get("foo"); + } + } + + @Test + public void connectWithCustomSocketFactory() throws Exception { + final SSLSocketFactory sslSocketFactory = SSLJedisTest.createTrustStoreSslSocketFactory(); + + try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), + DefaultJedisClientConfig.builder().password("cluster").ssl(true) + .sslSocketFactory(sslSocketFactory).hostAndPortMapper(portMap).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + assertEquals(3, jc.getClusterNodes().size()); + } + } + + @Test + public void connectWithEmptyTrustStore() throws Exception { + final SSLSocketFactory sslSocketFactory = SSLJedisTest.createTrustNoOneSslSocketFactory(); + + try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), + DefaultJedisClientConfig.builder().password("cluster").ssl(true) + .sslSocketFactory(sslSocketFactory).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + jc.get("key"); + Assert.fail("There should be no reachable node in cluster."); // } catch (JedisNoReachableClusterNodeException e) { -// assertEquals("No reachable node in cluster.", e.getMessage()); -// } -// } -// -// @Test -// public void defaultHostAndPortUsedIfMapReturnsNull() { -// HostAndPortMapper nullHostAndPortMap = (HostAndPort hostAndPort) -> null; -// -// try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 7379), -// DefaultJedisClientConfig.builder().password("cluster").ssl(false) -// .hostAndPortMapper(nullHostAndPortMap).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// + } catch (JedisClusterOperationException e) { + assertEquals("No reachable node in cluster.", e.getMessage()); + } + } + + @Test + public void defaultHostAndPortUsedIfMapReturnsNull() { + HostAndPortMapper nullHostAndPortMap = (HostAndPort hostAndPort) -> null; + + try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 7379), + DefaultJedisClientConfig.builder().password("cluster").ssl(false) + .hostAndPortMapper(nullHostAndPortMap).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + // Map clusterNodes = jc.getClusterNodes(); -// assertEquals(3, clusterNodes.size()); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); -// } -// } -// -// public class LocalhostVerifier extends BasicHostnameVerifier { -// @Override -// public boolean verify(String hostname, SSLSession session) { -// if (hostname.equals("127.0.0.1")) { -// hostname = "localhost"; -// } -// return super.verify(hostname, session); -// } -// } -//} + Map clusterNodes = jc.getClusterNodes(); + assertEquals(3, clusterNodes.size()); + assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); + } + } + + public class LocalhostVerifier extends BasicHostnameVerifier { + @Override + public boolean verify(String hostname, SSLSession session) { + if (hostname.equals("127.0.0.1")) { + hostname = "localhost"; + } + return super.verify(hostname, session); + } + } +} diff --git a/src/test/java/redis/clients/jedis/tests/SSLJedisClusterWithCompleteCredentialsTest.java b/src/test/java/redis/clients/jedis/tests/SSLJedisClusterWithCompleteCredentialsTest.java index d3d8b6d912..f0b58fb567 100644 --- a/src/test/java/redis/clients/jedis/tests/SSLJedisClusterWithCompleteCredentialsTest.java +++ b/src/test/java/redis/clients/jedis/tests/SSLJedisClusterWithCompleteCredentialsTest.java @@ -1,236 +1,243 @@ -//package redis.clients.jedis.tests; -// -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertTrue; -// -//import java.util.Collections; -//import java.util.Map; -//import javax.net.ssl.HostnameVerifier; -//import javax.net.ssl.SSLParameters; -//import javax.net.ssl.SSLSession; -//import javax.net.ssl.SSLSocketFactory; -// -//import org.junit.Assert; -//import org.junit.BeforeClass; -//import org.junit.Test; -// -//import redis.clients.jedis.*; +package redis.clients.jedis.tests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Collections; +import java.util.Map; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocketFactory; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.*; //import redis.clients.jedis.exceptions.JedisClusterMaxAttemptsException; +import redis.clients.jedis.exceptions.JedisClusterOperationException; //import redis.clients.jedis.exceptions.JedisNoReachableClusterNodeException; -//import redis.clients.jedis.tests.SSLJedisTest.BasicHostnameVerifier; -//import redis.clients.jedis.tests.utils.RedisVersionUtil; -// -//public class SSLJedisClusterWithCompleteCredentialsTest extends JedisClusterTest { -// -// private static final int DEFAULT_REDIRECTIONS = 5; -// private static final JedisPoolConfig DEFAULT_POOL_CONFIG = new JedisPoolConfig(); -// -// private final HostAndPortMapper hostAndPortMap = (HostAndPort hostAndPort) -> { -// String host = hostAndPort.getHost(); -// int port = hostAndPort.getPort(); -// if (host.equals("127.0.0.1")) { -// host = "localhost"; -// port = port + 1000; -// } -// return new HostAndPort(host, port); -// }; -// -// // don't map IP addresses so that we try to connect with host 127.0.0.1 -// private final HostAndPortMapper portMap = (HostAndPort hostAndPort) -> { -// if ("localhost".equals(hostAndPort.getHost())) { -// return hostAndPort; -// } -// return new HostAndPort(hostAndPort.getHost(), hostAndPort.getPort() + 1000); -// }; -// -// @BeforeClass -// public static void prepare() { -// org.junit.Assume.assumeTrue("Not running ACL test on this version of Redis", -// RedisVersionUtil.checkRedisMajorVersionNumber(6)); -// -// SSLJedisTest.setupTrustStore(); -// } -// -// @Test -// public void testSSLDiscoverNodesAutomatically() { -// try (JedisCluster jc = new JedisCluster(Collections.singleton(new HostAndPort("localhost", 8379)), -// DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) -// .hostAndPortMapper(hostAndPortMap).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// Map clusterNodes = jc.getClusterNodes(); -// assertEquals(3, clusterNodes.size()); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); -// jc.get("foo"); -// } -// -// try (JedisCluster jc2 = new JedisCluster(new HostAndPort("localhost", 8379), -// DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) -// .hostAndPortMapper(hostAndPortMap).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// Map clusterNodes = jc2.getClusterNodes(); -// assertEquals(3, clusterNodes.size()); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); -// jc2.get("foo"); -// } -// } -// -// @Test -// public void testSSLWithoutPortMap() { -// try (JedisCluster jc = new JedisCluster(Collections.singleton(new HostAndPort("localhost", 8379)), -// DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { +import redis.clients.jedis.tests.SSLJedisTest.BasicHostnameVerifier; +import redis.clients.jedis.tests.utils.RedisVersionUtil; + +public class SSLJedisClusterWithCompleteCredentialsTest extends JedisClusterTest { + + private static final int DEFAULT_REDIRECTIONS = 5; + private static final JedisPoolConfig DEFAULT_POOL_CONFIG = new JedisPoolConfig(); + + private final HostAndPortMapper hostAndPortMap = (HostAndPort hostAndPort) -> { + String host = hostAndPort.getHost(); + int port = hostAndPort.getPort(); + if (host.equals("127.0.0.1")) { + host = "localhost"; + port = port + 1000; + } + return new HostAndPort(host, port); + }; + + // don't map IP addresses so that we try to connect with host 127.0.0.1 + private final HostAndPortMapper portMap = (HostAndPort hostAndPort) -> { + if ("localhost".equals(hostAndPort.getHost())) { + return hostAndPort; + } + return new HostAndPort(hostAndPort.getHost(), hostAndPort.getPort() + 1000); + }; + + @BeforeClass + public static void prepare() { + org.junit.Assume.assumeTrue("Not running ACL test on this version of Redis", + RedisVersionUtil.checkRedisMajorVersionNumber(6)); + + SSLJedisTest.setupTrustStore(); + } + + @Test + public void testSSLDiscoverNodesAutomatically() { + try (JedisCluster jc = new JedisCluster(Collections.singleton(new HostAndPort("localhost", 8379)), + DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) + .hostAndPortMapper(hostAndPortMap).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + Map clusterNodes = jc.getClusterNodes(); + assertEquals(3, clusterNodes.size()); + assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); + jc.get("foo"); + } + + try (JedisCluster jc2 = new JedisCluster(new HostAndPort("localhost", 8379), + DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) + .hostAndPortMapper(hostAndPortMap).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + Map clusterNodes = jc2.getClusterNodes(); + assertEquals(3, clusterNodes.size()); + assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); + jc2.get("foo"); + } + } + + @Test + public void testSSLWithoutPortMap() { + try (JedisCluster jc = new JedisCluster(Collections.singleton(new HostAndPort("localhost", 8379)), + DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { // Map clusterNodes = jc.getClusterNodes(); -// assertEquals(3, clusterNodes.size()); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); -// } -// } -// -// @Test -// public void connectByIpAddress() { -// try (JedisCluster jc = new JedisCluster(new HostAndPort("127.0.0.1", 7379), -// DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) -// .hostAndPortMapper(hostAndPortMap).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// jc.get("foo"); -// } -// } -// -// @Test -// public void connectToNodesFailsWithSSLParametersAndNoHostMapping() { -// final SSLParameters sslParameters = new SSLParameters(); -// sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); -// -// try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), -// DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) -// .sslParameters(sslParameters).hostAndPortMapper(portMap).build(), DEFAULT_REDIRECTIONS, -// DEFAULT_POOL_CONFIG)) { -// jc.get("foo"); -// Assert.fail("It should fail after all cluster attempts."); + Map clusterNodes = jc.getClusterNodes(); + assertEquals(3, clusterNodes.size()); + assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); + } + } + + @Test + public void connectByIpAddress() { + try (JedisCluster jc = new JedisCluster(new HostAndPort("127.0.0.1", 7379), + DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) + .hostAndPortMapper(hostAndPortMap).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + jc.get("foo"); + } + } + + @Test + public void connectToNodesFailsWithSSLParametersAndNoHostMapping() { + final SSLParameters sslParameters = new SSLParameters(); + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); + + try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), + DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) + .sslParameters(sslParameters).hostAndPortMapper(portMap).build(), DEFAULT_REDIRECTIONS, + DEFAULT_POOL_CONFIG)) { + jc.get("foo"); + Assert.fail("It should fail after all cluster attempts."); // } catch (JedisClusterMaxAttemptsException e) { -// // initial connection to localhost works, but subsequent connections to nodes use 127.0.0.1 -// // and fail hostname verification -// assertEquals("No more cluster attempts left.", e.getMessage()); -// } -// } -// -// @Test -// public void connectToNodesSucceedsWithSSLParametersAndHostMapping() { -// final SSLParameters sslParameters = new SSLParameters(); -// sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); -// -// try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), -// DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) -// .sslParameters(sslParameters).hostAndPortMapper(hostAndPortMap).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// jc.get("foo"); -// } -// } -// -// @Test -// public void connectByIpAddressFailsWithSSLParameters() { -// final SSLParameters sslParameters = new SSLParameters(); -// sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); -// -// try (JedisCluster jc = new JedisCluster(new HostAndPort("127.0.0.1", 8379), -// DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) -// .sslParameters(sslParameters).hostAndPortMapper(hostAndPortMap).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// jc.get("key"); -// Assert.fail("There should be no reachable node in cluster."); + } catch (JedisClusterOperationException e) { + // initial connection to localhost works, but subsequent connections to nodes use 127.0.0.1 + // and fail hostname verification + assertEquals("No more cluster attempts left.", e.getMessage()); + } + } + + @Test + public void connectToNodesSucceedsWithSSLParametersAndHostMapping() { + final SSLParameters sslParameters = new SSLParameters(); + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); + + try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), + DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) + .sslParameters(sslParameters).hostAndPortMapper(hostAndPortMap).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + jc.get("foo"); + } + } + + @Test + public void connectByIpAddressFailsWithSSLParameters() { + final SSLParameters sslParameters = new SSLParameters(); + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); + + try (JedisCluster jc = new JedisCluster(new HostAndPort("127.0.0.1", 8379), + DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) + .sslParameters(sslParameters).hostAndPortMapper(hostAndPortMap).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + jc.get("key"); + Assert.fail("There should be no reachable node in cluster."); // } catch (JedisNoReachableClusterNodeException e) { -// assertEquals("No reachable node in cluster.", e.getMessage()); -// } -// } -// -// @Test -// public void connectWithCustomHostNameVerifier() { -// HostnameVerifier hostnameVerifier = new BasicHostnameVerifier(); -// HostnameVerifier localhostVerifier = new LocalhostVerifier(); -// -// try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), -// DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) -// .hostnameVerifier(hostnameVerifier).hostAndPortMapper(portMap).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// jc.get("foo"); -// Assert.fail("It should fail after all cluster attempts."); + } catch (JedisClusterOperationException e) { + assertEquals("No reachable node in cluster.", e.getMessage()); + } + } + + @Test + public void connectWithCustomHostNameVerifier() { + HostnameVerifier hostnameVerifier = new BasicHostnameVerifier(); + HostnameVerifier localhostVerifier = new LocalhostVerifier(); + + try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), + DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) + .hostnameVerifier(hostnameVerifier).hostAndPortMapper(portMap).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + jc.get("foo"); + Assert.fail("It should fail after all cluster attempts."); // } catch (JedisClusterMaxAttemptsException e) { -// // initial connection made with 'localhost' but subsequent connections to nodes use 127.0.0.1 -// // which causes custom hostname verification to fail -// assertEquals("No more cluster attempts left.", e.getMessage()); -// } -// -// try (JedisCluster jc2 = new JedisCluster(new HostAndPort("127.0.0.1", 8379), -// DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) -// .hostnameVerifier(hostnameVerifier).hostAndPortMapper(portMap).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// jc2.get("key"); -// Assert.fail("There should be no reachable node in cluster."); + } catch (JedisClusterOperationException e) { + // initial connection made with 'localhost' but subsequent connections to nodes use 127.0.0.1 + // which causes custom hostname verification to fail + assertEquals("No more cluster attempts left.", e.getMessage()); + } + + try (JedisCluster jc2 = new JedisCluster(new HostAndPort("127.0.0.1", 8379), + DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) + .hostnameVerifier(hostnameVerifier).hostAndPortMapper(portMap).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + jc2.get("key"); + Assert.fail("There should be no reachable node in cluster."); // } catch (JedisNoReachableClusterNodeException e) { -// // JedisNoReachableClusterNodeException exception occurs from not being able to connect since -// // the socket factory fails the hostname verification -// assertEquals("No reachable node in cluster.", e.getMessage()); -// } -// -// try (JedisCluster jc3 = new JedisCluster(new HostAndPort("localhost", 8379), -// DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) -// .hostnameVerifier(localhostVerifier).hostAndPortMapper(portMap).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// jc3.get("foo"); -// } -// } -// -// @Test -// public void connectWithCustomSocketFactory() throws Exception { -// final SSLSocketFactory sslSocketFactory = SSLJedisTest.createTrustStoreSslSocketFactory(); -// -// try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), -// DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) -// .sslSocketFactory(sslSocketFactory).hostAndPortMapper(portMap).build(), -// DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// assertEquals(3, jc.getClusterNodes().size()); -// } -// } -// -// @Test -// public void connectWithEmptyTrustStore() throws Exception { -// final SSLSocketFactory sslSocketFactory = SSLJedisTest.createTrustNoOneSslSocketFactory(); -// -// try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), -// DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) -// .sslSocketFactory(sslSocketFactory).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// jc.get("key"); -// Assert.fail("There should be no reachable node in cluster."); + } catch (JedisClusterOperationException e) { + // JedisNoReachableClusterNodeException exception occurs from not being able to connect since + // the socket factory fails the hostname verification + assertEquals("No reachable node in cluster.", e.getMessage()); + } + + try (JedisCluster jc3 = new JedisCluster(new HostAndPort("localhost", 8379), + DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) + .hostnameVerifier(localhostVerifier).hostAndPortMapper(portMap).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + jc3.get("foo"); + } + } + + @Test + public void connectWithCustomSocketFactory() throws Exception { + final SSLSocketFactory sslSocketFactory = SSLJedisTest.createTrustStoreSslSocketFactory(); + + try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), + DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) + .sslSocketFactory(sslSocketFactory).hostAndPortMapper(portMap).build(), + DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + assertEquals(3, jc.getClusterNodes().size()); + } + } + + @Test + public void connectWithEmptyTrustStore() throws Exception { + final SSLSocketFactory sslSocketFactory = SSLJedisTest.createTrustNoOneSslSocketFactory(); + + try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 8379), + DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true) + .sslSocketFactory(sslSocketFactory).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + jc.get("key"); + Assert.fail("There should be no reachable node in cluster."); // } catch (JedisNoReachableClusterNodeException e) { -// assertEquals("No reachable node in cluster.", e.getMessage()); -// } -// } -// -// @Test -// public void defaultHostAndPortUsedIfMapReturnsNull() { -// HostAndPortMapper nullHostAndPortMap = (HostAndPort hostAndPort) -> null; -// -// try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 7379), -// DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(false) -// .hostAndPortMapper(nullHostAndPortMap).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { -// Map clusterNodes = jc.getClusterNodes(); -// assertEquals(3, clusterNodes.size()); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); -// assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); -// } -// } -// -// public class LocalhostVerifier extends BasicHostnameVerifier { -// @Override -// public boolean verify(String hostname, SSLSession session) { -// if (hostname.equals("127.0.0.1")) { -// hostname = "localhost"; -// } -// return super.verify(hostname, session); -// } -// } -//} + } catch (JedisClusterOperationException e) { + assertEquals("No reachable node in cluster.", e.getMessage()); + } + } + + @Test + public void defaultHostAndPortUsedIfMapReturnsNull() { + HostAndPortMapper nullHostAndPortMap = (HostAndPort hostAndPort) -> null; + + try (JedisCluster jc = new JedisCluster(new HostAndPort("localhost", 7379), + DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(false) + .hostAndPortMapper(nullHostAndPortMap).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { + Map clusterNodes = jc.getClusterNodes(); + assertEquals(3, clusterNodes.size()); + assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); + assertTrue(clusterNodes.containsKey("127.0.0.1:7381")); + } + } + + public class LocalhostVerifier extends BasicHostnameVerifier { + @Override + public boolean verify(String hostname, SSLSession session) { + if (hostname.equals("127.0.0.1")) { + hostname = "localhost"; + } + return super.verify(hostname, session); + } + } +} diff --git a/src/test/java/redis/clients/jedis/tests/SSLJedisTest.java b/src/test/java/redis/clients/jedis/tests/SSLJedisTest.java index 20b1aa11b5..aad9032be9 100644 --- a/src/test/java/redis/clients/jedis/tests/SSLJedisTest.java +++ b/src/test/java/redis/clients/jedis/tests/SSLJedisTest.java @@ -1,114 +1,114 @@ -//package redis.clients.jedis.tests; -// -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertSame; -//import static org.junit.Assert.assertTrue; -//import static org.junit.Assert.fail; -// -//import java.io.File; -//import java.io.FileInputStream; -//import java.io.InputStream; -//import java.net.URI; -//import java.security.InvalidAlgorithmParameterException; -//import java.security.KeyStore; -//import java.security.SecureRandom; -//import java.security.cert.CertificateException; -//import java.security.cert.X509Certificate; -// -//import javax.net.ssl.HostnameVerifier; -//import javax.net.ssl.SSLContext; -//import javax.net.ssl.SSLException; -//import javax.net.ssl.SSLHandshakeException; -//import javax.net.ssl.SSLParameters; -//import javax.net.ssl.SSLPeerUnverifiedException; -//import javax.net.ssl.SSLSession; -//import javax.net.ssl.SSLSocketFactory; -//import javax.net.ssl.TrustManager; -//import javax.net.ssl.TrustManagerFactory; -//import javax.net.ssl.X509TrustManager; -// -//import org.junit.BeforeClass; -//import org.junit.Test; -// -//import redis.clients.jedis.DefaultJedisClientConfig; -//import redis.clients.jedis.HostAndPort; -//import redis.clients.jedis.Jedis; -//import redis.clients.jedis.JedisClientConfig; +package redis.clients.jedis.tests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.net.URI; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.DefaultJedisClientConfig; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisClientConfig; //import redis.clients.jedis.JedisShardInfo; -//import redis.clients.jedis.exceptions.JedisConnectionException; -// -//public class SSLJedisTest { -// -// @BeforeClass -// public static void prepare() { -// setupTrustStore(); -// } -// -// static void setupTrustStore() { -// setJvmTrustStore("src/test/resources/truststore.jceks", "jceks"); -// } -// -// private static void setJvmTrustStore(String trustStoreFilePath, String trustStoreType) { -// assertTrue(String.format("Could not find trust store at '%s'.", trustStoreFilePath), -// new File(trustStoreFilePath).exists()); -// System.setProperty("javax.net.ssl.trustStore", trustStoreFilePath); -// System.setProperty("javax.net.ssl.trustStoreType", trustStoreType); -// } -// -// @Test -// public void connectWithSsl() { -// try (Jedis jedis = new Jedis("localhost", 6390, true)) { -// jedis.auth("foobared"); -// assertEquals("PONG", jedis.ping()); -// } -// } -// -// @Test -// public void connectWithConfig() { -// try (Jedis jedis = new Jedis(new HostAndPort("localhost", 6390), DefaultJedisClientConfig -// .builder().ssl(true).build())) { -// jedis.auth("foobared"); -// assertEquals("PONG", jedis.ping()); -// } -// } -// -// @Test -// public void connectWithConfigInterface() { -// try (Jedis jedis = new Jedis(new HostAndPort("localhost", 6390), -// new JedisClientConfig() { -// @Override -// public boolean isSsl() { -// return true; -// } -// })) { -// jedis.auth("foobared"); -// assertEquals("PONG", jedis.ping()); -// } -// } -// -// /** -// * Tests opening a default SSL/TLS connection to redis using "rediss://" scheme url. -// */ -// @Test -// public void connectWithUrl() { -// // The "rediss" scheme instructs jedis to open a SSL/TLS connection. -// try (Jedis jedis = new Jedis("rediss://localhost:6390")) { -// jedis.auth("foobared"); -// assertEquals("PONG", jedis.ping()); -// } -// } -// -// /** -// * Tests opening a default SSL/TLS connection to redis. -// */ -// @Test -// public void connectWithUri() { -// // The "rediss" scheme instructs jedis to open a SSL/TLS connection. -// try (Jedis jedis = new Jedis(URI.create("rediss://localhost:6390"))) { -// jedis.auth("foobared"); -// assertEquals("PONG", jedis.ping()); -// } -// } +import redis.clients.jedis.exceptions.JedisConnectionException; + +public class SSLJedisTest { + + @BeforeClass + public static void prepare() { + setupTrustStore(); + } + + static void setupTrustStore() { + setJvmTrustStore("src/test/resources/truststore.jceks", "jceks"); + } + + private static void setJvmTrustStore(String trustStoreFilePath, String trustStoreType) { + assertTrue(String.format("Could not find trust store at '%s'.", trustStoreFilePath), + new File(trustStoreFilePath).exists()); + System.setProperty("javax.net.ssl.trustStore", trustStoreFilePath); + System.setProperty("javax.net.ssl.trustStoreType", trustStoreType); + } + + @Test + public void connectWithSsl() { + try (Jedis jedis = new Jedis("localhost", 6390, true)) { + jedis.auth("foobared"); + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void connectWithConfig() { + try (Jedis jedis = new Jedis(new HostAndPort("localhost", 6390), DefaultJedisClientConfig + .builder().ssl(true).build())) { + jedis.auth("foobared"); + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void connectWithConfigInterface() { + try (Jedis jedis = new Jedis(new HostAndPort("localhost", 6390), + new JedisClientConfig() { + @Override + public boolean isSsl() { + return true; + } + })) { + jedis.auth("foobared"); + assertEquals("PONG", jedis.ping()); + } + } + + /** + * Tests opening a default SSL/TLS connection to redis using "rediss://" scheme url. + */ + @Test + public void connectWithUrl() { + // The "rediss" scheme instructs jedis to open a SSL/TLS connection. + try (Jedis jedis = new Jedis("rediss://localhost:6390")) { + jedis.auth("foobared"); + assertEquals("PONG", jedis.ping()); + } + } + + /** + * Tests opening a default SSL/TLS connection to redis. + */ + @Test + public void connectWithUri() { + // The "rediss" scheme instructs jedis to open a SSL/TLS connection. + try (Jedis jedis = new Jedis(URI.create("rediss://localhost:6390"))) { + jedis.auth("foobared"); + assertEquals("PONG", jedis.ping()); + } + } // // /** // * Tests opening an SSL/TLS connection to redis. @@ -249,78 +249,78 @@ // e.getCause().getCause().getCause().getClass()); // } // } -// -// /** -// * Creates an SSLSocketFactory that trusts all certificates in truststore.jceks. -// */ -// static SSLSocketFactory createTrustStoreSslSocketFactory() throws Exception { -// -// KeyStore trustStore = KeyStore.getInstance("jceks"); -// -// try (InputStream inputStream = new FileInputStream("src/test/resources/truststore.jceks")) { -// trustStore.load(inputStream, null); -// } -// -// TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX"); -// trustManagerFactory.init(trustStore); -// TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); -// -// SSLContext sslContext = SSLContext.getInstance("TLS"); -// sslContext.init(null, trustManagers, new SecureRandom()); -// return sslContext.getSocketFactory(); -// } -// -// /** -// * Creates an SSLSocketFactory with a trust manager that does not trust any certificates. -// */ -// static SSLSocketFactory createTrustNoOneSslSocketFactory() throws Exception { -// TrustManager[] unTrustManagers = new TrustManager[] { new X509TrustManager() { -// public X509Certificate[] getAcceptedIssuers() { -// return new X509Certificate[0]; -// } -// -// public void checkClientTrusted(X509Certificate[] chain, String authType) { -// throw new RuntimeException(new InvalidAlgorithmParameterException()); -// } -// -// public void checkServerTrusted(X509Certificate[] chain, String authType) { -// throw new RuntimeException(new InvalidAlgorithmParameterException()); -// } -// } }; -// SSLContext sslContext = SSLContext.getInstance("TLS"); -// sslContext.init(null, unTrustManagers, new SecureRandom()); -// return sslContext.getSocketFactory(); -// } -// -// /** -// * Very basic hostname verifier implementation for testing. NOT recommended for production. -// */ -// static class BasicHostnameVerifier implements HostnameVerifier { -// -// private static final String COMMON_NAME_RDN_PREFIX = "CN="; -// -// @Override -// public boolean verify(String hostname, SSLSession session) { -// X509Certificate peerCertificate; -// try { -// peerCertificate = (X509Certificate) session.getPeerCertificates()[0]; -// } catch (SSLPeerUnverifiedException e) { -// throw new IllegalStateException("The session does not contain a peer X.509 certificate.", e); -// } -// String peerCertificateCN = getCommonName(peerCertificate); -// return hostname.equals(peerCertificateCN); -// } -// -// private String getCommonName(X509Certificate peerCertificate) { -// String subjectDN = peerCertificate.getSubjectDN().getName(); -// String[] dnComponents = subjectDN.split(","); -// for (String dnComponent : dnComponents) { -// dnComponent = dnComponent.trim(); -// if (dnComponent.startsWith(COMMON_NAME_RDN_PREFIX)) { -// return dnComponent.substring(COMMON_NAME_RDN_PREFIX.length()); -// } -// } -// throw new IllegalArgumentException("The certificate has no common name."); -// } -// } -//} + + /** + * Creates an SSLSocketFactory that trusts all certificates in truststore.jceks. + */ + static SSLSocketFactory createTrustStoreSslSocketFactory() throws Exception { + + KeyStore trustStore = KeyStore.getInstance("jceks"); + + try (InputStream inputStream = new FileInputStream("src/test/resources/truststore.jceks")) { + trustStore.load(inputStream, null); + } + + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX"); + trustManagerFactory.init(trustStore); + TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, trustManagers, new SecureRandom()); + return sslContext.getSocketFactory(); + } + + /** + * Creates an SSLSocketFactory with a trust manager that does not trust any certificates. + */ + static SSLSocketFactory createTrustNoOneSslSocketFactory() throws Exception { + TrustManager[] unTrustManagers = new TrustManager[] { new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + + public void checkClientTrusted(X509Certificate[] chain, String authType) { + throw new RuntimeException(new InvalidAlgorithmParameterException()); + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) { + throw new RuntimeException(new InvalidAlgorithmParameterException()); + } + } }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, unTrustManagers, new SecureRandom()); + return sslContext.getSocketFactory(); + } + + /** + * Very basic hostname verifier implementation for testing. NOT recommended for production. + */ + static class BasicHostnameVerifier implements HostnameVerifier { + + private static final String COMMON_NAME_RDN_PREFIX = "CN="; + + @Override + public boolean verify(String hostname, SSLSession session) { + X509Certificate peerCertificate; + try { + peerCertificate = (X509Certificate) session.getPeerCertificates()[0]; + } catch (SSLPeerUnverifiedException e) { + throw new IllegalStateException("The session does not contain a peer X.509 certificate.", e); + } + String peerCertificateCN = getCommonName(peerCertificate); + return hostname.equals(peerCertificateCN); + } + + private String getCommonName(X509Certificate peerCertificate) { + String subjectDN = peerCertificate.getSubjectDN().getName(); + String[] dnComponents = subjectDN.split(","); + for (String dnComponent : dnComponents) { + dnComponent = dnComponent.trim(); + if (dnComponent.startsWith(COMMON_NAME_RDN_PREFIX)) { + return dnComponent.substring(COMMON_NAME_RDN_PREFIX.length()); + } + } + throw new IllegalArgumentException("The certificate has no common name."); + } + } +} diff --git a/src/test/java/redis/clients/jedis/tests/SSLJedisWithCompleteCredentialsTest.java b/src/test/java/redis/clients/jedis/tests/SSLJedisWithCompleteCredentialsTest.java index 4cc8ced95c..9c0ccd8da7 100644 --- a/src/test/java/redis/clients/jedis/tests/SSLJedisWithCompleteCredentialsTest.java +++ b/src/test/java/redis/clients/jedis/tests/SSLJedisWithCompleteCredentialsTest.java @@ -1,103 +1,103 @@ -//package redis.clients.jedis.tests; -// -//import javax.net.ssl.*; -//import java.io.FileInputStream; -//import java.io.InputStream; -//import java.net.URI; -//import java.security.InvalidAlgorithmParameterException; -//import java.security.KeyStore; -//import java.security.SecureRandom; +package redis.clients.jedis.tests; + +import javax.net.ssl.*; +import java.io.FileInputStream; +import java.io.InputStream; +import java.net.URI; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyStore; +import java.security.SecureRandom; //import java.security.cert.CertificateException; -//import java.security.cert.X509Certificate; -// -//import org.junit.BeforeClass; -//import org.junit.Test; -// -//import redis.clients.jedis.DefaultJedisClientConfig; -//import redis.clients.jedis.HostAndPort; -//import redis.clients.jedis.Jedis; +import java.security.cert.X509Certificate; + +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.DefaultJedisClientConfig; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; //import redis.clients.jedis.JedisShardInfo; //import redis.clients.jedis.exceptions.JedisConnectionException; -//import redis.clients.jedis.tests.utils.RedisVersionUtil; -// -//import static org.junit.Assert.*; -// -///** -// * This test class is a copy of {@link SSLJedisTest}. -// *

-// * This test is only executed when the server/cluster is Redis 6. or more. -// */ -//public class SSLJedisWithCompleteCredentialsTest { -// -// @BeforeClass -// public static void prepare() { -// // Use to check if the ACL test should be ran. ACL are available only in 6.0 and later -// org.junit.Assume.assumeTrue("Not running ACL test on this version of Redis", -// RedisVersionUtil.checkRedisMajorVersionNumber(6)); -// -// SSLJedisTest.setupTrustStore(); -// } -// -// @Test -// public void connectWithSsl() { -// try (Jedis jedis = new Jedis("localhost", 6390, true)) { -// jedis.auth("acljedis", "fizzbuzz"); -// assertEquals("PONG", jedis.ping()); -// } -// } -// -// @Test -// public void connectWithConfig() { -// try (Jedis jedis = new Jedis(new HostAndPort("localhost", 6390), DefaultJedisClientConfig -// .builder().ssl(true).build())) { -// jedis.auth("acljedis", "fizzbuzz"); -// assertEquals("PONG", jedis.ping()); -// } -// } -// -// @Test -// public void connectWithUrl() { -// // The "rediss" scheme instructs jedis to open a SSL/TLS connection. -// try (Jedis jedis = new Jedis("rediss://localhost:6390")) { -// jedis.auth("default", "foobared"); -// assertEquals("PONG", jedis.ping()); -// } -// try (Jedis jedis = new Jedis("rediss://localhost:6390")) { -// jedis.auth("acljedis", "fizzbuzz"); -// assertEquals("PONG", jedis.ping()); -// } -// } -// -// @Test -// public void connectWithCompleteCredentialsUrl() { -// // The "rediss" scheme instructs jedis to open a SSL/TLS connection. -// try (Jedis jedis = new Jedis("rediss://default:foobared@localhost:6390")) { -// assertEquals("PONG", jedis.ping()); -// } -// try (Jedis jedis = new Jedis("rediss://acljedis:fizzbuzz@localhost:6390")) { -// assertEquals("PONG", jedis.ping()); -// } -// } -// -// @Test -// public void connectWithUri() { -// // The "rediss" scheme instructs jedis to open a SSL/TLS connection. -// try (Jedis jedis = new Jedis(URI.create("rediss://localhost:6390"))) { -// jedis.auth("acljedis", "fizzbuzz"); -// assertEquals("PONG", jedis.ping()); -// } -// } -// -// @Test -// public void connectWithCompleteCredentialsUri() { -// // The "rediss" scheme instructs jedis to open a SSL/TLS connection. -// try (Jedis jedis = new Jedis(URI.create("rediss://default:foobared@localhost:6390"))) { -// assertEquals("PONG", jedis.ping()); -// } -// try (Jedis jedis = new Jedis(URI.create("rediss://acljedis:fizzbuzz@localhost:6390"))) { -// assertEquals("PONG", jedis.ping()); -// } -// } +import redis.clients.jedis.tests.utils.RedisVersionUtil; + +import static org.junit.Assert.*; + +/** + * This test class is a copy of {@link SSLJedisTest}. + *

+ * This test is only executed when the server/cluster is Redis 6. or more. + */ +public class SSLJedisWithCompleteCredentialsTest { + + @BeforeClass + public static void prepare() { + // Use to check if the ACL test should be ran. ACL are available only in 6.0 and later + org.junit.Assume.assumeTrue("Not running ACL test on this version of Redis", + RedisVersionUtil.checkRedisMajorVersionNumber(6)); + + SSLJedisTest.setupTrustStore(); + } + + @Test + public void connectWithSsl() { + try (Jedis jedis = new Jedis("localhost", 6390, true)) { + jedis.auth("acljedis", "fizzbuzz"); + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void connectWithConfig() { + try (Jedis jedis = new Jedis(new HostAndPort("localhost", 6390), DefaultJedisClientConfig + .builder().ssl(true).build())) { + jedis.auth("acljedis", "fizzbuzz"); + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void connectWithUrl() { + // The "rediss" scheme instructs jedis to open a SSL/TLS connection. + try (Jedis jedis = new Jedis("rediss://localhost:6390")) { + jedis.auth("default", "foobared"); + assertEquals("PONG", jedis.ping()); + } + try (Jedis jedis = new Jedis("rediss://localhost:6390")) { + jedis.auth("acljedis", "fizzbuzz"); + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void connectWithCompleteCredentialsUrl() { + // The "rediss" scheme instructs jedis to open a SSL/TLS connection. + try (Jedis jedis = new Jedis("rediss://default:foobared@localhost:6390")) { + assertEquals("PONG", jedis.ping()); + } + try (Jedis jedis = new Jedis("rediss://acljedis:fizzbuzz@localhost:6390")) { + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void connectWithUri() { + // The "rediss" scheme instructs jedis to open a SSL/TLS connection. + try (Jedis jedis = new Jedis(URI.create("rediss://localhost:6390"))) { + jedis.auth("acljedis", "fizzbuzz"); + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void connectWithCompleteCredentialsUri() { + // The "rediss" scheme instructs jedis to open a SSL/TLS connection. + try (Jedis jedis = new Jedis(URI.create("rediss://default:foobared@localhost:6390"))) { + assertEquals("PONG", jedis.ping()); + } + try (Jedis jedis = new Jedis(URI.create("rediss://acljedis:fizzbuzz@localhost:6390"))) { + assertEquals("PONG", jedis.ping()); + } + } // // /** // * Tests opening an SSL/TLS connection to redis. NOTE: This test relies on a feature that is only @@ -248,77 +248,77 @@ // .getCause().getCause().getCause().getClass()); // } // } -// -// /** -// * Creates an SSLSocketFactory that trusts all certificates in truststore.jceks. -// */ -// static SSLSocketFactory createTrustStoreSslSocketFactory() throws Exception { -// -// KeyStore trustStore = KeyStore.getInstance("jceks"); -// try (InputStream inputStream = new FileInputStream("src/test/resources/truststore.jceks")) { -// trustStore.load(inputStream, null); -// } -// -// TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX"); -// trustManagerFactory.init(trustStore); -// TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); -// -// SSLContext sslContext = SSLContext.getInstance("TLS"); -// sslContext.init(null, trustManagers, new SecureRandom()); -// return sslContext.getSocketFactory(); -// } -// -// /** -// * Creates an SSLSocketFactory with a trust manager that does not trust any certificates. -// */ -// static SSLSocketFactory createTrustNoOneSslSocketFactory() throws Exception { -// TrustManager[] unTrustManagers = new TrustManager[] { new X509TrustManager() { -// public X509Certificate[] getAcceptedIssuers() { -// return new X509Certificate[0]; -// } -// -// public void checkClientTrusted(X509Certificate[] chain, String authType) { -// throw new RuntimeException(new InvalidAlgorithmParameterException()); -// } -// -// public void checkServerTrusted(X509Certificate[] chain, String authType) { -// throw new RuntimeException(new InvalidAlgorithmParameterException()); -// } -// } }; -// SSLContext sslContext = SSLContext.getInstance("TLS"); -// sslContext.init(null, unTrustManagers, new SecureRandom()); -// return sslContext.getSocketFactory(); -// } -// -// /** -// * Very basic hostname verifier implementation for testing. NOT recommended for production. -// */ -// static class BasicHostnameVerifier implements HostnameVerifier { -// -// private static final String COMMON_NAME_RDN_PREFIX = "CN="; -// -// @Override -// public boolean verify(String hostname, SSLSession session) { -// X509Certificate peerCertificate; -// try { -// peerCertificate = (X509Certificate) session.getPeerCertificates()[0]; -// } catch (SSLPeerUnverifiedException e) { -// throw new IllegalStateException("The session does not contain a peer X.509 certificate.", e); -// } -// String peerCertificateCN = getCommonName(peerCertificate); -// return hostname.equals(peerCertificateCN); -// } -// -// private String getCommonName(X509Certificate peerCertificate) { -// String subjectDN = peerCertificate.getSubjectDN().getName(); -// String[] dnComponents = subjectDN.split(","); -// for (String dnComponent : dnComponents) { -// dnComponent = dnComponent.trim(); -// if (dnComponent.startsWith(COMMON_NAME_RDN_PREFIX)) { -// return dnComponent.substring(COMMON_NAME_RDN_PREFIX.length()); -// } -// } -// throw new IllegalArgumentException("The certificate has no common name."); -// } -// } -//} + + /** + * Creates an SSLSocketFactory that trusts all certificates in truststore.jceks. + */ + static SSLSocketFactory createTrustStoreSslSocketFactory() throws Exception { + + KeyStore trustStore = KeyStore.getInstance("jceks"); + try (InputStream inputStream = new FileInputStream("src/test/resources/truststore.jceks")) { + trustStore.load(inputStream, null); + } + + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX"); + trustManagerFactory.init(trustStore); + TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, trustManagers, new SecureRandom()); + return sslContext.getSocketFactory(); + } + + /** + * Creates an SSLSocketFactory with a trust manager that does not trust any certificates. + */ + static SSLSocketFactory createTrustNoOneSslSocketFactory() throws Exception { + TrustManager[] unTrustManagers = new TrustManager[] { new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + + public void checkClientTrusted(X509Certificate[] chain, String authType) { + throw new RuntimeException(new InvalidAlgorithmParameterException()); + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) { + throw new RuntimeException(new InvalidAlgorithmParameterException()); + } + } }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, unTrustManagers, new SecureRandom()); + return sslContext.getSocketFactory(); + } + + /** + * Very basic hostname verifier implementation for testing. NOT recommended for production. + */ + static class BasicHostnameVerifier implements HostnameVerifier { + + private static final String COMMON_NAME_RDN_PREFIX = "CN="; + + @Override + public boolean verify(String hostname, SSLSession session) { + X509Certificate peerCertificate; + try { + peerCertificate = (X509Certificate) session.getPeerCertificates()[0]; + } catch (SSLPeerUnverifiedException e) { + throw new IllegalStateException("The session does not contain a peer X.509 certificate.", e); + } + String peerCertificateCN = getCommonName(peerCertificate); + return hostname.equals(peerCertificateCN); + } + + private String getCommonName(X509Certificate peerCertificate) { + String subjectDN = peerCertificate.getSubjectDN().getName(); + String[] dnComponents = subjectDN.split(","); + for (String dnComponent : dnComponents) { + dnComponent = dnComponent.trim(); + if (dnComponent.startsWith(COMMON_NAME_RDN_PREFIX)) { + return dnComponent.substring(COMMON_NAME_RDN_PREFIX.length()); + } + } + throw new IllegalArgumentException("The certificate has no common name."); + } + } +} diff --git a/src/test/java/redis/clients/jedis/tests/UdsTest.java b/src/test/java/redis/clients/jedis/tests/UdsTest.java index befc7ca699..c2be9bd902 100644 --- a/src/test/java/redis/clients/jedis/tests/UdsTest.java +++ b/src/test/java/redis/clients/jedis/tests/UdsTest.java @@ -85,14 +85,14 @@ public Socket createSocket() throws JedisConnectionException { // @Override // public void setSoTimeout(int soTimeout) { // } - - @Override - public void setSocketTimeout(int soTimeout) { - } - - @Override - public int getSocketTimeout() { - return Protocol.DEFAULT_TIMEOUT; - } +// +// @Override +// public void setSocketTimeout(int soTimeout) { +// } +// +// @Override +// public int getSocketTimeout() { +// return Protocol.DEFAULT_TIMEOUT; +// } } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/UnavailableConnectionTest.java b/src/test/java/redis/clients/jedis/tests/UnavailableConnectionTest.java index 40d0285e67..8f30317768 100644 --- a/src/test/java/redis/clients/jedis/tests/UnavailableConnectionTest.java +++ b/src/test/java/redis/clients/jedis/tests/UnavailableConnectionTest.java @@ -1,73 +1,74 @@ -//package redis.clients.jedis.tests; -// -//import static org.junit.Assert.assertFalse; -//import static org.junit.Assert.assertSame; -//import static org.junit.Assert.assertTrue; -//import static org.junit.Assert.fail; -// -//import org.apache.commons.pool2.impl.GenericObjectPoolConfig; -//import org.junit.BeforeClass; -//import org.junit.Test; -// -//import redis.clients.jedis.HostAndPort; -//import redis.clients.jedis.Jedis; -//import redis.clients.jedis.JedisPool; -//import redis.clients.jedis.exceptions.JedisConnectionException; -// -//public class UnavailableConnectionTest { -// -// private static final HostAndPort unavailableNode = new HostAndPort("localhost", 6400); -// -// @BeforeClass -// public static void setup() { -// setupAvoidQuitInDestroyObject(); -// -// try (Jedis j = new Jedis(unavailableNode)) { -// j.shutdown(); -// } -// } -// -// public static void cleanup() { -// cleanupAvoidQuitInDestroyObject(); -// } -// -// private static JedisPool poolForBrokenJedis1; -// private static Thread threadForBrokenJedis1; -// private static Jedis brokenJedis1; -// -// public static void setupAvoidQuitInDestroyObject() { -// GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); -// config.setMaxTotal(1); -// poolForBrokenJedis1 = new JedisPool(config, unavailableNode.getHost(), -// unavailableNode.getPort()); -// brokenJedis1 = poolForBrokenJedis1.getResource(); -// threadForBrokenJedis1 = new Thread(new Runnable() { -// @Override -// public void run() { -// brokenJedis1.blpop(0, "broken-key-1"); -// } -// }); -// threadForBrokenJedis1.start(); -// } -// -// @Test(timeout = 5000) -// public void testAvoidQuitInDestroyObjectForBrokenConnection() throws InterruptedException { -// threadForBrokenJedis1.join(); -// assertFalse(threadForBrokenJedis1.isAlive()); -// assertTrue(brokenJedis1.isBroken()); -// brokenJedis1.close(); // we need capture/mock to test this properly -// -// try { -// poolForBrokenJedis1.getResource(); -// fail("Should not get connection from pool"); -// } catch (Exception ex) { -// assertSame(JedisConnectionException.class, ex.getClass()); +package redis.clients.jedis.tests; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.exceptions.JedisConnectionException; + +public class UnavailableConnectionTest { + + private static final HostAndPort unavailableNode = new HostAndPort("localhost", 6400); + + @BeforeClass + public static void setup() { + setupAvoidQuitInDestroyObject(); + + try (Jedis j = new Jedis(unavailableNode)) { + j.shutdown(); + } + } + + public static void cleanup() { + cleanupAvoidQuitInDestroyObject(); + } + + private static JedisPool poolForBrokenJedis1; + private static Thread threadForBrokenJedis1; + private static Jedis brokenJedis1; + + public static void setupAvoidQuitInDestroyObject() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); + config.setMaxTotal(1); + poolForBrokenJedis1 = new JedisPool(config, unavailableNode.getHost(), + unavailableNode.getPort()); + brokenJedis1 = poolForBrokenJedis1.getResource(); + threadForBrokenJedis1 = new Thread(new Runnable() { + @Override + public void run() { + brokenJedis1.blpop(0, "broken-key-1"); + } + }); + threadForBrokenJedis1.start(); + } + + @Test(timeout = 5000) + public void testAvoidQuitInDestroyObjectForBrokenConnection() throws InterruptedException { + threadForBrokenJedis1.join(); + assertFalse(threadForBrokenJedis1.isAlive()); + assertTrue(brokenJedis1.isBroken()); + brokenJedis1.close(); // we need capture/mock to test this properly + + try { + poolForBrokenJedis1.getResource(); + fail("Should not get connection from pool"); + } catch (Exception ex) { + assertSame(JedisConnectionException.class, ex.getClass()); // assertSame(JedisConnectionException.class, ex.getCause().getClass()); // assertSame(java.net.ConnectException.class, ex.getCause().getCause().getClass()); -// } -// } -// -// public static void cleanupAvoidQuitInDestroyObject() { -// poolForBrokenJedis1.close(); -// } -//} + assertSame(java.net.ConnectException.class, ex.getCause().getClass()); + } + } + + public static void cleanupAvoidQuitInDestroyObject() { + poolForBrokenJedis1.close(); + } +} diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/PoolBenchmark.java b/src/test/java/redis/clients/jedis/tests/benchmark/PoolBenchmark.java index c421a0027f..948a7fab72 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/PoolBenchmark.java +++ b/src/test/java/redis/clients/jedis/tests/benchmark/PoolBenchmark.java @@ -1,64 +1,64 @@ -//package redis.clients.jedis.tests.benchmark; -// -//import java.util.ArrayList; -//import java.util.List; -//import java.util.concurrent.atomic.AtomicInteger; -// -//import org.apache.commons.pool2.impl.GenericObjectPoolConfig; -// -//import redis.clients.jedis.HostAndPort; -//import redis.clients.jedis.Jedis; -//import redis.clients.jedis.JedisPool; -//import redis.clients.jedis.tests.HostAndPortUtil; -// -//public class PoolBenchmark { -// private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); -// private static final int TOTAL_OPERATIONS = 100000; -// -// public static void main(String[] args) throws Exception { -// Jedis j = new Jedis(hnp); -// j.connect(); -// j.auth("foobared"); -// j.flushAll(); -// j.quit(); -// j.disconnect(); -// long t = System.currentTimeMillis(); -// // withoutPool(); -// withPool(); -// long elapsed = System.currentTimeMillis() - t; -// System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); -// } -// -// private static void withPool() throws Exception { -// final JedisPool pool = new JedisPool(new GenericObjectPoolConfig(), hnp.getHost(), -// hnp.getPort(), 2000, "foobared"); -// List tds = new ArrayList(); -// -// final AtomicInteger ind = new AtomicInteger(); -// for (int i = 0; i < 50; i++) { -// Thread hj = new Thread(new Runnable() { -// public void run() { -// for (int i = 0; (i = ind.getAndIncrement()) < TOTAL_OPERATIONS;) { -// try { -// Jedis j = pool.getResource(); -// final String key = "foo" + i; -// j.set(key, key); -// j.get(key); -// j.close(); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// }); -// tds.add(hj); -// hj.start(); -// } -// -// for (Thread t : tds) -// t.join(); -// -// pool.destroy(); -// -// } -//} \ No newline at end of file +package redis.clients.jedis.tests.benchmark; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; + +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.tests.HostAndPortUtil; + +public class PoolBenchmark { + private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); + private static final int TOTAL_OPERATIONS = 100000; + + public static void main(String[] args) throws Exception { + Jedis j = new Jedis(hnp); + j.connect(); + j.auth("foobared"); + j.flushAll(); + j.quit(); + j.disconnect(); + long t = System.currentTimeMillis(); + // withoutPool(); + withPool(); + long elapsed = System.currentTimeMillis() - t; + System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); + } + + private static void withPool() throws Exception { + final JedisPool pool = new JedisPool(new GenericObjectPoolConfig(), hnp.getHost(), + hnp.getPort(), 2000, "foobared"); + List tds = new ArrayList(); + + final AtomicInteger ind = new AtomicInteger(); + for (int i = 0; i < 50; i++) { + Thread hj = new Thread(new Runnable() { + public void run() { + for (int i = 0; (i = ind.getAndIncrement()) < TOTAL_OPERATIONS;) { + try { + Jedis j = pool.getResource(); + final String key = "foo" + i; + j.set(key, key); + j.get(key); + j.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + }); + tds.add(hj); + hj.start(); + } + + for (Thread t : tds) + t.join(); + + pool.destroy(); + + } +} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/AccessControlListCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/AccessControlListCommandsTest.java index 9f47461995..21b5877816 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/AccessControlListCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/AccessControlListCommandsTest.java @@ -1,484 +1,484 @@ -//package redis.clients.jedis.tests.commands; -// -//import static org.hamcrest.CoreMatchers.containsString; -//import static org.junit.Assert.*; -// -//import java.util.List; -//import org.junit.BeforeClass; -//import org.junit.Test; -// -//import redis.clients.jedis.AccessControlUser; -//import redis.clients.jedis.Jedis; -//import redis.clients.jedis.Transaction; -//import redis.clients.jedis.exceptions.JedisAccessControlException; -//import redis.clients.jedis.exceptions.JedisDataException; -//import redis.clients.jedis.tests.utils.RedisVersionUtil; -//import redis.clients.jedis.util.SafeEncoder; -// -///** -// * TODO: properly define and test exceptions -// */ -//public class AccessControlListCommandsTest extends JedisCommandTestBase { -// -// public static String USER_YYY = "yyy"; -// public static String USER_ZZZ = "zzz"; -// public static String USER_ZZZ_PASSWORD = "secret"; -// -// @BeforeClass -// public static void prepare() throws Exception { -// // Use to check if the ACL test should be ran. ACL are available only in 6.0 and later -// org.junit.Assume.assumeTrue("Not running ACL test on this version of Redis", -// RedisVersionUtil.checkRedisMajorVersionNumber(6)); -// } -// -// @Test -// public void aclWhoAmI() { -// String string = jedis.aclWhoAmI(); -// assertEquals("default", string); -// -// byte[] binary = jedis.aclWhoAmIBinary(); -// assertArrayEquals(SafeEncoder.encode("default"), binary); -// } -// -// @Test -// public void aclListDefault() { -// assertTrue(jedis.aclList().size() > 0); -// assertTrue(jedis.aclListBinary().size() > 0); -// } -// -// @Test -// public void addAndRemoveUser() { -// int existingUsers = jedis.aclList().size(); -// -// String status = jedis.aclSetUser(USER_ZZZ); -// assertEquals("OK", status); -// assertEquals(existingUsers + 1, jedis.aclList().size()); -// assertEquals(existingUsers + 1, jedis.aclListBinary().size()); // test binary -// -// jedis.aclDelUser(USER_ZZZ); -// assertEquals(existingUsers, jedis.aclList().size()); -// assertEquals(existingUsers, jedis.aclListBinary().size()); // test binary -// } -// -// @Test -// public void aclUsers() { -// List users = jedis.aclUsers(); -// assertEquals(2, users.size()); -// assertTrue(users.contains("default")); -// -// assertEquals(2, jedis.aclUsersBinary().size()); // Test binary -// } -// -// @Test -// public void aclGetUser() { -// -// // get default user information -// AccessControlUser userInfo = jedis.aclGetUser("default"); -// -// System.err.println("userInfo.getFlags(): " + userInfo.getFlags()); -// -// assertEquals(4, userInfo.getFlags().size()); -// assertEquals(1, userInfo.getPassword().size()); -// assertEquals("+@all", userInfo.getCommands()); -// assertEquals("*", userInfo.getKeys().get(0)); -// -// // create new user -// jedis.aclDelUser(USER_ZZZ); -// jedis.aclSetUser(USER_ZZZ); -// userInfo = jedis.aclGetUser(USER_ZZZ); -// assertEquals(2, userInfo.getFlags().size()); -// assertEquals("off", userInfo.getFlags().get(0)); -// assertTrue(userInfo.getPassword().isEmpty()); -// assertTrue(userInfo.getKeys().isEmpty()); -// -// // reset user -// jedis.aclSetUser(USER_ZZZ, "reset", "+@all", "~*", "-@string", "+incr", "-debug", -// "+debug|digest"); -// userInfo = jedis.aclGetUser(USER_ZZZ); -// assertThat(userInfo.getCommands(), containsString("+@all")); -// assertThat(userInfo.getCommands(), containsString("-@string")); -// assertThat(userInfo.getCommands(), containsString("+debug|digest")); -// -// jedis.aclDelUser(USER_ZZZ); -// -// } -// -// @Test -// public void createUserAndPasswords() { -// String status = jedis.aclSetUser(USER_ZZZ, ">" + USER_ZZZ_PASSWORD); -// assertEquals("OK", status); -// -// // create a new client to try to authenticate -// Jedis jedis2 = new Jedis(); -// String authResult = null; -// -// // the user is just created without any permission the authentication should fail -// try { -// authResult = jedis2.auth(USER_ZZZ, USER_ZZZ_PASSWORD); -// fail("Should throw a WRONGPASS exception"); -// } catch (JedisAccessControlException e) { -// assertNull(authResult); -// assertTrue(e.getMessage().startsWith("WRONGPASS ")); -// } -// -// // now activate the user -// authResult = jedis.aclSetUser(USER_ZZZ, "on", "+acl"); -// jedis2.auth(USER_ZZZ, USER_ZZZ_PASSWORD); -// String connectedUser = jedis2.aclWhoAmI(); -// assertEquals(USER_ZZZ, connectedUser); -// -// // test invalid password -// jedis2.close(); -// -// try { -// authResult = jedis2.auth(USER_ZZZ, "wrong-password"); -// fail("Should throw a WRONGPASS exception"); -// } catch (JedisAccessControlException e) { -// assertEquals("OK", authResult); -// assertTrue(e.getMessage().startsWith("WRONGPASS ")); -// } -// -// // remove password, and try to authenticate -// status = jedis.aclSetUser(USER_ZZZ, "<" + USER_ZZZ_PASSWORD); -// try { -// authResult = jedis2.auth(USER_ZZZ, USER_ZZZ_PASSWORD); -// fail("Should throw a WRONGPASS exception"); -// } catch (JedisAccessControlException e) { -// assertEquals("OK", authResult); -// assertTrue(e.getMessage().startsWith("WRONGPASS ")); -// } -// -// jedis.aclDelUser(USER_ZZZ); // delete the user -// try { -// authResult = jedis2.auth(USER_ZZZ, "wrong-password"); -// fail("Should throw a WRONGPASS exception"); -// } catch (JedisAccessControlException e) { -// assertEquals("OK", authResult); -// assertTrue(e.getMessage().startsWith("WRONGPASS ")); -// } -// -// jedis2.close(); -// -// } -// -// @Test -// public void aclSetUserWithAnyPassword() { -// jedis.aclDelUser(USER_ZZZ); -// String status = jedis.aclSetUser(USER_ZZZ, "nopass"); -// assertEquals("OK", status); -// status = jedis.aclSetUser(USER_ZZZ, "on", "+acl"); -// assertEquals("OK", status); -// -// // connect with this new user and try to get/set keys -// Jedis jedis2 = new Jedis(); -// String authResult = jedis2.auth(USER_ZZZ, "any password"); -// assertEquals("OK", authResult); -// -// jedis2.close(); -// jedis.aclDelUser(USER_ZZZ); -// -// } -// -// @Test -// public void aclExcudeSingleCommand() { -// jedis.aclDelUser(USER_ZZZ); -// String status = jedis.aclSetUser(USER_ZZZ, "nopass"); -// assertEquals("OK", status); -// -// status = jedis.aclSetUser(USER_ZZZ, "on", "+acl"); -// assertEquals("OK", status); -// -// status = jedis.aclSetUser(USER_ZZZ, "allcommands", "allkeys"); -// assertEquals("OK", status); -// -// status = jedis.aclSetUser(USER_ZZZ, "-ping"); -// assertEquals("OK", status); -// -// // connect with this new user and try to get/set keys -// Jedis jedis2 = new Jedis(); -// String authResult = jedis2.auth(USER_ZZZ, "any password"); -// assertEquals("OK", authResult); -// -// jedis2.incr("mycounter"); -// -// String result = null; -// try { -// result = jedis2.ping(); -// fail("Should throw a NOPERM exception"); -// } catch (JedisAccessControlException e) { -// assertNull(result); -// assertEquals( -// "NOPERM this user has no permissions to run the 'ping' command or its subcommand", -// e.getMessage()); -// } -// -// jedis2.close(); -// jedis.aclDelUser(USER_ZZZ); -// -// } -// -// @Test -// public void aclDelUser() { -// String statusSetUser = jedis.aclSetUser(USER_YYY); -// assertEquals("OK", statusSetUser); -// int before = jedis.aclList().size(); -// assertEquals(1L, jedis.aclDelUser(USER_YYY)); -// int after = jedis.aclList().size(); -// assertEquals(before - 1, after); -// } -// -// @Test -// public void basicPermissionsTest() { -// -// // create a user with login permissions -// -// jedis.aclDelUser(USER_ZZZ); // delete the user -// -// // users are not able to access any command -// String status = jedis.aclSetUser(USER_ZZZ, ">" + USER_ZZZ_PASSWORD); -// String authResult = jedis.aclSetUser(USER_ZZZ, "on", "+acl"); -// -// // connect with this new user and try to get/set keys -// Jedis jedis2 = new Jedis(); -// jedis2.auth(USER_ZZZ, USER_ZZZ_PASSWORD); -// -// String result = null; -// try { -// result = jedis2.set("foo", "bar"); -// fail("Should throw a NOPERM exception"); -// } catch (JedisAccessControlException e) { -// assertNull(result); -// assertEquals( -// "NOPERM this user has no permissions to run the 'set' command or its subcommand", -// e.getMessage()); -// } -// -// // change permissions of the user -// // by default users are not able to access any key -// status = jedis.aclSetUser(USER_ZZZ, "+set"); -// -// jedis2.close(); -// jedis2.auth(USER_ZZZ, USER_ZZZ_PASSWORD); -// -// result = null; -// try { -// result = jedis2.set("foo", "bar"); -// fail("Should throw a NOPERM exception"); -// } catch (JedisAccessControlException e) { -// assertNull(result); -// assertEquals( -// "NOPERM this user has no permissions to access one of the keys used as arguments", -// e.getMessage()); -// } -// -// // allow user to access a subset of the key -// result = jedis.aclSetUser(USER_ZZZ, "allcommands", "~foo:*", "~bar:*"); // TODO : Define a DSL -// -// // create key foo, bar and zap -// result = jedis2.set("foo:1", "a"); -// assertEquals("OK", status); -// -// result = jedis2.set("bar:2", "b"); -// assertEquals("OK", status); -// -// result = null; -// try { -// result = jedis2.set("zap:3", "c"); -// fail("Should throw a NOPERM exception"); -// } catch (JedisAccessControlException e) { -// assertNull(result); -// assertEquals( -// "NOPERM this user has no permissions to access one of the keys used as arguments", -// e.getMessage()); -// } -// -// // remove user -// jedis.aclDelUser(USER_ZZZ); // delete the user -// -// } -// -// @Test -// public void aclCatTest() { -// List categories = jedis.aclCat(); -// assertTrue(!categories.isEmpty()); -// -// // test binary -// List categoriesBinary = jedis.aclCatBinary(); -// assertTrue(!categories.isEmpty()); -// assertEquals(categories.size(), categoriesBinary.size()); -// -// // test commands in a category -// assertTrue(!jedis.aclCat("scripting").isEmpty()); -// -// try { -// jedis.aclCat("testcategory"); -// fail("Should throw a ERR exception"); -// } catch (Exception e) { -// assertEquals("ERR Unknown category 'testcategory'", e.getMessage()); -// } -// } -// -// @Test -// public void aclLogTest() { -// jedis.aclLog("RESET"); -// assertTrue(jedis.aclLog().isEmpty()); -// -// // create new user and cconnect -// jedis.aclSetUser("antirez", ">foo", "on", "+set", "~object:1234"); -// jedis.aclSetUser("antirez", "+eval", "+multi", "+exec"); -// jedis.auth("antirez", "foo"); -// -// // generate an error (antirez user does not have the permission to access foo) -// try { -// jedis.get("foo"); -// fail("Should have thrown an JedisAccessControlException: user does not have the permission to get(\"foo\")"); -// } catch (JedisAccessControlException e) { -// } -// -// // test the ACL Log -// jedis.auth("default", "foobared"); -// -// assertEquals("Number of log messages ", 1, jedis.aclLog().size()); -// assertEquals(1, jedis.aclLog().get(0).getCount()); -// assertEquals("antirez", jedis.aclLog().get(0).getUsername()); -// assertEquals("toplevel", jedis.aclLog().get(0).getContext()); -// assertEquals("command", jedis.aclLog().get(0).getReason()); -// assertEquals("get", jedis.aclLog().get(0).getObject()); -// -// // Capture similar event -// jedis.aclLog("RESET"); -// assertTrue(jedis.aclLog().isEmpty()); -// -// jedis.auth("antirez", "foo"); -// -// for (int i = 0; i < 10; i++) { -// // generate an error (antirez user does not have the permission to access foo) -// try { -// jedis.get("foo"); -// fail("Should have thrown an JedisAccessControlException: user does not have the permission to get(\"foo\")"); -// } catch (JedisAccessControlException e) { -// } -// } -// -// // test the ACL Log -// jedis.auth("default", "foobared"); -// assertEquals("Number of log messages ", 1, jedis.aclLog().size()); -// assertEquals(10, jedis.aclLog().get(0).getCount()); -// assertEquals("get", jedis.aclLog().get(0).getObject()); -// -// // Generate another type of error -// jedis.auth("antirez", "foo"); -// try { -// jedis.set("somekeynotallowed", "1234"); -// fail("Should have thrown an JedisAccessControlException: user does not have the permission to set(\"somekeynotallowed\", \"1234\")"); -// } catch (JedisAccessControlException e) { -// } -// -// // test the ACL Log -// jedis.auth("default", "foobared"); -// assertEquals("Number of log messages ", 2, jedis.aclLog().size()); -// assertEquals(1, jedis.aclLog().get(0).getCount()); -// assertEquals("somekeynotallowed", jedis.aclLog().get(0).getObject()); -// assertEquals("key", jedis.aclLog().get(0).getReason()); -// -// jedis.aclLog("RESET"); -// assertTrue(jedis.aclLog().isEmpty()); -// -// jedis.auth("antirez", "foo"); -// Transaction t = jedis.multi(); -// t.incr("foo"); -// try { -// t.exec(); -// fail("Should have thrown an JedisAccessControlException: user does not have the permission to incr(\"foo\")"); -// } catch (Exception e) { -// } -// t.close(); -// -// jedis.auth("default", "foobared"); -// assertEquals("Number of log messages ", 1, jedis.aclLog().size()); -// assertEquals(1, jedis.aclLog().get(0).getCount()); -// assertEquals("multi", jedis.aclLog().get(0).getContext()); -// assertEquals("incr", jedis.aclLog().get(0).getObject()); -// -// // ACL LOG can accept a numerical argument to show less entries -// jedis.auth("antirez", "foo"); -// for (int i = 0; i < 5; i++) { -// try { -// jedis.incr("foo"); -// fail("Should have thrown an JedisAccessControlException: user does not have the permission to incr(\"foo\")"); -// } catch (JedisAccessControlException e) { -// } -// } -// try { -// jedis.set("foo-2", "bar"); -// fail("Should have thrown an JedisAccessControlException: user does not have the permission to set(\"foo-2\", \"bar\")"); -// } catch (JedisAccessControlException e) { -// } -// -// jedis.auth("default", "foobared"); -// assertEquals("Number of log messages ", 3, jedis.aclLog().size()); -// assertEquals("Number of log messages ", 2, jedis.aclLog(2).size()); -// -// // Binary tests -// assertEquals("Number of log messages ", 3, jedis.aclLogBinary().size()); -// assertEquals("Number of log messages ", 2, jedis.aclLogBinary(2).size()); -// byte[] status = jedis.aclLog("RESET".getBytes()); -// assertNotNull(status); -// assertTrue(jedis.aclLog().isEmpty()); -// -// jedis.aclDelUser("antirez"); -// } -// -// @Test -// public void aclGenPass() { -// assertNotNull(jedis.aclGenPass()); -// } -// -// @Test -// public void aclGenPassBinary() { -// assertNotNull(jedis.aclGenPassBinary()); -// } -// -// @Test -// public void aclBinaryCommandsTest() { -// jedis.aclSetUser(USER_ZZZ.getBytes()); -// assertNotNull(jedis.aclGetUser(USER_ZZZ)); -// -// assertEquals(1L, jedis.aclDelUser(USER_ZZZ.getBytes())); -// -// jedis.aclSetUser(USER_ZZZ.getBytes(), "reset".getBytes(), "+@all".getBytes(), "~*".getBytes(), -// "-@string".getBytes(), "+incr".getBytes(), "-debug".getBytes(), "+debug|digest".getBytes()); -// -// AccessControlUser userInfo = jedis.aclGetUser(USER_ZZZ.getBytes()); -// -// assertThat(userInfo.getCommands(), containsString("+@all")); -// assertThat(userInfo.getCommands(), containsString("-@string")); -// assertThat(userInfo.getCommands(), containsString("+debug|digest")); -// -// jedis.aclDelUser(USER_ZZZ.getBytes()); -// } -// -// @Test -// public void aclLoadTest() { -// try { -// jedis.aclLoad(); -// fail("Should throw a JedisDataException: ERR This Redis instance is not configured to use an ACL file..."); -// } catch (JedisDataException e) { -// assertTrue(e.getMessage().contains("ERR This Redis instance is not configured to use an ACL file.")); -// } -// -// // TODO test with ACL file -// } -// -// @Test -// public void aclSaveTest() { -// try { -// jedis.aclSave(); -// fail("Should throw a JedisDataException: ERR This Redis instance is not configured to use an ACL file..."); -// } catch (JedisDataException e) { -// assertTrue(e.getMessage().contains("ERR This Redis instance is not configured to use an ACL file.")); -// } -// -// // TODO test with ACL file -// } -//} +package redis.clients.jedis.tests.commands; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.*; + +import java.util.List; +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.Transaction; +import redis.clients.jedis.exceptions.JedisAccessControlException; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.resps.AccessControlUser; +import redis.clients.jedis.tests.utils.RedisVersionUtil; +import redis.clients.jedis.util.SafeEncoder; + +/** + * TODO: properly define and test exceptions + */ +public class AccessControlListCommandsTest extends JedisCommandTestBase { + + public static String USER_YYY = "yyy"; + public static String USER_ZZZ = "zzz"; + public static String USER_ZZZ_PASSWORD = "secret"; + + @BeforeClass + public static void prepare() throws Exception { + // Use to check if the ACL test should be ran. ACL are available only in 6.0 and later + org.junit.Assume.assumeTrue("Not running ACL test on this version of Redis", + RedisVersionUtil.checkRedisMajorVersionNumber(6)); + } + + @Test + public void aclWhoAmI() { + String string = jedis.aclWhoAmI(); + assertEquals("default", string); + + byte[] binary = jedis.aclWhoAmIBinary(); + assertArrayEquals(SafeEncoder.encode("default"), binary); + } + + @Test + public void aclListDefault() { + assertTrue(jedis.aclList().size() > 0); + assertTrue(jedis.aclListBinary().size() > 0); + } + + @Test + public void addAndRemoveUser() { + int existingUsers = jedis.aclList().size(); + + String status = jedis.aclSetUser(USER_ZZZ); + assertEquals("OK", status); + assertEquals(existingUsers + 1, jedis.aclList().size()); + assertEquals(existingUsers + 1, jedis.aclListBinary().size()); // test binary + + jedis.aclDelUser(USER_ZZZ); + assertEquals(existingUsers, jedis.aclList().size()); + assertEquals(existingUsers, jedis.aclListBinary().size()); // test binary + } + + @Test + public void aclUsers() { + List users = jedis.aclUsers(); + assertEquals(2, users.size()); + assertTrue(users.contains("default")); + + assertEquals(2, jedis.aclUsersBinary().size()); // Test binary + } + + @Test + public void aclGetUser() { + + // get default user information + AccessControlUser userInfo = jedis.aclGetUser("default"); + + System.err.println("userInfo.getFlags(): " + userInfo.getFlags()); + + assertEquals(4, userInfo.getFlags().size()); + assertEquals(1, userInfo.getPassword().size()); + assertEquals("+@all", userInfo.getCommands()); + assertEquals("*", userInfo.getKeys().get(0)); + + // create new user + jedis.aclDelUser(USER_ZZZ); + jedis.aclSetUser(USER_ZZZ); + userInfo = jedis.aclGetUser(USER_ZZZ); + assertEquals(2, userInfo.getFlags().size()); + assertEquals("off", userInfo.getFlags().get(0)); + assertTrue(userInfo.getPassword().isEmpty()); + assertTrue(userInfo.getKeys().isEmpty()); + + // reset user + jedis.aclSetUser(USER_ZZZ, "reset", "+@all", "~*", "-@string", "+incr", "-debug", + "+debug|digest"); + userInfo = jedis.aclGetUser(USER_ZZZ); + assertThat(userInfo.getCommands(), containsString("+@all")); + assertThat(userInfo.getCommands(), containsString("-@string")); + assertThat(userInfo.getCommands(), containsString("+debug|digest")); + + jedis.aclDelUser(USER_ZZZ); + + } + + @Test + public void createUserAndPasswords() { + String status = jedis.aclSetUser(USER_ZZZ, ">" + USER_ZZZ_PASSWORD); + assertEquals("OK", status); + + // create a new client to try to authenticate + Jedis jedis2 = new Jedis(); + String authResult = null; + + // the user is just created without any permission the authentication should fail + try { + authResult = jedis2.auth(USER_ZZZ, USER_ZZZ_PASSWORD); + fail("Should throw a WRONGPASS exception"); + } catch (JedisAccessControlException e) { + assertNull(authResult); + assertTrue(e.getMessage().startsWith("WRONGPASS ")); + } + + // now activate the user + authResult = jedis.aclSetUser(USER_ZZZ, "on", "+acl"); + jedis2.auth(USER_ZZZ, USER_ZZZ_PASSWORD); + String connectedUser = jedis2.aclWhoAmI(); + assertEquals(USER_ZZZ, connectedUser); + + // test invalid password + jedis2.close(); + + try { + authResult = jedis2.auth(USER_ZZZ, "wrong-password"); + fail("Should throw a WRONGPASS exception"); + } catch (JedisAccessControlException e) { + assertEquals("OK", authResult); + assertTrue(e.getMessage().startsWith("WRONGPASS ")); + } + + // remove password, and try to authenticate + status = jedis.aclSetUser(USER_ZZZ, "<" + USER_ZZZ_PASSWORD); + try { + authResult = jedis2.auth(USER_ZZZ, USER_ZZZ_PASSWORD); + fail("Should throw a WRONGPASS exception"); + } catch (JedisAccessControlException e) { + assertEquals("OK", authResult); + assertTrue(e.getMessage().startsWith("WRONGPASS ")); + } + + jedis.aclDelUser(USER_ZZZ); // delete the user + try { + authResult = jedis2.auth(USER_ZZZ, "wrong-password"); + fail("Should throw a WRONGPASS exception"); + } catch (JedisAccessControlException e) { + assertEquals("OK", authResult); + assertTrue(e.getMessage().startsWith("WRONGPASS ")); + } + + jedis2.close(); + + } + + @Test + public void aclSetUserWithAnyPassword() { + jedis.aclDelUser(USER_ZZZ); + String status = jedis.aclSetUser(USER_ZZZ, "nopass"); + assertEquals("OK", status); + status = jedis.aclSetUser(USER_ZZZ, "on", "+acl"); + assertEquals("OK", status); + + // connect with this new user and try to get/set keys + Jedis jedis2 = new Jedis(); + String authResult = jedis2.auth(USER_ZZZ, "any password"); + assertEquals("OK", authResult); + + jedis2.close(); + jedis.aclDelUser(USER_ZZZ); + + } + + @Test + public void aclExcudeSingleCommand() { + jedis.aclDelUser(USER_ZZZ); + String status = jedis.aclSetUser(USER_ZZZ, "nopass"); + assertEquals("OK", status); + + status = jedis.aclSetUser(USER_ZZZ, "on", "+acl"); + assertEquals("OK", status); + + status = jedis.aclSetUser(USER_ZZZ, "allcommands", "allkeys"); + assertEquals("OK", status); + + status = jedis.aclSetUser(USER_ZZZ, "-ping"); + assertEquals("OK", status); + + // connect with this new user and try to get/set keys + Jedis jedis2 = new Jedis(); + String authResult = jedis2.auth(USER_ZZZ, "any password"); + assertEquals("OK", authResult); + + jedis2.incr("mycounter"); + + String result = null; + try { + result = jedis2.ping(); + fail("Should throw a NOPERM exception"); + } catch (JedisAccessControlException e) { + assertNull(result); + assertEquals( + "NOPERM this user has no permissions to run the 'ping' command or its subcommand", + e.getMessage()); + } + + jedis2.close(); + jedis.aclDelUser(USER_ZZZ); + + } + + @Test + public void aclDelUser() { + String statusSetUser = jedis.aclSetUser(USER_YYY); + assertEquals("OK", statusSetUser); + int before = jedis.aclList().size(); + assertEquals(1L, jedis.aclDelUser(USER_YYY)); + int after = jedis.aclList().size(); + assertEquals(before - 1, after); + } + + @Test + public void basicPermissionsTest() { + + // create a user with login permissions + + jedis.aclDelUser(USER_ZZZ); // delete the user + + // users are not able to access any command + String status = jedis.aclSetUser(USER_ZZZ, ">" + USER_ZZZ_PASSWORD); + String authResult = jedis.aclSetUser(USER_ZZZ, "on", "+acl"); + + // connect with this new user and try to get/set keys + Jedis jedis2 = new Jedis(); + jedis2.auth(USER_ZZZ, USER_ZZZ_PASSWORD); + + String result = null; + try { + result = jedis2.set("foo", "bar"); + fail("Should throw a NOPERM exception"); + } catch (JedisAccessControlException e) { + assertNull(result); + assertEquals( + "NOPERM this user has no permissions to run the 'set' command or its subcommand", + e.getMessage()); + } + + // change permissions of the user + // by default users are not able to access any key + status = jedis.aclSetUser(USER_ZZZ, "+set"); + + jedis2.close(); + jedis2.auth(USER_ZZZ, USER_ZZZ_PASSWORD); + + result = null; + try { + result = jedis2.set("foo", "bar"); + fail("Should throw a NOPERM exception"); + } catch (JedisAccessControlException e) { + assertNull(result); + assertEquals( + "NOPERM this user has no permissions to access one of the keys used as arguments", + e.getMessage()); + } + + // allow user to access a subset of the key + result = jedis.aclSetUser(USER_ZZZ, "allcommands", "~foo:*", "~bar:*"); // TODO : Define a DSL + + // create key foo, bar and zap + result = jedis2.set("foo:1", "a"); + assertEquals("OK", status); + + result = jedis2.set("bar:2", "b"); + assertEquals("OK", status); + + result = null; + try { + result = jedis2.set("zap:3", "c"); + fail("Should throw a NOPERM exception"); + } catch (JedisAccessControlException e) { + assertNull(result); + assertEquals( + "NOPERM this user has no permissions to access one of the keys used as arguments", + e.getMessage()); + } + + // remove user + jedis.aclDelUser(USER_ZZZ); // delete the user + + } + + @Test + public void aclCatTest() { + List categories = jedis.aclCat(); + assertTrue(!categories.isEmpty()); + + // test binary + List categoriesBinary = jedis.aclCatBinary(); + assertTrue(!categories.isEmpty()); + assertEquals(categories.size(), categoriesBinary.size()); + + // test commands in a category + assertTrue(!jedis.aclCat("scripting").isEmpty()); + + try { + jedis.aclCat("testcategory"); + fail("Should throw a ERR exception"); + } catch (Exception e) { + assertEquals("ERR Unknown category 'testcategory'", e.getMessage()); + } + } + + @Test + public void aclLogTest() { + jedis.aclLog("RESET"); + assertTrue(jedis.aclLog().isEmpty()); + + // create new user and cconnect + jedis.aclSetUser("antirez", ">foo", "on", "+set", "~object:1234"); + jedis.aclSetUser("antirez", "+eval", "+multi", "+exec"); + jedis.auth("antirez", "foo"); + + // generate an error (antirez user does not have the permission to access foo) + try { + jedis.get("foo"); + fail("Should have thrown an JedisAccessControlException: user does not have the permission to get(\"foo\")"); + } catch (JedisAccessControlException e) { + } + + // test the ACL Log + jedis.auth("default", "foobared"); + + assertEquals("Number of log messages ", 1, jedis.aclLog().size()); + assertEquals(1, jedis.aclLog().get(0).getCount()); + assertEquals("antirez", jedis.aclLog().get(0).getUsername()); + assertEquals("toplevel", jedis.aclLog().get(0).getContext()); + assertEquals("command", jedis.aclLog().get(0).getReason()); + assertEquals("get", jedis.aclLog().get(0).getObject()); + + // Capture similar event + jedis.aclLog("RESET"); + assertTrue(jedis.aclLog().isEmpty()); + + jedis.auth("antirez", "foo"); + + for (int i = 0; i < 10; i++) { + // generate an error (antirez user does not have the permission to access foo) + try { + jedis.get("foo"); + fail("Should have thrown an JedisAccessControlException: user does not have the permission to get(\"foo\")"); + } catch (JedisAccessControlException e) { + } + } + + // test the ACL Log + jedis.auth("default", "foobared"); + assertEquals("Number of log messages ", 1, jedis.aclLog().size()); + assertEquals(10, jedis.aclLog().get(0).getCount()); + assertEquals("get", jedis.aclLog().get(0).getObject()); + + // Generate another type of error + jedis.auth("antirez", "foo"); + try { + jedis.set("somekeynotallowed", "1234"); + fail("Should have thrown an JedisAccessControlException: user does not have the permission to set(\"somekeynotallowed\", \"1234\")"); + } catch (JedisAccessControlException e) { + } + + // test the ACL Log + jedis.auth("default", "foobared"); + assertEquals("Number of log messages ", 2, jedis.aclLog().size()); + assertEquals(1, jedis.aclLog().get(0).getCount()); + assertEquals("somekeynotallowed", jedis.aclLog().get(0).getObject()); + assertEquals("key", jedis.aclLog().get(0).getReason()); + + jedis.aclLog("RESET"); + assertTrue(jedis.aclLog().isEmpty()); + + jedis.auth("antirez", "foo"); + Transaction t = jedis.multi(); + t.incr("foo"); + try { + t.exec(); + fail("Should have thrown an JedisAccessControlException: user does not have the permission to incr(\"foo\")"); + } catch (Exception e) { + } + t.close(); + + jedis.auth("default", "foobared"); + assertEquals("Number of log messages ", 1, jedis.aclLog().size()); + assertEquals(1, jedis.aclLog().get(0).getCount()); + assertEquals("multi", jedis.aclLog().get(0).getContext()); + assertEquals("incr", jedis.aclLog().get(0).getObject()); + + // ACL LOG can accept a numerical argument to show less entries + jedis.auth("antirez", "foo"); + for (int i = 0; i < 5; i++) { + try { + jedis.incr("foo"); + fail("Should have thrown an JedisAccessControlException: user does not have the permission to incr(\"foo\")"); + } catch (JedisAccessControlException e) { + } + } + try { + jedis.set("foo-2", "bar"); + fail("Should have thrown an JedisAccessControlException: user does not have the permission to set(\"foo-2\", \"bar\")"); + } catch (JedisAccessControlException e) { + } + + jedis.auth("default", "foobared"); + assertEquals("Number of log messages ", 3, jedis.aclLog().size()); + assertEquals("Number of log messages ", 2, jedis.aclLog(2).size()); + + // Binary tests + assertEquals("Number of log messages ", 3, jedis.aclLogBinary().size()); + assertEquals("Number of log messages ", 2, jedis.aclLogBinary(2).size()); + byte[] status = jedis.aclLog("RESET".getBytes()); + assertNotNull(status); + assertTrue(jedis.aclLog().isEmpty()); + + jedis.aclDelUser("antirez"); + } + + @Test + public void aclGenPass() { + assertNotNull(jedis.aclGenPass()); + } + + @Test + public void aclGenPassBinary() { + assertNotNull(jedis.aclGenPassBinary()); + } + + @Test + public void aclBinaryCommandsTest() { + jedis.aclSetUser(USER_ZZZ.getBytes()); + assertNotNull(jedis.aclGetUser(USER_ZZZ)); + + assertEquals(1L, jedis.aclDelUser(USER_ZZZ.getBytes())); + + jedis.aclSetUser(USER_ZZZ.getBytes(), "reset".getBytes(), "+@all".getBytes(), "~*".getBytes(), + "-@string".getBytes(), "+incr".getBytes(), "-debug".getBytes(), "+debug|digest".getBytes()); + + AccessControlUser userInfo = jedis.aclGetUser(USER_ZZZ.getBytes()); + + assertThat(userInfo.getCommands(), containsString("+@all")); + assertThat(userInfo.getCommands(), containsString("-@string")); + assertThat(userInfo.getCommands(), containsString("+debug|digest")); + + jedis.aclDelUser(USER_ZZZ.getBytes()); + } + + @Test + public void aclLoadTest() { + try { + jedis.aclLoad(); + fail("Should throw a JedisDataException: ERR This Redis instance is not configured to use an ACL file..."); + } catch (JedisDataException e) { + assertTrue(e.getMessage().contains("ERR This Redis instance is not configured to use an ACL file.")); + } + + // TODO test with ACL file + } + + @Test + public void aclSaveTest() { + try { + jedis.aclSave(); + fail("Should throw a JedisDataException: ERR This Redis instance is not configured to use an ACL file..."); + } catch (JedisDataException e) { + assertTrue(e.getMessage().contains("ERR This Redis instance is not configured to use an ACL file.")); + } + + // TODO test with ACL file + } +} diff --git a/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java index 59ef4da09d..242e478679 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java @@ -33,8 +33,7 @@ import org.junit.Test; import redis.clients.jedis.HostAndPort; -//import redis.clients.jedis.Jedis; -import redis.clients.jedis.UnifiedJedis; +import redis.clients.jedis.Jedis; import redis.clients.jedis.Protocol.Keyword; import redis.clients.jedis.params.ScanParams; import redis.clients.jedis.resps.ScanResult; @@ -371,187 +370,187 @@ public void ttl() { long bttl = jedis.ttl(bfoo); assertTrue(bttl >= 0 && bttl <= 20); } -// -// @Test -// public void touch() throws Exception { -// assertEquals(0, jedis.touch("foo1", "foo2", "foo3")); -// -// jedis.set("foo1", "bar1"); -// -// Thread.sleep(1100); // little over 1 sec -// assertTrue(jedis.objectIdletime("foo1") > 0); -// -// assertEquals(1, jedis.touch("foo1")); -// assertEquals(0L, jedis.objectIdletime("foo1").longValue()); -// -// assertEquals(1, jedis.touch("foo1", "foo2", "foo3")); -// -// jedis.set("foo2", "bar2"); -// -// jedis.set("foo3", "bar3"); -// -// assertEquals(3, jedis.touch("foo1", "foo2", "foo3")); -// -// // Binary -// assertEquals(0, jedis.touch(bfoo1, bfoo2, bfoo3)); -// -// jedis.set(bfoo1, bbar1); -// -// Thread.sleep(1100); // little over 1 sec -// assertTrue(jedis.objectIdletime(bfoo1) > 0); -// -// assertEquals(1, jedis.touch(bfoo1)); -// assertEquals(0L, jedis.objectIdletime(bfoo1).longValue()); -// -// assertEquals(1, jedis.touch(bfoo1, bfoo2, bfoo3)); -// -// jedis.set(bfoo2, bbar2); -// -// jedis.set(bfoo3, bbar3); -// -// assertEquals(3, jedis.touch(bfoo1, bfoo2, bfoo3)); -// -// } -// -// @Test -// public void select() { -// jedis.set("foo", "bar"); -// String status = jedis.select(1); -// assertEquals("OK", status); -// assertNull(jedis.get("foo")); -// status = jedis.select(0); -// assertEquals("OK", status); -// assertEquals("bar", jedis.get("foo")); -// // Binary -// jedis.set(bfoo, bbar); -// String bstatus = jedis.select(1); -// assertEquals("OK", bstatus); -// assertNull(jedis.get(bfoo)); -// bstatus = jedis.select(0); -// assertEquals("OK", bstatus); -// assertArrayEquals(bbar, jedis.get(bfoo)); -// } -// -// @Test -// public void getDB() { -// assertEquals(0, jedis.getDB()); -// jedis.select(1); -// assertEquals(1, jedis.getDB()); -// } -// -// @Test -// public void move() { -// assertEquals(0, jedis.move("foo", 1)); -// -// jedis.set("foo", "bar"); -// assertEquals(1, jedis.move("foo", 1)); -// assertNull(jedis.get("foo")); -// -// jedis.select(1); -// assertEquals("bar", jedis.get("foo")); -// -// // Binary -// jedis.select(0); -// assertEquals(0, jedis.move(bfoo, 1)); -// -// jedis.set(bfoo, bbar); -// assertEquals(1, jedis.move(bfoo, 1)); -// assertNull(jedis.get(bfoo)); -// -// jedis.select(1); -// assertArrayEquals(bbar, jedis.get(bfoo)); -// -// } -// -// @Test -// public void swapDB() { -// jedis.set("foo1", "bar1"); -// jedis.select(1); -// assertNull(jedis.get("foo1")); -// jedis.set("foo2", "bar2"); -// String status = jedis.swapDB(0, 1); -// assertEquals("OK", status); -// assertEquals("bar1", jedis.get("foo1")); -// assertNull(jedis.get("foo2")); -// jedis.select(0); -// assertNull(jedis.get("foo1")); -// assertEquals("bar2", jedis.get("foo2")); -// -// // Binary -// jedis.set(bfoo1, bbar1); -// jedis.select(1); -// assertArrayEquals(null, jedis.get(bfoo1)); -// jedis.set(bfoo2, bbar2); -// status = jedis.swapDB(0, 1); -// assertEquals("OK", status); -// assertArrayEquals(bbar1, jedis.get(bfoo1)); -// assertArrayEquals(null, jedis.get(bfoo2)); -// jedis.select(0); -// assertArrayEquals(null, jedis.get(bfoo1)); -// assertArrayEquals(bbar2, jedis.get(bfoo2)); -// } -// -// @Test -// public void flushDB() { -// jedis.set("foo", "bar"); -// assertEquals(1, jedis.dbSize()); -// jedis.set("bar", "foo"); -// jedis.move("bar", 1); -// String status = jedis.flushDB(); -// assertEquals("OK", status); -// assertEquals(0, jedis.dbSize()); -// jedis.select(1); -// assertEquals(1, jedis.dbSize()); -// assertEquals("OK", jedis.flushDB(FlushMode.SYNC)); -// assertEquals(0, jedis.dbSize()); -// -// // Binary -// jedis.select(0); -// jedis.set(bfoo, bbar); -// assertEquals(1, jedis.dbSize()); -// jedis.set(bbar, bfoo); -// jedis.move(bbar, 1); -// String bstatus = jedis.flushDB(); -// assertEquals("OK", bstatus); -// assertEquals(0, jedis.dbSize()); -// jedis.select(1); -// assertEquals(1, jedis.dbSize()); -// assertEquals("OK", jedis.flushDB(FlushMode.ASYNC)); -// assertEquals(0, jedis.dbSize()); -// } -// -// @Test -// public void flushAll() { -// jedis.set("foo", "bar"); -// assertEquals(1, jedis.dbSize()); -// jedis.set("bar", "foo"); -// jedis.move("bar", 1); -// String status = jedis.flushAll(); -// assertEquals("OK", status); -// assertEquals(0, jedis.dbSize()); -// jedis.select(1); -// assertEquals(0, jedis.dbSize()); -// jedis.set("foo", "bar"); -// assertEquals(1, jedis.dbSize()); -// assertEquals("OK", jedis.flushAll(FlushMode.SYNC)); -// assertEquals(0, jedis.dbSize()); -// -// // Binary -// jedis.select(0); -// jedis.set(bfoo, bbar); -// assertEquals(1, jedis.dbSize()); -// jedis.set(bbar, bfoo); -// jedis.move(bbar, 1); -// String bstatus = jedis.flushAll(); -// assertEquals("OK", bstatus); -// assertEquals(0, jedis.dbSize()); -// jedis.select(1); -// assertEquals(0, jedis.dbSize()); -// jedis.set(bfoo, bbar); -// assertEquals(1, jedis.dbSize()); -// assertEquals("OK", jedis.flushAll(FlushMode.ASYNC)); -// assertEquals(0, jedis.dbSize()); -// } + + @Test + public void touch() throws Exception { + assertEquals(0, jedis.touch("foo1", "foo2", "foo3")); + + jedis.set("foo1", "bar1"); + + Thread.sleep(1100); // little over 1 sec + assertTrue(jedis.objectIdletime("foo1") > 0); + + assertEquals(1, jedis.touch("foo1")); + assertEquals(0L, jedis.objectIdletime("foo1").longValue()); + + assertEquals(1, jedis.touch("foo1", "foo2", "foo3")); + + jedis.set("foo2", "bar2"); + + jedis.set("foo3", "bar3"); + + assertEquals(3, jedis.touch("foo1", "foo2", "foo3")); + + // Binary + assertEquals(0, jedis.touch(bfoo1, bfoo2, bfoo3)); + + jedis.set(bfoo1, bbar1); + + Thread.sleep(1100); // little over 1 sec + assertTrue(jedis.objectIdletime(bfoo1) > 0); + + assertEquals(1, jedis.touch(bfoo1)); + assertEquals(0L, jedis.objectIdletime(bfoo1).longValue()); + + assertEquals(1, jedis.touch(bfoo1, bfoo2, bfoo3)); + + jedis.set(bfoo2, bbar2); + + jedis.set(bfoo3, bbar3); + + assertEquals(3, jedis.touch(bfoo1, bfoo2, bfoo3)); + + } + + @Test + public void select() { + jedis.set("foo", "bar"); + String status = jedis.select(1); + assertEquals("OK", status); + assertNull(jedis.get("foo")); + status = jedis.select(0); + assertEquals("OK", status); + assertEquals("bar", jedis.get("foo")); + // Binary + jedis.set(bfoo, bbar); + String bstatus = jedis.select(1); + assertEquals("OK", bstatus); + assertNull(jedis.get(bfoo)); + bstatus = jedis.select(0); + assertEquals("OK", bstatus); + assertArrayEquals(bbar, jedis.get(bfoo)); + } + + @Test + public void getDB() { + assertEquals(0, jedis.getDB()); + jedis.select(1); + assertEquals(1, jedis.getDB()); + } + + @Test + public void move() { + assertEquals(0, jedis.move("foo", 1)); + + jedis.set("foo", "bar"); + assertEquals(1, jedis.move("foo", 1)); + assertNull(jedis.get("foo")); + + jedis.select(1); + assertEquals("bar", jedis.get("foo")); + + // Binary + jedis.select(0); + assertEquals(0, jedis.move(bfoo, 1)); + + jedis.set(bfoo, bbar); + assertEquals(1, jedis.move(bfoo, 1)); + assertNull(jedis.get(bfoo)); + + jedis.select(1); + assertArrayEquals(bbar, jedis.get(bfoo)); + + } + + @Test + public void swapDB() { + jedis.set("foo1", "bar1"); + jedis.select(1); + assertNull(jedis.get("foo1")); + jedis.set("foo2", "bar2"); + String status = jedis.swapDB(0, 1); + assertEquals("OK", status); + assertEquals("bar1", jedis.get("foo1")); + assertNull(jedis.get("foo2")); + jedis.select(0); + assertNull(jedis.get("foo1")); + assertEquals("bar2", jedis.get("foo2")); + + // Binary + jedis.set(bfoo1, bbar1); + jedis.select(1); + assertArrayEquals(null, jedis.get(bfoo1)); + jedis.set(bfoo2, bbar2); + status = jedis.swapDB(0, 1); + assertEquals("OK", status); + assertArrayEquals(bbar1, jedis.get(bfoo1)); + assertArrayEquals(null, jedis.get(bfoo2)); + jedis.select(0); + assertArrayEquals(null, jedis.get(bfoo1)); + assertArrayEquals(bbar2, jedis.get(bfoo2)); + } + + @Test + public void flushDB() { + jedis.set("foo", "bar"); + assertEquals(1, jedis.dbSize()); + jedis.set("bar", "foo"); + jedis.move("bar", 1); + String status = jedis.flushDB(); + assertEquals("OK", status); + assertEquals(0, jedis.dbSize()); + jedis.select(1); + assertEquals(1, jedis.dbSize()); + assertEquals("OK", jedis.flushDB(FlushMode.SYNC)); + assertEquals(0, jedis.dbSize()); + + // Binary + jedis.select(0); + jedis.set(bfoo, bbar); + assertEquals(1, jedis.dbSize()); + jedis.set(bbar, bfoo); + jedis.move(bbar, 1); + String bstatus = jedis.flushDB(); + assertEquals("OK", bstatus); + assertEquals(0, jedis.dbSize()); + jedis.select(1); + assertEquals(1, jedis.dbSize()); + assertEquals("OK", jedis.flushDB(FlushMode.ASYNC)); + assertEquals(0, jedis.dbSize()); + } + + @Test + public void flushAll() { + jedis.set("foo", "bar"); + assertEquals(1, jedis.dbSize()); + jedis.set("bar", "foo"); + jedis.move("bar", 1); + String status = jedis.flushAll(); + assertEquals("OK", status); + assertEquals(0, jedis.dbSize()); + jedis.select(1); + assertEquals(0, jedis.dbSize()); + jedis.set("foo", "bar"); + assertEquals(1, jedis.dbSize()); + assertEquals("OK", jedis.flushAll(FlushMode.SYNC)); + assertEquals(0, jedis.dbSize()); + + // Binary + jedis.select(0); + jedis.set(bfoo, bbar); + assertEquals(1, jedis.dbSize()); + jedis.set(bbar, bfoo); + jedis.move(bbar, 1); + String bstatus = jedis.flushAll(); + assertEquals("OK", bstatus); + assertEquals(0, jedis.dbSize()); + jedis.select(1); + assertEquals(0, jedis.dbSize()); + jedis.set(bfoo, bbar); + assertEquals(1, jedis.dbSize()); + assertEquals("OK", jedis.flushAll(FlushMode.ASYNC)); + assertEquals(0, jedis.dbSize()); + } @Test public void persist() { @@ -566,16 +565,16 @@ public void persist() { assertEquals(1, jedis.persist(bfoo)); assertEquals(-1, jedis.ttl(bfoo)); } -// -// @Test -// public void echo() { -// String result = jedis.echo("hello world"); -// assertEquals("hello world", result); -// -// // Binary -// byte[] bresult = jedis.echo(SafeEncoder.encode("hello world")); -// assertArrayEquals(SafeEncoder.encode("hello world"), bresult); -// } + + @Test + public void echo() { + String result = jedis.echo("hello world"); + assertEquals("hello world", result); + + // Binary + byte[] bresult = jedis.echo(SafeEncoder.encode("hello world")); + assertArrayEquals(SafeEncoder.encode("hello world"), bresult); + } @Test public void dumpAndRestore() { @@ -619,42 +618,50 @@ public void dumpAndRestore() { // // jedis2.close(); // } -// -// @Test -// public void restoreParams() { -// // take a separate instance -// Jedis jedis2 = new Jedis(hnp.getHost(), 6380, 500); -// jedis2.auth("foobared"); -// jedis2.flushAll(); -// -// jedis2.set("foo", "bar"); -// jedis.set("from", "a"); -// byte[] serialized = jedis.dump("from"); -// -// try { + + @Test + public void restoreParams() { + // take a separate instance + Jedis jedis2 = new Jedis(hnp.getHost(), 6380, 500); + jedis2.auth("foobared"); + jedis2.flushAll(); + + jedis2.set("foo", "bar"); + jedis.set("from", "a"); + byte[] serialized = jedis.dump("from"); + + try { // jedis2.restore("foo", 0, serialized, null); -// fail("Simple restore on a existing key should fail"); -// } catch (JedisDataException e) { -// // should be here -// } -// assertEquals("bar", jedis2.get("foo")); -// -// jedis2.restore("foo", 1000, serialized, RestoreParams.restoreParams().replace()); -// assertEquals("a", jedis2.get("foo")); -// assertTrue(jedis2.pttl("foo") <= 1000); -// -// jedis2.restore("bar", System.currentTimeMillis() + 1000, serialized, RestoreParams.restoreParams().replace().absTtl()); -// assertTrue(jedis2.pttl("bar") <= 1000); -// -// jedis2.restore("bar1", 1000, serialized, RestoreParams.restoreParams().replace().idleTime(1000)); -// assertEquals(1000, jedis2.objectIdletime("bar1").longValue()); -// jedis2.close(); -// -// Jedis lfuJedis = new Jedis(lfuHnp.getHost(), lfuHnp.getPort(), 500); -// lfuJedis.restore("bar1", 1000, serialized, RestoreParams.restoreParams().replace().frequency(90)); -// assertEquals(90, lfuJedis.objectFreq("bar1").longValue()); -// lfuJedis.close(); -// } + jedis2.restore("foo", 0, serialized); + fail("Simple restore on a existing key should fail"); + } catch (JedisDataException e) { + // should be here + } + try { +// jedis2.restore("foo", 0, serialized, null); + jedis2.restore("foo", 0, serialized, RestoreParams.restoreParams()); + fail("Simple restore on a existing key should fail"); + } catch (JedisDataException e) { + // should be here + } + assertEquals("bar", jedis2.get("foo")); + + jedis2.restore("foo", 1000, serialized, RestoreParams.restoreParams().replace()); + assertEquals("a", jedis2.get("foo")); + assertTrue(jedis2.pttl("foo") <= 1000); + + jedis2.restore("bar", System.currentTimeMillis() + 1000, serialized, RestoreParams.restoreParams().replace().absTtl()); + assertTrue(jedis2.pttl("bar") <= 1000); + + jedis2.restore("bar1", 1000, serialized, RestoreParams.restoreParams().replace().idleTime(1000)); + assertEquals(1000, jedis2.objectIdletime("bar1").longValue()); + jedis2.close(); + + Jedis lfuJedis = new Jedis(lfuHnp.getHost(), lfuHnp.getPort(), 500); + lfuJedis.restore("bar1", 1000, serialized, RestoreParams.restoreParams().replace().frequency(90)); + assertEquals(90, lfuJedis.objectFreq("bar1").longValue()); + lfuJedis.close(); + } @Test public void pexpire() { @@ -935,110 +942,110 @@ public void setGetOptionTest() { String nullValue = jedis.set("key", "value", setParams().get()); assertNull(nullValue); } -// -// @Test -// public void sendCommandTest() { -// Object obj = jedis.sendCommand(SET, "x", "1"); -// String returnValue = SafeEncoder.encode((byte[]) obj); -// assertEquals("OK", returnValue); -// obj = jedis.sendCommand(GET, "x"); -// returnValue = SafeEncoder.encode((byte[]) obj); -// assertEquals("1", returnValue); -// -// jedis.sendCommand(RPUSH, "foo", "a"); -// jedis.sendCommand(RPUSH, "foo", "b"); -// jedis.sendCommand(RPUSH, "foo", "c"); -// -// obj = jedis.sendCommand(LRANGE, "foo", "0", "2"); -// List list = (List) obj; -// List expected = new ArrayList<>(3); -// expected.add("a".getBytes()); -// expected.add("b".getBytes()); -// expected.add("c".getBytes()); -// for (int i = 0; i < 3; i++) -// assertArrayEquals(expected.get(i), list.get(i)); -// -// assertEquals("PONG", SafeEncoder.encode((byte[]) jedis.sendCommand(PING))); -// } -// -// @Test -// public void sendBlockingCommandTest() { -// assertNull(jedis.sendBlockingCommand(BLPOP, "foo", Long.toString(1L))); -// -// jedis.sendCommand(RPUSH, "foo", "bar"); -// assertEquals(Arrays.asList("foo", "bar"), -// SafeEncoder.encodeObject(jedis.sendBlockingCommand(BLPOP, "foo", Long.toString(1L)))); -// -// assertNull(jedis.sendBlockingCommand(BLPOP, "foo", Long.toString(1L))); -// } -// -// @Test -// public void encodeCompleteResponse() { -// HashMap entry = new HashMap<>(); -// entry.put("foo", "bar"); -// jedis.xadd("mystream", StreamEntryID.NEW_ENTRY, entry); -// String status = jedis.xgroupCreate("mystream", "mygroup", null, false); -// -// Object obj = jedis.sendCommand(XINFO, "STREAM", "mystream"); -// List encodeObj = (List) SafeEncoder.encodeObject(obj); -// -// assertEquals(14, encodeObj.size()); -// assertEquals("length", encodeObj.get(0)); -// assertEquals(1L, encodeObj.get(1)); -// -// List entryAsList = new ArrayList<>(2); -// entryAsList.add("foo"); -// entryAsList.add("bar"); -// -// assertEquals(entryAsList, ((List) encodeObj.get(11)).get(1)); -// -// assertEquals("PONG", SafeEncoder.encodeObject(jedis.sendCommand(PING))); -// -// entry.put("foo2", "bar2"); -// jedis.hset("hash:test:encode", entry); -// encodeObj = (List) SafeEncoder.encodeObject(jedis.sendCommand(HGETALL, "hash:test:encode")); -// -// assertEquals(4, encodeObj.size()); -// assertTrue(encodeObj.contains("foo")); -// assertTrue(encodeObj.contains("foo2")); -// -// } -// -// @Test -// public void copy() { -// assertFalse(jedis.copy("unknown", "foo", false)); -// -// jedis.set("foo1", "bar"); -// assertTrue(jedis.copy("foo1", "foo2", false)); -// assertEquals("bar", jedis.get("foo2")); -// -// // with destinationDb -// assertTrue(jedis.copy("foo1", "foo3", 2, false)); -// jedis.select(2); -// assertEquals("bar", jedis.get("foo3")); -// jedis.select(0); // getting back to original db, for next tests -// -// // replace -// jedis.set("foo1", "bar1"); -// assertTrue(jedis.copy("foo1", "foo2", true)); -// assertEquals("bar1", jedis.get("foo2")); -// -// // Binary -// assertFalse(jedis.copy(bfoobar, bfoo, false)); -// -// jedis.set(bfoo1, bbar); -// assertTrue(jedis.copy(bfoo1, bfoo2, false)); -// assertArrayEquals(bbar, jedis.get(bfoo2)); -// -// // with destinationDb -// assertTrue(jedis.copy(bfoo1, bfoo3, 3, false)); -// jedis.select(3); -// assertArrayEquals(bbar, jedis.get(bfoo3)); -// jedis.select(0); // getting back to original db, for next tests -// -// // replace -// jedis.set(bfoo1, bbar1); -// assertTrue(jedis.copy(bfoo1, bfoo2, true)); -// assertArrayEquals(bbar1, jedis.get(bfoo2)); -// } + + @Test + public void sendCommandTest() { + Object obj = jedis.sendCommand(SET, "x", "1"); + String returnValue = SafeEncoder.encode((byte[]) obj); + assertEquals("OK", returnValue); + obj = jedis.sendCommand(GET, "x"); + returnValue = SafeEncoder.encode((byte[]) obj); + assertEquals("1", returnValue); + + jedis.sendCommand(RPUSH, "foo", "a"); + jedis.sendCommand(RPUSH, "foo", "b"); + jedis.sendCommand(RPUSH, "foo", "c"); + + obj = jedis.sendCommand(LRANGE, "foo", "0", "2"); + List list = (List) obj; + List expected = new ArrayList<>(3); + expected.add("a".getBytes()); + expected.add("b".getBytes()); + expected.add("c".getBytes()); + for (int i = 0; i < 3; i++) + assertArrayEquals(expected.get(i), list.get(i)); + + assertEquals("PONG", SafeEncoder.encode((byte[]) jedis.sendCommand(PING))); + } + + @Test + public void sendBlockingCommandTest() { + assertNull(jedis.sendBlockingCommand(BLPOP, "foo", Long.toString(1L))); + + jedis.sendCommand(RPUSH, "foo", "bar"); + assertEquals(Arrays.asList("foo", "bar"), + SafeEncoder.encodeObject(jedis.sendBlockingCommand(BLPOP, "foo", Long.toString(1L)))); + + assertNull(jedis.sendBlockingCommand(BLPOP, "foo", Long.toString(1L))); + } + + @Test + public void encodeCompleteResponse() { + HashMap entry = new HashMap<>(); + entry.put("foo", "bar"); + jedis.xadd("mystream", StreamEntryID.NEW_ENTRY, entry); + String status = jedis.xgroupCreate("mystream", "mygroup", null, false); + + Object obj = jedis.sendCommand(XINFO, "STREAM", "mystream"); + List encodeObj = (List) SafeEncoder.encodeObject(obj); + + assertEquals(14, encodeObj.size()); + assertEquals("length", encodeObj.get(0)); + assertEquals(1L, encodeObj.get(1)); + + List entryAsList = new ArrayList<>(2); + entryAsList.add("foo"); + entryAsList.add("bar"); + + assertEquals(entryAsList, ((List) encodeObj.get(11)).get(1)); + + assertEquals("PONG", SafeEncoder.encodeObject(jedis.sendCommand(PING))); + + entry.put("foo2", "bar2"); + jedis.hset("hash:test:encode", entry); + encodeObj = (List) SafeEncoder.encodeObject(jedis.sendCommand(HGETALL, "hash:test:encode")); + + assertEquals(4, encodeObj.size()); + assertTrue(encodeObj.contains("foo")); + assertTrue(encodeObj.contains("foo2")); + + } + + @Test + public void copy() { + assertFalse(jedis.copy("unknown", "foo", false)); + + jedis.set("foo1", "bar"); + assertTrue(jedis.copy("foo1", "foo2", false)); + assertEquals("bar", jedis.get("foo2")); + + // with destinationDb + assertTrue(jedis.copy("foo1", "foo3", 2, false)); + jedis.select(2); + assertEquals("bar", jedis.get("foo3")); + jedis.select(0); // getting back to original db, for next tests + + // replace + jedis.set("foo1", "bar1"); + assertTrue(jedis.copy("foo1", "foo2", true)); + assertEquals("bar1", jedis.get("foo2")); + + // Binary + assertFalse(jedis.copy(bfoobar, bfoo, false)); + + jedis.set(bfoo1, bbar); + assertTrue(jedis.copy(bfoo1, bfoo2, false)); + assertArrayEquals(bbar, jedis.get(bfoo2)); + + // with destinationDb + assertTrue(jedis.copy(bfoo1, bfoo3, 3, false)); + jedis.select(3); + assertArrayEquals(bbar, jedis.get(bfoo3)); + jedis.select(0); // getting back to original db, for next tests + + // replace + jedis.set(bfoo1, bbar1); + assertTrue(jedis.copy(bfoo1, bfoo2, true)); + assertArrayEquals(bbar1, jedis.get(bfoo2)); + } } diff --git a/src/test/java/redis/clients/jedis/tests/commands/BitCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/BitCommandsTest.java index 4b4a3d2e1b..811ee7b19a 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/BitCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/BitCommandsTest.java @@ -9,10 +9,10 @@ import java.util.List; import org.junit.Test; -import redis.clients.jedis.args.BitOP; -import redis.clients.jedis.args.BitPosParams; import redis.clients.jedis.Protocol; +import redis.clients.jedis.args.BitOP; import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.params.BitPosParams; import redis.clients.jedis.util.SafeEncoder; public class BitCommandsTest extends JedisCommandTestBase { diff --git a/src/test/java/redis/clients/jedis/tests/commands/ClientCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ClientCommandsTest.java index 7c9051c9e6..1b19fd3a71 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClientCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ClientCommandsTest.java @@ -1,274 +1,277 @@ -//package redis.clients.jedis.tests.commands; -// -//import static org.junit.Assert.assertArrayEquals; -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertNotNull; -//import static org.junit.Assert.assertTrue; -//import static org.junit.Assert.fail; -//import static redis.clients.jedis.params.ClientKillParams.Type; -//import static redis.clients.jedis.params.ClientKillParams.SkipMe; -// -//import java.util.concurrent.ExecutionException; -//import java.util.concurrent.Executors; -//import java.util.concurrent.Future; -//import java.util.concurrent.TimeUnit; -//import java.util.concurrent.TimeoutException; -//import java.util.regex.Matcher; -//import java.util.regex.Pattern; -// -//import org.junit.After; -//import org.junit.Before; -//import org.junit.Test; -// -//import redis.clients.jedis.HostAndPort; -//import redis.clients.jedis.Jedis; -//import redis.clients.jedis.args.ClientType; -//import redis.clients.jedis.args.UnblockType; -//import redis.clients.jedis.exceptions.JedisConnectionException; -//import redis.clients.jedis.params.ClientKillParams; -// -//public class ClientCommandsTest extends JedisCommandTestBase { -// -// private final String clientName = "fancy_jedis_name"; -// private final Pattern pattern = Pattern.compile("\\bname=" + clientName + "\\b"); -// -// private Jedis client; -// -// @Before -// @Override -// public void setUp() throws Exception { -// super.setUp(); -// client = new Jedis(hnp.getHost(), hnp.getPort(), 500); -// client.auth("foobared"); -// client.clientSetname(clientName); -// } -// -// @After -// @Override -// public void tearDown() throws Exception { -// client.close(); -// super.tearDown(); -// } -// -// @Test -// public void nameString() { -// String name = "string"; -// client.clientSetname(name); -// assertEquals(name, client.clientGetname()); -// } -// -// @Test -// public void nameBinary() { -// byte[] name = "binary".getBytes(); -// client.clientSetname(name); -// assertArrayEquals(name, client.clientGetnameBinary()); -// } -// -// @Test -// public void clientId() { -// long clientId = client.clientId(); -// -// String info = findInClientList(); -// Matcher matcher = Pattern.compile("\\bid=(\\d+)\\b").matcher(info); -// matcher.find(); -// -// assertEquals(clientId, Long.parseLong(matcher.group(1))); -// } -// -// @Test -// public void clientIdmultipleConnection() { -// try (Jedis client2 = new Jedis(hnp.getHost(), hnp.getPort(), 500)) { -// client2.auth("foobared"); -// client2.clientSetname("fancy_jedis_another_name"); -// -// // client-id is monotonically increasing -// assertTrue(client.clientId() < client2.clientId()); -// } -// } -// -// @Test -// public void clientIdReconnect() { -// long clientIdInitial = client.clientId(); -// client.disconnect(); +package redis.clients.jedis.tests.commands; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static redis.clients.jedis.params.ClientKillParams.Type; +import static redis.clients.jedis.params.ClientKillParams.SkipMe; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.args.ClientType; +import redis.clients.jedis.args.UnblockType; +import redis.clients.jedis.exceptions.JedisConnectionException; +import redis.clients.jedis.params.ClientKillParams; + +public class ClientCommandsTest extends JedisCommandTestBase { + + private final String clientName = "fancy_jedis_name"; + private final Pattern pattern = Pattern.compile("\\bname=" + clientName + "\\b"); + + private Jedis client; + + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + client = new Jedis(hnp.getHost(), hnp.getPort(), 500); + client.auth("foobared"); + client.clientSetname(clientName); + } + + @After + @Override + public void tearDown() throws Exception { + client.close(); + super.tearDown(); + } + + @Test + public void nameString() { + String name = "string"; + client.clientSetname(name); + assertEquals(name, client.clientGetname()); + } + + @Test + public void nameBinary() { + byte[] name = "binary".getBytes(); + client.clientSetname(name); + assertArrayEquals(name, client.clientGetnameBinary()); + } + + @Test + public void clientId() { + long clientId = client.clientId(); + + String info = findInClientList(); + Matcher matcher = Pattern.compile("\\bid=(\\d+)\\b").matcher(info); + matcher.find(); + + assertEquals(clientId, Long.parseLong(matcher.group(1))); + } + + @Test + public void clientIdmultipleConnection() { + try (Jedis client2 = new Jedis(hnp.getHost(), hnp.getPort(), 500)) { + client2.auth("foobared"); + client2.clientSetname("fancy_jedis_another_name"); + + // client-id is monotonically increasing + assertTrue(client.clientId() < client2.clientId()); + } + } + + @Test + public void clientIdReconnect() { + long clientIdInitial = client.clientId(); + client.disconnect(); // client.connect(); -// long clientIdAfterReconnect = client.clientId(); -// -// assertTrue(clientIdInitial < clientIdAfterReconnect); -// } -// -// @Test -// public void clientUnblock() throws InterruptedException, TimeoutException { -// long clientId = client.clientId(); -// assertEquals(0, jedis.clientUnblock(clientId, UnblockType.ERROR)); -// Future future = Executors.newSingleThreadExecutor().submit(() -> client.brpop(100000, "foo")); -// -// try { -// // to make true command already executed -// TimeUnit.MILLISECONDS.sleep(500); -// assertEquals(1, jedis.clientUnblock(clientId, UnblockType.ERROR)); -// future.get(1, TimeUnit.SECONDS); -// } catch (ExecutionException e) { -// assertEquals("redis.clients.jedis.exceptions.JedisDataException: UNBLOCKED client unblocked via CLIENT UNBLOCK", e.getMessage()); -// } -// } -// -// @Test -// public void killIdString() { -// String info = findInClientList(); -// Matcher matcher = Pattern.compile("\\bid=(\\d+)\\b").matcher(info); -// matcher.find(); -// String id = matcher.group(1); -// -// assertEquals(1, jedis.clientKill(new ClientKillParams().id(id))); -// -// assertDisconnected(client); -// } -// -// @Test -// public void killIdBinary() { -// String info = findInClientList(); -// Matcher matcher = Pattern.compile("\\bid=(\\d+)\\b").matcher(info); -// matcher.find(); -// byte[] id = matcher.group(1).getBytes(); -// -// assertEquals(1, jedis.clientKill(new ClientKillParams().id(id))); -// -// assertDisconnected(client); -// } -// -// @Test -// public void killTypeNormal() { -// long clients = jedis.clientKill(new ClientKillParams().type(Type.NORMAL)); -// assertTrue(clients > 0); -// assertDisconnected(client); -// } -// -// @Test -// public void killSkipmeNo() { -// jedis.clientKill(new ClientKillParams().type(Type.NORMAL).skipMe(SkipMe.NO)); -// assertDisconnected(client); -// assertDisconnected(jedis); -// } -// -// @Test -// public void killSkipmeYesNo() { -// jedis.clientKill(new ClientKillParams().type(Type.NORMAL).skipMe(SkipMe.YES)); -// assertDisconnected(client); -// assertEquals(1, jedis.clientKill(new ClientKillParams().type(Type.NORMAL).skipMe(SkipMe.NO))); -// assertDisconnected(jedis); -// } -// -// @Test -// public void killSkipmeYesNo2() { -// jedis.clientKill(new ClientKillParams().type(ClientType.NORMAL).skipMe(SkipMe.YES)); -// assertDisconnected(client); -// assertEquals(1, jedis.clientKill(new ClientKillParams().type(ClientType.NORMAL).skipMe(SkipMe.NO))); -// assertDisconnected(jedis); -// } -// -// @Test -// public void killAddrString() { -// String info = findInClientList(); -// Matcher matcher = Pattern.compile("\\baddr=(\\S+)\\b").matcher(info); -// matcher.find(); -// String addr = matcher.group(1); -// -// assertEquals(1, jedis.clientKill(new ClientKillParams().addr(addr))); -// -// assertDisconnected(client); -// } -// -// @Test -// public void killAddrBinary() { -// String info = findInClientList(); -// Matcher matcher = Pattern.compile("\\baddr=(\\S+)\\b").matcher(info); -// matcher.find(); -// String addr = matcher.group(1); -// -// assertEquals(1, jedis.clientKill(new ClientKillParams().addr(addr))); -// -// assertDisconnected(client); -// } -// -// @Test -// public void killLAddr() { -// String info = findInClientList(); -// Matcher matcher = Pattern.compile("\\bladdr=(\\S+)\\b").matcher(info); -// matcher.find(); -// String laddr = matcher.group(1); -// -// long clients = jedis.clientKill(new ClientKillParams().laddr(laddr)); -// assertTrue(clients >= 1); -// -// assertDisconnected(client); -// } -// -// @Test -// public void killAddrIpPort() { -// String info = findInClientList(); -// Matcher matcher = Pattern.compile("\\baddr=(\\S+)\\b").matcher(info); -// matcher.find(); -// String addr = matcher.group(1); + client.auth("foobared"); + long clientIdAfterReconnect = client.clientId(); + + assertTrue(clientIdInitial < clientIdAfterReconnect); + } + + @Test + public void clientUnblock() throws InterruptedException, TimeoutException { + long clientId = client.clientId(); + assertEquals(0, jedis.clientUnblock(clientId, UnblockType.ERROR)); + Future future = Executors.newSingleThreadExecutor().submit(() -> client.brpop(100000, "foo")); + + try { + // to make true command already executed + TimeUnit.MILLISECONDS.sleep(500); + assertEquals(1, jedis.clientUnblock(clientId, UnblockType.ERROR)); + future.get(1, TimeUnit.SECONDS); + } catch (ExecutionException e) { + assertEquals("redis.clients.jedis.exceptions.JedisDataException: UNBLOCKED client unblocked via CLIENT UNBLOCK", e.getMessage()); + } + } + + @Test + public void killIdString() { + String info = findInClientList(); + Matcher matcher = Pattern.compile("\\bid=(\\d+)\\b").matcher(info); + matcher.find(); + String id = matcher.group(1); + + assertEquals(1, jedis.clientKill(new ClientKillParams().id(id))); + + assertDisconnected(client); + } + + @Test + public void killIdBinary() { + String info = findInClientList(); + Matcher matcher = Pattern.compile("\\bid=(\\d+)\\b").matcher(info); + matcher.find(); + byte[] id = matcher.group(1).getBytes(); + + assertEquals(1, jedis.clientKill(new ClientKillParams().id(id))); + + assertDisconnected(client); + } + + @Test + public void killTypeNormal() { + long clients = jedis.clientKill(new ClientKillParams().type(Type.NORMAL)); + assertTrue(clients > 0); + assertDisconnected(client); + } + + @Test + public void killSkipmeNo() { + jedis.clientKill(new ClientKillParams().type(Type.NORMAL).skipMe(SkipMe.NO)); + assertDisconnected(client); + assertDisconnected(jedis); + } + + @Test + public void killSkipmeYesNo() { + jedis.clientKill(new ClientKillParams().type(Type.NORMAL).skipMe(SkipMe.YES)); + assertDisconnected(client); + assertEquals(1, jedis.clientKill(new ClientKillParams().type(Type.NORMAL).skipMe(SkipMe.NO))); + assertDisconnected(jedis); + } + + @Test + public void killSkipmeYesNo2() { + jedis.clientKill(new ClientKillParams().type(ClientType.NORMAL).skipMe(SkipMe.YES)); + assertDisconnected(client); + assertEquals(1, jedis.clientKill(new ClientKillParams().type(ClientType.NORMAL).skipMe(SkipMe.NO))); + assertDisconnected(jedis); + } + + @Test + public void killAddrString() { + String info = findInClientList(); + Matcher matcher = Pattern.compile("\\baddr=(\\S+)\\b").matcher(info); + matcher.find(); + String addr = matcher.group(1); + + assertEquals(1, jedis.clientKill(new ClientKillParams().addr(addr))); + + assertDisconnected(client); + } + + @Test + public void killAddrBinary() { + String info = findInClientList(); + Matcher matcher = Pattern.compile("\\baddr=(\\S+)\\b").matcher(info); + matcher.find(); + String addr = matcher.group(1); + + assertEquals(1, jedis.clientKill(new ClientKillParams().addr(addr))); + + assertDisconnected(client); + } + + @Test + public void killLAddr() { + String info = findInClientList(); + Matcher matcher = Pattern.compile("\\bladdr=(\\S+)\\b").matcher(info); + matcher.find(); + String laddr = matcher.group(1); + + long clients = jedis.clientKill(new ClientKillParams().laddr(laddr)); + assertTrue(clients >= 1); + + assertDisconnected(client); + } + + @Test + public void killAddrIpPort() { + String info = findInClientList(); + Matcher matcher = Pattern.compile("\\baddr=(\\S+)\\b").matcher(info); + matcher.find(); + String addr = matcher.group(1); // String[] hp = HostAndPort.extractParts(addr); -// -// assertEquals(1, jedis.clientKill(new ClientKillParams().addr(hp[0], Integer.parseInt(hp[1])))); -// -// assertDisconnected(client); -// } -// -// @Test -// public void killUser() { -// Jedis client2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); -// client.aclSetUser("test_kill", "on", "+acl", ">password1"); -// try { -// client2.auth("test_kill", "password1"); -// assertEquals(1, jedis.clientKill(new ClientKillParams().user("test_kill"))); -// assertDisconnected(client2); -// } finally { -// jedis.aclDelUser("test_kill"); -// } -// } -// -// @Test -// public void clientInfo() { -// String info = client.clientInfo(); -// assertNotNull(info); -// assertEquals(1, info.split("\n").length); -// assertTrue(info.contains(clientName)); -// } -// -// @Test -// public void clientListWithClientId() { -// long id = client.clientId(); -// String listInfo = jedis.clientList(id); -// assertNotNull(listInfo); -// assertTrue(listInfo.contains(clientName)); -// } -// -// @Test -// public void listWithType() { -// assertTrue(client.clientList(ClientType.NORMAL).split("\\n").length > 1); -// assertEquals(0, client.clientList(ClientType.MASTER).length()); -// assertEquals(1, client.clientList(ClientType.SLAVE).split("\\n").length); -// assertEquals(1, client.clientList(ClientType.REPLICA).split("\\n").length); -// assertEquals(1, client.clientList(ClientType.PUBSUB).split("\\n").length); -// } -// -// private void assertDisconnected(Jedis j) { -// try { -// j.ping(); -// fail("Jedis connection should be disconnected"); -// } catch (JedisConnectionException jce) { -// // should be here -// } -// } -// -// private String findInClientList() { -// for (String clientInfo : jedis.clientList().split("\n")) { -// if (pattern.matcher(clientInfo).find()) { -// return clientInfo; -// } -// } -// return null; -// } -//} + int lastColon = addr.lastIndexOf(":"); + String[] hp = new String[]{addr.substring(0, lastColon), addr.substring(lastColon + 1)}; + + assertEquals(1, jedis.clientKill(new ClientKillParams().addr(hp[0], Integer.parseInt(hp[1])))); + + assertDisconnected(client); + } + + @Test + public void killUser() { + Jedis client2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); + client.aclSetUser("test_kill", "on", "+acl", ">password1"); + try { + client2.auth("test_kill", "password1"); + assertEquals(1, jedis.clientKill(new ClientKillParams().user("test_kill"))); + assertDisconnected(client2); + } finally { + jedis.aclDelUser("test_kill"); + } + } + + @Test + public void clientInfo() { + String info = client.clientInfo(); + assertNotNull(info); + assertEquals(1, info.split("\n").length); + assertTrue(info.contains(clientName)); + } + + @Test + public void clientListWithClientId() { + long id = client.clientId(); + String listInfo = jedis.clientList(id); + assertNotNull(listInfo); + assertTrue(listInfo.contains(clientName)); + } + + @Test + public void listWithType() { + assertTrue(client.clientList(ClientType.NORMAL).split("\\n").length > 1); + assertEquals(0, client.clientList(ClientType.MASTER).length()); + assertEquals(1, client.clientList(ClientType.SLAVE).split("\\n").length); + assertEquals(1, client.clientList(ClientType.REPLICA).split("\\n").length); + assertEquals(1, client.clientList(ClientType.PUBSUB).split("\\n").length); + } + + private void assertDisconnected(Jedis j) { + try { + j.ping(); + fail("Jedis connection should be disconnected"); + } catch (JedisConnectionException jce) { + // should be here + } + } + + private String findInClientList() { + for (String clientInfo : jedis.clientList().split("\n")) { + if (pattern.matcher(clientInfo).find()) { + return clientInfo; + } + } + return null; + } +} diff --git a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java index 7c9eaf59c7..46bb0c277a 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java @@ -19,10 +19,10 @@ import redis.clients.jedis.tests.utils.JedisClusterTestUtil; public class ClusterCommandsTest { -// private static Jedis node1; -// private static Jedis node2; - private Jedis node1; - private Jedis node2; + private static Jedis node1; + private static Jedis node2; +// private Jedis node1; +// private Jedis node2; private static HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0); private static HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1); @@ -41,10 +41,10 @@ public void setUp() throws Exception { @After public void tearDown() { -// node1.disconnect(); -// node2.disconnect(); - node1.close(); - node2.close(); + node1.disconnect(); + node2.disconnect(); +// node1.close(); +// node2.close(); } @AfterClass diff --git a/src/test/java/redis/clients/jedis/tests/commands/ClusterValuesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ClusterValuesCommandsTest.java index 40a5eb6d49..4efcf7a0ba 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ClusterValuesCommandsTest.java @@ -1,6 +1,5 @@ package redis.clients.jedis.tests.commands; -import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import org.junit.Test; diff --git a/src/test/java/redis/clients/jedis/tests/commands/ConnectionHandlingCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ConnectionHandlingCommandsTest.java index 870e4e8482..e57cdf5899 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ConnectionHandlingCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ConnectionHandlingCommandsTest.java @@ -1,26 +1,19 @@ -//package redis.clients.jedis.tests.commands; -// -//import static org.junit.Assert.assertEquals; -// -//import org.junit.Test; -// -//import redis.clients.jedis.BinaryJedis; -//import redis.clients.jedis.HostAndPort; -//import redis.clients.jedis.Jedis; -//import redis.clients.jedis.tests.HostAndPortUtil; -// -//public class ConnectionHandlingCommandsTest { -// private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); -// -// @Test -// public void quit() { -// Jedis jedis = new Jedis(hnp); -// assertEquals("OK", jedis.quit()); -// } -// -// @Test -// public void binary_quit() { -// BinaryJedis bj = new BinaryJedis(hnp); -// assertEquals("OK", bj.quit()); -// } -//} \ No newline at end of file +package redis.clients.jedis.tests.commands; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.tests.HostAndPortUtil; + +public class ConnectionHandlingCommandsTest { + private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); + + @Test + public void quit() { + Jedis jedis = new Jedis(hnp); + assertEquals("OK", jedis.quit()); + } +} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java index cb12e32fae..e3591d28e0 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java @@ -1,150 +1,150 @@ -//package redis.clients.jedis.tests.commands; -// -//import static org.junit.Assert.assertArrayEquals; -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertNotNull; -//import static org.junit.Assert.assertNull; -//import static org.junit.Assert.assertTrue; -// -//import java.util.List; -//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 org.junit.Test; -// +package redis.clients.jedis.tests.commands; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.List; +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 org.junit.Test; + //import redis.clients.jedis.DebugParams; -//import redis.clients.jedis.DefaultJedisClientConfig; -//import redis.clients.jedis.Jedis; +import redis.clients.jedis.DefaultJedisClientConfig; +import redis.clients.jedis.Jedis; //import redis.clients.jedis.JedisMonitor; -//import redis.clients.jedis.Protocol; -//import redis.clients.jedis.args.ClientPauseMode; -//import redis.clients.jedis.exceptions.JedisDataException; -//import redis.clients.jedis.tests.HostAndPortUtil; -//import redis.clients.jedis.tests.utils.AssertUtil; -//import redis.clients.jedis.util.SafeEncoder; -// -//public class ControlCommandsTest extends JedisCommandTestBase { -// @Test -// public void save() { -// try { -// String status = jedis.save(); -// assertEquals("OK", status); -// } catch (JedisDataException e) { -// assertTrue("ERR Background save already in progress".equalsIgnoreCase(e.getMessage())); -// } -// } -// -// @Test -// public void bgsave() { -// try { -// String status = jedis.bgsave(); -// assertEquals("Background saving started", status); -// } catch (JedisDataException e) { -// assertTrue("ERR Background save already in progress".equalsIgnoreCase(e.getMessage())); -// } -// } -// -// @Test -// public void bgrewriteaof() { -// String scheduled = "Background append only file rewriting scheduled"; -// String started = "Background append only file rewriting started"; -// -// String status = jedis.bgrewriteaof(); -// -// boolean ok = status.equals(scheduled) || status.equals(started); -// assertTrue(ok); -// } -// -// @Test -// public void lastsave() throws InterruptedException { -// long saved = jedis.lastsave(); -// assertTrue(saved > 0); -// } -// -// @Test -// public void info() { -// String info = jedis.info(); -// assertNotNull(info); -// info = jedis.info("server"); -// assertNotNull(info); -// } -// -// @Test -// public void readonly() { -// try { -// jedis.readonly(); -// } catch (JedisDataException e) { -// assertTrue("ERR This instance has cluster support disabled".equalsIgnoreCase(e.getMessage())); -// } -// } -// -// @Test -// public void readwrite() { -// try { -// jedis.readwrite(); -// } catch (JedisDataException e) { -// assertTrue("ERR This instance has cluster support disabled".equalsIgnoreCase(e.getMessage())); -// } -// } -// -// @Test -// public void roleMaster() { -// try (Jedis master = new Jedis(HostAndPortUtil.getRedisServers().get(0), -// DefaultJedisClientConfig.builder().password("foobared").build())) { -// -// List role = master.role(); -// assertEquals("master", role.get(0)); -// assertTrue(role.get(1) instanceof Long); -// assertTrue(role.get(2) instanceof List); -// -// // binary -// List brole = master.roleBinary(); -// assertArrayEquals("master".getBytes(), (byte[]) brole.get(0)); -// assertTrue(brole.get(1) instanceof Long); -// assertTrue(brole.get(2) instanceof List); -// } -// } -// -// @Test -// public void roleSlave() { -// try (Jedis slave = new Jedis(HostAndPortUtil.getRedisServers().get(4), -// DefaultJedisClientConfig.builder().password("foobared").build())) { -// -// List role = slave.role(); -// assertEquals("slave", role.get(0)); -// assertEquals((long) HostAndPortUtil.getRedisServers().get(0).getPort(), role.get(2)); -// assertEquals("connected", role.get(3)); -// assertTrue(role.get(4) instanceof Long); -// -// // binary -// List brole = slave.roleBinary(); -// assertArrayEquals("slave".getBytes(), (byte[]) brole.get(0)); -// assertEquals((long) HostAndPortUtil.getRedisServers().get(0).getPort(), brole.get(2)); -// assertArrayEquals("connected".getBytes(), (byte[]) brole.get(3)); -// assertTrue(brole.get(4) instanceof Long); -// } -// } -// -// @Test -// public void roleSentinel() { -// try (Jedis sentinel = new Jedis(HostAndPortUtil.getSentinelServers().get(0))) { -// -// List role = sentinel.role(); -// assertEquals("sentinel", role.get(0)); -// assertTrue(role.get(1) instanceof List); -// assertTrue(((List) role.get(1)).contains("mymaster")); -// -// // binary -// List brole = sentinel.roleBinary(); -// assertArrayEquals("sentinel".getBytes(), (byte[]) brole.get(0)); -// assertTrue(brole.get(1) instanceof List); -// AssertUtil.assertCollectionContains((List) brole.get(1), "mymaster".getBytes()); -// } -// } +import redis.clients.jedis.Protocol; +import redis.clients.jedis.args.ClientPauseMode; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.tests.HostAndPortUtil; +import redis.clients.jedis.tests.utils.AssertUtil; +import redis.clients.jedis.util.SafeEncoder; + +public class ControlCommandsTest extends JedisCommandTestBase { + @Test + public void save() { + try { + String status = jedis.save(); + assertEquals("OK", status); + } catch (JedisDataException e) { + assertTrue("ERR Background save already in progress".equalsIgnoreCase(e.getMessage())); + } + } + + @Test + public void bgsave() { + try { + String status = jedis.bgsave(); + assertEquals("Background saving started", status); + } catch (JedisDataException e) { + assertTrue("ERR Background save already in progress".equalsIgnoreCase(e.getMessage())); + } + } + + @Test + public void bgrewriteaof() { + String scheduled = "Background append only file rewriting scheduled"; + String started = "Background append only file rewriting started"; + + String status = jedis.bgrewriteaof(); + + boolean ok = status.equals(scheduled) || status.equals(started); + assertTrue(ok); + } + + @Test + public void lastsave() throws InterruptedException { + long saved = jedis.lastsave(); + assertTrue(saved > 0); + } + + @Test + public void info() { + String info = jedis.info(); + assertNotNull(info); + info = jedis.info("server"); + assertNotNull(info); + } + + @Test + public void readonly() { + try { + jedis.readonly(); + } catch (JedisDataException e) { + assertTrue("ERR This instance has cluster support disabled".equalsIgnoreCase(e.getMessage())); + } + } + + @Test + public void readwrite() { + try { + jedis.readwrite(); + } catch (JedisDataException e) { + assertTrue("ERR This instance has cluster support disabled".equalsIgnoreCase(e.getMessage())); + } + } + + @Test + public void roleMaster() { + try (Jedis master = new Jedis(HostAndPortUtil.getRedisServers().get(0), + DefaultJedisClientConfig.builder().password("foobared").build())) { + + List role = master.role(); + assertEquals("master", role.get(0)); + assertTrue(role.get(1) instanceof Long); + assertTrue(role.get(2) instanceof List); + + // binary + List brole = master.roleBinary(); + assertArrayEquals("master".getBytes(), (byte[]) brole.get(0)); + assertTrue(brole.get(1) instanceof Long); + assertTrue(brole.get(2) instanceof List); + } + } + + @Test + public void roleSlave() { + try (Jedis slave = new Jedis(HostAndPortUtil.getRedisServers().get(4), + DefaultJedisClientConfig.builder().password("foobared").build())) { + + List role = slave.role(); + assertEquals("slave", role.get(0)); + assertEquals((long) HostAndPortUtil.getRedisServers().get(0).getPort(), role.get(2)); + assertEquals("connected", role.get(3)); + assertTrue(role.get(4) instanceof Long); + + // binary + List brole = slave.roleBinary(); + assertArrayEquals("slave".getBytes(), (byte[]) brole.get(0)); + assertEquals((long) HostAndPortUtil.getRedisServers().get(0).getPort(), brole.get(2)); + assertArrayEquals("connected".getBytes(), (byte[]) brole.get(3)); + assertTrue(brole.get(4) instanceof Long); + } + } + + @Test + public void roleSentinel() { + try (Jedis sentinel = new Jedis(HostAndPortUtil.getSentinelServers().get(0))) { + + List role = sentinel.role(); + assertEquals("sentinel", role.get(0)); + assertTrue(role.get(1) instanceof List); + assertTrue(((List) role.get(1)).contains("mymaster")); + + // binary + List brole = sentinel.roleBinary(); + assertArrayEquals("sentinel".getBytes(), (byte[]) brole.get(0)); + assertTrue(brole.get(1) instanceof List); + AssertUtil.assertCollectionContains((List) brole.get(1), "mymaster".getBytes()); + } + } // // @Test // public void monitor() { @@ -179,40 +179,31 @@ // } // }); // } -// -// @Test -// public void configGet() { -// List info = jedis.configGet("m*"); -// assertNotNull(info); -// } -// -// @Test -// public void configSet() { -// List info = jedis.configGet("maxmemory"); -// assertEquals("maxmemory", info.get(0)); -// String memory = info.get(1); -// assertEquals("OK", jedis.configSet("maxmemory", "200")); -// assertEquals("OK", jedis.configSet("maxmemory", memory)); -// } -// -// @Test -// public void configGetSetBinary() { -// byte[] maxmemory = SafeEncoder.encode("maxmemory"); -// List info = jedis.configGet(maxmemory); -// assertArrayEquals(maxmemory, info.get(0)); -// byte[] memory = info.get(1); -// assertEquals("OK", jedis.configSet(maxmemory, Protocol.toByteArray(200))); -// assertEquals("OK", jedis.configSet(maxmemory, memory)); -// } -// -// @Test -// public void configGetSetBinary2() { -// byte[] maxmemory = SafeEncoder.encode("maxmemory"); -// List info = jedis.configGet(maxmemory); -// assertArrayEquals(maxmemory, info.get(0)); -// byte[] memory = info.get(1); -// assertEquals("OK", jedis.configSetBinary(maxmemory, memory)); -// } + + @Test + public void configGet() { + List info = jedis.configGet("m*"); + assertNotNull(info); + } + + @Test + public void configSet() { + List info = jedis.configGet("maxmemory"); + assertEquals("maxmemory", info.get(0)); + String memory = info.get(1); + assertEquals("OK", jedis.configSet("maxmemory", "200")); + assertEquals("OK", jedis.configSet("maxmemory", memory)); + } + + @Test + public void configGetSetBinary() { + byte[] maxmemory = SafeEncoder.encode("maxmemory"); + List info = jedis.configGet(maxmemory); + assertArrayEquals(maxmemory, info.get(0)); + byte[] memory = info.get(1); + assertEquals("OK", jedis.configSet(maxmemory, Protocol.toByteArray(200))); + assertEquals("OK", jedis.configSet(maxmemory, memory)); + } // // @Test // public void debug() { @@ -222,176 +213,176 @@ // resp = jedis.debug(DebugParams.RELOAD()); // assertNotNull(resp); // } -// -// @Test -// public void waitReplicas() { -// assertEquals(1, jedis.waitReplicas(1, 100)); -// } -// -// @Test -// public void clientPause() throws InterruptedException, ExecutionException { -// ExecutorService executorService = Executors.newFixedThreadPool(2); -// try { -// final Jedis jedisToPause1 = createJedis(); -// final Jedis jedisToPause2 = createJedis(); -// -// int pauseMillis = 1250; -// jedis.clientPause(pauseMillis); -// -// Future latency1 = executorService.submit(new Callable() { -// @Override -// public Long call() throws Exception { -// long startMillis = System.currentTimeMillis(); -// assertEquals("PONG", jedisToPause1.ping()); -// return System.currentTimeMillis() - startMillis; -// } -// }); -// Future latency2 = executorService.submit(new Callable() { -// @Override -// public Long call() throws Exception { -// long startMillis = System.currentTimeMillis(); -// assertEquals("PONG", jedisToPause2.ping()); -// return System.currentTimeMillis() - startMillis; -// } -// }); -// -// long latencyMillis1 = latency1.get(); -// long latencyMillis2 = latency2.get(); -// -// int pauseMillisDelta = 100; -// assertTrue(pauseMillis <= latencyMillis1 && latencyMillis1 <= pauseMillis + pauseMillisDelta); -// assertTrue(pauseMillis <= latencyMillis2 && latencyMillis2 <= pauseMillis + pauseMillisDelta); -// -// jedisToPause1.close(); -// jedisToPause2.close(); -// } finally { -// executorService.shutdown(); -// if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { -// executorService.shutdownNow(); -// } -// } -// } -// -// @Test -// public void clientPauseAll() throws InterruptedException, ExecutionException { -// final int pauseMillis = 1250; -// final int pauseMillisDelta = 100; -// -// ExecutorService executorService = Executors.newFixedThreadPool(1); -// try (Jedis jedisPause = createJedis()) { -// -// jedis.clientPause(pauseMillis, ClientPauseMode.ALL); -// -// Future latency = executorService.submit(new Callable() { -// @Override -// public Long call() throws Exception { -// long startMillis = System.currentTimeMillis(); -// jedisPause.get("key"); -// return System.currentTimeMillis() - startMillis; -// } -// }); -// -// long latencyMillis = latency.get(); -// assertTrue(pauseMillis <= latencyMillis && latencyMillis <= pauseMillis + pauseMillisDelta); -// -// } finally { -// executorService.shutdown(); -// if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { -// executorService.shutdownNow(); -// } -// } -// } -// -// @Test -// public void clientPauseWrite() throws InterruptedException, ExecutionException { -// final int pauseMillis = 1250; -// final int pauseMillisDelta = 100; -// -// ExecutorService executorService = Executors.newFixedThreadPool(2); -// try (Jedis jedisRead = createJedis(); Jedis jedisWrite = createJedis();) { -// -// jedis.clientPause(pauseMillis, ClientPauseMode.WRITE); -// -// Future latencyRead = executorService.submit(new Callable() { -// @Override -// public Long call() throws Exception { -// long startMillis = System.currentTimeMillis(); -// jedisRead.get("key"); -// return System.currentTimeMillis() - startMillis; -// } -// }); -// Future latencyWrite = executorService.submit(new Callable() { -// @Override -// public Long call() throws Exception { -// long startMillis = System.currentTimeMillis(); -// jedisWrite.set("key", "value"); -// return System.currentTimeMillis() - startMillis; -// } -// }); -// -// long latencyReadMillis = latencyRead.get(); -// assertTrue(0 <= latencyReadMillis && latencyReadMillis <= pauseMillisDelta); -// -// long latencyWriteMillis = latencyWrite.get(); -// assertTrue(pauseMillis <= latencyWriteMillis && latencyWriteMillis <= pauseMillis + pauseMillisDelta); -// -// } finally { -// executorService.shutdown(); -// if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { -// executorService.shutdownNow(); -// } -// } -// } -// -// @Test -// public void memoryDoctorString() { -// String memoryInfo = jedis.memoryDoctor(); -// assertNotNull(memoryInfo); -// } -// -// @Test -// public void memoryDoctorBinary() { -// byte[] memoryInfo = jedis.memoryDoctorBinary(); -// assertNotNull(memoryInfo); -// } -// -// @Test -// public void memoryUsageString() { -// // Note: It has been recommended not to base MEMORY USAGE test on exact value, as the response -// // may subject to be 'tuned' especially targeting a major Redis release. -// -// jedis.set("foo", "bar"); -// long usage = jedis.memoryUsage("foo"); -// assertTrue(usage >= 30); -// assertTrue(usage <= 80); -// -// jedis.lpush("foobar", "fo", "ba", "sha"); -// usage = jedis.memoryUsage("foobar", 2); -// assertTrue(usage >= 110); -// assertTrue(usage <= 190); -// -// assertNull(jedis.memoryUsage("roo", 2)); -// } -// -// @Test -// public void memoryUsageBinary() { -// // Note: It has been recommended not to base MEMORY USAGE test on exact value, as the response -// // may subject to be 'tuned' especially targeting a major Redis release. -// -// byte[] bfoo = {0x01, 0x02, 0x03, 0x04}; -// byte[] bbar = {0x05, 0x06, 0x07, 0x08}; -// byte[] bfoobar = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; -// -// jedis.set(bfoo, bbar); -// long usage = jedis.memoryUsage(bfoo); -// assertTrue(usage >= 30); -// assertTrue(usage <= 80); -// -// jedis.lpush(bfoobar, new byte[]{0x01, 0x02}, new byte[]{0x05, 0x06}, new byte[]{0x00}); -// usage = jedis.memoryUsage(bfoobar, 2); -// assertTrue(usage >= 110); -// assertTrue(usage <= 190); -// -// assertNull(jedis.memoryUsage("roo", 2)); -// } -//} + + @Test + public void waitReplicas() { + assertEquals(1, jedis.waitReplicas(1, 100)); + } + + @Test + public void clientPause() throws InterruptedException, ExecutionException { + ExecutorService executorService = Executors.newFixedThreadPool(2); + try { + final Jedis jedisToPause1 = createJedis(); + final Jedis jedisToPause2 = createJedis(); + + int pauseMillis = 1250; + jedis.clientPause(pauseMillis); + + Future latency1 = executorService.submit(new Callable() { + @Override + public Long call() throws Exception { + long startMillis = System.currentTimeMillis(); + assertEquals("PONG", jedisToPause1.ping()); + return System.currentTimeMillis() - startMillis; + } + }); + Future latency2 = executorService.submit(new Callable() { + @Override + public Long call() throws Exception { + long startMillis = System.currentTimeMillis(); + assertEquals("PONG", jedisToPause2.ping()); + return System.currentTimeMillis() - startMillis; + } + }); + + long latencyMillis1 = latency1.get(); + long latencyMillis2 = latency2.get(); + + int pauseMillisDelta = 100; + assertTrue(pauseMillis <= latencyMillis1 && latencyMillis1 <= pauseMillis + pauseMillisDelta); + assertTrue(pauseMillis <= latencyMillis2 && latencyMillis2 <= pauseMillis + pauseMillisDelta); + + jedisToPause1.close(); + jedisToPause2.close(); + } finally { + executorService.shutdown(); + if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + } + } + } + + @Test + public void clientPauseAll() throws InterruptedException, ExecutionException { + final int pauseMillis = 1250; + final int pauseMillisDelta = 100; + + ExecutorService executorService = Executors.newFixedThreadPool(1); + try (Jedis jedisPause = createJedis()) { + + jedis.clientPause(pauseMillis, ClientPauseMode.ALL); + + Future latency = executorService.submit(new Callable() { + @Override + public Long call() throws Exception { + long startMillis = System.currentTimeMillis(); + jedisPause.get("key"); + return System.currentTimeMillis() - startMillis; + } + }); + + long latencyMillis = latency.get(); + assertTrue(pauseMillis <= latencyMillis && latencyMillis <= pauseMillis + pauseMillisDelta); + + } finally { + executorService.shutdown(); + if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + } + } + } + + @Test + public void clientPauseWrite() throws InterruptedException, ExecutionException { + final int pauseMillis = 1250; + final int pauseMillisDelta = 100; + + ExecutorService executorService = Executors.newFixedThreadPool(2); + try (Jedis jedisRead = createJedis(); Jedis jedisWrite = createJedis();) { + + jedis.clientPause(pauseMillis, ClientPauseMode.WRITE); + + Future latencyRead = executorService.submit(new Callable() { + @Override + public Long call() throws Exception { + long startMillis = System.currentTimeMillis(); + jedisRead.get("key"); + return System.currentTimeMillis() - startMillis; + } + }); + Future latencyWrite = executorService.submit(new Callable() { + @Override + public Long call() throws Exception { + long startMillis = System.currentTimeMillis(); + jedisWrite.set("key", "value"); + return System.currentTimeMillis() - startMillis; + } + }); + + long latencyReadMillis = latencyRead.get(); + assertTrue(0 <= latencyReadMillis && latencyReadMillis <= pauseMillisDelta); + + long latencyWriteMillis = latencyWrite.get(); + assertTrue(pauseMillis <= latencyWriteMillis && latencyWriteMillis <= pauseMillis + pauseMillisDelta); + + } finally { + executorService.shutdown(); + if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + } + } + } + + @Test + public void memoryDoctorString() { + String memoryInfo = jedis.memoryDoctor(); + assertNotNull(memoryInfo); + } + + @Test + public void memoryDoctorBinary() { + byte[] memoryInfo = jedis.memoryDoctorBinary(); + assertNotNull(memoryInfo); + } + + @Test + public void memoryUsageString() { + // Note: It has been recommended not to base MEMORY USAGE test on exact value, as the response + // may subject to be 'tuned' especially targeting a major Redis release. + + jedis.set("foo", "bar"); + long usage = jedis.memoryUsage("foo"); + assertTrue(usage >= 30); + assertTrue(usage <= 80); + + jedis.lpush("foobar", "fo", "ba", "sha"); + usage = jedis.memoryUsage("foobar", 2); + assertTrue(usage >= 110); + assertTrue(usage <= 190); + + assertNull(jedis.memoryUsage("roo", 2)); + } + + @Test + public void memoryUsageBinary() { + // Note: It has been recommended not to base MEMORY USAGE test on exact value, as the response + // may subject to be 'tuned' especially targeting a major Redis release. + + byte[] bfoo = {0x01, 0x02, 0x03, 0x04}; + byte[] bbar = {0x05, 0x06, 0x07, 0x08}; + byte[] bfoobar = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; + + jedis.set(bfoo, bbar); + long usage = jedis.memoryUsage(bfoo); + assertTrue(usage >= 30); + assertTrue(usage <= 80); + + jedis.lpush(bfoobar, new byte[]{0x01, 0x02}, new byte[]{0x05, 0x06}, new byte[]{0x00}); + usage = jedis.memoryUsage(bfoobar, 2); + assertTrue(usage >= 110); + assertTrue(usage <= 190); + + assertNull(jedis.memoryUsage("roo", 2)); + } +} diff --git a/src/test/java/redis/clients/jedis/tests/commands/FailoverCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/FailoverCommandsTest.java index 00964ab4e8..969d3d2130 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/FailoverCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/FailoverCommandsTest.java @@ -1,145 +1,145 @@ -//package redis.clients.jedis.tests.commands; -// -//import org.junit.After; -//import org.junit.Before; -//import org.junit.BeforeClass; -//import org.junit.Test; -// -//import redis.clients.jedis.HostAndPort; -//import redis.clients.jedis.Jedis; -//import redis.clients.jedis.exceptions.JedisDataException; -//import redis.clients.jedis.params.FailoverParams; -//import redis.clients.jedis.tests.HostAndPortUtil; -// -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.fail; -// -//public class FailoverCommandsTest { -// -// private static HostAndPort node1; -// private static HostAndPort node2; -// -// private HostAndPort masterAddress; -// private HostAndPort replicaAddress; -// -// private boolean switched; -// -// @BeforeClass -// public static void setUp() { -// node1 = HostAndPortUtil.getRedisServers().get(9); -// node2 = HostAndPortUtil.getRedisServers().get(10); -// } -// -// @Before -// public void prepare() { -// String role1, role2; -// try (Jedis jedis1 = new Jedis(node1)) { -// role1 = (String) jedis1.role().get(0); -// } -// try (Jedis jedis2 = new Jedis(node2)) { -// role2 = (String) jedis2.role().get(0); -// } -// -// if ("master".equals(role1) && "slave".equals(role2)) { -// masterAddress = node1; -// replicaAddress = node2; -// } else if ("master".equals(role2) && "slave".equals(role1)) { -// masterAddress = node2; -// replicaAddress = node1; -// } else { -// fail(); -// } -// -// switched = false; -// } -// -// @After -// public void cleanUp() { -// if (switched) { -// try { -// Thread.sleep(250); -// } catch (InterruptedException ex) { } -// } -// } -// -// @Test -// public void failoverMaster() throws InterruptedException { -// // -// try (Jedis master = new Jedis(masterAddress)) { -// assertEquals("OK", master.failover()); -// Thread.sleep(20); // allow some time to failover; -// // not too much as everything is happening in same machine -// assertEquals("slave", master.role().get(0)); -// } -// } -// -// @Test -// public void failoverReplica() { -// try (Jedis replica = new Jedis(replicaAddress)) { -// replica.failover(); -// } catch(JedisDataException ex) { -// assertEquals("ERR FAILOVER is not valid when server is a replica.", ex.getMessage()); -// } -// } -// -// @Test -// public void failoverToHAP() throws InterruptedException { -// try (Jedis master = new Jedis(masterAddress)) { -// assertEquals("OK", master.failover(FailoverParams.failoverParams() -// .to(new HostAndPort("127.0.0.1", replicaAddress.getPort())))); -// switched = true; -// } -// } -// -// @Test(expected = IllegalStateException.class) -// public void failoverForceWithoutToFailFast() { -// try (Jedis master = new Jedis(masterAddress)) { -// assertEquals("OK", master.failover(FailoverParams.failoverParams() -// .timeout(100).force())); -// } -// } -// -// @Test(expected = IllegalStateException.class) -// public void failoverForceWithoutTimeoutFailFast() { -// try (Jedis master = new Jedis(masterAddress)) { -// assertEquals("OK", master.failover(FailoverParams.failoverParams() -// .to(new HostAndPort("127.0.0.1", replicaAddress.getPort())).force())); -// } -// } -// -// @Test -// public void failoverForce() throws InterruptedException { -// try (Jedis master = new Jedis(masterAddress)) { -// assertEquals("OK", master.failover(FailoverParams.failoverParams() -// .to(new HostAndPort("127.0.0.1", replicaAddress.getPort())).force().timeout(100))); -// switched = true; -// } -// } -// -// @Test -// public void failoverToWrongPort() { -// try (Jedis master = new Jedis(masterAddress)) { -// master.failover(FailoverParams.failoverParams().to("127.0.0.1", 6300)); -// } catch(JedisDataException ex) { -// assertEquals("ERR FAILOVER target HOST and PORT is not a replica.", ex.getMessage()); -// } -// } -// -// @Test -// public void abortMaster() { -// try (Jedis master = new Jedis(masterAddress)) { -// master.failoverAbort(); -// } catch(JedisDataException ex) { -// assertEquals("ERR No failover in progress.", ex.getMessage()); -// } -// } -// -// @Test -// public void abortReplica() { -// try (Jedis replica = new Jedis(replicaAddress)) { -// replica.failoverAbort(); -// } catch(JedisDataException ex) { -// assertEquals("ERR No failover in progress.", ex.getMessage()); -// } -// } -//} +package redis.clients.jedis.tests.commands; + +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.params.FailoverParams; +import redis.clients.jedis.tests.HostAndPortUtil; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +public class FailoverCommandsTest { + + private static HostAndPort node1; + private static HostAndPort node2; + + private HostAndPort masterAddress; + private HostAndPort replicaAddress; + + private boolean switched; + + @BeforeClass + public static void setUp() { + node1 = HostAndPortUtil.getRedisServers().get(9); + node2 = HostAndPortUtil.getRedisServers().get(10); + } + + @Before + public void prepare() { + String role1, role2; + try (Jedis jedis1 = new Jedis(node1)) { + role1 = (String) jedis1.role().get(0); + } + try (Jedis jedis2 = new Jedis(node2)) { + role2 = (String) jedis2.role().get(0); + } + + if ("master".equals(role1) && "slave".equals(role2)) { + masterAddress = node1; + replicaAddress = node2; + } else if ("master".equals(role2) && "slave".equals(role1)) { + masterAddress = node2; + replicaAddress = node1; + } else { + fail(); + } + + switched = false; + } + + @After + public void cleanUp() { + if (switched) { + try { + Thread.sleep(250); + } catch (InterruptedException ex) { } + } + } + + @Test + public void failoverMaster() throws InterruptedException { + // + try (Jedis master = new Jedis(masterAddress)) { + assertEquals("OK", master.failover()); + Thread.sleep(120); // allow some time to failover; + // not too much as everything is happening in same machine + assertEquals("slave", master.role().get(0)); + } + } + + @Test + public void failoverReplica() { + try (Jedis replica = new Jedis(replicaAddress)) { + replica.failover(); + } catch(JedisDataException ex) { + assertEquals("ERR FAILOVER is not valid when server is a replica.", ex.getMessage()); + } + } + + @Test + public void failoverToHAP() throws InterruptedException { + try (Jedis master = new Jedis(masterAddress)) { + assertEquals("OK", master.failover(FailoverParams.failoverParams() + .to(new HostAndPort("127.0.0.1", replicaAddress.getPort())))); + switched = true; + } + } + + @Test(expected = IllegalStateException.class) + public void failoverForceWithoutToFailFast() { + try (Jedis master = new Jedis(masterAddress)) { + assertEquals("OK", master.failover(FailoverParams.failoverParams() + .timeout(100).force())); + } + } + + @Test(expected = IllegalStateException.class) + public void failoverForceWithoutTimeoutFailFast() { + try (Jedis master = new Jedis(masterAddress)) { + assertEquals("OK", master.failover(FailoverParams.failoverParams() + .to(new HostAndPort("127.0.0.1", replicaAddress.getPort())).force())); + } + } + + @Test + public void failoverForce() throws InterruptedException { + try (Jedis master = new Jedis(masterAddress)) { + assertEquals("OK", master.failover(FailoverParams.failoverParams() + .to(new HostAndPort("127.0.0.1", replicaAddress.getPort())).force().timeout(100))); + switched = true; + } + } + + @Test + public void failoverToWrongPort() { + try (Jedis master = new Jedis(masterAddress)) { + master.failover(FailoverParams.failoverParams().to("127.0.0.1", 6300)); + } catch(JedisDataException ex) { + assertEquals("ERR FAILOVER target HOST and PORT is not a replica.", ex.getMessage()); + } + } + + @Test + public void abortMaster() { + try (Jedis master = new Jedis(masterAddress)) { + master.failoverAbort(); + } catch(JedisDataException ex) { + assertEquals("ERR No failover in progress.", ex.getMessage()); + } + } + + @Test + public void abortReplica() { + try (Jedis replica = new Jedis(replicaAddress)) { + replica.failoverAbort(); + } catch(JedisDataException ex) { + assertEquals("ERR No failover in progress.", ex.getMessage()); + } + } +} diff --git a/src/test/java/redis/clients/jedis/tests/commands/GeoCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/GeoCommandsTest.java index bf889813b4..813125b580 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/GeoCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/GeoCommandsTest.java @@ -482,9 +482,4 @@ private void prepareGeoData() { assertEquals(3, jedis.geoadd(bfoo, bcoordinateMap)); } - - private boolean equalsWithinEpsilon(double d1, double d2) { - double epsilon = 1E-5; - return Math.abs(d1 - d2) < epsilon; - } } diff --git a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java index fac0dcaf5e..2f8c043e75 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java @@ -315,22 +315,22 @@ public void hgetAll() { assertArrayEquals(bcar, bhash.get(bbar)); assertArrayEquals(bbar, bhash.get(bcar)); } -// -// @Test -// public void hgetAllPipeline() { -// Map bh = new HashMap(); -// bh.put(bbar, bcar); -// bh.put(bcar, bbar); -// jedis.hmset(bfoo, bh); -// Pipeline pipeline = jedis.pipelined(); -// Response> bhashResponse = pipeline.hgetAll(bfoo); -// pipeline.sync(); -// Map bhash = bhashResponse.get(); -// -// assertEquals(2, bhash.size()); -// assertArrayEquals(bcar, bhash.get(bbar)); -// assertArrayEquals(bbar, bhash.get(bcar)); -// } + + @Test + public void hgetAllPipeline() { + Map bh = new HashMap(); + bh.put(bbar, bcar); + bh.put(bcar, bbar); + jedis.hmset(bfoo, bh); + Pipeline pipeline = jedis.pipelined(); + Response> bhashResponse = pipeline.hgetAll(bfoo); + pipeline.sync(); + Map bhash = bhashResponse.get(); + + assertEquals(2, bhash.size()); + assertArrayEquals(bcar, bhash.get(bbar)); + assertArrayEquals(bbar, bhash.get(bcar)); + } @Test public void hscan() { diff --git a/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java b/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java index 7eb54b9b65..a926aed99a 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java +++ b/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java @@ -7,13 +7,13 @@ import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.Connection; -import redis.clients.jedis.Protocol; import redis.clients.jedis.tests.HostAndPortUtil; public abstract class JedisCommandTestBase { protected static final HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); + protected Connection connection; protected Jedis jedis; public JedisCommandTestBase() { @@ -22,10 +22,12 @@ public JedisCommandTestBase() { @Before public void setUp() throws Exception { - Connection connection = new Connection(hnp, DefaultJedisClientConfig.builder() +// Connection connection = new Connection(hnp, DefaultJedisClientConfig.builder() +// .timeoutMillis(500).password("foobared").build()); + connection = new Connection(hnp, DefaultJedisClientConfig.builder() .timeoutMillis(500).password("foobared").build()); - connection.executeCommand(Protocol.Command.FLUSHALL); jedis = new Jedis(connection); + jedis.flushAll(); } @After diff --git a/src/test/java/redis/clients/jedis/tests/commands/MigrateTest.java b/src/test/java/redis/clients/jedis/tests/commands/MigrateTest.java index 664340c789..f4e7ffb641 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/MigrateTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/MigrateTest.java @@ -1,238 +1,238 @@ -//package redis.clients.jedis.tests.commands; -// -//import static org.junit.Assert.assertArrayEquals; -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertNull; -//import static org.junit.Assert.assertTrue; -//import static org.junit.Assert.fail; -// -//import org.junit.After; -//import org.junit.Before; -//import org.junit.Test; -// -//import redis.clients.jedis.Jedis; -//import redis.clients.jedis.Protocol; -//import redis.clients.jedis.exceptions.JedisDataException; -//import redis.clients.jedis.params.MigrateParams; -// -//public class MigrateTest extends JedisCommandTestBase { -// -// private static final byte[] bfoo = { 0x01, 0x02, 0x03 }; -// private static final byte[] bbar = { 0x04, 0x05, 0x06 }; -// private static final byte[] bfoo1 = { 0x07, 0x08, 0x01 }; -// private static final byte[] bbar1 = { 0x09, 0x00, 0x01 }; -// private static final byte[] bfoo2 = { 0x07, 0x08, 0x02 }; -// private static final byte[] bbar2 = { 0x09, 0x00, 0x02 }; -// private static final byte[] bfoo3 = { 0x07, 0x08, 0x03 }; -// private static final byte[] bbar3 = { 0x09, 0x00, 0x03 }; -// -// private Jedis dest; -// private Jedis destAuth; -// private static final String host = hnp.getHost(); -// private static final int port = 6386; -// private static final int portAuth = hnp.getPort() + 1; -// private static final int db = 2; -// private static final int dbAuth = 3; -// private static final int timeout = Protocol.DEFAULT_TIMEOUT; -// -// @Before -// @Override -// public void setUp() throws Exception { -// super.setUp(); -// -// dest = new Jedis(host, port, 500); -// dest.flushAll(); -// dest.select(db); -// -// destAuth = new Jedis(host, portAuth, 500); -// destAuth.auth("foobared"); -// destAuth.flushAll(); -// destAuth.select(dbAuth); -// } -// -// @After -// @Override -// public void tearDown() throws Exception { -// dest.close(); -// destAuth.close(); -// super.tearDown(); -// } -// -// @Test -// public void nokey() { -// assertEquals("NOKEY", jedis.migrate(host, port, "foo", db, timeout)); -// assertEquals("NOKEY", jedis.migrate(host, port, bfoo, db, timeout)); -// assertEquals("NOKEY", -// jedis.migrate(host, port, db, timeout, new MigrateParams(), "foo1", "foo2", "foo3")); -// assertEquals("NOKEY", -// jedis.migrate(host, port, db, timeout, new MigrateParams(), bfoo1, bfoo2, bfoo3)); -// } -// -// @Test -// public void migrate() { -// jedis.set("foo", "bar"); -// assertEquals("OK", jedis.migrate(host, port, "foo", db, timeout)); -// assertEquals("bar", dest.get("foo")); -// assertNull(jedis.get("foo")); -// -// jedis.set(bfoo, bbar); -// assertEquals("OK", jedis.migrate(host, port, bfoo, db, timeout)); -// assertArrayEquals(bbar, dest.get(bfoo)); -// assertNull(jedis.get(bfoo)); -// } -// -// @Test -// public void migrateEmptyParams() { -// jedis.set("foo", "bar"); -// assertEquals("OK", jedis.migrate(host, port, db, timeout, new MigrateParams(), "foo")); -// assertEquals("bar", dest.get("foo")); -// assertNull(jedis.get("foo")); -// -// jedis.set(bfoo, bbar); -// assertEquals("OK", jedis.migrate(host, port, db, timeout, new MigrateParams(), bfoo)); -// assertArrayEquals(bbar, dest.get(bfoo)); -// assertNull(jedis.get(bfoo)); -// } -// -// @Test -// public void migrateCopy() { -// jedis.set("foo", "bar"); -// assertEquals("OK", jedis.migrate(host, port, db, timeout, new MigrateParams().copy(), "foo")); -// assertEquals("bar", dest.get("foo")); -// assertEquals("bar", jedis.get("foo")); -// -// jedis.set(bfoo, bbar); -// assertEquals("OK", jedis.migrate(host, port, db, timeout, new MigrateParams().copy(), bfoo)); -// assertArrayEquals(bbar, dest.get(bfoo)); -// assertArrayEquals(bbar, jedis.get(bfoo)); -// } -// -// @Test -// public void migrateReplace() { -// jedis.set("foo", "bar1"); -// dest.set("foo", "bar2"); -// assertEquals("OK", jedis.migrate(host, port, db, timeout, new MigrateParams().replace(), "foo")); -// assertEquals("bar1", dest.get("foo")); -// assertNull(jedis.get("foo")); -// -// jedis.set(bfoo, bbar1); -// dest.set(bfoo, bbar2); -// assertEquals("OK", jedis.migrate(host, port, db, timeout, new MigrateParams().replace(), bfoo)); -// assertArrayEquals(bbar1, dest.get(bfoo)); -// assertNull(jedis.get(bfoo)); -// } -// -// @Test -// public void migrateCopyReplace() { -// jedis.set("foo", "bar1"); -// dest.set("foo", "bar2"); -// assertEquals("OK", -// jedis.migrate(host, port, db, timeout, new MigrateParams().copy().replace(), "foo")); -// assertEquals("bar1", dest.get("foo")); -// assertEquals("bar1", jedis.get("foo")); -// -// jedis.set(bfoo, bbar1); -// dest.set(bfoo, bbar2); -// assertEquals("OK", -// jedis.migrate(host, port, db, timeout, new MigrateParams().copy().replace(), bfoo)); -// assertArrayEquals(bbar1, dest.get(bfoo)); -// assertArrayEquals(bbar1, jedis.get(bfoo)); -// } -// -// @Test -// public void migrateAuth() { -// jedis.set("foo", "bar"); -// assertEquals("OK", -// jedis.migrate(host, portAuth, dbAuth, timeout, new MigrateParams().auth("foobared"), "foo")); -// assertEquals("bar", destAuth.get("foo")); -// assertNull(jedis.get("foo")); -// -// jedis.set(bfoo, bbar); -// assertEquals("OK", -// jedis.migrate(host, portAuth, dbAuth, timeout, new MigrateParams().auth("foobared"), bfoo)); -// assertArrayEquals(bbar, destAuth.get(bfoo)); -// assertNull(jedis.get(bfoo)); -// } -// -// @Test -// public void migrateAuth2() { -// destAuth.set("foo", "bar"); -// assertEquals("OK", destAuth.migrate(host, hnp.getPort(), 0, timeout, -// new MigrateParams().auth2("acljedis", "fizzbuzz"), "foo")); -// assertEquals("bar", jedis.get("foo")); -// assertNull(destAuth.get("foo")); -// -// // binary -// dest.set(bfoo1, bbar1); -// assertEquals("OK", dest.migrate(host, hnp.getPort(), 0, timeout, -// new MigrateParams().auth2("acljedis", "fizzbuzz"), bfoo1)); -// assertArrayEquals(bbar1, jedis.get(bfoo1)); -// assertNull(dest.get(bfoo1)); -// } -// -// @Test -// public void migrateCopyReplaceAuth() { -// jedis.set("foo", "bar1"); -// destAuth.set("foo", "bar2"); -// assertEquals( -// "OK", -// jedis.migrate(host, portAuth, dbAuth, timeout, -// new MigrateParams().copy().replace().auth("foobared"), "foo")); -// assertEquals("bar1", destAuth.get("foo")); -// assertEquals("bar1", jedis.get("foo")); -// -// jedis.set(bfoo, bbar1); -// destAuth.set(bfoo, bbar2); -// assertEquals( -// "OK", -// jedis.migrate(host, portAuth, dbAuth, timeout, -// new MigrateParams().copy().replace().auth("foobared"), bfoo)); -// assertArrayEquals(bbar1, destAuth.get(bfoo)); -// assertArrayEquals(bbar1, jedis.get(bfoo)); -// } -// -// @Test -// public void migrateMulti() { -// jedis.mset("foo1", "bar1", "foo2", "bar2", "foo3", "bar3"); -// assertEquals("OK", -// jedis.migrate(host, port, db, timeout, new MigrateParams(), "foo1", "foo2", "foo3")); -// assertEquals("bar1", dest.get("foo1")); -// assertEquals("bar2", dest.get("foo2")); -// assertEquals("bar3", dest.get("foo3")); -// -// jedis.mset(bfoo1, bbar1, bfoo2, bbar2, bfoo3, bbar3); -// assertEquals("OK", -// jedis.migrate(host, port, db, timeout, new MigrateParams(), bfoo1, bfoo2, bfoo3)); -// assertArrayEquals(bbar1, dest.get(bfoo1)); -// assertArrayEquals(bbar2, dest.get(bfoo2)); -// assertArrayEquals(bbar3, dest.get(bfoo3)); -// } -// -// @Test -// public void migrateConflict() { -// jedis.mset("foo1", "bar1", "foo2", "bar2", "foo3", "bar3"); -// dest.set("foo2", "bar"); -// try { -// jedis.migrate(host, port, db, timeout, new MigrateParams(), "foo1", "foo2", "foo3"); -// fail("Should get BUSYKEY error"); -// } catch (JedisDataException jde) { -// assertTrue(jde.getMessage().contains("BUSYKEY")); -// } -// assertEquals("bar1", dest.get("foo1")); -// assertEquals("bar", dest.get("foo2")); -// assertEquals("bar3", dest.get("foo3")); -// -// jedis.mset(bfoo1, bbar1, bfoo2, bbar2, bfoo3, bbar3); -// dest.set(bfoo2, bbar); -// try { -// jedis.migrate(host, port, db, timeout, new MigrateParams(), bfoo1, bfoo2, bfoo3); -// fail("Should get BUSYKEY error"); -// } catch (JedisDataException jde) { -// assertTrue(jde.getMessage().contains("BUSYKEY")); -// } -// assertArrayEquals(bbar1, dest.get(bfoo1)); -// assertArrayEquals(bbar, dest.get(bfoo2)); -// assertArrayEquals(bbar3, dest.get(bfoo3)); -// } -// -//} +package redis.clients.jedis.tests.commands; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.Protocol; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.params.MigrateParams; + +public class MigrateTest extends JedisCommandTestBase { + + private static final byte[] bfoo = { 0x01, 0x02, 0x03 }; + private static final byte[] bbar = { 0x04, 0x05, 0x06 }; + private static final byte[] bfoo1 = { 0x07, 0x08, 0x01 }; + private static final byte[] bbar1 = { 0x09, 0x00, 0x01 }; + private static final byte[] bfoo2 = { 0x07, 0x08, 0x02 }; + private static final byte[] bbar2 = { 0x09, 0x00, 0x02 }; + private static final byte[] bfoo3 = { 0x07, 0x08, 0x03 }; + private static final byte[] bbar3 = { 0x09, 0x00, 0x03 }; + + private Jedis dest; + private Jedis destAuth; + private static final String host = hnp.getHost(); + private static final int port = 6386; + private static final int portAuth = hnp.getPort() + 1; + private static final int db = 2; + private static final int dbAuth = 3; + private static final int timeout = Protocol.DEFAULT_TIMEOUT; + + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + + dest = new Jedis(host, port, 500); + dest.flushAll(); + dest.select(db); + + destAuth = new Jedis(host, portAuth, 500); + destAuth.auth("foobared"); + destAuth.flushAll(); + destAuth.select(dbAuth); + } + + @After + @Override + public void tearDown() throws Exception { + dest.close(); + destAuth.close(); + super.tearDown(); + } + + @Test + public void nokey() { + assertEquals("NOKEY", jedis.migrate(host, port, "foo", db, timeout)); + assertEquals("NOKEY", jedis.migrate(host, port, bfoo, db, timeout)); + assertEquals("NOKEY", + jedis.migrate(host, port, db, timeout, new MigrateParams(), "foo1", "foo2", "foo3")); + assertEquals("NOKEY", + jedis.migrate(host, port, db, timeout, new MigrateParams(), bfoo1, bfoo2, bfoo3)); + } + + @Test + public void migrate() { + jedis.set("foo", "bar"); + assertEquals("OK", jedis.migrate(host, port, "foo", db, timeout)); + assertEquals("bar", dest.get("foo")); + assertNull(jedis.get("foo")); + + jedis.set(bfoo, bbar); + assertEquals("OK", jedis.migrate(host, port, bfoo, db, timeout)); + assertArrayEquals(bbar, dest.get(bfoo)); + assertNull(jedis.get(bfoo)); + } + + @Test + public void migrateEmptyParams() { + jedis.set("foo", "bar"); + assertEquals("OK", jedis.migrate(host, port, db, timeout, new MigrateParams(), "foo")); + assertEquals("bar", dest.get("foo")); + assertNull(jedis.get("foo")); + + jedis.set(bfoo, bbar); + assertEquals("OK", jedis.migrate(host, port, db, timeout, new MigrateParams(), bfoo)); + assertArrayEquals(bbar, dest.get(bfoo)); + assertNull(jedis.get(bfoo)); + } + + @Test + public void migrateCopy() { + jedis.set("foo", "bar"); + assertEquals("OK", jedis.migrate(host, port, db, timeout, new MigrateParams().copy(), "foo")); + assertEquals("bar", dest.get("foo")); + assertEquals("bar", jedis.get("foo")); + + jedis.set(bfoo, bbar); + assertEquals("OK", jedis.migrate(host, port, db, timeout, new MigrateParams().copy(), bfoo)); + assertArrayEquals(bbar, dest.get(bfoo)); + assertArrayEquals(bbar, jedis.get(bfoo)); + } + + @Test + public void migrateReplace() { + jedis.set("foo", "bar1"); + dest.set("foo", "bar2"); + assertEquals("OK", jedis.migrate(host, port, db, timeout, new MigrateParams().replace(), "foo")); + assertEquals("bar1", dest.get("foo")); + assertNull(jedis.get("foo")); + + jedis.set(bfoo, bbar1); + dest.set(bfoo, bbar2); + assertEquals("OK", jedis.migrate(host, port, db, timeout, new MigrateParams().replace(), bfoo)); + assertArrayEquals(bbar1, dest.get(bfoo)); + assertNull(jedis.get(bfoo)); + } + + @Test + public void migrateCopyReplace() { + jedis.set("foo", "bar1"); + dest.set("foo", "bar2"); + assertEquals("OK", + jedis.migrate(host, port, db, timeout, new MigrateParams().copy().replace(), "foo")); + assertEquals("bar1", dest.get("foo")); + assertEquals("bar1", jedis.get("foo")); + + jedis.set(bfoo, bbar1); + dest.set(bfoo, bbar2); + assertEquals("OK", + jedis.migrate(host, port, db, timeout, new MigrateParams().copy().replace(), bfoo)); + assertArrayEquals(bbar1, dest.get(bfoo)); + assertArrayEquals(bbar1, jedis.get(bfoo)); + } + + @Test + public void migrateAuth() { + jedis.set("foo", "bar"); + assertEquals("OK", + jedis.migrate(host, portAuth, dbAuth, timeout, new MigrateParams().auth("foobared"), "foo")); + assertEquals("bar", destAuth.get("foo")); + assertNull(jedis.get("foo")); + + jedis.set(bfoo, bbar); + assertEquals("OK", + jedis.migrate(host, portAuth, dbAuth, timeout, new MigrateParams().auth("foobared"), bfoo)); + assertArrayEquals(bbar, destAuth.get(bfoo)); + assertNull(jedis.get(bfoo)); + } + + @Test + public void migrateAuth2() { + destAuth.set("foo", "bar"); + assertEquals("OK", destAuth.migrate(host, hnp.getPort(), 0, timeout, + new MigrateParams().auth2("acljedis", "fizzbuzz"), "foo")); + assertEquals("bar", jedis.get("foo")); + assertNull(destAuth.get("foo")); + + // binary + dest.set(bfoo1, bbar1); + assertEquals("OK", dest.migrate(host, hnp.getPort(), 0, timeout, + new MigrateParams().auth2("acljedis", "fizzbuzz"), bfoo1)); + assertArrayEquals(bbar1, jedis.get(bfoo1)); + assertNull(dest.get(bfoo1)); + } + + @Test + public void migrateCopyReplaceAuth() { + jedis.set("foo", "bar1"); + destAuth.set("foo", "bar2"); + assertEquals( + "OK", + jedis.migrate(host, portAuth, dbAuth, timeout, + new MigrateParams().copy().replace().auth("foobared"), "foo")); + assertEquals("bar1", destAuth.get("foo")); + assertEquals("bar1", jedis.get("foo")); + + jedis.set(bfoo, bbar1); + destAuth.set(bfoo, bbar2); + assertEquals( + "OK", + jedis.migrate(host, portAuth, dbAuth, timeout, + new MigrateParams().copy().replace().auth("foobared"), bfoo)); + assertArrayEquals(bbar1, destAuth.get(bfoo)); + assertArrayEquals(bbar1, jedis.get(bfoo)); + } + + @Test + public void migrateMulti() { + jedis.mset("foo1", "bar1", "foo2", "bar2", "foo3", "bar3"); + assertEquals("OK", + jedis.migrate(host, port, db, timeout, new MigrateParams(), "foo1", "foo2", "foo3")); + assertEquals("bar1", dest.get("foo1")); + assertEquals("bar2", dest.get("foo2")); + assertEquals("bar3", dest.get("foo3")); + + jedis.mset(bfoo1, bbar1, bfoo2, bbar2, bfoo3, bbar3); + assertEquals("OK", + jedis.migrate(host, port, db, timeout, new MigrateParams(), bfoo1, bfoo2, bfoo3)); + assertArrayEquals(bbar1, dest.get(bfoo1)); + assertArrayEquals(bbar2, dest.get(bfoo2)); + assertArrayEquals(bbar3, dest.get(bfoo3)); + } + + @Test + public void migrateConflict() { + jedis.mset("foo1", "bar1", "foo2", "bar2", "foo3", "bar3"); + dest.set("foo2", "bar"); + try { + jedis.migrate(host, port, db, timeout, new MigrateParams(), "foo1", "foo2", "foo3"); + fail("Should get BUSYKEY error"); + } catch (JedisDataException jde) { + assertTrue(jde.getMessage().contains("BUSYKEY")); + } + assertEquals("bar1", dest.get("foo1")); + assertEquals("bar", dest.get("foo2")); + assertEquals("bar3", dest.get("foo3")); + + jedis.mset(bfoo1, bbar1, bfoo2, bbar2, bfoo3, bbar3); + dest.set(bfoo2, bbar); + try { + jedis.migrate(host, port, db, timeout, new MigrateParams(), bfoo1, bfoo2, bfoo3); + fail("Should get BUSYKEY error"); + } catch (JedisDataException jde) { + assertTrue(jde.getMessage().contains("BUSYKEY")); + } + assertArrayEquals(bbar1, dest.get(bfoo1)); + assertArrayEquals(bbar, dest.get(bfoo2)); + assertArrayEquals(bbar3, dest.get(bfoo3)); + } + +} diff --git a/src/test/java/redis/clients/jedis/tests/commands/ObjectCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ObjectCommandsTest.java index 0a6e600541..8847aa6867 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ObjectCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ObjectCommandsTest.java @@ -1,110 +1,110 @@ -//package redis.clients.jedis.tests.commands; -// -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertNotNull; -//import static org.junit.Assert.assertNull; -//import static org.junit.Assert.assertTrue; -//import static org.junit.Assert.fail; -// -//import org.junit.After; -//import org.junit.Before; -//import org.junit.Test; -// -//import redis.clients.jedis.HostAndPort; -//import redis.clients.jedis.Jedis; -//import redis.clients.jedis.exceptions.JedisDataException; -//import redis.clients.jedis.tests.HostAndPortUtil; -//import redis.clients.jedis.util.SafeEncoder; -// -//import java.util.List; -// -//public class ObjectCommandsTest extends JedisCommandTestBase { -// -// private String key = "mylist"; -// private byte[] binaryKey = SafeEncoder.encode(key); -// private static final HostAndPort lfuHnp = HostAndPortUtil.getRedisServers().get(7); -// private Jedis lfuJedis; -// -// @Before -// public void setUp() throws Exception { -// super.setUp(); -// -// lfuJedis = new Jedis(lfuHnp.getHost(), lfuHnp.getPort(), 500); -// lfuJedis.connect(); -// lfuJedis.flushAll(); -// } -// -// @After -// public void tearDown() throws Exception { -// lfuJedis.disconnect(); -// super.tearDown(); -// } -// -// @Test -// public void objectRefcount() { -// jedis.lpush(key, "hello world"); -// Long refcount = jedis.objectRefcount(key); -// assertEquals(new Long(1), refcount); -// -// // Binary -// refcount = jedis.objectRefcount(binaryKey); -// assertEquals(new Long(1), refcount); -// -// } -// -// @Test -// public void objectEncoding() { -// jedis.lpush(key, "hello world"); -// String encoding = jedis.objectEncoding(key); -// assertEquals("quicklist", encoding); -// -// // Binary -// encoding = SafeEncoder.encode(jedis.objectEncoding(binaryKey)); -// assertEquals("quicklist", encoding); -// } -// -// @Test -// public void objectIdletime() throws InterruptedException { -// jedis.lpush(key, "hello world"); -// -// Long time = jedis.objectIdletime(key); -// assertEquals(new Long(0), time); -// -// // Binary -// time = jedis.objectIdletime(binaryKey); -// assertEquals(new Long(0), time); -// } -// -// @Test -// public void objectHelp() { -// // String -// List helpTexts = jedis.objectHelp(); -// assertNotNull(helpTexts); -// -// // Binary -// List helpBinaryTexts = jedis.objectHelpBinary(); -// assertNotNull(helpBinaryTexts); -// } -// -// @Test -// public void objectFreq() { -// lfuJedis.set(key, "test1"); -// lfuJedis.get(key); -// // String -// Long count = lfuJedis.objectFreq(key); -// assertTrue(count > 0); -// -// // Binary -// count = lfuJedis.objectFreq(binaryKey); -// assertTrue(count > 0); -// -// assertNull(lfuJedis.objectFreq("no_such_key")); -// -// try { -// jedis.set(key, "test2"); -// jedis.objectFreq(key); -// fail("Freq is only allowed with LFU policy"); -// } catch (JedisDataException e) { -// } -// } -//} +package redis.clients.jedis.tests.commands; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.tests.HostAndPortUtil; +import redis.clients.jedis.util.SafeEncoder; + +import java.util.List; + +public class ObjectCommandsTest extends JedisCommandTestBase { + + private String key = "mylist"; + private byte[] binaryKey = SafeEncoder.encode(key); + private static final HostAndPort lfuHnp = HostAndPortUtil.getRedisServers().get(7); + private Jedis lfuJedis; + + @Before + public void setUp() throws Exception { + super.setUp(); + + lfuJedis = new Jedis(lfuHnp.getHost(), lfuHnp.getPort(), 500); + lfuJedis.connect(); + lfuJedis.flushAll(); + } + + @After + public void tearDown() throws Exception { + lfuJedis.disconnect(); + super.tearDown(); + } + + @Test + public void objectRefcount() { + jedis.lpush(key, "hello world"); + Long refcount = jedis.objectRefcount(key); + assertEquals(new Long(1), refcount); + + // Binary + refcount = jedis.objectRefcount(binaryKey); + assertEquals(new Long(1), refcount); + + } + + @Test + public void objectEncoding() { + jedis.lpush(key, "hello world"); + String encoding = jedis.objectEncoding(key); + assertEquals("quicklist", encoding); + + // Binary + encoding = SafeEncoder.encode(jedis.objectEncoding(binaryKey)); + assertEquals("quicklist", encoding); + } + + @Test + public void objectIdletime() throws InterruptedException { + jedis.lpush(key, "hello world"); + + Long time = jedis.objectIdletime(key); + assertEquals(new Long(0), time); + + // Binary + time = jedis.objectIdletime(binaryKey); + assertEquals(new Long(0), time); + } + + @Test + public void objectHelp() { + // String + List helpTexts = jedis.objectHelp(); + assertNotNull(helpTexts); + + // Binary + List helpBinaryTexts = jedis.objectHelpBinary(); + assertNotNull(helpBinaryTexts); + } + + @Test + public void objectFreq() { + lfuJedis.set(key, "test1"); + lfuJedis.get(key); + // String + Long count = lfuJedis.objectFreq(key); + assertTrue(count > 0); + + // Binary + count = lfuJedis.objectFreq(binaryKey); + assertTrue(count > 0); + + assertNull(lfuJedis.objectFreq("no_such_key")); + + try { + jedis.set(key, "test2"); + jedis.objectFreq(key); + fail("Freq is only allowed with LFU policy"); + } catch (JedisDataException e) { + } + } +} diff --git a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java index a53faab2df..4f7f783c79 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java @@ -16,12 +16,12 @@ import org.hamcrest.Matcher; import org.junit.Test; -//import redis.clients.jedis.Jedis; -import redis.clients.jedis.UnifiedJedis; +import redis.clients.jedis.Jedis; import redis.clients.jedis.args.FlushMode; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisNoScriptException; +import redis.clients.jedis.tests.utils.ClientKillerUtil; import redis.clients.jedis.util.SafeEncoder; public class ScriptingCommandsTest extends JedisCommandTestBase { @@ -161,66 +161,66 @@ public void evalshaBinary() { public void evalshaShaNotFound() { jedis.evalsha("ffffffffffffffffffffffffffffffffffffffff"); } -// -// @Test -// public void scriptFlush() { -// jedis.set("foo", "bar"); -// jedis.eval("return redis.call('get','foo')"); -// jedis.scriptFlush(); -// assertFalse(jedis.scriptExists("6b1bf486c81ceb7edf3c093f4c48582e38c0e791")); -// } -// -// @Test -// public void scriptFlushMode() { -// jedis.set("foo", "bar"); -// jedis.eval("return redis.call('get','foo')"); -// String sha1 = "6b1bf486c81ceb7edf3c093f4c48582e38c0e791"; -// assertTrue(jedis.scriptExists(sha1)); -// jedis.scriptFlush(FlushMode.SYNC); -// assertFalse(jedis.scriptExists(sha1)); -// } -// -// @Test -// public void scriptExists() { -// jedis.scriptLoad("return redis.call('get','foo')"); -// List exists = jedis.scriptExists("ffffffffffffffffffffffffffffffffffffffff", -// "6b1bf486c81ceb7edf3c093f4c48582e38c0e791"); -// assertFalse(exists.get(0)); -// assertTrue(exists.get(1)); -// } -// -// @Test -// public void scriptExistsBinary() { -// jedis.scriptLoad(SafeEncoder.encode("return redis.call('get','foo')")); -// List exists = jedis.scriptExists( -// SafeEncoder.encode("ffffffffffffffffffffffffffffffffffffffff"), -// SafeEncoder.encode("6b1bf486c81ceb7edf3c093f4c48582e38c0e791")); -// assertEquals(new Long(0), exists.get(0)); -// assertEquals(new Long(1), exists.get(1)); -// } -// -// @Test -// public void scriptLoad() { -// jedis.scriptLoad("return redis.call('get','foo')"); -// assertTrue(jedis.scriptExists("6b1bf486c81ceb7edf3c093f4c48582e38c0e791")); -// } -// -// @Test -// public void scriptLoadBinary() { -// jedis.scriptLoad(SafeEncoder.encode("return redis.call('get','foo')")); -// Long exists = jedis -// .scriptExists(SafeEncoder.encode("6b1bf486c81ceb7edf3c093f4c48582e38c0e791")); -// assertEquals((Long) 1L, exists); -// } -// -// @Test -// public void scriptKill() { -// try { -// jedis.scriptKill(); -// } catch (JedisDataException e) { -// assertTrue(e.getMessage().contains("No scripts in execution right now.")); -// } -// } + + @Test + public void scriptFlush() { + jedis.set("foo", "bar"); + jedis.eval("return redis.call('get','foo')"); + jedis.scriptFlush(); + assertFalse(jedis.scriptExists("6b1bf486c81ceb7edf3c093f4c48582e38c0e791")); + } + + @Test + public void scriptFlushMode() { + jedis.set("foo", "bar"); + jedis.eval("return redis.call('get','foo')"); + String sha1 = "6b1bf486c81ceb7edf3c093f4c48582e38c0e791"; + assertTrue(jedis.scriptExists(sha1)); + jedis.scriptFlush(FlushMode.SYNC); + assertFalse(jedis.scriptExists(sha1)); + } + + @Test + public void scriptExists() { + jedis.scriptLoad("return redis.call('get','foo')"); + List exists = jedis.scriptExists("ffffffffffffffffffffffffffffffffffffffff", + "6b1bf486c81ceb7edf3c093f4c48582e38c0e791"); + assertFalse(exists.get(0)); + assertTrue(exists.get(1)); + } + + @Test + public void scriptExistsBinary() { + jedis.scriptLoad(SafeEncoder.encode("return redis.call('get','foo')")); + List exists = jedis.scriptExists( + SafeEncoder.encode("ffffffffffffffffffffffffffffffffffffffff"), + SafeEncoder.encode("6b1bf486c81ceb7edf3c093f4c48582e38c0e791")); + assertFalse(exists.get(0)); + assertTrue(exists.get(1)); + } + + @Test + public void scriptLoad() { + jedis.scriptLoad("return redis.call('get','foo')"); + assertTrue(jedis.scriptExists("6b1bf486c81ceb7edf3c093f4c48582e38c0e791")); + } + + @Test + public void scriptLoadBinary() { + jedis.scriptLoad(SafeEncoder.encode("return redis.call('get','foo')")); + Boolean exists = jedis + .scriptExists(SafeEncoder.encode("6b1bf486c81ceb7edf3c093f4c48582e38c0e791")); + assertTrue(exists); + } + + @Test + public void scriptKill() { + try { + jedis.scriptKill(); + } catch (JedisDataException e) { + assertTrue(e.getMessage().contains("No scripts in execution right now.")); + } + } @Test public void scriptEvalReturnNullValues() { @@ -233,66 +233,67 @@ public void scriptEvalReturnNullValues() { assertNull(results.get(0)); assertNull(results.get(1)); } -// -// @Test -// public void scriptEvalShaReturnNullValues() { -// jedis.del("key1"); -// jedis.del("key2"); -// -// String script = "return {redis.call('hget',KEYS[1],ARGV[1]),redis.call('hget',KEYS[2],ARGV[2])}"; -// String sha = jedis.scriptLoad(script); -// List results = (List) jedis.evalsha(sha, 2, "key1", "key2", "1", "2"); -// assertEquals(2, results.size()); -// assertNull(results.get(0)); -// assertNull(results.get(1)); -// } -// -// @Test -// public void scriptEvalShaReturnValues() { -// jedis.hset("foo", "foo1", "bar1"); -// jedis.hset("foobar", "foo2", "bar2"); -// -// String script = "return {redis.call('hget',KEYS[1],ARGV[1]),redis.call('hget',KEYS[2],ARGV[2])}"; -// String sha = jedis.scriptLoad(script); -// List results = (List) jedis.evalsha(sha, Arrays.asList("foo", "foobar"), Arrays.asList("foo1", "foo2")); -// assertEquals(2, results.size()); -// assertEquals("bar1", results.get(0)); -// assertEquals("bar2", results.get(1)); -// } -// -// @Test -// public void scriptEvalShaReturnValuesBinary() { -// jedis.hset(bfoo, bfoo1, bbar1); -// jedis.hset(bfoobar, bfoo2, bbar2); -// -// byte[] script = "return {redis.call('hget',KEYS[1],ARGV[1]),redis.call('hget',KEYS[2],ARGV[2])}".getBytes(); -// byte[] sha = jedis.scriptLoad(script); -// List results = (List) jedis.evalsha(sha, Arrays.asList(bfoo, bfoobar), Arrays.asList(bfoo1, bfoo2)); -// assertEquals(2, results.size()); -// assertArrayEquals(bbar1, results.get(0)); -// assertArrayEquals(bbar2, results.get(1)); -// } -// -// @Test -// public void scriptExistsWithBrokenConnection() { + + @Test + public void scriptEvalShaReturnNullValues() { + jedis.del("key1"); + jedis.del("key2"); + + String script = "return {redis.call('hget',KEYS[1],ARGV[1]),redis.call('hget',KEYS[2],ARGV[2])}"; + String sha = jedis.scriptLoad(script); + List results = (List) jedis.evalsha(sha, 2, "key1", "key2", "1", "2"); + assertEquals(2, results.size()); + assertNull(results.get(0)); + assertNull(results.get(1)); + } + + @Test + public void scriptEvalShaReturnValues() { + jedis.hset("foo", "foo1", "bar1"); + jedis.hset("foobar", "foo2", "bar2"); + + String script = "return {redis.call('hget',KEYS[1],ARGV[1]),redis.call('hget',KEYS[2],ARGV[2])}"; + String sha = jedis.scriptLoad(script); + List results = (List) jedis.evalsha(sha, Arrays.asList("foo", "foobar"), Arrays.asList("foo1", "foo2")); + assertEquals(2, results.size()); + assertEquals("bar1", results.get(0)); + assertEquals("bar2", results.get(1)); + } + + @Test + public void scriptEvalShaReturnValuesBinary() { + jedis.hset(bfoo, bfoo1, bbar1); + jedis.hset(bfoobar, bfoo2, bbar2); + + byte[] script = "return {redis.call('hget',KEYS[1],ARGV[1]),redis.call('hget',KEYS[2],ARGV[2])}".getBytes(); + byte[] sha = jedis.scriptLoad(script); + List results = (List) jedis.evalsha(sha, Arrays.asList(bfoo, bfoobar), Arrays.asList(bfoo1, bfoo2)); + assertEquals(2, results.size()); + assertArrayEquals(bbar1, results.get(0)); + assertArrayEquals(bbar2, results.get(1)); + } + + @Test + public void scriptExistsWithBrokenConnection() { // Jedis deadClient = new Jedis(jedis.getClient().getHost(), jedis.getClient().getPort()); // deadClient.auth("foobared"); -// -// deadClient.clientSetname("DEAD"); -// -// ClientKillerUtil.killClient(deadClient, "DEAD"); -// -// // sure, script doesn't exist, but it's just for checking connection -// try { -// deadClient.scriptExists("abcdefg"); -// } catch (JedisConnectionException e) { -// // ignore it -// } -// -// assertEquals(true, deadClient.isBroken()); -// -// deadClient.close(); -// } + Jedis deadClient = createJedis(); + + deadClient.clientSetname("DEAD"); + + ClientKillerUtil.killClient(deadClient, "DEAD"); + + // sure, script doesn't exist, but it's just for checking connection + try { + deadClient.scriptExists("abcdefg"); + } catch (JedisConnectionException e) { + // ignore it + } + + assertEquals(true, deadClient.isBroken()); + + deadClient.close(); + } private Matcher> listWithItem(T expected) { return CoreMatchers. hasItem(equalTo(expected)); diff --git a/src/test/java/redis/clients/jedis/tests/commands/SlowlogCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/SlowlogCommandsTest.java index aa7a5fd913..df702ec96e 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SlowlogCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SlowlogCommandsTest.java @@ -1,109 +1,109 @@ -//package redis.clients.jedis.tests.commands; -// -//import static org.junit.Assert.assertArrayEquals; -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertNotNull; -//import static org.junit.Assert.assertTrue; -// -//import java.util.List; -//import org.junit.After; -//import org.junit.Before; -//import org.junit.Test; -// -//import redis.clients.jedis.Protocol; -//import redis.clients.jedis.util.SafeEncoder; -//import redis.clients.jedis.util.Slowlog; -// -//public class SlowlogCommandsTest extends JedisCommandTestBase { -// -// private static final String SLOWLOG_TIME_PARAM = "slowlog-log-slower-than"; -// private static final String ZERO = "0"; -// private String slowlogTimeValue; -// -// @Before -// @Override -// public void setUp() throws Exception { -// super.setUp(); -// slowlogTimeValue = jedis.configGet(SLOWLOG_TIME_PARAM).get(1); -// } -// -// @After -// @Override -// public void tearDown() throws Exception { -// jedis.configSet(SLOWLOG_TIME_PARAM, slowlogTimeValue); -// super.tearDown(); -// } -// -// @Test -// public void slowlog() { -// jedis.configSet(SLOWLOG_TIME_PARAM, ZERO); -// jedis.set("foo", "bar"); -// jedis.set("foo2", "bar2"); -// -// List reducedLog = jedis.slowlogGet(1); -// assertEquals(1, reducedLog.size()); -// -// Slowlog log = reducedLog.get(0); -// assertTrue(log.getId() > 0); -// assertTrue(log.getTimeStamp() > 0); -// assertTrue(log.getExecutionTime() >= 0); -// assertNotNull(log.getArgs()); -// -// List breducedLog = jedis.slowlogGetBinary(1); -// assertEquals(1, breducedLog.size()); -// -// List log1 = jedis.slowlogGet(); -// List blog1 = jedis.slowlogGetBinary(); -// -// assertNotNull(log1); -// assertNotNull(blog1); -// -// assertEquals(7, jedis.slowlogLen()); -// } -// -// @Test -// public void slowlogObjectDetails() { -// final String clientName = "slowlog-object-client"; -// jedis.clientSetname(clientName); -// jedis.slowlogReset(); -// jedis.configSet(SLOWLOG_TIME_PARAM, ZERO); -// -// List logs = jedis.slowlogGet(); // Get only 'CONFIG SET' -// assertEquals(1, logs.size()); -// Slowlog log = logs.get(0); -// assertTrue(log.getId() > 0); -// assertTrue(log.getTimeStamp() > 0); -// assertTrue(log.getExecutionTime() > 0); -// assertEquals(4, log.getArgs().size()); -// assertEquals(SafeEncoder.encode(Protocol.Command.CONFIG.getRaw()), log.getArgs().get(0)); -// assertEquals(SafeEncoder.encode(Protocol.Keyword.SET.getRaw()), log.getArgs().get(1)); -// assertEquals(SLOWLOG_TIME_PARAM, log.getArgs().get(2)); -// assertEquals(ZERO, log.getArgs().get(3)); -// assertEquals("127.0.0.1", log.getClientIpPort().getHost()); -// assertTrue(log.getClientIpPort().getPort() > 0); -// assertEquals(clientName, log.getClientName()); -// } -// -// @Test -// public void slowlogBinaryDetails() { -// final byte[] clientName = SafeEncoder.encode("slowlog-binary-client"); -// jedis.clientSetname(clientName); -// jedis.slowlogReset(); -// jedis.configSet(SafeEncoder.encode(SLOWLOG_TIME_PARAM), SafeEncoder.encode(ZERO)); -// -// List logs = jedis.slowlogGetBinary(); // Get only 'CONFIG SET' -// assertEquals(1, logs.size()); -// List log = (List) logs.get(0); -// assertTrue((Long) log.get(0) > 0); -// assertTrue((Long) log.get(1) > 0); -// assertTrue((Long) log.get(2) > 0); -// List args = (List) log.get(3); -// assertEquals(4, args.size()); -// assertArrayEquals(Protocol.Command.CONFIG.getRaw(), (byte[]) args.get(0)); -// assertArrayEquals(Protocol.Keyword.SET.getRaw(), (byte[]) args.get(1)); -// assertArrayEquals(SafeEncoder.encode(SLOWLOG_TIME_PARAM), (byte[]) args.get(2)); -// assertArrayEquals(Protocol.toByteArray(0), (byte[]) args.get(3)); -// assertTrue(SafeEncoder.encode((byte[]) log.get(4)).startsWith("127.0.0.1:")); -// assertArrayEquals(clientName, (byte[]) log.get(5)); -// } -//} \ No newline at end of file +package redis.clients.jedis.tests.commands; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import redis.clients.jedis.Protocol; +import redis.clients.jedis.resps.Slowlog; +import redis.clients.jedis.util.SafeEncoder; + +public class SlowlogCommandsTest extends JedisCommandTestBase { + + private static final String SLOWLOG_TIME_PARAM = "slowlog-log-slower-than"; + private static final String ZERO = "0"; + private String slowlogTimeValue; + + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + slowlogTimeValue = jedis.configGet(SLOWLOG_TIME_PARAM).get(1); + } + + @After + @Override + public void tearDown() throws Exception { + jedis.configSet(SLOWLOG_TIME_PARAM, slowlogTimeValue); + super.tearDown(); + } + + @Test + public void slowlog() { + jedis.configSet(SLOWLOG_TIME_PARAM, ZERO); + jedis.set("foo", "bar"); + jedis.set("foo2", "bar2"); + + List reducedLog = jedis.slowlogGet(1); + assertEquals(1, reducedLog.size()); + + Slowlog log = reducedLog.get(0); + assertTrue(log.getId() > 0); + assertTrue(log.getTimeStamp() > 0); + assertTrue(log.getExecutionTime() >= 0); + assertNotNull(log.getArgs()); + + List breducedLog = jedis.slowlogGetBinary(1); + assertEquals(1, breducedLog.size()); + + List log1 = jedis.slowlogGet(); + List blog1 = jedis.slowlogGetBinary(); + + assertNotNull(log1); + assertNotNull(blog1); + + assertEquals(7, jedis.slowlogLen()); + } + + @Test + public void slowlogObjectDetails() { + final String clientName = "slowlog-object-client"; + jedis.clientSetname(clientName); + jedis.slowlogReset(); + jedis.configSet(SLOWLOG_TIME_PARAM, ZERO); + + List logs = jedis.slowlogGet(); // Get only 'CONFIG SET' + assertEquals(1, logs.size()); + Slowlog log = logs.get(0); + assertTrue(log.getId() > 0); + assertTrue(log.getTimeStamp() > 0); + assertTrue(log.getExecutionTime() > 0); + assertEquals(4, log.getArgs().size()); + assertEquals(SafeEncoder.encode(Protocol.Command.CONFIG.getRaw()), log.getArgs().get(0)); + assertEquals(SafeEncoder.encode(Protocol.Keyword.SET.getRaw()), log.getArgs().get(1)); + assertEquals(SLOWLOG_TIME_PARAM, log.getArgs().get(2)); + assertEquals(ZERO, log.getArgs().get(3)); + assertEquals("127.0.0.1", log.getClientIpPort().getHost()); + assertTrue(log.getClientIpPort().getPort() > 0); + assertEquals(clientName, log.getClientName()); + } + + @Test + public void slowlogBinaryDetails() { + final byte[] clientName = SafeEncoder.encode("slowlog-binary-client"); + jedis.clientSetname(clientName); + jedis.slowlogReset(); + jedis.configSet(SafeEncoder.encode(SLOWLOG_TIME_PARAM), SafeEncoder.encode(ZERO)); + + List logs = jedis.slowlogGetBinary(); // Get only 'CONFIG SET' + assertEquals(1, logs.size()); + List log = (List) logs.get(0); + assertTrue((Long) log.get(0) > 0); + assertTrue((Long) log.get(1) > 0); + assertTrue((Long) log.get(2) > 0); + List args = (List) log.get(3); + assertEquals(4, args.size()); + assertArrayEquals(Protocol.Command.CONFIG.getRaw(), (byte[]) args.get(0)); + assertArrayEquals(Protocol.Keyword.SET.getRaw(), (byte[]) args.get(1)); + assertArrayEquals(SafeEncoder.encode(SLOWLOG_TIME_PARAM), (byte[]) args.get(2)); + assertArrayEquals(Protocol.toByteArray(0), (byte[]) args.get(3)); + assertTrue(SafeEncoder.encode((byte[]) log.get(4)).startsWith("127.0.0.1:")); + assertArrayEquals(clientName, (byte[]) log.get(5)); + } +} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/StreamsCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/StreamsCommandsTest.java index 031b4a4203..39c55fb3e3 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/StreamsCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/StreamsCommandsTest.java @@ -23,22 +23,14 @@ import redis.clients.jedis.BuilderFactory; import redis.clients.jedis.Jedis; +import redis.clients.jedis.Pipeline; import redis.clients.jedis.Protocol.Keyword; +import redis.clients.jedis.Response; +import redis.clients.jedis.Transaction; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisException; -import redis.clients.jedis.params.XAddParams; -import redis.clients.jedis.params.XAutoClaimParams; -import redis.clients.jedis.params.XClaimParams; -import redis.clients.jedis.params.XPendingParams; -import redis.clients.jedis.params.XReadGroupParams; -import redis.clients.jedis.params.XReadParams; -import redis.clients.jedis.params.XTrimParams; -import redis.clients.jedis.stream.StreamConsumersInfo; -import redis.clients.jedis.stream.StreamEntry; -import redis.clients.jedis.stream.StreamEntryID; -import redis.clients.jedis.stream.StreamGroupInfo; -import redis.clients.jedis.stream.StreamInfo; -import redis.clients.jedis.stream.StreamPendingEntry; +import redis.clients.jedis.params.*; +import redis.clients.jedis.stream.*; import redis.clients.jedis.util.SafeEncoder; public class StreamsCommandsTest extends JedisCommandTestBase { @@ -739,45 +731,45 @@ public void xinfo() throws InterruptedException { } } -// -// @Test -// public void pipeline() { -// Map map = new HashMap<>(); -// map.put("a", "b"); -// Pipeline p = jedis.pipelined(); -// Response id1 = p.xadd("stream1", StreamEntryID.NEW_ENTRY, map); -// Response id2 = p.xadd("stream1", StreamEntryID.NEW_ENTRY, map); -// Response> results = p.xrange("stream1", null, null, 2); -// p.sync(); -// -// List entries = results.get(); -// assertEquals(2, entries.size()); -// assertEquals(id1.get(), entries.get(0).getID()); -// assertEquals(map, entries.get(0).getFields()); -// assertEquals(id2.get(), entries.get(1).getID()); -// assertEquals(map, entries.get(1).getFields()); -// -// p = jedis.pipelined(); -// Response> results2 = p.xrevrange("stream1", null, id1.get(), 2); -// p.sync(); -// assertEquals(2, results2.get().size()); -// } -// -// @Test -// public void transaction() { -// Map map = new HashMap<>(); -// map.put("a", "b"); -// Transaction t = jedis.multi(); -// Response id1 = t.xadd("stream1", StreamEntryID.NEW_ENTRY, map); -// Response id2 = t.xadd("stream1", StreamEntryID.NEW_ENTRY, map); -// Response> results = t.xrange("stream1", null, null, 2); -// t.exec(); -// -// List entries = results.get(); -// assertEquals(2, entries.size()); -// assertEquals(id1.get(), entries.get(0).getID()); -// assertEquals(map, entries.get(0).getFields()); -// assertEquals(id2.get(), entries.get(1).getID()); -// assertEquals(map, entries.get(1).getFields()); -// } + + @Test + public void pipeline() { + Map map = new HashMap<>(); + map.put("a", "b"); + Pipeline p = jedis.pipelined(); + Response id1 = p.xadd("stream1", StreamEntryID.NEW_ENTRY, map); + Response id2 = p.xadd("stream1", StreamEntryID.NEW_ENTRY, map); + Response> results = p.xrange("stream1", null, null, 2); + p.sync(); + + List entries = results.get(); + assertEquals(2, entries.size()); + assertEquals(id1.get(), entries.get(0).getID()); + assertEquals(map, entries.get(0).getFields()); + assertEquals(id2.get(), entries.get(1).getID()); + assertEquals(map, entries.get(1).getFields()); + + p = jedis.pipelined(); + Response> results2 = p.xrevrange("stream1", null, id1.get(), 2); + p.sync(); + assertEquals(2, results2.get().size()); + } + + @Test + public void transaction() { + Map map = new HashMap<>(); + map.put("a", "b"); + Transaction t = jedis.multi(); + Response id1 = t.xadd("stream1", StreamEntryID.NEW_ENTRY, map); + Response id2 = t.xadd("stream1", StreamEntryID.NEW_ENTRY, map); + Response> results = t.xrange("stream1", null, null, 2); + t.exec(); + + List entries = results.get(); + assertEquals(2, entries.size()); + assertEquals(id1.get(), entries.get(0).getID()); + assertEquals(map, entries.get(0).getFields()); + assertEquals(id2.get(), entries.get(1).getID()); + assertEquals(map, entries.get(1).getFields()); + } } diff --git a/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java index cef47258c6..b75630cb04 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java @@ -1,244 +1,248 @@ -//package redis.clients.jedis.tests.commands; -// -//import static org.junit.Assert.assertArrayEquals; -//import static org.junit.Assert.assertEquals; -//import static org.junit.Assert.assertNotNull; -//import static org.junit.Assert.assertNull; -//import static org.junit.Assert.assertSame; -//import static org.junit.Assert.assertTrue; -//import static org.junit.Assert.fail; -//import static redis.clients.jedis.Protocol.Command.*; -// -//import java.io.IOException; -//import java.net.UnknownHostException; -//import java.util.ArrayList; -//import java.util.List; -//import java.util.Set; -//import org.junit.After; -// -//import org.junit.Before; -//import org.junit.Test; -// -//import redis.clients.jedis.DefaultJedisClientConfig; -//import redis.clients.jedis.Jedis; -//import redis.clients.jedis.Pipeline; -//import redis.clients.jedis.Protocol.Keyword; -//import redis.clients.jedis.Response; -//import redis.clients.jedis.Transaction; -//import redis.clients.jedis.exceptions.JedisDataException; -//import redis.clients.jedis.util.SafeEncoder; -// -//public class TransactionCommandsTest extends JedisCommandTestBase { -// final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; -// final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; -// final byte[] ba = { 0x0A }; -// final byte[] bb = { 0x0B }; -// -// final byte[] bmykey = { 0x42, 0x02, 0x03, 0x04 }; -// -// Jedis nj; -// -// @Before -// @Override -// public void setUp() throws Exception { -// super.setUp(); -// -// nj = new Jedis(hnp, DefaultJedisClientConfig.builder().timeoutMillis(500).password("foobared").build()); -// } -// -// @After -// @Override -// public void tearDown() throws Exception { -// nj.close(); -// super.tearDown(); -// } -// -// @Test -// public void multi() { -// Transaction trans = jedis.multi(); -// -// trans.sadd("foo", "a"); -// trans.sadd("foo", "b"); -// trans.scard("foo"); -// -// List response = trans.exec(); -// -// List expected = new ArrayList(); -// expected.add(1L); -// expected.add(1L); -// expected.add(2L); -// assertEquals(expected, response); -// -// // Binary -// trans = jedis.multi(); -// -// trans.sadd(bfoo, ba); -// trans.sadd(bfoo, bb); -// trans.scard(bfoo); -// -// response = trans.exec(); -// -// expected = new ArrayList(); -// expected.add(1L); -// expected.add(1L); -// expected.add(2L); -// assertEquals(expected, response); -// -// } -// -// @Test -// public void watch() throws UnknownHostException, IOException { -// jedis.watch("mykey", "somekey"); -// Transaction t = jedis.multi(); -// +package redis.clients.jedis.tests.commands; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static redis.clients.jedis.Protocol.Command.*; + +import java.io.IOException; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import org.junit.After; + +import org.junit.Before; +import org.junit.Test; + +import redis.clients.jedis.DefaultJedisClientConfig; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.Pipeline; +import redis.clients.jedis.Protocol.Keyword; +import redis.clients.jedis.Response; +import redis.clients.jedis.Transaction; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.util.SafeEncoder; + +public class TransactionCommandsTest extends JedisCommandTestBase { + final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + final byte[] ba = { 0x0A }; + final byte[] bb = { 0x0B }; + + final byte[] bmykey = { 0x42, 0x02, 0x03, 0x04 }; + + Jedis nj; + + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + + nj = new Jedis(hnp, DefaultJedisClientConfig.builder().timeoutMillis(500).password("foobared").build()); + } + + @After + @Override + public void tearDown() throws Exception { + nj.close(); + super.tearDown(); + } + + @Test + public void multi() { + Transaction trans = jedis.multi(); + + trans.sadd("foo", "a"); + trans.sadd("foo", "b"); + trans.scard("foo"); + + List response = trans.exec(); + + List expected = new ArrayList(); + expected.add(1L); + expected.add(1L); + expected.add(2L); + assertEquals(expected, response); + + // Binary + trans = jedis.multi(); + + trans.sadd(bfoo, ba); + trans.sadd(bfoo, bb); + trans.scard(bfoo); + + response = trans.exec(); + + expected = new ArrayList(); + expected.add(1L); + expected.add(1L); + expected.add(2L); + assertEquals(expected, response); + + } + + @Test + public void watch() throws UnknownHostException, IOException { + jedis.watch("mykey", "somekey"); + Transaction t = jedis.multi(); + // nj.connect(); // nj.auth("foobared"); // nj.set("mykey", "bar"); // nj.disconnect(); -// -// t.set("mykey", "foo"); -// List resp = t.exec(); -// assertNull(resp); -// assertEquals("bar", jedis.get("mykey")); -// -// // Binary -// jedis.watch(bmykey, "foobar".getBytes()); -// t = jedis.multi(); -// + nj.set("mykey", "bar"); + + t.set("mykey", "foo"); + List resp = t.exec(); + assertNull(resp); + assertEquals("bar", jedis.get("mykey")); + + // Binary + jedis.watch(bmykey, "foobar".getBytes()); + t = jedis.multi(); + // nj.connect(); // nj.auth("foobared"); // nj.set(bmykey, bbar); // nj.disconnect(); -// -// t.set(bmykey, bfoo); -// resp = t.exec(); -// assertNull(resp); -// assertArrayEquals(bbar, jedis.get(bmykey)); -// } -// -// @Test -// public void unwatch() { -// jedis.watch("mykey"); -// jedis.get("mykey"); -// String val = "foo"; -// String status = jedis.unwatch(); -// assertEquals("OK", status); -// Transaction t = jedis.multi(); -// + nj.set(bmykey, bbar); + + t.set(bmykey, bfoo); + resp = t.exec(); + assertNull(resp); + assertArrayEquals(bbar, jedis.get(bmykey)); + } + + @Test + public void unwatch() { + jedis.watch("mykey"); + jedis.get("mykey"); + String val = "foo"; + String status = jedis.unwatch(); + assertEquals("OK", status); + Transaction t = jedis.multi(); + // nj.connect(); // nj.auth("foobared"); // nj.set("mykey", "bar"); // nj.disconnect(); -// -// t.set("mykey", val); -// List resp = t.exec(); -// assertEquals(1, resp.size()); -// assertEquals("OK", resp.get(0)); -// -// // Binary -// jedis.watch(bmykey); -// jedis.get(bmykey); -// byte[] bval = bfoo; -// status = jedis.unwatch(); -// assertEquals(Keyword.OK.name(), status); -// t = jedis.multi(); -// + nj.set("mykey", "bar"); + + t.set("mykey", val); + List resp = t.exec(); + assertEquals(1, resp.size()); + assertEquals("OK", resp.get(0)); + + // Binary + jedis.watch(bmykey); + jedis.get(bmykey); + byte[] bval = bfoo; + status = jedis.unwatch(); + assertEquals(Keyword.OK.name(), status); + t = jedis.multi(); + // nj.connect(); // nj.auth("foobared"); // nj.set(bmykey, bbar); // nj.disconnect(); -// -// t.set(bmykey, bval); -// resp = t.exec(); -// assertEquals(1, resp.size()); -// assertEquals("OK", resp.get(0)); -// } -// -// @Test(expected = IllegalStateException.class) -// public void validateWhenInMulti() { -// jedis.multi(); -// jedis.ping(); -// } -// -// @Test -// public void discard() { -// Transaction t = jedis.multi(); -// String status = t.discard(); -// assertEquals("OK", status); -// } -// -// @Test -// public void transactionResponse() { -// jedis.set("string", "foo"); -// jedis.lpush("list", "foo"); -// jedis.hset("hash", "foo", "bar"); -// jedis.zadd("zset", 1, "foo"); -// jedis.sadd("set", "foo"); -// -// Transaction t = jedis.multi(); -// Response string = t.get("string"); -// Response list = t.lpop("list"); -// Response hash = t.hget("hash", "foo"); -// Response> zset = t.zrange("zset", 0, -1); -// Response set = t.spop("set"); -// t.exec(); -// -// assertEquals("foo", string.get()); -// assertEquals("foo", list.get()); -// assertEquals("bar", hash.get()); -// assertEquals("foo", zset.get().iterator().next()); -// assertEquals("foo", set.get()); -// } -// -// @Test -// public void transactionResponseBinary() { -// jedis.set("string", "foo"); -// jedis.lpush("list", "foo"); -// jedis.hset("hash", "foo", "bar"); -// jedis.zadd("zset", 1, "foo"); -// jedis.sadd("set", "foo"); -// -// Transaction t = jedis.multi(); -// Response string = t.get("string".getBytes()); -// Response list = t.lpop("list".getBytes()); -// Response hash = t.hget("hash".getBytes(), "foo".getBytes()); -// Response> zset = t.zrange("zset".getBytes(), 0, -1); -// Response set = t.spop("set".getBytes()); -// t.exec(); -// -// assertArrayEquals("foo".getBytes(), string.get()); -// assertArrayEquals("foo".getBytes(), list.get()); -// assertArrayEquals("bar".getBytes(), hash.get()); -// assertArrayEquals("foo".getBytes(), zset.get().iterator().next()); -// assertArrayEquals("foo".getBytes(), set.get()); -// } -// -// @Test(expected = IllegalStateException.class) -// public void transactionResponseWithinPipeline() { -// jedis.set("string", "foo"); -// -// Transaction t = jedis.multi(); -// Response string = t.get("string"); -// string.get(); -// t.exec(); -// } -// -// @Test -// public void transactionResponseWithError() { -// Transaction t = jedis.multi(); -// t.set("foo", "bar"); -// Response> error = t.smembers("foo"); -// Response r = t.get("foo"); -// List l = t.exec(); -// assertSame(JedisDataException.class, l.get(1).getClass()); -// try { -// error.get(); -// fail("We expect exception here!"); -// } catch (JedisDataException e) { -// // that is fine we should be here -// } -// assertEquals("bar", r.get()); -// } + nj.set(bmykey, bbar); + + t.set(bmykey, bval); + resp = t.exec(); + assertEquals(1, resp.size()); + assertEquals("OK", resp.get(0)); + } + + @Test(expected = IllegalStateException.class) + public void validateWhenInMulti() { + jedis.multi(); + jedis.ping(); + } + + @Test + public void discard() { + Transaction t = jedis.multi(); + String status = t.discard(); + assertEquals("OK", status); + } + + @Test + public void transactionResponse() { + jedis.set("string", "foo"); + jedis.lpush("list", "foo"); + jedis.hset("hash", "foo", "bar"); + jedis.zadd("zset", 1, "foo"); + jedis.sadd("set", "foo"); + + Transaction t = jedis.multi(); + Response string = t.get("string"); + Response list = t.lpop("list"); + Response hash = t.hget("hash", "foo"); + Response> zset = t.zrange("zset", 0, -1); + Response set = t.spop("set"); + t.exec(); + + assertEquals("foo", string.get()); + assertEquals("foo", list.get()); + assertEquals("bar", hash.get()); + assertEquals("foo", zset.get().iterator().next()); + assertEquals("foo", set.get()); + } + + @Test + public void transactionResponseBinary() { + jedis.set("string", "foo"); + jedis.lpush("list", "foo"); + jedis.hset("hash", "foo", "bar"); + jedis.zadd("zset", 1, "foo"); + jedis.sadd("set", "foo"); + + Transaction t = jedis.multi(); + Response string = t.get("string".getBytes()); + Response list = t.lpop("list".getBytes()); + Response hash = t.hget("hash".getBytes(), "foo".getBytes()); + Response> zset = t.zrange("zset".getBytes(), 0, -1); + Response set = t.spop("set".getBytes()); + t.exec(); + + assertArrayEquals("foo".getBytes(), string.get()); + assertArrayEquals("foo".getBytes(), list.get()); + assertArrayEquals("bar".getBytes(), hash.get()); + assertArrayEquals("foo".getBytes(), zset.get().iterator().next()); + assertArrayEquals("foo".getBytes(), set.get()); + } + + @Test(expected = IllegalStateException.class) + public void transactionResponseWithinPipeline() { + jedis.set("string", "foo"); + + Transaction t = jedis.multi(); + Response string = t.get("string"); + string.get(); + t.exec(); + } + + @Test + public void transactionResponseWithError() { + Transaction t = jedis.multi(); + t.set("foo", "bar"); + Response> error = t.smembers("foo"); + Response r = t.get("foo"); + List l = t.exec(); + assertSame(JedisDataException.class, l.get(1).getClass()); + try { + error.get(); + fail("We expect exception here!"); + } catch (JedisDataException e) { + // that is fine we should be here + } + assertEquals("bar", r.get()); + } // // @Test // public void execGetResponse() { @@ -274,17 +278,17 @@ // List results = t.exec(); // assertNull(results); // } -// -// @Test -// public void testResetStateWhenInMulti() { -// jedis.auth("foobared"); -// -// Transaction t = jedis.multi(); -// t.set("foooo", "barrr"); -// -// jedis.resetState(); -// assertNull(jedis.get("foooo")); -// } + + @Test + public void testResetStateWhenInMulti() { + jedis.auth("foobared"); + + Transaction t = jedis.multi(); + t.set("foooo", "barrr"); + + jedis.resetState(); + assertNull(jedis.get("foooo")); + } // // @Test // public void testResetStateWhenInMultiWithinPipeline() { @@ -297,65 +301,68 @@ // jedis.resetState(); // assertNull(jedis.get("foooo")); // } -// -// @Test -// public void testResetStateWhenInWatch() { -// jedis.watch("mykey", "somekey"); -// -// // state reset : unwatch -// jedis.resetState(); -// -// Transaction t = jedis.multi(); -// + + @Test + public void testResetStateWhenInWatch() { + jedis.watch("mykey", "somekey"); + + // state reset : unwatch + jedis.resetState(); + + Transaction t = jedis.multi(); + // nj.connect(); // nj.auth("foobared"); // nj.set("mykey", "bar"); // nj.disconnect(); -// -// t.set("mykey", "foo"); -// List resp = t.exec(); -// assertNotNull(resp); -// assertEquals(1, resp.size()); -// assertEquals("foo", jedis.get("mykey")); -// } -// -// @Test -// public void testResetStateWithFullyExecutedTransaction() { + nj.set("mykey", "bar"); + + t.set("mykey", "foo"); + List resp = t.exec(); + assertNotNull(resp); + assertEquals(1, resp.size()); + assertEquals("foo", jedis.get("mykey")); + } + + @Test + public void testResetStateWithFullyExecutedTransaction() { // Jedis jedis2 = new Jedis(jedis.getClient().getHost(), jedis.getClient().getPort()); -// jedis2.auth("foobared"); -// -// Transaction t = jedis2.multi(); -// t.set("mykey", "foo"); -// t.get("mykey"); -// -// List resp = t.exec(); -// assertNotNull(resp); -// assertEquals(2, resp.size()); -// -// jedis2.resetState(); -// jedis2.close(); -// } -// -// @Test -// public void testCloseable() throws IOException { -// // we need to test with fresh instance of Jedis -// Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); -// jedis2.auth("foobared"); -// -// Transaction transaction = jedis2.multi(); -// transaction.set("a", "1"); -// transaction.set("b", "2"); -// -// transaction.close(); -// -// try { -// transaction.exec(); -// fail("close should discard transaction"); + Jedis jedis2 = createJedis(); + jedis2.auth("foobared"); + + Transaction t = jedis2.multi(); + t.set("mykey", "foo"); + t.get("mykey"); + + List resp = t.exec(); + assertNotNull(resp); + assertEquals(2, resp.size()); + + jedis2.resetState(); + jedis2.close(); + } + + @Test + public void testCloseable() { + // we need to test with fresh instance of Jedis + Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); + jedis2.auth("foobared"); + + Transaction transaction = jedis2.multi(); + transaction.set("a", "1"); + transaction.set("b", "2"); + + transaction.close(); + + try { + transaction.exec(); + fail("close should discard transaction"); // } catch (JedisDataException e) { -// assertTrue(e.getMessage().contains("EXEC without MULTI")); -// // pass -// } -// } + } catch (IllegalStateException e) { + assertTrue(e.getMessage().contains("EXEC without MULTI")); + // pass + } + } // // @Test // public void testTransactionWithGeneralCommand() { @@ -403,21 +410,20 @@ // assertEquals("bar", r.get()); // assertEquals("1", SafeEncoder.encode((byte[]) x.get())); // } -// -// @Test -// public void unwatchWithinMulti() { -// final String key = "foo"; -// final String val = "bar"; -// jedis.set(key, val); -// jedis.watch(key); -// -// List exp = new ArrayList<>(); -// Transaction t = jedis.multi(); -// t.get(key); exp.add(val); -// t.unwatch(); exp.add("OK"); -// t.get(key); exp.add(val); -// List res = t.exec(); -// assertEquals(exp, res); -// } -// -//} \ No newline at end of file + + @Test + public void unwatchWithinMulti() { + final String key = "foo"; + final String val = "bar"; + jedis.set(key, val); + jedis.watch(key); + + List exp = new ArrayList<>(); + Transaction t = jedis.multi(); + t.get(key); exp.add(val); + t.unwatch(); exp.add("OK"); + t.get(key); exp.add(val); + List res = t.exec(); + assertEquals(exp, res); + } +} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/utils/ClientKillerUtil.java b/src/test/java/redis/clients/jedis/tests/utils/ClientKillerUtil.java index 14df9def95..b0a00ad350 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/ClientKillerUtil.java +++ b/src/test/java/redis/clients/jedis/tests/utils/ClientKillerUtil.java @@ -1,9 +1,11 @@ package redis.clients.jedis.tests.utils; -import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Connection; +//import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; public class ClientKillerUtil { + public static void killClient(Jedis jedis, String clientName) { for (String clientInfo : jedis.clientList().split("\n")) { if (clientInfo.contains("name=" + clientName)) { @@ -17,8 +19,22 @@ public static void killClient(Jedis jedis, String clientName) { } } } +// +// public static void killClient(Connection connection, String clientName) { +// Jedis jedis = new Jedis(connection); +// for (String clientInfo : jedis.clientList().split("\n")) { +// if (clientInfo.contains("name=" + clientName)) { +// String hostAndPortString = clientInfo.split(" ")[1].split("=")[1]; +// jedis.clientKill(hostAndPortString); +// } +// } +// } public static void tagClient(Jedis j, String name) { j.clientSetname(name); } +// +// public static void tagClient(Connection c, String name) { +// new Jedis(c).clientSetname(name); +// } }