diff --git a/pom.xml b/pom.xml index b550c90..2f5723b 100644 --- a/pom.xml +++ b/pom.xml @@ -54,7 +54,7 @@ junit 4.8.1 jar - compile + test diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java new file mode 100644 index 0000000..4893cc6 --- /dev/null +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -0,0 +1,629 @@ +package redis.clients.jedis; + +import static redis.clients.jedis.Protocol.toByteArray; +import static redis.clients.jedis.Protocol.Command.*; +import static redis.clients.jedis.Protocol.Keyword.LIMIT; +import static redis.clients.jedis.Protocol.Keyword.NO; +import static redis.clients.jedis.Protocol.Keyword.ONE; +import static redis.clients.jedis.Protocol.Keyword.STORE; +import static redis.clients.jedis.Protocol.Keyword.WITHSCORES; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import redis.clients.jedis.Protocol.Command; +import redis.clients.jedis.Protocol.Keyword; + +public class BinaryClient extends Connection { + public enum LIST_POSITION { + BEFORE, AFTER; + public final byte[] raw; + + private LIST_POSITION() { + raw = name().getBytes(Protocol.UTF8); + } + } + + private boolean isInMulti; + + public boolean isInMulti() { + return isInMulti; + } + + public BinaryClient(final String host) { + super(host); + } + + public BinaryClient(final String host, final int port) { + super(host, port); + } + + public void ping() { + sendCommand(PING); + } + + public void set(final byte[] key, final byte[] value) { + sendCommand(Command.SET, key, value); + } + + public void get(final byte[] key) { + sendCommand(Command.GET, key); + } + + public void quit() { + sendCommand(QUIT); + } + + public void exists(final byte[] key) { + sendCommand(EXISTS, key); + } + + public void del(final byte[]... keys) { + sendCommand(DEL, keys); + } + + public void type(final byte[] key) { + sendCommand(TYPE, key); + } + + public void flushDB() { + sendCommand(FLUSHDB); + } + + public void keys(final byte[] pattern) { + sendCommand(KEYS, pattern); + } + + public void randomKey() { + sendCommand(RANDOMKEY); + } + + public void rename(final byte[] oldkey, final byte[] newkey) { + sendCommand(RENAME, oldkey, newkey); + } + + public void renamenx(final byte[] oldkey, final byte[] newkey) { + sendCommand(RENAMENX, oldkey, newkey); + } + + public void dbSize() { + sendCommand(DBSIZE); + } + + public void expire(final byte[] key, final int seconds) { + sendCommand(EXPIRE, key, toByteArray(seconds)); + } + + public void expireAt(final byte[] key, final long unixTime) { + sendCommand(EXPIREAT, key, toByteArray(unixTime)); + } + + public void ttl(final byte[] key) { + sendCommand(TTL, key); + } + + public void select(final int index) { + sendCommand(SELECT, toByteArray(index)); + } + + public void move(final byte[] key, final int dbIndex) { + sendCommand(MOVE, key, toByteArray(dbIndex)); + } + + public void flushAll() { + sendCommand(FLUSHALL); + } + + public void getSet(final byte[] key, final byte[] value) { + sendCommand(GETSET, key, value); + } + + public void mget(final byte[]... keys) { + sendCommand(MGET, keys); + } + + public void setnx(final byte[] key, final byte[] value) { + sendCommand(SETNX, key, value); + } + + public void setex(final byte[] key, final int seconds, final byte[] value) { + sendCommand(SETEX, key, toByteArray(seconds), value); + } + + public void mset(final byte[]... keysvalues) { + sendCommand(MSET, keysvalues); + } + + public void msetnx(final byte[]... keysvalues) { + sendCommand(MSETNX, keysvalues); + } + + public void decrBy(final byte[] key, final int integer) { + sendCommand(DECRBY, key, toByteArray(integer)); + } + + public void decr(final byte[] key) { + sendCommand(DECR, key); + } + + public void incrBy(final byte[] key, final int integer) { + sendCommand(INCRBY, key, toByteArray(integer)); + } + + public void incr(final byte[] key) { + sendCommand(INCR, key); + } + + public void append(final byte[] key, final byte[] value) { + sendCommand(APPEND, key, value); + } + + public void substr(final byte[] key, final int start, final int end) { + sendCommand(SUBSTR, key, toByteArray(start), toByteArray(end)); + } + + public void hset(final byte[] key, final byte[] field, final byte[] value) { + sendCommand(HSET, key, field, value); + } + + public void hget(final byte[] key, final byte[] field) { + sendCommand(HGET, key, field); + } + + public void hsetnx(final byte[] key, final byte[] field, final byte[] value) { + sendCommand(HSETNX, key, field, value); + } + + public void hmset(final byte[] key, final Map hash) { + final List params = new ArrayList(); + params.add(key); + + for (final byte[] field : hash.keySet()) { + params.add(field); + params.add(hash.get(field)); + } + sendCommand(HMSET, params.toArray(new byte[params.size()][])); + } + + public void hmget(final byte[] key, final byte[]... fields) { + final byte[][] params = new byte[fields.length + 1][]; + params[0] = key; + System.arraycopy(fields, 0, params, 1, fields.length); + sendCommand(HMGET, params); + } + + public void hincrBy(final byte[] key, final byte[] field, final int value) { + sendCommand(HINCRBY, key, field, toByteArray(value)); + } + + public void hexists(final byte[] key, final byte[] field) { + sendCommand(HEXISTS, key, field); + } + + public void hdel(final byte[] key, final byte[] field) { + sendCommand(HDEL, key, field); + } + + public void hlen(final byte[] key) { + sendCommand(HLEN, key); + } + + public void hkeys(final byte[] key) { + sendCommand(HKEYS, key); + } + + public void hvals(final byte[] key) { + sendCommand(HVALS, key); + } + + public void hgetAll(final byte[] key) { + sendCommand(HGETALL, key); + } + + public void rpush(final byte[] key, final byte[] string) { + sendCommand(RPUSH, key, string); + } + + public void lpush(final byte[] key, final byte[] string) { + sendCommand(LPUSH, key, string); + } + + public void llen(final byte[] key) { + sendCommand(LLEN, key); + } + + public void lrange(final byte[] key, final int start, final int end) { + sendCommand(LRANGE, key, toByteArray(start), toByteArray(end)); + } + + public void ltrim(final byte[] key, final int start, final int end) { + sendCommand(LTRIM, key, toByteArray(start), toByteArray(end)); + } + + public void lindex(final byte[] key, final int index) { + sendCommand(LINDEX, key, toByteArray(index)); + } + + public void lset(final byte[] key, final int index, final byte[] value) { + sendCommand(LSET, key, toByteArray(index), value); + } + + public void lrem(final byte[] key, int count, final byte[] value) { + sendCommand(LREM, key, toByteArray(count), value); + } + + public void lpop(final byte[] key) { + sendCommand(LPOP, key); + } + + public void rpop(final byte[] key) { + sendCommand(RPOP, key); + } + + public void rpoplpush(final byte[] srckey, final byte[] dstkey) { + sendCommand(RPOPLPUSH, srckey, dstkey); + } + + public void sadd(final byte[] key, final byte[] member) { + sendCommand(SADD, key, member); + } + + public void smembers(final byte[] key) { + sendCommand(SMEMBERS, key); + } + + public void srem(final byte[] key, final byte[] member) { + sendCommand(SREM, key, member); + } + + public void spop(final byte[] key) { + sendCommand(SPOP, key); + } + + public void smove(final byte[] srckey, final byte[] dstkey, + final byte[] member) { + sendCommand(SMOVE, srckey, dstkey, member); + } + + public void scard(final byte[] key) { + sendCommand(SCARD, key); + } + + public void sismember(final byte[] key, final byte[] member) { + sendCommand(SISMEMBER, key, member); + } + + public void sinter(final byte[]... keys) { + sendCommand(SINTER, keys); + } + + public void sinterstore(final byte[] dstkey, final byte[]... keys) { + final byte[][] params = new byte[keys.length + 1][]; + params[0] = dstkey; + System.arraycopy(keys, 0, params, 1, keys.length); + sendCommand(SINTERSTORE, params); + } + + public void sunion(final byte[]... keys) { + sendCommand(SUNION, keys); + } + + public void sunionstore(final byte[] dstkey, final byte[]... keys) { + byte[][] params = new byte[keys.length + 1][]; + params[0] = dstkey; + System.arraycopy(keys, 0, params, 1, keys.length); + sendCommand(SUNIONSTORE, params); + } + + public void sdiff(final byte[]... keys) { + sendCommand(SDIFF, keys); + } + + public void sdiffstore(final byte[] dstkey, final byte[]... keys) { + byte[][] params = new byte[keys.length + 1][]; + params[0] = dstkey; + System.arraycopy(keys, 0, params, 1, keys.length); + sendCommand(SDIFFSTORE, params); + } + + public void srandmember(final byte[] key) { + sendCommand(SRANDMEMBER, key); + } + + public void zadd(final byte[] key, final double score, final byte[] member) { + sendCommand(ZADD, key, toByteArray(score), member); + } + + public void zrange(final byte[] key, final int start, final int end) { + sendCommand(ZRANGE, key, toByteArray(start), toByteArray(end)); + } + + public void zrem(final byte[] key, final byte[] member) { + sendCommand(ZREM, key, member); + } + + public void zincrby(final byte[] key, final double score, + final byte[] member) { + sendCommand(ZINCRBY, key, toByteArray(score), member); + } + + public void zrank(final byte[] key, final byte[] member) { + sendCommand(ZRANK, key, member); + } + + public void zrevrank(final byte[] key, final byte[] member) { + sendCommand(ZREVRANK, key, member); + } + + public void zrevrange(final byte[] key, final int start, final int end) { + sendCommand(ZREVRANGE, key, toByteArray(start), toByteArray(end)); + } + + public void zrangeWithScores(final byte[] key, final int start, + final int end) { + sendCommand(ZRANGE, key, toByteArray(start), toByteArray(end), + WITHSCORES.raw); + } + + public void zrevrangeWithScores(final byte[] key, final int start, + final int end) { + sendCommand(ZREVRANGE, key, toByteArray(start), toByteArray(end), + WITHSCORES.raw); + } + + public void zcard(final byte[] key) { + sendCommand(ZCARD, key); + } + + public void zscore(final byte[] key, final byte[] member) { + sendCommand(ZSCORE, key, member); + } + + public void multi() { + sendCommand(MULTI); + isInMulti = true; + } + + public void discard() { + sendCommand(DISCARD); + isInMulti = false; + } + + public void exec() { + sendCommand(EXEC); + isInMulti = false; + } + + public void watch(final byte[] key) { + sendCommand(WATCH, key); + } + + public void unwatch() { + sendCommand(UNWATCH); + } + + public void sort(final byte[] key) { + sendCommand(SORT, key); + } + + public void sort(final byte[] key, final SortingParams sortingParameters) { + final List args = new ArrayList(); + args.add(key); + args.addAll(sortingParameters.getParams()); + sendCommand(SORT, args.toArray(new byte[args.size()][])); + } + + public void blpop(final byte[][] args) { + sendCommand(BLPOP, args); + } + + public void sort(final byte[] key, final SortingParams sortingParameters, + final byte[] dstkey) { + final List args = new ArrayList(); + args.add(key); + args.addAll(sortingParameters.getParams()); + args.add(STORE.raw); + args.add(dstkey); + sendCommand(SORT, args.toArray(new byte[args.size()][])); + } + + public void sort(final byte[] key, final byte[] dstkey) { + sendCommand(SORT, key, STORE.raw, dstkey); + } + + public void brpop(final byte[][] args) { + sendCommand(BRPOP, args); + } + + public void auth(final String password) { + sendCommand(AUTH, password); + } + + public void subscribe(final String... channels) { + sendCommand(SUBSCRIBE, channels); + } + + public void publish(final String channel, final String message) { + sendCommand(PUBLISH, channel, message); + } + + public void unsubscribe() { + sendCommand(UNSUBSCRIBE); + } + + public void unsubscribe(final String... channels) { + sendCommand(UNSUBSCRIBE, channels); + } + + public void psubscribe(final String[] patterns) { + sendCommand(PSUBSCRIBE, patterns); + } + + public void punsubscribe() { + sendCommand(PUNSUBSCRIBE); + } + + public void punsubscribe(final String... patterns) { + sendCommand(PUNSUBSCRIBE, patterns); + } + + public void zcount(final byte[] key, final double min, final double max) { + sendCommand(ZCOUNT, key, toByteArray(min), toByteArray(max)); + } + + public void zrangeByScore(final byte[] key, final double min, + final double max) { + sendCommand(ZRANGEBYSCORE, key, toByteArray(min), toByteArray(max)); + } + + public void zrangeByScore(final byte[] key, final byte[] min, + final byte[] max) { + sendCommand(ZRANGEBYSCORE, key, min, max); + } + + public void zrangeByScore(final byte[] key, final double min, + final double max, final int offset, int count) { + sendCommand(ZRANGEBYSCORE, key, toByteArray(min), toByteArray(max), + LIMIT.raw, toByteArray(offset), toByteArray(count)); + } + + public void zrangeByScoreWithScores(final byte[] key, final double min, + final double max) { + sendCommand(ZRANGEBYSCORE, key, toByteArray(min), toByteArray(max), + WITHSCORES.raw); + } + + public void zrangeByScoreWithScores(final byte[] key, final double min, + final double max, final int offset, final int count) { + sendCommand(ZRANGEBYSCORE, key, toByteArray(min), toByteArray(max), + LIMIT.raw, toByteArray(offset), toByteArray(count), + WITHSCORES.raw); + } + + public void zremrangeByRank(final byte[] key, final int start, final int end) { + sendCommand(ZREMRANGEBYRANK, key, toByteArray(start), toByteArray(end)); + } + + public void zremrangeByScore(final byte[] key, final double start, + final double end) { + sendCommand(ZREMRANGEBYSCORE, key, toByteArray(start), toByteArray(end)); + } + + public void zunionstore(final byte[] dstkey, final byte[]... sets) { + final byte[][] params = new byte[sets.length + 2][]; + params[0] = dstkey; + params[1] = toByteArray(sets.length); + System.arraycopy(sets, 0, params, 2, sets.length); + sendCommand(ZUNIONSTORE, params); + } + + public void zunionstore(final byte[] dstkey, final ZParams params, + final byte[]... sets) { + final List args = new ArrayList(); + args.add(dstkey); + args.add(Protocol.toByteArray(sets.length)); + for (final byte[] set : sets) { + args.add(set); + } + args.addAll(params.getParams()); + sendCommand(ZUNIONSTORE, args.toArray(new byte[args.size()][])); + } + + public void zinterstore(final byte[] dstkey, final byte[]... sets) { + final byte[][] params = new byte[sets.length + 2][]; + params[0] = dstkey; + params[1] = Protocol.toByteArray(sets.length); + System.arraycopy(sets, 0, params, 2, sets.length); + sendCommand(ZINTERSTORE, params); + } + + public void zinterstore(final byte[] dstkey, final ZParams params, + final byte[]... sets) { + final List args = new ArrayList(); + args.add(dstkey); + args.add(Protocol.toByteArray(sets.length)); + for (final byte[] set : sets) { + args.add(set); + } + args.addAll(params.getParams()); + sendCommand(ZINTERSTORE, args.toArray(new byte[args.size()][])); + } + + public void save() { + sendCommand(SAVE); + } + + public void bgsave() { + sendCommand(BGSAVE); + } + + public void bgrewriteaof() { + sendCommand(BGREWRITEAOF); + } + + public void lastsave() { + sendCommand(LASTSAVE); + } + + public void shutdown() { + sendCommand(SHUTDOWN); + } + + public void info() { + sendCommand(INFO); + } + + public void monitor() { + sendCommand(MONITOR); + } + + public void slaveof(final String host, final int port) { + sendCommand(SLAVEOF, host, String.valueOf(port)); + } + + public void slaveofNoOne() { + sendCommand(SLAVEOF, NO.raw, ONE.raw); + } + + public void configGet(final String pattern) { + sendCommand(CONFIG, Keyword.GET.name(), pattern); + } + + public void configSet(final String parameter, final String value) { + sendCommand(CONFIG, Keyword.SET.name(), parameter, value); + } + + public void strlen(final byte[] key) { + sendCommand(STRLEN, key); + } + + public void sync() { + sendCommand(SYNC); + } + + public void lpushx(final byte[] key, final byte[] string) { + sendCommand(LPUSHX, key, string); + } + + public void persist(final byte[] key) { + sendCommand(PERSIST, key); + } + + public void rpushx(final byte[] key, final byte[] string) { + sendCommand(RPUSHX, key, string); + } + + public void echo(final byte[] string) { + sendCommand(ECHO, string); + } + + public void linsert(final byte[] key, final LIST_POSITION where, + final byte[] pivot, final byte[] value) { + sendCommand(LINSERT, key, where.raw, pivot, value); + } + + public void debug(final DebugParams params) { + sendCommand(DEBUG, params.getCommand()); + } +} \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java new file mode 100644 index 0000000..8f57a3d --- /dev/null +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -0,0 +1,2877 @@ +package redis.clients.jedis; + +import java.io.IOException; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import redis.clients.jedis.BinaryClient.LIST_POSITION; +import redis.clients.util.JedisByteHashMap; + +public class BinaryJedis implements BinaryJedisCommands { + protected Client client = null; + protected String password = null; + + public BinaryJedis(final String host) { + client = new Client(host); + } + + public BinaryJedis(final String host, final int port) { + client = new Client(host, port); + } + + public BinaryJedis(final String host, final int port, final int timeout) { + client = new Client(host, port); + client.setTimeout(timeout); + } + + public BinaryJedis(final JedisShardInfo shardInfo) { + client = new Client(shardInfo.getHost(), shardInfo.getPort()); + client.setTimeout(shardInfo.getTimeout()); + this.password = shardInfo.getPassword(); + } + + public String ping() { + checkIsInMulti(); + client.ping(); + return client.getStatusCodeReply(); + } + + /** + * Set the string value as value of the key. The string can't be longer than + * 1073741824 bytes (1 GB). + *

+ * Time complexity: O(1) + * + * @param key + * @param value + * @return Status code reply + */ + public String set(final byte[] key, final byte[] value) { + checkIsInMulti(); + client.set(key, value); + return client.getStatusCodeReply(); + } + + /** + * Get the value of the specified key. If the key does not exist the special + * value 'nil' is returned. If the value stored at key is not a string an + * error is returned because GET can only handle string values. + *

+ * Time complexity: O(1) + * + * @param key + * @return Bulk reply + */ + public byte[] get(final byte[] key) { + checkIsInMulti(); + client.get(key); + return client.getBinaryBulkReply(); + } + + /** + * Ask the server to silently close the connection. + */ + public void quit() { + checkIsInMulti(); + client.quit(); + } + + /** + * Test if the specified key exists. The command returns "0" if the key + * exists, otherwise "1" is returned. Note that even keys set with an empty + * string as value will return "1". + * + * Time complexity: O(1) + * + * @param key + * @return Integer reply, "0" if the key exists, otherwise "1" + */ + public Integer exists(final byte[] key) { + checkIsInMulti(); + client.exists(key); + return client.getIntegerReply(); + } + + /** + * Remove the specified keys. If a given key does not exist no operation is + * performed for this key. The command returns the number of keys removed. + * + * Time complexity: O(1) + * + * @param keys + * @return Integer reply, specifically: an integer greater than 0 if one or + * more keys were removed 0 if none of the specified key existed + */ + public Integer del(final byte[]... keys) { + checkIsInMulti(); + client.del(keys); + return client.getIntegerReply(); + } + + /** + * Return the type of the value stored at key in form of a string. The type + * can be one of "none", "string", "list", "set". "none" is returned if the + * key does not exist. + * + * Time complexity: O(1) + * + * @param key + * @return Status code reply, specifically: "none" if the key does not exist + * "string" if the key contains a String value "list" if the key + * contains a List value "set" if the key contains a Set value + * "zset" if the key contains a Sorted Set value "hash" if the key + * contains a Hash value + */ + public String type(final byte[] key) { + checkIsInMulti(); + client.type(key); + return client.getStatusCodeReply(); + } + + /** + * Delete all the keys of the currently selected DB. This command never + * fails. + * + * @return Status code reply + */ + public String flushDB() { + checkIsInMulti(); + client.flushDB(); + return client.getStatusCodeReply(); + } + + /** + * Returns all the keys matching the glob-style pattern as space separated + * strings. For example if you have in the database the keys "foo" and + * "foobar" the command "KEYS foo*" will return "foo foobar". + *

+ * Note that while the time complexity for this operation is O(n) the + * constant times are pretty low. For example Redis running on an entry + * level laptop can scan a 1 million keys database in 40 milliseconds. + * Still it's better to consider this one of the slow commands that may + * ruin the DB performance if not used with care. + *

+ * In other words this command is intended only for debugging and special + * operations like creating a script to change the DB schema. Don't use it + * in your normal code. Use Redis Sets in order to group together a subset + * of objects. + *

+ * Glob style patterns examples: + *

    + *
  • h?llo will match hello hallo hhllo + *
  • h*llo will match hllo heeeello + *
  • h[ae]llo will match hello and hallo, but not hillo + *
+ *

+ * Use \ to escape special chars if you want to match them verbatim. + *

+ * Time complexity: O(n) (with n being the number of keys in the DB, and + * assuming keys and pattern of limited length) + * + * @param pattern + * @return Multi bulk reply + */ + public Set keys(final byte[] pattern) { + checkIsInMulti(); + client.keys(pattern); + final HashSet keySet = new LinkedHashSet(client + .getBinaryMultiBulkReply()); + return keySet; + } + + /** + * Return a randomly selected key from the currently selected DB. + *

+ * Time complexity: O(1) + * + * @return Singe line reply, specifically the randomly selected key or an + * empty string is the database is empty + */ + public byte[] randomBinaryKey() { + checkIsInMulti(); + client.randomKey(); + return client.getBinaryBulkReply(); + } + + /** + * Atomically renames the key oldkey to newkey. If the source and + * destination name are the same an error is returned. If newkey already + * exists it is overwritten. + *

+ * Time complexity: O(1) + * + * @param oldkey + * @param newkey + * @return Status code repy + */ + public String rename(final byte[] oldkey, final byte[] newkey) { + checkIsInMulti(); + client.rename(oldkey, newkey); + return client.getStatusCodeReply(); + } + + /** + * Rename oldkey into newkey but fails if the destination key newkey already + * exists. + *

+ * Time complexity: O(1) + * + * @param oldkey + * @param newkey + * @return Integer reply, specifically: 1 if the key was renamed 0 if the + * target key already exist + */ + public Integer renamenx(final byte[] oldkey, final byte[] newkey) { + checkIsInMulti(); + client.renamenx(oldkey, newkey); + return client.getIntegerReply(); + } + + /** + * Return the number of keys in the currently selected database. + * + * @return Integer reply + */ + public Integer dbSize() { + checkIsInMulti(); + client.dbSize(); + return client.getIntegerReply(); + } + + /** + * Set a timeout on the specified key. After the timeout the key will be + * automatically deleted by the server. A key with an associated timeout is + * said to be volatile in Redis terminology. + *

+ * Voltile keys are stored on disk like the other keys, the timeout is + * persistent too like all the other aspects of the dataset. Saving a + * dataset containing expires and stopping the server does not stop the flow + * of time as Redis stores on disk the time when the key will no longer be + * available as Unix time, and not the remaining seconds. + *

+ * Since Redis 2.1.3 you can update the value of the timeout of a key + * already having an expire set. It is also possible to undo the expire at + * all turning the key into a normal key using the {@link #persist(String) + * PERSIST} command. + *

+ * Time complexity: O(1) + * + * @see ExpireCommand + * + * @param key + * @param seconds + * @return Integer reply, specifically: 1: the timeout was set. 0: the + * timeout was not set since the key already has an associated + * timeout (this may happen only in Redis versions < 2.1.3, Redis >= + * 2.1.3 will happily update the timeout), or the key does not + * exist. + */ + public Integer expire(final byte[] key, final int seconds) { + checkIsInMulti(); + client.expire(key, seconds); + return client.getIntegerReply(); + } + + /** + * EXPIREAT works exctly like {@link #expire(String, int) EXPIRE} but + * instead to get the number of seconds representing the Time To Live of the + * key as a second argument (that is a relative way of specifing the TTL), + * it takes an absolute one in the form of a UNIX timestamp (Number of + * seconds elapsed since 1 Gen 1970). + *

+ * EXPIREAT was introduced in order to implement the Append Only File + * persistence mode so that EXPIRE commands are automatically translated + * into EXPIREAT commands for the append only file. Of course EXPIREAT can + * also used by programmers that need a way to simply specify that a given + * key should expire at a given time in the future. + *

+ * Since Redis 2.1.3 you can update the value of the timeout of a key + * already having an expire set. It is also possible to undo the expire at + * all turning the key into a normal key using the {@link #persist(String) + * PERSIST} command. + *

+ * Time complexity: O(1) + * + * @see ExpireCommand + * + * @param key + * @param unixTime + * @return Integer reply, specifically: 1: the timeout was set. 0: the + * timeout was not set since the key already has an associated + * timeout (this may happen only in Redis versions < 2.1.3, Redis >= + * 2.1.3 will happily update the timeout), or the key does not + * exist. + */ + public Integer expireAt(final byte[] key, final long unixTime) { + checkIsInMulti(); + client.expireAt(key, unixTime); + return client.getIntegerReply(); + } + + /** + * The TTL command returns the remaining time to live in seconds of a key + * that has an {@link #expire(String, int) EXPIRE} set. This introspection + * capability allows a Redis client to check how many seconds a given key + * will continue to be part of the dataset. + * + * @param key + * @return Integer reply, returns the remaining time to live in seconds of a + * key that has an EXPIRE. If the Key does not exists or does not + * have an associated expire, -1 is returned. + */ + public Integer ttl(final byte[] key) { + checkIsInMulti(); + client.ttl(key); + return client.getIntegerReply(); + } + + /** + * Select the DB with having the specified zero-based numeric index. For + * default every new client connection is automatically selected to DB 0. + * + * @param index + * @return Status code reply + */ + public String select(final int index) { + checkIsInMulti(); + client.select(index); + return client.getStatusCodeReply(); + } + + /** + * Move the specified key from the currently selected DB to the specified + * destination DB. Note that this command returns 1 only if the key was + * successfully moved, and 0 if the target key was already there or if the + * source key was not found at all, so it is possible to use MOVE as a + * locking primitive. + * + * @param key + * @param dbIndex + * @return Integer reply, specifically: 1 if the key was moved 0 if the key + * was not moved because already present on the target DB or was not + * found in the current DB. + */ + public Integer move(final byte[] key, final int dbIndex) { + checkIsInMulti(); + client.move(key, dbIndex); + return client.getIntegerReply(); + } + + /** + * Delete all the keys of all the existing databases, not just the currently + * selected one. This command never fails. + * + * @return Status code reply + */ + public String flushAll() { + checkIsInMulti(); + client.flushAll(); + return client.getStatusCodeReply(); + } + + /** + * GETSET is an atomic set this value and return the old value command. Set + * key to the string value and return the old value stored at key. The + * string can't be longer than 1073741824 bytes (1 GB). + *

+ * Time complexity: O(1) + * + * @param key + * @param value + * @return Bulk reply + */ + public byte[] getSet(final byte[] key, final byte[] value) { + checkIsInMulti(); + client.getSet(key, value); + return client.getBinaryBulkReply(); + } + + /** + * Get the values of all the specified keys. If one or more keys dont exist + * or is not of type String, a 'nil' value is returned instead of the value + * of the specified key, but the operation never fails. + *

+ * Time complexity: O(1) for every key + * + * @param keys + * @return Multi bulk reply + */ + public List mget(final byte[]... keys) { + checkIsInMulti(); + client.mget(keys); + return client.getBinaryMultiBulkReply(); + } + + /** + * SETNX works exactly like {@link #set(String, String) SET} with the only + * difference that if the key already exists no operation is performed. + * SETNX actually means "SET if Not eXists". + *

+ * Time complexity: O(1) + * + * @param key + * @param value + * @return Integer reply, specifically: 1 if the key was set 0 if the key + * was not set + */ + public Integer setnx(final byte[] key, final byte[] value) { + checkIsInMulti(); + client.setnx(key, value); + return client.getIntegerReply(); + } + + /** + * The command is exactly equivalent to the following group of commands: + * {@link #set(String, String) SET} + {@link #expire(String, int) EXPIRE}. + * The operation is atomic. + *

+ * Time complexity: O(1) + * + * @param key + * @param seconds + * @param value + * @return Status code reply + */ + public String setex(final byte[] key, final int seconds, final byte[] value) { + checkIsInMulti(); + client.setex(key, seconds, value); + return client.getStatusCodeReply(); + } + + /** + * Set the the respective keys to the respective values. MSET will replace + * old values with new values, while {@link #msetnx(String...) MSETNX} will + * not perform any operation at all even if just a single key already + * exists. + *

+ * Because of this semantic MSETNX can be used in order to set different + * keys representing different fields of an unique logic object in a way + * that ensures that either all the fields or none at all are set. + *

+ * Both MSET and MSETNX are atomic operations. This means that for instance + * if the keys A and B are modified, another client talking to Redis can + * either see the changes to both A and B at once, or no modification at + * all. + * + * @see #msetnx(String...) + * + * @param keysvalues + * @return Status code reply Basically +OK as MSET can't fail + */ + public String mset(final byte[]... keysvalues) { + checkIsInMulti(); + client.mset(keysvalues); + return client.getStatusCodeReply(); + } + + /** + * Set the the respective keys to the respective values. + * {@link #mset(String...) MSET} will replace old values with new values, + * while MSETNX will not perform any operation at all even if just a single + * key already exists. + *

+ * Because of this semantic MSETNX can be used in order to set different + * keys representing different fields of an unique logic object in a way + * that ensures that either all the fields or none at all are set. + *

+ * Both MSET and MSETNX are atomic operations. This means that for instance + * if the keys A and B are modified, another client talking to Redis can + * either see the changes to both A and B at once, or no modification at + * all. + * + * @see #mset(String...) + * + * @param keysvalues + * @return Integer reply, specifically: 1 if the all the keys were set 0 if + * no key was set (at least one key already existed) + */ + public Integer msetnx(final byte[]... keysvalues) { + checkIsInMulti(); + client.msetnx(keysvalues); + return client.getIntegerReply(); + } + + /** + * IDECRBY work just like {@link #decr(String) INCR} but instead to + * decrement by 1 the decrement is integer. + *

+ * INCR commands are limited to 64 bit signed integers. + *

+ * Note: this is actually a string operation, that is, in Redis there are + * not "integer" types. Simply the string stored at the key is parsed as a + * base 10 64 bit signed integer, incremented, and then converted back as a + * string. + *

+ * Time complexity: O(1) + * + * @see #incr(String) + * @see #decr(String) + * @see #incrBy(String, int) + * + * @param key + * @param integer + * @return Integer reply, this commands will reply with the new value of key + * after the increment. + */ + public Integer decrBy(final byte[] key, final int integer) { + checkIsInMulti(); + client.decrBy(key, integer); + return client.getIntegerReply(); + } + + /** + * Decrement the number stored at key by one. If the key does not exist or + * contains a value of a wrong type, set the key to the value of "0" before + * to perform the decrement operation. + *

+ * INCR commands are limited to 64 bit signed integers. + *

+ * Note: this is actually a string operation, that is, in Redis there are + * not "integer" types. Simply the string stored at the key is parsed as a + * base 10 64 bit signed integer, incremented, and then converted back as a + * string. + *

+ * Time complexity: O(1) + * + * @see #incr(String) + * @see #incrBy(String, int) + * @see #decrBy(String, int) + * + * @param key + * @return Integer reply, this commands will reply with the new value of key + * after the increment. + */ + public Integer decr(final byte[] key) { + checkIsInMulti(); + client.decr(key); + return client.getIntegerReply(); + } + + /** + * INCRBY work just like {@link #incr(String) INCR} but instead to increment + * by 1 the increment is integer. + *

+ * INCR commands are limited to 64 bit signed integers. + *

+ * Note: this is actually a string operation, that is, in Redis there are + * not "integer" types. Simply the string stored at the key is parsed as a + * base 10 64 bit signed integer, incremented, and then converted back as a + * string. + *

+ * Time complexity: O(1) + * + * @see #incr(String) + * @see #decr(String) + * @see #decrBy(String, int) + * + * @param key + * @param integer + * @return Integer reply, this commands will reply with the new value of key + * after the increment. + */ + public Integer incrBy(final byte[] key, final int integer) { + checkIsInMulti(); + client.incrBy(key, integer); + return client.getIntegerReply(); + } + + /** + * Increment the number stored at key by one. If the key does not exist or + * contains a value of a wrong type, set the key to the value of "0" before + * to perform the increment operation. + *

+ * INCR commands are limited to 64 bit signed integers. + *

+ * Note: this is actually a string operation, that is, in Redis there are + * not "integer" types. Simply the string stored at the key is parsed as a + * base 10 64 bit signed integer, incremented, and then converted back as a + * string. + *

+ * Time complexity: O(1) + * + * @see #incrBy(String, int) + * @see #decr(String) + * @see #decrBy(String, int) + * + * @param key + * @return Integer reply, this commands will reply with the new value of key + * after the increment. + */ + public Integer incr(final byte[] key) { + checkIsInMulti(); + client.incr(key); + return client.getIntegerReply(); + } + + /** + * If the key already exists and is a string, this command appends the + * provided value at the end of the string. If the key does not exist it is + * created and set as an empty string, so APPEND will be very similar to SET + * in this special case. + *

+ * Time complexity: O(1). The amortized time complexity is O(1) assuming the + * appended value is small and the already present value is of any size, + * since the dynamic string library used by Redis will double the free space + * available on every reallocation. + * + * @param key + * @param value + * @return Integer reply, specifically the total length of the string after + * the append operation. + */ + public Integer append(final byte[] key, final byte[] value) { + checkIsInMulti(); + client.append(key, value); + return client.getIntegerReply(); + } + + /** + * Return a subset of the string from offset start to offset end (both + * offsets are inclusive). Negative offsets can be used in order to provide + * an offset starting from the end of the string. So -1 means the last char, + * -2 the penultimate and so forth. + *

+ * The function handles out of range requests without raising an error, but + * just limiting the resulting range to the actual length of the string. + *

+ * Time complexity: O(start+n) (with start being the start index and n the + * total length of the requested range). Note that the lookup part of this + * command is O(1) so for small strings this is actually an O(1) command. + * + * @param key + * @param start + * @param end + * @return Bulk reply + */ + public byte[] substr(final byte[] key, final int start, final int end) { + checkIsInMulti(); + client.substr(key, start, end); + return client.getBinaryBulkReply(); + } + + /** + * + * Set the specified hash field to the specified value. + *

+ * If key does not exist, a new key holding a hash is created. + *

+ * Time complexity: O(1) + * + * @param key + * @param field + * @param value + * @return If the field already exists, and the HSET just produced an update + * of the value, 0 is returned, otherwise if a new field is created + * 1 is returned. + */ + public Integer hset(final byte[] key, final byte[] field, final byte[] value) { + checkIsInMulti(); + client.hset(key, field, value); + return client.getIntegerReply(); + } + + /** + * If key holds a hash, retrieve the value associated to the specified + * field. + *

+ * If the field is not found or the key does not exist, a special 'nil' + * value is returned. + *

+ * Time complexity: O(1) + * + * @param key + * @param field + * @return Bulk reply + */ + public byte[] hget(final byte[] key, final byte[] field) { + checkIsInMulti(); + client.hget(key, field); + return client.getBinaryBulkReply(); + } + + /** + * + * Set the specified hash field to the specified value if the field not + * exists. Time complexity: O(1) + * + * @param key + * @param field + * @param value + * @return If the field already exists, 0 is returned, otherwise if a new + * field is created 1 is returned. + */ + public Integer hsetnx(final byte[] key, final byte[] field, + final byte[] value) { + checkIsInMulti(); + client.hsetnx(key, field, value); + return client.getIntegerReply(); + } + + /** + * Set the respective fields to the respective values. HMSET replaces old + * values with new values. + *

+ * If key does not exist, a new key holding a hash is created. + *

+ * Time complexity: O(N) (with N being the number of fields) + * + * @param key + * @param hash + * @return Always OK because HMSET can't fail + */ + public String hmset(final byte[] key, final Map hash) { + checkIsInMulti(); + client.hmset(key, hash); + return client.getStatusCodeReply(); + } + + /** + * Retrieve the values associated to the specified fields. + *

+ * If some of the specified fields do not exist, nil values are returned. + * Non existing keys are considered like empty hashes. + *

+ * Time complexity: O(N) (with N being the number of fields) + * + * @param key + * @param fields + * @return Multi Bulk Reply specifically a list of all the values associated + * with the specified fields, in the same order of the request. + */ + public List hmget(final byte[] key, final byte[]... fields) { + checkIsInMulti(); + client.hmget(key, fields); + return client.getBinaryMultiBulkReply(); + } + + /** + * Increment the number stored at field in the hash at key by value. If key + * does not exist, a new key holding a hash is created. If field does not + * exist or holds a string, the value is set to 0 before applying the + * operation. Since the value argument is signed you can use this command to + * perform both increments and decrements. + *

+ * The range of values supported by HINCRBY is limited to 64 bit signed + * integers. + *

+ * Time complexity: O(1) + * + * @param key + * @param field + * @param value + * @return Integer reply The new value at field after the increment + * operation. + */ + public Integer hincrBy(final byte[] key, final byte[] field, final int value) { + checkIsInMulti(); + client.hincrBy(key, field, value); + return client.getIntegerReply(); + } + + /** + * Test for existence of a specified field in a hash. + * + * Time complexity: O(1) + * + * @param key + * @param field + * @return Return 1 if the hash stored at key contains the specified field. + * Return 0 if the key is not found or the field is not present. + */ + public Integer hexists(final byte[] key, final byte[] field) { + checkIsInMulti(); + client.hexists(key, field); + return client.getIntegerReply(); + } + + /** + * Remove the specified field from an hash stored at key. + *

+ * Time complexity: O(1) + * + * @param key + * @param field + * @return If the field was present in the hash it is deleted and 1 is + * returned, otherwise 0 is returned and no operation is performed. + */ + public Integer hdel(final byte[] key, final byte[] field) { + checkIsInMulti(); + client.hdel(key, field); + return client.getIntegerReply(); + } + + /** + * Return the number of items in a hash. + *

+ * Time complexity: O(1) + * + * @param key + * @return The number of entries (fields) contained in the hash stored at + * key. If the specified key does not exist, 0 is returned assuming + * an empty hash. + */ + public Integer hlen(final byte[] key) { + checkIsInMulti(); + client.hlen(key); + return client.getIntegerReply(); + } + + /** + * Return all the fields in a hash. + *

+ * Time complexity: O(N), where N is the total number of entries + * + * @param key + * @return All the fields names contained into a hash. + */ + public Set hkeys(final byte[] key) { + checkIsInMulti(); + client.hkeys(key); + final List lresult = client.getBinaryMultiBulkReply(); + return new LinkedHashSet(lresult); + } + + /** + * Return all the values in a hash. + *

+ * Time complexity: O(N), where N is the total number of entries + * + * @param key + * @return All the fields values contained into a hash. + */ + public List hvals(final byte[] key) { + checkIsInMulti(); + client.hvals(key); + final List lresult = client.getBinaryMultiBulkReply(); + return lresult; + } + + /** + * Return all the fields and associated values in a hash. + *

+ * Time complexity: O(N), where N is the total number of entries + * + * @param key + * @return All the fields and values contained into a hash. + */ + public Map hgetAll(final byte[] key) { + checkIsInMulti(); + client.hgetAll(key); + final List flatHash = client.getBinaryMultiBulkReply(); + final Map hash = new JedisByteHashMap(); + final Iterator iterator = flatHash.iterator(); + while (iterator.hasNext()) { + hash.put(iterator.next(), iterator.next()); + } + + return hash; + } + + /** + * Add the string value to the head (LPUSH) or tail (RPUSH) of the list + * stored at key. If the key does not exist an empty list is created just + * before the append operation. If the key exists but is not a List an error + * is returned. + *

+ * Time complexity: O(1) + * + * @see BinaryJedis#lpush(String, String) + * + * @param key + * @param string + * @return Integer reply, specifically, the number of elements inside the + * list after the push operation. + */ + public Integer rpush(final byte[] key, final byte[] string) { + checkIsInMulti(); + client.rpush(key, string); + return client.getIntegerReply(); + } + + /** + * Add the string value to the head (LPUSH) or tail (RPUSH) of the list + * stored at key. If the key does not exist an empty list is created just + * before the append operation. If the key exists but is not a List an error + * is returned. + *

+ * Time complexity: O(1) + * + * @see BinaryJedis#rpush(String, String) + * + * @param key + * @param string + * @return Integer reply, specifically, the number of elements inside the + * list after the push operation. + */ + public Integer lpush(final byte[] key, final byte[] string) { + checkIsInMulti(); + client.lpush(key, string); + return client.getIntegerReply(); + } + + /** + * Return the length of the list stored at the specified key. If the key + * does not exist zero is returned (the same behaviour as for empty lists). + * If the value stored at key is not a list an error is returned. + *

+ * Time complexity: O(1) + * + * @param key + * @return The length of the list. + */ + public Integer llen(final byte[] key) { + checkIsInMulti(); + client.llen(key); + return client.getIntegerReply(); + } + + /** + * Return the specified elements of the list stored at the specified key. + * Start and end are zero-based indexes. 0 is the first element of the list + * (the list head), 1 the next element and so on. + *

+ * For example LRANGE foobar 0 2 will return the first three elements of the + * list. + *

+ * start and end can also be negative numbers indicating offsets from the + * end of the list. For example -1 is the last element of the list, -2 the + * penultimate element and so on. + *

+ * Consistency with range functions in various programming languages + *

+ * Note that if you have a list of numbers from 0 to 100, LRANGE 0 10 will + * return 11 elements, that is, rightmost item is included. This may or may + * not be consistent with behavior of range-related functions in your + * programming language of choice (think Ruby's Range.new, Array#slice or + * Python's range() function). + *

+ * LRANGE behavior is consistent with one of Tcl. + *

+ * Out-of-range indexes + *

+ * Indexes out of range will not produce an error: if start is over the end + * of the list, or start > end, an empty list is returned. If end is over + * the end of the list Redis will threat it just like the last element of + * the list. + *

+ * Time complexity: O(start+n) (with n being the length of the range and + * start being the start offset) + * + * @param key + * @param start + * @param end + * @return Multi bulk reply, specifically a list of elements in the + * specified range. + */ + public List lrange(final byte[] key, final int start, final int end) { + checkIsInMulti(); + client.lrange(key, start, end); + return client.getBinaryMultiBulkReply(); + } + + /** + * Trim an existing list so that it will contain only the specified range of + * elements specified. Start and end are zero-based indexes. 0 is the first + * element of the list (the list head), 1 the next element and so on. + *

+ * For example LTRIM foobar 0 2 will modify the list stored at foobar key so + * that only the first three elements of the list will remain. + *

+ * start and end can also be negative numbers indicating offsets from the + * end of the list. For example -1 is the last element of the list, -2 the + * penultimate element and so on. + *

+ * Indexes out of range will not produce an error: if start is over the end + * of the list, or start > end, an empty list is left as value. If end over + * the end of the list Redis will threat it just like the last element of + * the list. + *

+ * Hint: the obvious use of LTRIM is together with LPUSH/RPUSH. For example: + *

+ * {@code lpush("mylist", "someelement"); ltrim("mylist", 0, 99); * } + *

+ * The above two commands will push elements in the list taking care that + * the list will not grow without limits. This is very useful when using + * Redis to store logs for example. It is important to note that when used + * in this way LTRIM is an O(1) operation because in the average case just + * one element is removed from the tail of the list. + *

+ * Time complexity: O(n) (with n being len of list - len of range) + * + * @param key + * @param start + * @param end + * @return Status code reply + */ + public String ltrim(final byte[] key, final int start, final int end) { + checkIsInMulti(); + client.ltrim(key, start, end); + return client.getStatusCodeReply(); + } + + /** + * Return the specified element of the list stored at the specified key. 0 + * is the first element, 1 the second and so on. Negative indexes are + * supported, for example -1 is the last element, -2 the penultimate and so + * on. + *

+ * If the value stored at key is not of list type an error is returned. If + * the index is out of range a 'nil' reply is returned. + *

+ * Note that even if the average time complexity is O(n) asking for the + * first or the last element of the list is O(1). + *

+ * Time complexity: O(n) (with n being the length of the list) + * + * @param key + * @param index + * @return Bulk reply, specifically the requested element + */ + public byte[] lindex(final byte[] key, final int index) { + checkIsInMulti(); + client.lindex(key, index); + return client.getBinaryBulkReply(); + } + + /** + * Set a new value as the element at index position of the List at key. + *

+ * Out of range indexes will generate an error. + *

+ * Similarly to other list commands accepting indexes, the index can be + * negative to access elements starting from the end of the list. So -1 is + * the last element, -2 is the penultimate, and so forth. + *

+ * Time complexity: + *

+ * O(N) (with N being the length of the list), setting the first or last + * elements of the list is O(1). + * + * @see #lindex(String, int) + * + * @param key + * @param index + * @param value + * @return Status code reply + */ + public String lset(final byte[] key, final int index, final byte[] value) { + checkIsInMulti(); + client.lset(key, index, value); + return client.getStatusCodeReply(); + } + + /** + * Remove the first count occurrences of the value element from the list. If + * count is zero all the elements are removed. If count is negative elements + * are removed from tail to head, instead to go from head to tail that is + * the normal behaviour. So for example LREM with count -2 and hello as + * value to remove against the list (a,b,c,hello,x,hello,hello) will lave + * the list (a,b,c,hello,x). The number of removed elements is returned as + * an integer, see below for more information about the returned value. Note + * that non existing keys are considered like empty lists by LREM, so LREM + * against non existing keys will always return 0. + *

+ * Time complexity: O(N) (with N being the length of the list) + * + * @param key + * @param count + * @param value + * @return Integer Reply, specifically: The number of removed elements if + * the operation succeeded + */ + public Integer lrem(final byte[] key, final int count, final byte[] value) { + checkIsInMulti(); + client.lrem(key, count, value); + return client.getIntegerReply(); + } + + /** + * Atomically return and remove the first (LPOP) or last (RPOP) element of + * the list. For example if the list contains the elements "a","b","c" LPOP + * will return "a" and the list will become "b","c". + *

+ * If the key does not exist or the list is already empty the special value + * 'nil' is returned. + * + * @see #rpop(String) + * + * @param key + * @return Bulk reply + */ + public byte[] lpop(final byte[] key) { + checkIsInMulti(); + client.lpop(key); + return client.getBinaryBulkReply(); + } + + /** + * Atomically return and remove the first (LPOP) or last (RPOP) element of + * the list. For example if the list contains the elements "a","b","c" LPOP + * will return "a" and the list will become "b","c". + *

+ * If the key does not exist or the list is already empty the special value + * 'nil' is returned. + * + * @see #lpop(String) + * + * @param key + * @return Bulk reply + */ + public byte[] rpop(final byte[] key) { + checkIsInMulti(); + client.rpop(key); + return client.getBinaryBulkReply(); + } + + /** + * Atomically return and remove the last (tail) element of the srckey list, + * and push the element as the first (head) element of the dstkey list. For + * example if the source list contains the elements "a","b","c" and the + * destination list contains the elements "foo","bar" after an RPOPLPUSH + * command the content of the two lists will be "a","b" and "c","foo","bar". + *

+ * If the key does not exist or the list is already empty the special value + * 'nil' is returned. If the srckey and dstkey are the same the operation is + * equivalent to removing the last element from the list and pusing it as + * first element of the list, so it's a "list rotation" command. + *

+ * Time complexity: O(1) + * + * @param srckey + * @param dstkey + * @return Bulk reply + */ + public byte[] rpoplpush(final byte[] srckey, final byte[] dstkey) { + checkIsInMulti(); + client.rpoplpush(srckey, dstkey); + return client.getBinaryBulkReply(); + } + + /** + * Add the specified member to the set value stored at key. If member is + * already a member of the set no operation is performed. If key does not + * exist a new set with the specified member as sole member is created. If + * the key exists but does not hold a set value an error is returned. + *

+ * Time complexity O(1) + * + * @param key + * @param member + * @return Integer reply, specifically: 1 if the new element was added 0 if + * the element was already a member of the set + */ + public Integer sadd(final byte[] key, final byte[] member) { + checkIsInMulti(); + client.sadd(key, member); + return client.getIntegerReply(); + } + + /** + * Return all the members (elements) of the set value stored at key. This is + * just syntax glue for {@link #sinter(String...) SINTER}. + *

+ * Time complexity O(N) + * + * @param key + * @return Multi bulk reply + */ + public Set smembers(final byte[] key) { + checkIsInMulti(); + client.smembers(key); + final List members = client.getBinaryMultiBulkReply(); + return new LinkedHashSet(members); + } + + /** + * Remove the specified member from the set value stored at key. If member + * was not a member of the set no operation is performed. If key does not + * hold a set value an error is returned. + *

+ * Time complexity O(1) + * + * @param key + * @param member + * @return Integer reply, specifically: 1 if the new element was removed 0 + * if the new element was not a member of the set + */ + public Integer srem(final byte[] key, final byte[] member) { + checkIsInMulti(); + client.srem(key, member); + return client.getIntegerReply(); + } + + /** + * Remove a random element from a Set returning it as return value. If the + * Set is empty or the key does not exist, a nil object is returned. + *

+ * The {@link #srandmember(String)} command does a similar work but the + * returned element is not removed from the Set. + *

+ * Time complexity O(1) + * + * @param key + * @return Bulk reply + */ + public byte[] spop(final byte[] key) { + checkIsInMulti(); + client.spop(key); + return client.getBinaryBulkReply(); + } + + /** + * Move the specifided member from the set at srckey to the set at dstkey. + * This operation is atomic, in every given moment the element will appear + * to be in the source or destination set for accessing clients. + *

+ * If the source set does not exist or does not contain the specified + * element no operation is performed and zero is returned, otherwise the + * element is removed from the source set and added to the destination set. + * On success one is returned, even if the element was already present in + * the destination set. + *

+ * An error is raised if the source or destination keys contain a non Set + * value. + *

+ * Time complexity O(1) + * + * @param srckey + * @param dstkey + * @param member + * @return Integer reply, specifically: 1 if the element was moved 0 if the + * element was not found on the first set and no operation was + * performed + */ + public Integer smove(final byte[] srckey, final byte[] dstkey, + final byte[] member) { + checkIsInMulti(); + client.smove(srckey, dstkey, member); + return client.getIntegerReply(); + } + + /** + * Return the set cardinality (number of elements). If the key does not + * exist 0 is returned, like for empty sets. + * + * @param key + * @return Integer reply, specifically: the cardinality (number of elements) + * of the set as an integer. + */ + public Integer scard(final byte[] key) { + checkIsInMulti(); + client.scard(key); + return client.getIntegerReply(); + } + + /** + * Return 1 if member is a member of the set stored at key, otherwise 0 is + * returned. + *

+ * Time complexity O(1) + * + * @param key + * @param member + * @return Integer reply, specifically: 1 if the element is a member of the + * set 0 if the element is not a member of the set OR if the key + * does not exist + */ + public Integer sismember(final byte[] key, final byte[] member) { + checkIsInMulti(); + client.sismember(key, member); + return client.getIntegerReply(); + } + + /** + * Return the members of a set resulting from the intersection of all the + * sets hold at the specified keys. Like in + * {@link #lrange(String, int, int) LRANGE} the result is sent to the client + * as a multi-bulk reply (see the protocol specification for more + * information). If just a single key is specified, then this command + * produces the same result as {@link #smembers(String) SMEMBERS}. Actually + * SMEMBERS is just syntax sugar for SINTER. + *

+ * Non existing keys are considered like empty sets, so if one of the keys + * is missing an empty set is returned (since the intersection with an empty + * set always is an empty set). + *

+ * Time complexity O(N*M) worst case where N is the cardinality of the + * smallest set and M the number of sets + * + * @param keys + * @return Multi bulk reply, specifically the list of common elements. + */ + public Set sinter(final byte[]... keys) { + checkIsInMulti(); + client.sinter(keys); + final List members = client.getBinaryMultiBulkReply(); + return new LinkedHashSet(members); + } + + /** + * This commnad works exactly like {@link #sinter(String...) SINTER} but + * instead of being returned the resulting set is sotred as dstkey. + *

+ * Time complexity O(N*M) worst case where N is the cardinality of the + * smallest set and M the number of sets + * + * @param dstkey + * @param keys + * @return Status code reply + */ + public Integer sinterstore(final byte[] dstkey, final byte[]... keys) { + checkIsInMulti(); + client.sinterstore(dstkey, keys); + return client.getIntegerReply(); + } + + /** + * Return the members of a set resulting from the union of all the sets hold + * at the specified keys. Like in {@link #lrange(String, int, int) LRANGE} + * the result is sent to the client as a multi-bulk reply (see the protocol + * specification for more information). If just a single key is specified, + * then this command produces the same result as {@link #smembers(String) + * SMEMBERS}. + *

+ * Non existing keys are considered like empty sets. + *

+ * Time complexity O(N) where N is the total number of elements in all the + * provided sets + * + * @param keys + * @return Multi bulk reply, specifically the list of common elements. + */ + public Set sunion(final byte[]... keys) { + checkIsInMulti(); + client.sunion(keys); + final List members = client.getBinaryMultiBulkReply(); + return new LinkedHashSet(members); + } + + /** + * This command works exactly like {@link #sunion(String...) SUNION} but + * instead of being returned the resulting set is stored as dstkey. Any + * existing value in dstkey will be over-written. + *

+ * Time complexity O(N) where N is the total number of elements in all the + * provided sets + * + * @param dstkey + * @param keys + * @return Status code reply + */ + public Integer sunionstore(final byte[] dstkey, final byte[]... keys) { + checkIsInMulti(); + client.sunionstore(dstkey, keys); + return client.getIntegerReply(); + } + + /** + * Return the difference between the Set stored at key1 and all the Sets + * key2, ..., keyN + *

+ * Example: + * + *

+     * key1 = [x, a, b, c]
+     * key2 = [c]
+     * key3 = [a, d]
+     * SDIFF key1,key2,key3 => [x, b]
+     * 
+ * + * Non existing keys are considered like empty sets. + *

+ * Time complexity: + *

+ * O(N) with N being the total number of elements of all the sets + * + * @param keys + * @return Return the members of a set resulting from the difference between + * the first set provided and all the successive sets. + */ + public Set sdiff(final byte[]... keys) { + checkIsInMulti(); + client.sdiff(keys); + final List members = client.getBinaryMultiBulkReply(); + return new LinkedHashSet(members); + } + + /** + * This command works exactly like {@link #sdiff(String...) SDIFF} but + * instead of being returned the resulting set is stored in dstkey. + * + * @param dstkey + * @param keys + * @return Status code reply + */ + public Integer sdiffstore(final byte[] dstkey, final byte[]... keys) { + checkIsInMulti(); + client.sdiffstore(dstkey, keys); + return client.getIntegerReply(); + } + + /** + * Return a random element from a Set, without removing the element. If the + * Set is empty or the key does not exist, a nil object is returned. + *

+ * The SPOP command does a similar work but the returned element is popped + * (removed) from the Set. + *

+ * Time complexity O(1) + * + * @param key + * @return Bulk reply + */ + public byte[] srandmember(final byte[] key) { + checkIsInMulti(); + client.srandmember(key); + return client.getBinaryBulkReply(); + } + + /** + * Add the specified member having the specifeid score to the sorted set + * stored at key. If member is already a member of the sorted set the score + * is updated, and the element reinserted in the right position to ensure + * sorting. If key does not exist a new sorted set with the specified member + * as sole member is crated. If the key exists but does not hold a sorted + * set value an error is returned. + *

+ * The score value can be the string representation of a double precision + * floating point number. + *

+ * Time complexity O(log(N)) with N being the number of elements in the + * sorted set + * + * @param key + * @param score + * @param member + * @return Integer reply, specifically: 1 if the new element was added 0 if + * the element was already a member of the sorted set and the score + * was updated + */ + public Integer zadd(final byte[] key, final double score, + final byte[] member) { + checkIsInMulti(); + client.zadd(key, score, member); + return client.getIntegerReply(); + } + + public Set zrange(final byte[] key, final int start, final int end) { + checkIsInMulti(); + client.zrange(key, start, end); + final List members = client.getBinaryMultiBulkReply(); + return new LinkedHashSet(members); + } + + /** + * Remove the specified member from the sorted set value stored at key. If + * member was not a member of the set no operation is performed. If key does + * not not hold a set value an error is returned. + *

+ * Time complexity O(log(N)) with N being the number of elements in the + * sorted set + * + * + * + * @param key + * @param member + * @return Integer reply, specifically: 1 if the new element was removed 0 + * if the new element was not a member of the set + */ + public Integer zrem(final byte[] key, final byte[] member) { + checkIsInMulti(); + client.zrem(key, member); + return client.getIntegerReply(); + } + + /** + * If member already exists in the sorted set adds the increment to its + * score and updates the position of the element in the sorted set + * accordingly. If member does not already exist in the sorted set it is + * added with increment as score (that is, like if the previous score was + * virtually zero). If key does not exist a new sorted set with the + * specified member as sole member is crated. If the key exists but does not + * hold a sorted set value an error is returned. + *

+ * The score value can be the string representation of a double precision + * floating point number. It's possible to provide a negative value to + * perform a decrement. + *

+ * For an introduction to sorted sets check the Introduction to Redis data + * types page. + *

+ * Time complexity O(log(N)) with N being the number of elements in the + * sorted set + * + * @param key + * @param score + * @param member + * @return The new score + */ + public Double zincrby(final byte[] key, final double score, + final byte[] member) { + checkIsInMulti(); + client.zincrby(key, score, member); + String newscore = client.getBulkReply(); + return Double.valueOf(newscore); + } + + /** + * Return the rank (or index) or member in the sorted set at key, with + * scores being ordered from low to high. + *

+ * When the given member does not exist in the sorted set, the special value + * 'nil' is returned. The returned rank (or index) of the member is 0-based + * for both commands. + *

+ * Time complexity: + *

+ * O(log(N)) + * + * @see #zrevrank(String, String) + * + * @param key + * @param member + * @return Integer reply or a nil bulk reply, specifically: the rank of the + * element as an integer reply if the element exists. A nil bulk + * reply if there is no such element. + */ + public Integer zrank(final byte[] key, final byte[] member) { + checkIsInMulti(); + client.zrank(key, member); + return client.getIntegerReply(); + } + + /** + * Return the rank (or index) or member in the sorted set at key, with + * scores being ordered from high to low. + *

+ * When the given member does not exist in the sorted set, the special value + * 'nil' is returned. The returned rank (or index) of the member is 0-based + * for both commands. + *

+ * Time complexity: + *

+ * O(log(N)) + * + * @see #zrank(String, String) + * + * @param key + * @param member + * @return Integer reply or a nil bulk reply, specifically: the rank of the + * element as an integer reply if the element exists. A nil bulk + * reply if there is no such element. + */ + public Integer zrevrank(final byte[] key, final byte[] member) { + checkIsInMulti(); + client.zrevrank(key, member); + return client.getIntegerReply(); + } + + public Set zrevrange(final byte[] key, final int start, + final int end) { + checkIsInMulti(); + client.zrevrange(key, start, end); + final List members = client.getBinaryMultiBulkReply(); + return new LinkedHashSet(members); + } + + public Set zrangeWithScores(final byte[] key, final int start, + final int end) { + checkIsInMulti(); + client.zrangeWithScores(key, start, end); + Set set = getBinaryTupledSet(); + return set; + } + + public Set zrevrangeWithScores(final byte[] key, final int start, + final int end) { + checkIsInMulti(); + client.zrevrangeWithScores(key, start, end); + Set set = getBinaryTupledSet(); + return set; + } + + /** + * Return the sorted set cardinality (number of elements). If the key does + * not exist 0 is returned, like for empty sorted sets. + *

+ * Time complexity O(1) + * + * @param key + * @return the cardinality (number of elements) of the set as an integer. + */ + public Integer zcard(final byte[] key) { + checkIsInMulti(); + client.zcard(key); + return client.getIntegerReply(); + } + + /** + * Return the score of the specified element of the sorted set at key. If + * the specified element does not exist in the sorted set, or the key does + * not exist at all, a special 'nil' value is returned. + *

+ * Time complexity: O(1) + * + * @param key + * @param member + * @return the score + */ + public Double zscore(final byte[] key, final byte[] member) { + checkIsInMulti(); + client.zscore(key, member); + final String score = client.getBulkReply(); + return (score != null ? new Double(score) : null); + } + + public Transaction multi() { + client.multi(); + client.getStatusCodeReply(); + return new Transaction(client); + } + + public List multi(final TransactionBlock jedisTransaction) { + List results = null; + try { + jedisTransaction.setClient(client); + multi(); + jedisTransaction.execute(); + results = jedisTransaction.exec(); + } catch (Exception ex) { + client.discard(); + } + return results; + } + + protected void checkIsInMulti() { + if (client.isInMulti()) { + throw new JedisException( + "Cannot use Jedis when in Multi. Please use JedisTransaction instead."); + } + } + + public void connect() throws UnknownHostException, IOException { + client.connect(); + } + + public void disconnect() throws IOException { + client.disconnect(); + } + + public String watch(final byte[] key) { + client.watch(key); + return client.getStatusCodeReply(); + } + + public String unwatch() { + client.unwatch(); + return client.getStatusCodeReply(); + } + + /** + * Sort a Set or a List. + *

+ * Sort the elements contained in the List, Set, or Sorted Set value at key. + * By default sorting is numeric with elements being compared as double + * precision floating point numbers. This is the simplest form of SORT. + * + * @see #sort(String, String) + * @see #sort(String, SortingParams) + * @see #sort(String, SortingParams, String) + * + * + * @param key + * @return Assuming the Set/List at key contains a list of numbers, the + * return value will be the list of numbers ordered from the + * smallest to the biggest number. + */ + public List sort(final byte[] key) { + checkIsInMulti(); + client.sort(key); + return client.getBinaryMultiBulkReply(); + } + + /** + * Sort a Set or a List accordingly to the specified parameters. + *

+ * examples: + *

+ * Given are the following sets and key/values: + * + *

+     * x = [1, 2, 3]
+     * y = [a, b, c]
+     * 
+     * k1 = z
+     * k2 = y
+     * k3 = x
+     * 
+     * w1 = 9
+     * w2 = 8
+     * w3 = 7
+     * 
+ * + * Sort Order: + * + *
+     * sort(x) or sort(x, sp.asc())
+     * -> [1, 2, 3]
+     * 
+     * sort(x, sp.desc())
+     * -> [3, 2, 1]
+     * 
+     * sort(y)
+     * -> [c, a, b]
+     * 
+     * sort(y, sp.alpha())
+     * -> [a, b, c]
+     * 
+     * sort(y, sp.alpha().desc())
+     * -> [c, a, b]
+     * 
+ * + * Limit (e.g. for Pagination): + * + *
+     * sort(x, sp.limit(0, 2))
+     * -> [1, 2]
+     * 
+     * sort(y, sp.alpha().desc().limit(1, 2))
+     * -> [b, a]
+     * 
+ * + * Sorting by external keys: + * + *
+     * sort(x, sb.by(w*))
+     * -> [3, 2, 1]
+     * 
+     * sort(x, sb.by(w*).desc())
+     * -> [1, 2, 3]
+     * 
+ * + * Getting external keys: + * + *
+     * sort(x, sp.by(w*).get(k*))
+     * -> [x, y, z]
+     * 
+     * sort(x, sp.by(w*).get(#).get(k*))
+     * -> [3, x, 2, y, 1, z]
+     * 
+ * + * @see #sort(String) + * @see #sort(String, SortingParams, String) + * + * @param key + * @param sortingParameters + * @return a list of sorted elements. + */ + public List sort(final byte[] key, + final SortingParams sortingParameters) { + checkIsInMulti(); + client.sort(key, sortingParameters); + return client.getBinaryMultiBulkReply(); + } + + /** + * BLPOP (and BRPOP) is a blocking list pop primitive. You can see this + * commands as blocking versions of LPOP and RPOP able to block if the + * specified keys don't exist or contain empty lists. + *

+ * The following is a description of the exact semantic. We describe BLPOP + * but the two commands are identical, the only difference is that BLPOP + * pops the element from the left (head) of the list, and BRPOP pops from + * the right (tail). + *

+ * Non blocking behavior + *

+ * When BLPOP is called, if at least one of the specified keys contain a non + * empty list, an element is popped from the head of the list and returned + * to the caller together with the name of the key (BLPOP returns a two + * elements array, the first element is the key, the second the popped + * value). + *

+ * Keys are scanned from left to right, so for instance if you issue BLPOP + * list1 list2 list3 0 against a dataset where list1 does not exist but + * list2 and list3 contain non empty lists, BLPOP guarantees to return an + * element from the list stored at list2 (since it is the first non empty + * list starting from the left). + *

+ * Blocking behavior + *

+ * If none of the specified keys exist or contain non empty lists, BLPOP + * blocks until some other client performs a LPUSH or an RPUSH operation + * against one of the lists. + *

+ * Once new data is present on one of the lists, the client finally returns + * with the name of the key unblocking it and the popped value. + *

+ * When blocking, if a non-zero timeout is specified, the client will + * unblock returning a nil special value if the specified amount of seconds + * passed without a push operation against at least one of the specified + * keys. + *

+ * The timeout argument is interpreted as an integer value. A timeout of + * zero means instead to block forever. + *

+ * Multiple clients blocking for the same keys + *

+ * Multiple clients can block for the same key. They are put into a queue, + * so the first to be served will be the one that started to wait earlier, + * in a first-blpopping first-served fashion. + *

+ * blocking POP inside a MULTI/EXEC transaction + *

+ * BLPOP and BRPOP can be used with pipelining (sending multiple commands + * and reading the replies in batch), but it does not make sense to use + * BLPOP or BRPOP inside a MULTI/EXEC block (a Redis transaction). + *

+ * The behavior of BLPOP inside MULTI/EXEC when the list is empty is to + * return a multi-bulk nil reply, exactly what happens when the timeout is + * reached. If you like science fiction, think at it like if inside + * MULTI/EXEC the time will flow at infinite speed :) + *

+ * Time complexity: O(1) + * + * @see #brpop(int, String...) + * + * @param timeout + * @param keys + * @return BLPOP returns a two-elements array via a multi bulk reply in + * order to return both the unblocking key and the popped value. + *

+ * When a non-zero timeout is specified, and the BLPOP operation + * timed out, the return value is a nil multi bulk reply. Most + * client values will return false or nil accordingly to the + * programming language used. + */ + public List blpop(final int timeout, final byte[]... keys) { + checkIsInMulti(); + final List args = new ArrayList(); + for (final byte[] arg : keys) { + args.add(arg); + } + args.add(Protocol.toByteArray(timeout)); + + client.blpop(args.toArray(new byte[args.size()][])); + client.setTimeoutInfinite(); + final List multiBulkReply = client.getBinaryMultiBulkReply(); + client.rollbackTimeout(); + return multiBulkReply; + } + + /** + * Sort a Set or a List accordingly to the specified parameters and store + * the result at dstkey. + * + * @see #sort(String, SortingParams) + * @see #sort(String) + * @see #sort(String, String) + * + * @param key + * @param sortingParameters + * @param dstkey + * @return The number of elements of the list at dstkey. + */ + public Integer sort(final byte[] key, + final SortingParams sortingParameters, final byte[] dstkey) { + checkIsInMulti(); + client.sort(key, sortingParameters, dstkey); + return client.getIntegerReply(); + } + + /** + * Sort a Set or a List and Store the Result at dstkey. + *

+ * Sort the elements contained in the List, Set, or Sorted Set value at key + * and store the result at dstkey. By default sorting is numeric with + * elements being compared as double precision floating point numbers. This + * is the simplest form of SORT. + * + * @see #sort(String) + * @see #sort(String, SortingParams) + * @see #sort(String, SortingParams, String) + * + * @param key + * @param dstkey + * @return The number of elements of the list at dstkey. + */ + public Integer sort(final byte[] key, final byte[] dstkey) { + checkIsInMulti(); + client.sort(key, dstkey); + return client.getIntegerReply(); + } + + /** + * BLPOP (and BRPOP) is a blocking list pop primitive. You can see this + * commands as blocking versions of LPOP and RPOP able to block if the + * specified keys don't exist or contain empty lists. + *

+ * The following is a description of the exact semantic. We describe BLPOP + * but the two commands are identical, the only difference is that BLPOP + * pops the element from the left (head) of the list, and BRPOP pops from + * the right (tail). + *

+ * Non blocking behavior + *

+ * When BLPOP is called, if at least one of the specified keys contain a non + * empty list, an element is popped from the head of the list and returned + * to the caller together with the name of the key (BLPOP returns a two + * elements array, the first element is the key, the second the popped + * value). + *

+ * Keys are scanned from left to right, so for instance if you issue BLPOP + * list1 list2 list3 0 against a dataset where list1 does not exist but + * list2 and list3 contain non empty lists, BLPOP guarantees to return an + * element from the list stored at list2 (since it is the first non empty + * list starting from the left). + *

+ * Blocking behavior + *

+ * If none of the specified keys exist or contain non empty lists, BLPOP + * blocks until some other client performs a LPUSH or an RPUSH operation + * against one of the lists. + *

+ * Once new data is present on one of the lists, the client finally returns + * with the name of the key unblocking it and the popped value. + *

+ * When blocking, if a non-zero timeout is specified, the client will + * unblock returning a nil special value if the specified amount of seconds + * passed without a push operation against at least one of the specified + * keys. + *

+ * The timeout argument is interpreted as an integer value. A timeout of + * zero means instead to block forever. + *

+ * Multiple clients blocking for the same keys + *

+ * Multiple clients can block for the same key. They are put into a queue, + * so the first to be served will be the one that started to wait earlier, + * in a first-blpopping first-served fashion. + *

+ * blocking POP inside a MULTI/EXEC transaction + *

+ * BLPOP and BRPOP can be used with pipelining (sending multiple commands + * and reading the replies in batch), but it does not make sense to use + * BLPOP or BRPOP inside a MULTI/EXEC block (a Redis transaction). + *

+ * The behavior of BLPOP inside MULTI/EXEC when the list is empty is to + * return a multi-bulk nil reply, exactly what happens when the timeout is + * reached. If you like science fiction, think at it like if inside + * MULTI/EXEC the time will flow at infinite speed :) + *

+ * Time complexity: O(1) + * + * @see #blpop(int, String...) + * + * @param timeout + * @param keys + * @return BLPOP returns a two-elements array via a multi bulk reply in + * order to return both the unblocking key and the popped value. + *

+ * When a non-zero timeout is specified, and the BLPOP operation + * timed out, the return value is a nil multi bulk reply. Most + * client values will return false or nil accordingly to the + * programming language used. + */ + public List brpop(final int timeout, final byte[]... keys) { + checkIsInMulti(); + final List args = new ArrayList(); + for (final byte[] arg : keys) { + args.add(arg); + } + args.add(Protocol.toByteArray(timeout)); + + client.brpop(args.toArray(new byte[args.size()][])); + client.setTimeoutInfinite(); + final List multiBulkReply = client.getBinaryMultiBulkReply(); + client.rollbackTimeout(); + + return multiBulkReply; + } + + /** + * Request for authentication in a password protected Redis server. A Redis + * server can be instructed to require a password before to allow clients to + * issue commands. This is done using the requirepass directive in the Redis + * configuration file. If the password given by the client is correct the + * server replies with an OK status code reply and starts accepting commands + * from the client. Otherwise an error is returned and the clients needs to + * try a new password. Note that for the high performance nature of Redis it + * is possible to try a lot of passwords in parallel in very short time, so + * make sure to generate a strong and very long password so that this attack + * is infeasible. + * + * @param password + * @return Status code reply + */ + public String auth(final String password) { + checkIsInMulti(); + client.auth(password); + return client.getStatusCodeReply(); + } + + public List pipelined(final JedisPipeline jedisPipeline) { + jedisPipeline.setClient(client); + jedisPipeline.execute(); + return client.getAll(); + } + + public void subscribe(final JedisPubSub jedisPubSub, + final String... channels) { + client.setTimeoutInfinite(); + jedisPubSub.proceed(client, channels); + client.rollbackTimeout(); + } + + public Integer publish(final String channel, final String message) { + client.publish(channel, message); + return client.getIntegerReply(); + } + + public void psubscribe(final JedisPubSub jedisPubSub, + final String... patterns) { + client.setTimeoutInfinite(); + jedisPubSub.proceedWithPatterns(client, patterns); + client.rollbackTimeout(); + } + + public Integer zcount(final byte[] key, final double min, final double max) { + checkIsInMulti(); + client.zcount(key, min, max); + return client.getIntegerReply(); + } + + /** + * Return the all the elements in the sorted set at key with a score between + * min and max (including elements with score equal to min or max). + *

+ * The elements having the same score are returned sorted lexicographically + * as ASCII strings (this follows from a property of Redis sorted sets and + * does not involve further computation). + *

+ * Using the optional + * {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's + * possible to get only a range of the matching elements in an SQL-alike + * way. Note that if offset is large the commands needs to traverse the list + * for offset elements and this adds up to the O(M) figure. + *

+ * The {@link #zcount(String, double, double) ZCOUNT} command is similar to + * {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead + * of returning the actual elements in the specified interval, it just + * returns the number of matching elements. + *

+ * Exclusive intervals and infinity + *

+ * min and max can be -inf and +inf, so that you are not required to know + * what's the greatest or smallest element in order to take, for instance, + * elements "up to a given value". + *

+ * Also while the interval is for default closed (inclusive) it's possible + * to specify open intervals prefixing the score with a "(" character, so + * for instance: + *

+ * {@code ZRANGEBYSCORE zset (1.3 5} + *

+ * Will return all the values with score > 1.3 and <= 5, while for instance: + *

+ * {@code ZRANGEBYSCORE zset (5 (10} + *

+ * Will return all the values with score > 5 and < 10 (5 and 10 excluded). + *

+ * Time complexity: + *

+ * O(log(N))+O(M) with N being the number of elements in the sorted set and + * M the number of elements returned by the command, so if M is constant + * (for instance you always ask for the first ten elements with LIMIT) you + * can consider it O(log(N)) + * + * @see #zrangeByScore(String, double, double) + * @see #zrangeByScore(String, double, double, int, int) + * @see #zrangeByScoreWithScores(String, double, double) + * @see #zrangeByScoreWithScores(String, String, String) + * @see #zrangeByScoreWithScores(String, double, double, int, int) + * @see #zcount(String, double, double) + * + * @param key + * @param min + * @param max + * @return Multi bulk reply specifically a list of elements in the specified + * score range. + */ + public Set zrangeByScore(final byte[] key, final double min, + final double max) { + checkIsInMulti(); + client.zrangeByScore(key, min, max); + return new LinkedHashSet(client.getBinaryMultiBulkReply()); + } + + public Set zrangeByScore(final byte[] key, final byte[] min, + final byte[] max) { + checkIsInMulti(); + client.zrangeByScore(key, min, max); + return new LinkedHashSet(client.getBinaryMultiBulkReply()); + } + + /** + * Return the all the elements in the sorted set at key with a score between + * min and max (including elements with score equal to min or max). + *

+ * The elements having the same score are returned sorted lexicographically + * as ASCII strings (this follows from a property of Redis sorted sets and + * does not involve further computation). + *

+ * Using the optional + * {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's + * possible to get only a range of the matching elements in an SQL-alike + * way. Note that if offset is large the commands needs to traverse the list + * for offset elements and this adds up to the O(M) figure. + *

+ * The {@link #zcount(String, double, double) ZCOUNT} command is similar to + * {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead + * of returning the actual elements in the specified interval, it just + * returns the number of matching elements. + *

+ * Exclusive intervals and infinity + *

+ * min and max can be -inf and +inf, so that you are not required to know + * what's the greatest or smallest element in order to take, for instance, + * elements "up to a given value". + *

+ * Also while the interval is for default closed (inclusive) it's possible + * to specify open intervals prefixing the score with a "(" character, so + * for instance: + *

+ * {@code ZRANGEBYSCORE zset (1.3 5} + *

+ * Will return all the values with score > 1.3 and <= 5, while for instance: + *

+ * {@code ZRANGEBYSCORE zset (5 (10} + *

+ * Will return all the values with score > 5 and < 10 (5 and 10 excluded). + *

+ * Time complexity: + *

+ * O(log(N))+O(M) with N being the number of elements in the sorted set and + * M the number of elements returned by the command, so if M is constant + * (for instance you always ask for the first ten elements with LIMIT) you + * can consider it O(log(N)) + * + * @see #zrangeByScore(String, double, double) + * @see #zrangeByScore(String, double, double, int, int) + * @see #zrangeByScoreWithScores(String, double, double) + * @see #zrangeByScoreWithScores(String, double, double, int, int) + * @see #zcount(String, double, double) + * + * @param key + * @param min + * @param max + * @return Multi bulk reply specifically a list of elements in the specified + * score range. + */ + public Set zrangeByScore(final byte[] key, final double min, + final double max, final int offset, final int count) { + checkIsInMulti(); + client.zrangeByScore(key, min, max, offset, count); + return new LinkedHashSet(client.getBinaryMultiBulkReply()); + } + + /** + * Return the all the elements in the sorted set at key with a score between + * min and max (including elements with score equal to min or max). + *

+ * The elements having the same score are returned sorted lexicographically + * as ASCII strings (this follows from a property of Redis sorted sets and + * does not involve further computation). + *

+ * Using the optional + * {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's + * possible to get only a range of the matching elements in an SQL-alike + * way. Note that if offset is large the commands needs to traverse the list + * for offset elements and this adds up to the O(M) figure. + *

+ * The {@link #zcount(String, double, double) ZCOUNT} command is similar to + * {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead + * of returning the actual elements in the specified interval, it just + * returns the number of matching elements. + *

+ * Exclusive intervals and infinity + *

+ * min and max can be -inf and +inf, so that you are not required to know + * what's the greatest or smallest element in order to take, for instance, + * elements "up to a given value". + *

+ * Also while the interval is for default closed (inclusive) it's possible + * to specify open intervals prefixing the score with a "(" character, so + * for instance: + *

+ * {@code ZRANGEBYSCORE zset (1.3 5} + *

+ * Will return all the values with score > 1.3 and <= 5, while for instance: + *

+ * {@code ZRANGEBYSCORE zset (5 (10} + *

+ * Will return all the values with score > 5 and < 10 (5 and 10 excluded). + *

+ * Time complexity: + *

+ * O(log(N))+O(M) with N being the number of elements in the sorted set and + * M the number of elements returned by the command, so if M is constant + * (for instance you always ask for the first ten elements with LIMIT) you + * can consider it O(log(N)) + * + * @see #zrangeByScore(String, double, double) + * @see #zrangeByScore(String, double, double, int, int) + * @see #zrangeByScoreWithScores(String, double, double) + * @see #zrangeByScoreWithScores(String, double, double, int, int) + * @see #zcount(String, double, double) + * + * @param key + * @param min + * @param max + * @return Multi bulk reply specifically a list of elements in the specified + * score range. + */ + public Set zrangeByScoreWithScores(final byte[] key, + final double min, final double max) { + checkIsInMulti(); + client.zrangeByScoreWithScores(key, min, max); + Set set = getBinaryTupledSet(); + return set; + } + + /** + * Return the all the elements in the sorted set at key with a score between + * min and max (including elements with score equal to min or max). + *

+ * The elements having the same score are returned sorted lexicographically + * as ASCII strings (this follows from a property of Redis sorted sets and + * does not involve further computation). + *

+ * Using the optional + * {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's + * possible to get only a range of the matching elements in an SQL-alike + * way. Note that if offset is large the commands needs to traverse the list + * for offset elements and this adds up to the O(M) figure. + *

+ * The {@link #zcount(String, double, double) ZCOUNT} command is similar to + * {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead + * of returning the actual elements in the specified interval, it just + * returns the number of matching elements. + *

+ * Exclusive intervals and infinity + *

+ * min and max can be -inf and +inf, so that you are not required to know + * what's the greatest or smallest element in order to take, for instance, + * elements "up to a given value". + *

+ * Also while the interval is for default closed (inclusive) it's possible + * to specify open intervals prefixing the score with a "(" character, so + * for instance: + *

+ * {@code ZRANGEBYSCORE zset (1.3 5} + *

+ * Will return all the values with score > 1.3 and <= 5, while for instance: + *

+ * {@code ZRANGEBYSCORE zset (5 (10} + *

+ * Will return all the values with score > 5 and < 10 (5 and 10 excluded). + *

+ * Time complexity: + *

+ * O(log(N))+O(M) with N being the number of elements in the sorted set and + * M the number of elements returned by the command, so if M is constant + * (for instance you always ask for the first ten elements with LIMIT) you + * can consider it O(log(N)) + * + * @see #zrangeByScore(String, double, double) + * @see #zrangeByScore(String, double, double, int, int) + * @see #zrangeByScoreWithScores(String, double, double) + * @see #zrangeByScoreWithScores(String, double, double, int, int) + * @see #zcount(String, double, double) + * + * @param key + * @param min + * @param max + * @return Multi bulk reply specifically a list of elements in the specified + * score range. + */ + public Set zrangeByScoreWithScores(final byte[] key, + final double min, final double max, final int offset, + final int count) { + checkIsInMulti(); + client.zrangeByScoreWithScores(key, min, max, offset, count); + Set set = getBinaryTupledSet(); + return set; + } + + private Set getBinaryTupledSet() { + checkIsInMulti(); + List membersWithScores = client.getBinaryMultiBulkReply(); + Set set = new LinkedHashSet(); + Iterator iterator = membersWithScores.iterator(); + while (iterator.hasNext()) { + set.add(new Tuple(iterator.next(), Double.valueOf(new String( + iterator.next(), Protocol.UTF8)))); + } + return set; + } + + /** + * Remove all elements in the sorted set at key with rank between start and + * end. Start and end are 0-based with rank 0 being the element with the + * lowest score. Both start and end can be negative numbers, where they + * indicate offsets starting at the element with the highest rank. For + * example: -1 is the element with the highest score, -2 the element with + * the second highest score and so forth. + *

+ * Time complexity: O(log(N))+O(M) with N being the number of + * elements in the sorted set and M the number of elements removed by the + * operation + * + */ + public Integer zremrangeByRank(final byte[] key, final int start, + final int end) { + checkIsInMulti(); + client.zremrangeByRank(key, start, end); + return client.getIntegerReply(); + } + + /** + * Remove all the elements in the sorted set at key with a score between min + * and max (including elements with score equal to min or max). + *

+ * Time complexity: + *

+ * O(log(N))+O(M) with N being the number of elements in the sorted set and + * M the number of elements removed by the operation + * + * @param key + * @param start + * @param end + * @return Integer reply, specifically the number of elements removed. + */ + public Integer zremrangeByScore(final byte[] key, final double start, + final double end) { + checkIsInMulti(); + client.zremrangeByScore(key, start, end); + return client.getIntegerReply(); + } + + /** + * Creates a union or intersection of N sorted sets given by keys k1 through + * kN, and stores it at dstkey. It is mandatory to provide the number of + * input keys N, before passing the input keys and the other (optional) + * arguments. + *

+ * As the terms imply, the {@link #zinterstore(String, String...) + * ZINTERSTORE} command requires an element to be present in each of the + * given inputs to be inserted in the result. The + * {@link #zunionstore(String, String...) ZUNIONSTORE} command inserts all + * elements across all inputs. + *

+ * Using the WEIGHTS option, it is possible to add weight to each input + * sorted set. This means that the score of each element in the sorted set + * is first multiplied by this weight before being passed to the + * aggregation. When this option is not given, all weights default to 1. + *

+ * With the AGGREGATE option, it's possible to specify how the results of + * the union or intersection are aggregated. This option defaults to SUM, + * where the score of an element is summed across the inputs where it + * exists. When this option is set to be either MIN or MAX, the resulting + * set will contain the minimum or maximum score of an element across the + * inputs where it exists. + *

+ * Time complexity: O(N) + O(M log(M)) with N being the sum of the + * sizes of the input sorted sets, and M being the number of elements in the + * resulting sorted set + * + * @see #zunionstore(String, String...) + * @see #zunionstore(String, ZParams, String...) + * @see #zinterstore(String, String...) + * @see #zinterstore(String, ZParams, String...) + * + * @param dstkey + * @param sets + * @return Integer reply, specifically the number of elements in the sorted + * set at dstkey + */ + public Integer zunionstore(final byte[] dstkey, final byte[]... sets) { + checkIsInMulti(); + client.zunionstore(dstkey, sets); + return client.getIntegerReply(); + } + + /** + * Creates a union or intersection of N sorted sets given by keys k1 through + * kN, and stores it at dstkey. It is mandatory to provide the number of + * input keys N, before passing the input keys and the other (optional) + * arguments. + *

+ * As the terms imply, the {@link #zinterstore(String, String...) + * ZINTERSTORE} command requires an element to be present in each of the + * given inputs to be inserted in the result. The + * {@link #zunionstore(String, String...) ZUNIONSTORE} command inserts all + * elements across all inputs. + *

+ * Using the WEIGHTS option, it is possible to add weight to each input + * sorted set. This means that the score of each element in the sorted set + * is first multiplied by this weight before being passed to the + * aggregation. When this option is not given, all weights default to 1. + *

+ * With the AGGREGATE option, it's possible to specify how the results of + * the union or intersection are aggregated. This option defaults to SUM, + * where the score of an element is summed across the inputs where it + * exists. When this option is set to be either MIN or MAX, the resulting + * set will contain the minimum or maximum score of an element across the + * inputs where it exists. + *

+ * Time complexity: O(N) + O(M log(M)) with N being the sum of the + * sizes of the input sorted sets, and M being the number of elements in the + * resulting sorted set + * + * @see #zunionstore(String, String...) + * @see #zunionstore(String, ZParams, String...) + * @see #zinterstore(String, String...) + * @see #zinterstore(String, ZParams, String...) + * + * @param dstkey + * @param sets + * @param params + * @return Integer reply, specifically the number of elements in the sorted + * set at dstkey + */ + public Integer zunionstore(final byte[] dstkey, final ZParams params, + final byte[]... sets) { + checkIsInMulti(); + client.zunionstore(dstkey, params, sets); + return client.getIntegerReply(); + } + + /** + * Creates a union or intersection of N sorted sets given by keys k1 through + * kN, and stores it at dstkey. It is mandatory to provide the number of + * input keys N, before passing the input keys and the other (optional) + * arguments. + *

+ * As the terms imply, the {@link #zinterstore(String, String...) + * ZINTERSTORE} command requires an element to be present in each of the + * given inputs to be inserted in the result. The + * {@link #zunionstore(String, String...) ZUNIONSTORE} command inserts all + * elements across all inputs. + *

+ * Using the WEIGHTS option, it is possible to add weight to each input + * sorted set. This means that the score of each element in the sorted set + * is first multiplied by this weight before being passed to the + * aggregation. When this option is not given, all weights default to 1. + *

+ * With the AGGREGATE option, it's possible to specify how the results of + * the union or intersection are aggregated. This option defaults to SUM, + * where the score of an element is summed across the inputs where it + * exists. When this option is set to be either MIN or MAX, the resulting + * set will contain the minimum or maximum score of an element across the + * inputs where it exists. + *

+ * Time complexity: O(N) + O(M log(M)) with N being the sum of the + * sizes of the input sorted sets, and M being the number of elements in the + * resulting sorted set + * + * @see #zunionstore(String, String...) + * @see #zunionstore(String, ZParams, String...) + * @see #zinterstore(String, String...) + * @see #zinterstore(String, ZParams, String...) + * + * @param dstkey + * @param sets + * @return Integer reply, specifically the number of elements in the sorted + * set at dstkey + */ + public Integer zinterstore(final byte[] dstkey, final byte[]... sets) { + checkIsInMulti(); + client.zinterstore(dstkey, sets); + return client.getIntegerReply(); + } + + /** + * Creates a union or intersection of N sorted sets given by keys k1 through + * kN, and stores it at dstkey. It is mandatory to provide the number of + * input keys N, before passing the input keys and the other (optional) + * arguments. + *

+ * As the terms imply, the {@link #zinterstore(String, String...) + * ZINTERSTORE} command requires an element to be present in each of the + * given inputs to be inserted in the result. The + * {@link #zunionstore(String, String...) ZUNIONSTORE} command inserts all + * elements across all inputs. + *

+ * Using the WEIGHTS option, it is possible to add weight to each input + * sorted set. This means that the score of each element in the sorted set + * is first multiplied by this weight before being passed to the + * aggregation. When this option is not given, all weights default to 1. + *

+ * With the AGGREGATE option, it's possible to specify how the results of + * the union or intersection are aggregated. This option defaults to SUM, + * where the score of an element is summed across the inputs where it + * exists. When this option is set to be either MIN or MAX, the resulting + * set will contain the minimum or maximum score of an element across the + * inputs where it exists. + *

+ * Time complexity: O(N) + O(M log(M)) with N being the sum of the + * sizes of the input sorted sets, and M being the number of elements in the + * resulting sorted set + * + * @see #zunionstore(String, String...) + * @see #zunionstore(String, ZParams, String...) + * @see #zinterstore(String, String...) + * @see #zinterstore(String, ZParams, String...) + * + * @param dstkey + * @param sets + * @param params + * @return Integer reply, specifically the number of elements in the sorted + * set at dstkey + */ + public Integer zinterstore(final byte[] dstkey, final ZParams params, + final byte[]... sets) { + checkIsInMulti(); + client.zinterstore(dstkey, params, sets); + return client.getIntegerReply(); + } + + /** + * Synchronously save the DB on disk. + *

+ * Save the whole dataset on disk (this means that all the databases are + * saved, as well as keys with an EXPIRE set (the expire is preserved). The + * server hangs while the saving is not completed, no connection is served + * in the meanwhile. An OK code is returned when the DB was fully stored in + * disk. + *

+ * The background variant of this command is {@link #bgsave() BGSAVE} that + * is able to perform the saving in the background while the server + * continues serving other clients. + *

+ * + * @return Status code reply + */ + public String save() { + client.save(); + return client.getStatusCodeReply(); + } + + /** + * Asynchronously save the DB on disk. + *

+ * Save the DB in background. The OK code is immediately returned. Redis + * forks, the parent continues to server the clients, the child saves the DB + * on disk then exit. A client my be able to check if the operation + * succeeded using the LASTSAVE command. + * + * @return Status code reply + */ + public String bgsave() { + client.bgsave(); + return client.getStatusCodeReply(); + } + + /** + * Rewrite the append only file in background when it gets too big. Please + * for detailed information about the Redis Append Only File check the Append + * Only File Howto. + *

+ * BGREWRITEAOF rewrites the Append Only File in background when it gets too + * big. The Redis Append Only File is a Journal, so every operation + * modifying the dataset is logged in the Append Only File (and replayed at + * startup). This means that the Append Only File always grows. In order to + * rebuild its content the BGREWRITEAOF creates a new version of the append + * only file starting directly form the dataset in memory in order to + * guarantee the generation of the minimal number of commands needed to + * rebuild the database. + *

+ * + * @return Status code reply + */ + public String bgrewriteaof() { + client.bgrewriteaof(); + return client.getStatusCodeReply(); + } + + /** + * Return the UNIX time stamp of the last successfully saving of the dataset + * on disk. + *

+ * Return the UNIX TIME of the last DB save executed with success. A client + * may check if a {@link #bgsave() BGSAVE} command succeeded reading the + * LASTSAVE value, then issuing a BGSAVE command and checking at regular + * intervals every N seconds if LASTSAVE changed. + * + * @return Integer reply, specifically an UNIX time stamp. + */ + public Integer lastsave() { + client.lastsave(); + return client.getIntegerReply(); + } + + /** + * Synchronously save the DB on disk, then shutdown the server. + *

+ * Stop all the clients, save the DB, then quit the server. This commands + * makes sure that the DB is switched off without the lost of any data. This + * is not guaranteed if the client uses simply {@link #save() SAVE} and then + * {@link #quit() QUIT} because other clients may alter the DB data between + * the two commands. + * + * @return Status code reply on error. On success nothing is returned since + * the server quits and the connection is closed. + */ + public String shutdown() { + client.shutdown(); + String status = null; + try { + status = client.getStatusCodeReply(); + } catch (JedisException ex) { + status = null; + } + return status; + } + + /** + * Provide information and statistics about the server. + *

+ * The info command returns different information and statistics about the + * server in an format that's simple to parse by computers and easy to read + * by humans. + *

+ * Format of the returned String: + *

+ * All the fields are in the form field:value + * + *

+     * edis_version:0.07
+     * connected_clients:1
+     * connected_slaves:0
+     * used_memory:3187
+     * changes_since_last_save:0
+     * last_save_time:1237655729
+     * total_connections_received:1
+     * total_commands_processed:1
+     * uptime_in_seconds:25
+     * uptime_in_days:0
+     * 
+ * + * Notes + *

+ * used_memory is returned in bytes, and is the total number of bytes + * allocated by the program using malloc. + *

+ * uptime_in_days is redundant since the uptime in seconds contains already + * the full uptime information, this field is only mainly present for + * humans. + *

+ * changes_since_last_save does not refer to the number of key changes, but + * to the number of operations that produced some kind of change in the + * dataset. + *

+ * + * @return Bulk reply + */ + public String info() { + client.info(); + return client.getBulkReply(); + } + + /** + * Dump all the received requests in real time. + *

+ * MONITOR is a debugging command that outputs the whole sequence of + * commands received by the Redis server. is very handy in order to + * understand what is happening into the database. This command is used + * directly via telnet. + * + * @param jedisMonitor + */ + public void monitor(final JedisMonitor jedisMonitor) { + client.monitor(); + jedisMonitor.proceed(client); + } + + /** + * Change the replication settings. + *

+ * The SLAVEOF command can change the replication settings of a slave on the + * fly. If a Redis server is arleady acting as slave, the command SLAVEOF NO + * ONE will turn off the replicaiton turning the Redis server into a MASTER. + * In the proper form SLAVEOF hostname port will make the server a slave of + * the specific server listening at the specified hostname and port. + *

+ * If a server is already a slave of some master, SLAVEOF hostname port will + * stop the replication against the old server and start the + * synchrnonization against the new one discarding the old dataset. + *

+ * The form SLAVEOF no one will stop replication turning the server into a + * MASTER but will not discard the replication. So if the old master stop + * working it is possible to turn the slave into a master and set the + * application to use the new master in read/write. Later when the other + * Redis server will be fixed it can be configured in order to work as + * slave. + *

+ * + * @param host + * @param port + * @return Status code reply + */ + public String slaveof(final String host, final int port) { + client.slaveof(host, port); + return client.getStatusCodeReply(); + } + + public String slaveofNoOne() { + client.slaveofNoOne(); + return client.getStatusCodeReply(); + } + + /** + * Retrieve the configuration of a running Redis server. Not all the + * configuration parameters are supported. + *

+ * CONFIG GET returns the current configuration parameters. This sub command + * only accepts a single argument, that is glob style pattern. All the + * configuration parameters matching this parameter are reported as a list + * of key-value pairs. + *

+ * Example: + * + *

+     * $ redis-cli config get '*'
+     * 1. "dbfilename"
+     * 2. "dump.rdb"
+     * 3. "requirepass"
+     * 4. (nil)
+     * 5. "masterauth"
+     * 6. (nil)
+     * 7. "maxmemory"
+     * 8. "0\n"
+     * 9. "appendfsync"
+     * 10. "everysec"
+     * 11. "save"
+     * 12. "3600 1 300 100 60 10000"
+     * 
+     * $ redis-cli config get 'm*'
+     * 1. "masterauth"
+     * 2. (nil)
+     * 3. "maxmemory"
+     * 4. "0\n"
+     * 
+ * + * @param pattern + * @return Bulk reply. + */ + public List configGet(final String pattern) { + client.configGet(pattern); + return client.getMultiBulkReply(); + } + + /** + * Alter the configuration of a running Redis server. Not all the + * configuration parameters are supported. + *

+ * The list of configuration parameters supported by CONFIG SET can be + * obtained issuing a {@link #configGet(String) CONFIG GET *} command. + *

+ * The configuration set using CONFIG SET is immediately loaded by the Redis + * server that will start acting as specified starting from the next + * command. + *

+ * + * Parameters value format + *

+ * The value of the configuration parameter is the same as the one of the + * same parameter in the Redis configuration file, with the following + * exceptions: + *

+ *

    + *
  • The save paramter is a list of space-separated integers. Every pair + * of integers specify the time and number of changes limit to trigger a + * save. For instance the command CONFIG SET save "3600 10 60 10000" will + * configure the server to issue a background saving of the RDB file every + * 3600 seconds if there are at least 10 changes in the dataset, and every + * 60 seconds if there are at least 10000 changes. To completely disable + * automatic snapshots just set the parameter as an empty string. + *
  • All the integer parameters representing memory are returned and + * accepted only using bytes as unit. + *
+ * + * @param parameter + * @param value + * @return Status code reply + */ + public String configSet(final String parameter, final String value) { + client.configSet(parameter, value); + return client.getStatusCodeReply(); + } + + public boolean isConnected() { + return client.isConnected(); + } + + public Integer strlen(final byte[] key) { + client.strlen(key); + return client.getIntegerReply(); + } + + public void sync() { + client.sync(); + } + + public Integer lpushx(final byte[] key, final byte[] string) { + client.lpushx(key, string); + return client.getIntegerReply(); + } + + /** + * Undo a {@link #expire(String, int) expire} at turning the expire key into + * a normal key. + *

+ * Time complexity: O(1) + * + * @param key + * @return Integer reply, specifically: 1: the key is now persist. 0: the + * key is not persist (only happens when key not set). + */ + public Integer persist(final byte[] key) { + client.persist(key); + return client.getIntegerReply(); + } + + public Integer rpushx(final byte[] key, final byte[] string) { + client.rpushx(key, string); + return client.getIntegerReply(); + } + + public byte[] echo(final byte[] string) { + client.echo(string); + return client.getBinaryBulkReply(); + } + + public Integer linsert(final byte[] key, final LIST_POSITION where, + final byte[] pivot, final byte[] value) { + client.linsert(key, where, pivot, value); + return client.getIntegerReply(); + } + + public String debug(final DebugParams params) { + client.debug(params); + return client.getStatusCodeReply(); + } + + public Client getClient() { + return client; + } +} \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/BinaryJedisCommands.java b/src/main/java/redis/clients/jedis/BinaryJedisCommands.java new file mode 100644 index 0000000..052c686 --- /dev/null +++ b/src/main/java/redis/clients/jedis/BinaryJedisCommands.java @@ -0,0 +1,159 @@ +package redis.clients.jedis; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import redis.clients.jedis.BinaryClient.LIST_POSITION; + +/** + * Common interface for sharded and non-sharded BinaryJedis + */ +public interface BinaryJedisCommands { + String set(byte[] key, byte[] value); + + byte[] get(byte[] key); + + Integer exists(byte[] key); + + String type(byte[] key); + + Integer expire(byte[] key, int seconds); + + Integer expireAt(byte[] key, long unixTime); + + Integer ttl(byte[] key); + + byte[] getSet(byte[] key, byte[] value); + + Integer setnx(byte[] key, byte[] value); + + String setex(byte[] key, int seconds, byte[] value); + + Integer decrBy(byte[] key, int integer); + + Integer decr(byte[] key); + + Integer incrBy(byte[] key, int integer); + + Integer incr(byte[] key); + + Integer append(byte[] key, byte[] value); + + byte[] substr(byte[] key, int start, int end); + + Integer hset(byte[] key, byte[] field, byte[] value); + + byte[] hget(byte[] key, byte[] field); + + Integer hsetnx(byte[] key, byte[] field, byte[] value); + + String hmset(byte[] key, Map hash); + + List hmget(byte[] key, byte[]... fields); + + Integer hincrBy(byte[] key, byte[] field, int value); + + Integer hexists(byte[] key, byte[] field); + + Integer hdel(byte[] key, byte[] field); + + Integer hlen(byte[] key); + + Set hkeys(byte[] key); + + Collection hvals(byte[] key); + + Map hgetAll(byte[] key); + + Integer rpush(byte[] key, byte[] string); + + Integer lpush(byte[] key, byte[] string); + + Integer llen(byte[] key); + + List lrange(byte[] key, int start, int end); + + String ltrim(byte[] key, int start, int end); + + byte[] lindex(byte[] key, int index); + + String lset(byte[] key, int index, byte[] value); + + Integer lrem(byte[] key, int count, byte[] value); + + byte[] lpop(byte[] key); + + byte[] rpop(byte[] key); + + Integer sadd(byte[] key, byte[] member); + + Set smembers(byte[] key); + + Integer srem(byte[] key, byte[] member); + + byte[] spop(byte[] key); + + Integer scard(byte[] key); + + Integer sismember(byte[] key, byte[] member); + + byte[] srandmember(byte[] key); + + Integer zadd(byte[] key, double score, byte[] member); + + Set zrange(byte[] key, int start, int end); + + Integer zrem(byte[] key, byte[] member); + + Double zincrby(byte[] key, double score, byte[] member); + + Integer zrank(byte[] key, byte[] member); + + Integer zrevrank(byte[] key, byte[] member); + + Set zrevrange(byte[] key, int start, int end); + + Set zrangeWithScores(byte[] key, int start, int end); + + Set zrevrangeWithScores(byte[] key, int start, int end); + + Integer zcard(byte[] key); + + Double zscore(byte[] key, byte[] member); + + List sort(byte[] key); + + List sort(byte[] key, SortingParams sortingParameters); + + Integer zcount(byte[] key, double min, double max); + + Set zrangeByScore(byte[] key, double min, double max); + + Set zrangeByScore( + byte[] key, + double min, + double max, + int offset, + int count); + + Set zrangeByScoreWithScores(byte[] key, double min, double max); + + Set zrangeByScoreWithScores( + byte[] key, + double min, + double max, + int offset, + int count); + + Integer zremrangeByRank(byte[] key, int start, int end); + + Integer zremrangeByScore(byte[] key, double start, double end); + + Integer linsert( + byte[] key, + LIST_POSITION where, + byte[] pivot, + byte[] value); +} diff --git a/src/main/java/redis/clients/jedis/BinaryShardedJedis.java b/src/main/java/redis/clients/jedis/BinaryShardedJedis.java new file mode 100644 index 0000000..56630d5 --- /dev/null +++ b/src/main/java/redis/clients/jedis/BinaryShardedJedis.java @@ -0,0 +1,381 @@ +package redis.clients.jedis; + +import java.io.IOException; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +import redis.clients.jedis.BinaryClient.LIST_POSITION; +import redis.clients.util.Hashing; +import redis.clients.util.Sharded; + +public class BinaryShardedJedis extends Sharded + implements BinaryJedisCommands { + public BinaryShardedJedis(List shards) { + super(shards); + } + + public BinaryShardedJedis(List shards, Hashing algo) { + super(shards, algo); + } + + public BinaryShardedJedis(List shards, Pattern keyTagPattern) { + super(shards, keyTagPattern); + } + + public BinaryShardedJedis(List shards, Hashing algo, + Pattern keyTagPattern) { + super(shards, algo, keyTagPattern); + } + + public void disconnect() throws IOException { + for (JedisShardInfo jedis : getAllShards()) { + jedis.getResource().disconnect(); + } + } + + protected Jedis create(JedisShardInfo shard) { + return new Jedis(shard); + } + + public String set(byte[] key, byte[] value) { + Jedis j = getShard(key); + return j.set(key, value); + } + + public byte[] get(byte[] key) { + Jedis j = getShard(key); + return j.get(key); + } + + public Integer exists(byte[] key) { + Jedis j = getShard(key); + return j.exists(key); + } + + public String type(byte[] key) { + Jedis j = getShard(key); + return j.type(key); + } + + public Integer expire(byte[] key, int seconds) { + Jedis j = getShard(key); + return j.expire(key, seconds); + } + + public Integer expireAt(byte[] key, long unixTime) { + Jedis j = getShard(key); + return j.expireAt(key, unixTime); + } + + public Integer ttl(byte[] key) { + Jedis j = getShard(key); + return j.ttl(key); + } + + public byte[] getSet(byte[] key, byte[] value) { + Jedis j = getShard(key); + return j.getSet(key, value); + } + + public Integer setnx(byte[] key, byte[] value) { + Jedis j = getShard(key); + return j.setnx(key, value); + } + + public String setex(byte[] key, int seconds, byte[] value) { + Jedis j = getShard(key); + return j.setex(key, seconds, value); + } + + public Integer decrBy(byte[] key, int integer) { + Jedis j = getShard(key); + return j.decrBy(key, integer); + } + + public Integer decr(byte[] key) { + Jedis j = getShard(key); + return j.decr(key); + } + + public Integer incrBy(byte[] key, int integer) { + Jedis j = getShard(key); + return j.incrBy(key, integer); + } + + public Integer incr(byte[] key) { + Jedis j = getShard(key); + return j.incr(key); + } + + public Integer append(byte[] key, byte[] value) { + Jedis j = getShard(key); + return j.append(key, value); + } + + public byte[] substr(byte[] key, int start, int end) { + Jedis j = getShard(key); + return j.substr(key, start, end); + } + + public Integer hset(byte[] key, byte[] field, byte[] value) { + Jedis j = getShard(key); + return j.hset(key, field, value); + } + + public byte[] hget(byte[] key, byte[] field) { + Jedis j = getShard(key); + return j.hget(key, field); + } + + public Integer hsetnx(byte[] key, byte[] field, byte[] value) { + Jedis j = getShard(key); + return j.hsetnx(key, field, value); + } + + public String hmset(byte[] key, Map hash) { + Jedis j = getShard(key); + return j.hmset(key, hash); + } + + public List hmget(byte[] key, byte[]... fields) { + Jedis j = getShard(key); + return j.hmget(key, fields); + } + + public Integer hincrBy(byte[] key, byte[] field, int value) { + Jedis j = getShard(key); + return j.hincrBy(key, field, value); + } + + public Integer hexists(byte[] key, byte[] field) { + Jedis j = getShard(key); + return j.hexists(key, field); + } + + public Integer hdel(byte[] key, byte[] field) { + Jedis j = getShard(key); + return j.hdel(key, field); + } + + public Integer hlen(byte[] key) { + Jedis j = getShard(key); + return j.hlen(key); + } + + public Set hkeys(byte[] key) { + Jedis j = getShard(key); + return j.hkeys(key); + } + + public Collection hvals(byte[] key) { + Jedis j = getShard(key); + return j.hvals(key); + } + + public Map hgetAll(byte[] key) { + Jedis j = getShard(key); + return j.hgetAll(key); + } + + public Integer rpush(byte[] key, byte[] string) { + Jedis j = getShard(key); + return j.rpush(key, string); + } + + public Integer lpush(byte[] key, byte[] string) { + Jedis j = getShard(key); + return j.lpush(key, string); + } + + public Integer llen(byte[] key) { + Jedis j = getShard(key); + return j.llen(key); + } + + public List lrange(byte[] key, int start, int end) { + Jedis j = getShard(key); + return j.lrange(key, start, end); + } + + public String ltrim(byte[] key, int start, int end) { + Jedis j = getShard(key); + return j.ltrim(key, start, end); + } + + public byte[] lindex(byte[] key, int index) { + Jedis j = getShard(key); + return j.lindex(key, index); + } + + public String lset(byte[] key, int index, byte[] value) { + Jedis j = getShard(key); + return j.lset(key, index, value); + } + + public Integer lrem(byte[] key, int count, byte[] value) { + Jedis j = getShard(key); + return j.lrem(key, count, value); + } + + public byte[] lpop(byte[] key) { + Jedis j = getShard(key); + return j.lpop(key); + } + + public byte[] rpop(byte[] key) { + Jedis j = getShard(key); + return j.rpop(key); + } + + public Integer sadd(byte[] key, byte[] member) { + Jedis j = getShard(key); + return j.sadd(key, member); + } + + public Set smembers(byte[] key) { + Jedis j = getShard(key); + return j.smembers(key); + } + + public Integer srem(byte[] key, byte[] member) { + Jedis j = getShard(key); + return j.srem(key, member); + } + + public byte[] spop(byte[] key) { + Jedis j = getShard(key); + return j.spop(key); + } + + public Integer scard(byte[] key) { + Jedis j = getShard(key); + return j.scard(key); + } + + public Integer sismember(byte[] key, byte[] member) { + Jedis j = getShard(key); + return j.sismember(key, member); + } + + public byte[] srandmember(byte[] key) { + Jedis j = getShard(key); + return j.srandmember(key); + } + + public Integer zadd(byte[] key, double score, byte[] member) { + Jedis j = getShard(key); + return j.zadd(key, score, member); + } + + public Set zrange(byte[] key, int start, int end) { + Jedis j = getShard(key); + return j.zrange(key, start, end); + } + + public Integer zrem(byte[] key, byte[] member) { + Jedis j = getShard(key); + return j.zrem(key, member); + } + + public Double zincrby(byte[] key, double score, byte[] member) { + Jedis j = getShard(key); + return j.zincrby(key, score, member); + } + + public Integer zrank(byte[] key, byte[] member) { + Jedis j = getShard(key); + return j.zrank(key, member); + } + + public Integer zrevrank(byte[] key, byte[] member) { + Jedis j = getShard(key); + return j.zrevrank(key, member); + } + + public Set zrevrange(byte[] key, int start, int end) { + Jedis j = getShard(key); + return j.zrevrange(key, start, end); + } + + public Set zrangeWithScores(byte[] key, int start, int end) { + Jedis j = getShard(key); + return j.zrangeWithScores(key, start, end); + } + + public Set zrevrangeWithScores(byte[] key, int start, int end) { + Jedis j = getShard(key); + return j.zrevrangeWithScores(key, start, end); + } + + public Integer zcard(byte[] key) { + Jedis j = getShard(key); + return j.zcard(key); + } + + public Double zscore(byte[] key, byte[] member) { + Jedis j = getShard(key); + return j.zscore(key, member); + } + + public List sort(byte[] key) { + Jedis j = getShard(key); + return j.sort(key); + } + + public List sort(byte[] key, SortingParams sortingParameters) { + Jedis j = getShard(key); + return j.sort(key, sortingParameters); + } + + public Integer zcount(byte[] key, double min, double max) { + Jedis j = getShard(key); + return j.zcount(key, min, max); + } + + public Set zrangeByScore(byte[] key, double min, double max) { + Jedis j = getShard(key); + return j.zrangeByScore(key, min, max); + } + + public Set zrangeByScore(byte[] key, double min, double max, + int offset, int count) { + Jedis j = getShard(key); + return j.zrangeByScore(key, min, max, offset, count); + } + + public Set zrangeByScoreWithScores(byte[] key, double min, double max) { + Jedis j = getShard(key); + return j.zrangeByScoreWithScores(key, min, max); + } + + public Set zrangeByScoreWithScores(byte[] key, double min, + double max, int offset, int count) { + Jedis j = getShard(key); + return j.zrangeByScoreWithScores(key, min, max, offset, count); + } + + public Integer zremrangeByRank(byte[] key, int start, int end) { + Jedis j = getShard(key); + return j.zremrangeByRank(key, start, end); + } + + public Integer zremrangeByScore(byte[] key, double start, double end) { + Jedis j = getShard(key); + return j.zremrangeByScore(key, start, end); + } + + public Integer linsert(byte[] key, LIST_POSITION where, byte[] pivot, + byte[] value) { + Jedis j = getShard(key); + return j.linsert(key, where, pivot, value); + } + + public List pipelined(ShardedJedisPipeline shardedJedisPipeline) { + shardedJedisPipeline.setShardedJedis(this); + shardedJedisPipeline.execute(); + return shardedJedisPipeline.getResults(); + } +} \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/BinaryTransaction.java b/src/main/java/redis/clients/jedis/BinaryTransaction.java new file mode 100644 index 0000000..5ce4f88 --- /dev/null +++ b/src/main/java/redis/clients/jedis/BinaryTransaction.java @@ -0,0 +1,430 @@ +package redis.clients.jedis; + +import java.util.List; +import java.util.Map; + +public class BinaryTransaction { + protected Client client = null; + + public BinaryTransaction() { + } + + public BinaryTransaction(final Client client) { + this.client = client; + } + + public String ping() { + client.ping(); + return client.getStatusCodeReply(); + } + + public String set(final byte[] key, final byte[] value) { + client.set(key, value); + return client.getStatusCodeReply(); + } + + public String get(final byte[] key) { + client.get(key); + return client.getStatusCodeReply(); + } + + public String exists(final byte[] key) { + client.exists(key); + return client.getStatusCodeReply(); + } + + public String del(final byte[]... keys) { + client.del(keys); + return client.getStatusCodeReply(); + } + + public String type(final byte[] key) { + client.type(key); + return client.getStatusCodeReply(); + } + + public String flushDB() { + client.flushDB(); + return client.getStatusCodeReply(); + } + + public String keys(final byte[] pattern) { + client.keys(pattern); + return client.getStatusCodeReply(); + } + + public byte[] randomBinaryKey() { + client.randomKey(); + return client.getBinaryBulkReply(); + } + + public String rename(final byte[] oldkey, final byte[] newkey) { + client.rename(oldkey, newkey); + return client.getStatusCodeReply(); + } + + public String renamenx(final byte[] oldkey, final byte[] newkey) { + client.renamenx(oldkey, newkey); + return client.getStatusCodeReply(); + } + + public String dbSize() { + client.dbSize(); + return client.getStatusCodeReply(); + } + + public String expire(final byte[] key, final int seconds) { + client.expire(key, seconds); + return client.getStatusCodeReply(); + } + + public String expireAt(final byte[] key, final long unixTime) { + client.expireAt(key, unixTime); + return client.getStatusCodeReply(); + } + + public String ttl(final byte[] key) { + client.ttl(key); + return client.getStatusCodeReply(); + } + + public String select(final int index) { + client.select(index); + return client.getStatusCodeReply(); + } + + public String move(final byte[] key, final int dbIndex) { + client.move(key, dbIndex); + return client.getStatusCodeReply(); + } + + public String flushAll() { + client.flushAll(); + return client.getStatusCodeReply(); + } + + public String getSet(final byte[] key, final byte[] value) { + client.getSet(key, value); + return client.getStatusCodeReply(); + } + + public String mget(final byte[]... keys) { + client.mget(keys); + return client.getStatusCodeReply(); + } + + public String setnx(final byte[] key, final byte[] value) { + client.setnx(key, value); + return client.getStatusCodeReply(); + } + + public String setex(final byte[] key, final int seconds, final byte[] value) { + client.setex(key, seconds, value); + return client.getStatusCodeReply(); + } + + public String mset(final byte[]... keysvalues) { + client.mset(keysvalues); + return client.getStatusCodeReply(); + } + + public String msetnx(final byte[]... keysvalues) { + client.msetnx(keysvalues); + return client.getStatusCodeReply(); + } + + public String decrBy(final byte[] key, final int integer) { + client.decrBy(key, integer); + return client.getStatusCodeReply(); + } + + public String decr(final byte[] key) { + client.decr(key); + return client.getStatusCodeReply(); + } + + public String incrBy(final byte[] key, final int integer) { + client.incrBy(key, integer); + return client.getStatusCodeReply(); + } + + public String incr(final byte[] key) { + client.incr(key); + return client.getStatusCodeReply(); + } + + public String append(final byte[] key, final byte[] value) { + client.append(key, value); + return client.getStatusCodeReply(); + } + + public String substr(final byte[] key, final int start, final int end) { + client.substr(key, start, end); + return client.getStatusCodeReply(); + } + + public String hset(final byte[] key, final byte[] field, final byte[] value) { + client.hset(key, field, value); + return client.getStatusCodeReply(); + } + + public String hget(final byte[] key, final byte[] field) { + client.hget(key, field); + return client.getStatusCodeReply(); + } + + public String hsetnx(final byte[] key, final byte[] field, + final byte[] value) { + client.hsetnx(key, field, value); + return client.getStatusCodeReply(); + } + + public String hmset(final byte[] key, final Map hash) { + client.hmset(key, hash); + return client.getStatusCodeReply(); + } + + public String hmget(final byte[] key, final byte[]... fields) { + client.hmget(key, fields); + return client.getStatusCodeReply(); + } + + public String hincrBy(final byte[] key, final byte[] field, final int value) { + client.hincrBy(key, field, value); + return client.getStatusCodeReply(); + } + + public String hexists(final byte[] key, final byte[] field) { + client.hexists(key, field); + return client.getStatusCodeReply(); + } + + public String hdel(final byte[] key, final byte[] field) { + client.hdel(key, field); + return client.getStatusCodeReply(); + } + + public String hlen(final byte[] key) { + client.hlen(key); + return client.getStatusCodeReply(); + } + + public String hkeys(final byte[] key) { + client.hkeys(key); + return client.getStatusCodeReply(); + } + + public String hvals(final byte[] key) { + client.hvals(key); + return client.getStatusCodeReply(); + } + + public String hgetAll(final byte[] key) { + client.hgetAll(key); + return client.getStatusCodeReply(); + } + + public String rpush(final byte[] key, final byte[] string) { + client.rpush(key, string); + return client.getStatusCodeReply(); + } + + public String lpush(final byte[] key, final byte[] string) { + client.lpush(key, string); + return client.getStatusCodeReply(); + } + + public String llen(final byte[] key) { + client.llen(key); + return client.getStatusCodeReply(); + } + + public String lrange(final byte[] key, final int start, final int end) { + client.lrange(key, start, end); + return client.getStatusCodeReply(); + } + + public String ltrim(final byte[] key, final int start, final int end) { + client.ltrim(key, start, end); + return client.getStatusCodeReply(); + } + + public String lindex(final byte[] key, final int index) { + client.lindex(key, index); + return client.getStatusCodeReply(); + } + + public String lset(final byte[] key, final int index, final byte[] value) { + client.lset(key, index, value); + return client.getStatusCodeReply(); + } + + public String lrem(final byte[] key, final int count, final byte[] value) { + client.lrem(key, count, value); + return client.getStatusCodeReply(); + } + + public String lpop(final byte[] key) { + client.lpop(key); + return client.getStatusCodeReply(); + } + + public String rpop(final byte[] key) { + client.rpop(key); + return client.getStatusCodeReply(); + } + + public String rpoplpush(final byte[] srckey, final byte[] dstkey) { + client.rpoplpush(srckey, dstkey); + return client.getStatusCodeReply(); + } + + public String sadd(final byte[] key, final byte[] member) { + client.sadd(key, member); + return client.getStatusCodeReply(); + } + + public String smembers(final byte[] key) { + client.smembers(key); + return client.getStatusCodeReply(); + } + + public String srem(final byte[] key, final byte[] member) { + client.srem(key, member); + return client.getStatusCodeReply(); + } + + public String spop(final byte[] key) { + client.spop(key); + return client.getStatusCodeReply(); + } + + public String smove(final byte[] srckey, final byte[] dstkey, + final byte[] member) { + client.smove(srckey, dstkey, member); + return client.getStatusCodeReply(); + } + + public String scard(final byte[] key) { + client.scard(key); + return client.getStatusCodeReply(); + } + + public String sismember(final byte[] key, final byte[] member) { + client.sismember(key, member); + return client.getStatusCodeReply(); + } + + public String sinter(final byte[]... keys) { + client.sinter(keys); + return client.getStatusCodeReply(); + } + + public String sinterstore(final byte[] dstkey, final byte[]... keys) { + client.sinterstore(dstkey, keys); + return client.getStatusCodeReply(); + } + + public String sunion(final byte[]... keys) { + client.sunion(keys); + return client.getStatusCodeReply(); + } + + public String sunionstore(final byte[] dstkey, final byte[]... keys) { + client.sunionstore(dstkey, keys); + return client.getStatusCodeReply(); + } + + public String sdiff(final byte[]... keys) { + client.sdiff(keys); + return client.getStatusCodeReply(); + } + + public String sdiffstore(final byte[] dstkey, final byte[]... keys) { + client.sdiffstore(dstkey, keys); + return client.getStatusCodeReply(); + } + + public String srandmember(final byte[] key) { + client.srandmember(key); + return client.getStatusCodeReply(); + } + + public String zadd(final byte[] key, final double score, final byte[] member) { + client.zadd(key, score, member); + return client.getStatusCodeReply(); + } + + public String zrange(final byte[] key, final int start, final int end) { + client.zrange(key, start, end); + return client.getStatusCodeReply(); + } + + public String zrem(final byte[] key, final byte[] member) { + client.zrem(key, member); + return client.getStatusCodeReply(); + } + + public String zincrby(final byte[] key, final double score, + final byte[] member) { + client.zincrby(key, score, member); + return client.getStatusCodeReply(); + } + + public String zrank(final byte[] key, final byte[] member) { + client.zrank(key, member); + return client.getStatusCodeReply(); + } + + public String zrevrank(final byte[] key, final byte[] member) { + client.zrevrank(key, member); + return client.getStatusCodeReply(); + } + + public String zrevrange(final byte[] key, final int start, final int end) { + client.zrevrange(key, start, end); + return client.getStatusCodeReply(); + } + + public String zrangeWithScores(final byte[] key, final int start, + final int end) { + client.zrangeWithScores(key, start, end); + return client.getStatusCodeReply(); + } + + public String zrevrangeWithScores(final byte[] key, final int start, + final int end) { + client.zrevrangeWithScores(key, start, end); + return client.getStatusCodeReply(); + } + + public String zcard(final byte[] key) { + client.zcard(key); + return client.getStatusCodeReply(); + } + + public String zscore(final byte[] key, final byte[] member) { + client.zscore(key, member); + return client.getStatusCodeReply(); + } + + public List exec() { + client.exec(); + + return client.getObjectMultiBulkReply(); + } + + public String sort(final byte[] key) { + client.sort(key); + return client.getStatusCodeReply(); + } + + public String sort(final byte[] key, final SortingParams sortingParameters) { + client.sort(key, sortingParameters); + return client.getStatusCodeReply(); + } + + public void discard() { + client.discard(); + } +} \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index 78d3d73..9e66593 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -1,607 +1,502 @@ package redis.clients.jedis; -import java.util.ArrayList; -import java.util.List; +import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; -public class Client extends Connection { - public enum LIST_POSITION { - BEFORE, AFTER - } - - private boolean isInMulti; - - public boolean isInMulti() { - return isInMulti; - } - - public Client(String host) { +public class Client extends BinaryClient { + public Client(final String host) { super(host); } - public Client(String host, int port) { + public Client(final String host, final int port) { super(host, port); } - public void ping() { - sendCommand("PING"); + public void set(final String key, final String value) { + set(key.getBytes(Protocol.UTF8), value.getBytes(Protocol.UTF8)); } - public void set(String key, String value) { - sendCommand("SET", key, value); + public void get(final String key) { + get(key.getBytes(Protocol.UTF8)); } - public void get(String key) { - sendCommand("GET", key); + public void exists(final String key) { + exists(key.getBytes(Protocol.UTF8)); } - public void quit() { - sendCommand("QUIT"); - } - - public void exists(String key) { - sendCommand("EXISTS", key); - } - - public void del(String... keys) { - sendCommand("DEL", keys); - } - - public void type(String key) { - sendCommand("TYPE", key); - } - - public void flushDB() { - sendCommand("FLUSHDB"); - } - - public void keys(String pattern) { - sendCommand("KEYS", pattern); - } - - public void randomKey() { - sendCommand("RANDOMKEY"); - } - - public void rename(String oldkey, String newkey) { - sendCommand("RENAME", oldkey, newkey); - } - - public void renamenx(String oldkey, String newkey) { - sendCommand("RENAMENX", oldkey, newkey); - } - - public void dbSize() { - sendCommand("DBSIZE"); - } - - public void expire(String key, int seconds) { - sendCommand("EXPIRE", key, String.valueOf(seconds)); - } - - public void expireAt(String key, long unixTime) { - sendCommand("EXPIREAT", key, String.valueOf(unixTime)); - } - - public void ttl(String key) { - sendCommand("TTL", key); - } - - public void select(int index) { - sendCommand("SELECT", String.valueOf(index)); - } - - public void move(String key, int dbIndex) { - sendCommand("MOVE", key, String.valueOf(dbIndex)); - } - - public void flushAll() { - sendCommand("FLUSHALL"); - } - - public void getSet(String key, String value) { - sendCommand("GETSET", key, value); - } - - public void mget(String... keys) { - sendCommand("MGET", keys); - } - - public void setnx(String key, String value) { - sendCommand("SETNX", key, value); - } - - public void setex(String key, int seconds, String value) { - sendCommand("SETEX", key, String.valueOf(seconds), value); - } - - public void mset(String... keysvalues) { - sendCommand("MSET", keysvalues); - } - - public void msetnx(String... keysvalues) { - sendCommand("MSETNX", keysvalues); - } - - public void decrBy(String key, int integer) { - sendCommand("DECRBY", key, String.valueOf(integer)); - } - - public void decr(String key) { - sendCommand("DECR", key); - } - - public void incrBy(String key, int integer) { - sendCommand("INCRBY", key, String.valueOf(integer)); - } - - public void incr(String key) { - sendCommand("INCR", key); - } - - public void append(String key, String value) { - sendCommand("APPEND", key, value); - } - - public void substr(String key, int start, int end) { - sendCommand("SUBSTR", key, String.valueOf(start), String.valueOf(end)); - } - - public void hset(String key, String field, String value) { - sendCommand("HSET", key, field, value); - } - - public void hget(String key, String field) { - sendCommand("HGET", key, field); - } - - public void hsetnx(String key, String field, String value) { - sendCommand("HSETNX", key, field, value); - } - - public void hmset(String key, Map hash) { - List params = new ArrayList(); - params.add(key); - - for (String field : hash.keySet()) { - params.add(field); - params.add(hash.get(field)); + public void del(final String... keys) { + final byte[][] bkeys = new byte[keys.length][]; + for (int i = 0; i < keys.length; i++) { + bkeys[i] = keys[i].getBytes(Protocol.UTF8); } - sendCommand("HMSET", params.toArray(new String[params.size()])); + del(bkeys); } - public void hmget(String key, String... fields) { - String[] params = new String[fields.length + 1]; - params[0] = key; - System.arraycopy(fields, 0, params, 1, fields.length); - sendCommand("HMGET", params); + public void type(final String key) { + type(key.getBytes(Protocol.UTF8)); } - public void hincrBy(String key, String field, int value) { - sendCommand("HINCRBY", key, field, String.valueOf(value)); + public void keys(final String pattern) { + keys(pattern.getBytes(Protocol.UTF8)); } - public void hexists(String key, String field) { - sendCommand("HEXISTS", key, field); + public void rename(final String oldkey, final String newkey) { + rename(oldkey.getBytes(Protocol.UTF8), newkey.getBytes(Protocol.UTF8)); } - public void hdel(String key, String field) { - sendCommand("HDEL", key, field); + public void renamenx(final String oldkey, final String newkey) { + renamenx(oldkey.getBytes(Protocol.UTF8), newkey.getBytes(Protocol.UTF8)); } - public void hlen(String key) { - sendCommand("HLEN", key); + public void expire(final String key, final int seconds) { + expire(key.getBytes(Protocol.UTF8), seconds); } - public void hkeys(String key) { - sendCommand("HKEYS", key); + public void expireAt(final String key, final long unixTime) { + expireAt(key.getBytes(Protocol.UTF8), unixTime); } - public void hvals(String key) { - sendCommand("HVALS", key); + public void ttl(final String key) { + ttl(key.getBytes(Protocol.UTF8)); } - public void hgetAll(String key) { - sendCommand("HGETALL", key); + public void move(final String key, final int dbIndex) { + move(key.getBytes(Protocol.UTF8), dbIndex); } - public void rpush(String key, String string) { - sendCommand("RPUSH", key, string); + public void getSet(final String key, final String value) { + getSet(key.getBytes(Protocol.UTF8), value.getBytes(Protocol.UTF8)); } - public void lpush(String key, String string) { - sendCommand("LPUSH", key, string); - } - - public void llen(String key) { - sendCommand("LLEN", key); - } - - public void lrange(String key, int start, int end) { - sendCommand("LRANGE", key, String.valueOf(start), String.valueOf(end)); - } - - public void ltrim(String key, int start, int end) { - sendCommand("LTRIM", key, String.valueOf(start), String.valueOf(end)); - } - - public void lindex(String key, int index) { - sendCommand("LINDEX", key, String.valueOf(index)); - } - - public void lset(String key, int index, String value) { - sendCommand("LSET", key, String.valueOf(index), value); - } - - public void lrem(String key, int count, String value) { - sendCommand("LREM", key, String.valueOf(count), value); - } - - public void lpop(String key) { - sendCommand("LPOP", key); - } - - public void rpop(String key) { - sendCommand("RPOP", key); - } - - public void rpoplpush(String srckey, String dstkey) { - sendCommand("RPOPLPUSH", srckey, dstkey); - } - - public void sadd(String key, String member) { - sendCommand("SADD", key, member); - } - - public void smembers(String key) { - sendCommand("SMEMBERS", key); - } - - public void srem(String key, String member) { - sendCommand("SREM", key, member); - } - - public void spop(String key) { - sendCommand("SPOP", key); - } - - public void smove(String srckey, String dstkey, String member) { - sendCommand("SMOVE", srckey, dstkey, member); - } - - public void scard(String key) { - sendCommand("SCARD", key); - } - - public void sismember(String key, String member) { - sendCommand("SISMEMBER", key, member); - } - - public void sinter(String... keys) { - sendCommand("SINTER", keys); - } - - public void sinterstore(String dstkey, String... keys) { - String[] params = new String[keys.length + 1]; - params[0] = dstkey; - System.arraycopy(keys, 0, params, 1, keys.length); - sendCommand("SINTERSTORE", params); - } - - public void sunion(String... keys) { - sendCommand("SUNION", keys); - } - - public void sunionstore(String dstkey, String... keys) { - String[] params = new String[keys.length + 1]; - params[0] = dstkey; - System.arraycopy(keys, 0, params, 1, keys.length); - sendCommand("SUNIONSTORE", params); - } - - public void sdiff(String... keys) { - sendCommand("SDIFF", keys); - } - - public void sdiffstore(String dstkey, String... keys) { - String[] params = new String[keys.length + 1]; - params[0] = dstkey; - System.arraycopy(keys, 0, params, 1, keys.length); - sendCommand("SDIFFSTORE", params); - } - - public void srandmember(String key) { - sendCommand("SRANDMEMBER", key); - } - - public void zadd(String key, double score, String member) { - sendCommand("ZADD", key, String.valueOf(score), member); - } - - public void zrange(String key, int start, int end) { - sendCommand("ZRANGE", key, String.valueOf(start), String.valueOf(end)); - } - - public void zrem(String key, String member) { - sendCommand("ZREM", key, member); - } - - public void zincrby(String key, double score, String member) { - sendCommand("ZINCRBY", key, String.valueOf(score), member); - } - - public void zrank(String key, String member) { - sendCommand("ZRANK", key, member); - } - - public void zrevrank(String key, String member) { - sendCommand("ZREVRANK", key, member); - } - - public void zrevrange(String key, int start, int end) { - sendCommand("ZREVRANGE", key, String.valueOf(start), String - .valueOf(end)); - } - - public void zrangeWithScores(String key, int start, int end) { - sendCommand("ZRANGE", key, String.valueOf(start), String.valueOf(end), - "WITHSCORES"); - } - - public void zrevrangeWithScores(String key, int start, int end) { - sendCommand("ZREVRANGE", key, String.valueOf(start), String - .valueOf(end), "WITHSCORES"); - } - - public void zcard(String key) { - sendCommand("ZCARD", key); - } - - public void zscore(String key, String member) { - sendCommand("ZSCORE", key, member); - } - - public void multi() { - sendCommand("MULTI"); - isInMulti = true; - } - - public void discard() { - sendCommand("DISCARD"); - isInMulti = false; - } - - public void exec() { - sendCommand("EXEC"); - isInMulti = false; - } - - public void watch(String key) { - sendCommand("WATCH", key); - } - - public void unwatch() { - sendCommand("UNWATCH"); - } - - public void sort(String key) { - sendCommand("SORT", key); - } - - public void sort(String key, SortingParams sortingParameters) { - List args = new ArrayList(); - args.add(key); - args.addAll(sortingParameters.getParams()); - sendCommand("SORT", args.toArray(new String[args.size()])); - } - - public void blpop(String[] args) { - sendCommand("BLPOP", args); - } - - public void sort(String key, SortingParams sortingParameters, String dstkey) { - List args = new ArrayList(); - args.add(key); - args.addAll(sortingParameters.getParams()); - args.add("STORE"); - args.add(dstkey); - sendCommand("SORT", args.toArray(new String[args.size()])); - } - - public void sort(String key, String dstkey) { - sendCommand("SORT", key, "STORE", dstkey); - } - - public void brpop(String[] args) { - sendCommand("BRPOP", args); - } - - public void auth(String password) { - sendCommand("AUTH", password); - } - - public void subscribe(String... channels) { - sendCommand("SUBSCRIBE", channels); - } - - public void publish(String channel, String message) { - sendCommand("PUBLISH", channel, message); - } - - public void unsubscribe() { - sendCommand("UNSUBSCRIBE"); - } - - public void unsubscribe(String... channels) { - sendCommand("UNSUBSCRIBE", channels); - } - - public void psubscribe(String[] patterns) { - sendCommand("PSUBSCRIBE", patterns); - } - - public void punsubscribe() { - sendCommand("PUNSUBSCRIBE"); - } - - public void punsubscribe(String... patterns) { - sendCommand("PUNSUBSCRIBE", patterns); - } - - public void zcount(String key, double min, double max) { - sendCommand("ZCOUNT", key, String.valueOf(min), String.valueOf(max)); - } - - public void zrangeByScore(String key, double min, double max) { - sendCommand("ZRANGEBYSCORE", key, String.valueOf(min), String - .valueOf(max)); - } - - public void zrangeByScore(String key, String min, String max) { - sendCommand("ZRANGEBYSCORE", key, min, max); - } - - public void zrangeByScore(String key, double min, double max, int offset, - int count) { - sendCommand("ZRANGEBYSCORE", key, String.valueOf(min), String - .valueOf(max), "LIMIT", String.valueOf(offset), String - .valueOf(count)); - } - - public void zrangeByScoreWithScores(String key, double min, double max) { - sendCommand("ZRANGEBYSCORE", key, String.valueOf(min), String - .valueOf(max), "WITHSCORES"); - } - - public void zrangeByScoreWithScores(String key, double min, double max, - int offset, int count) { - sendCommand("ZRANGEBYSCORE", key, String.valueOf(min), String - .valueOf(max), "LIMIT", String.valueOf(offset), String - .valueOf(count), "WITHSCORES"); - } - - public void zremrangeByRank(String key, int start, int end) { - sendCommand("ZREMRANGEBYRANK", key, String.valueOf(start), String - .valueOf(end)); - } - - public void zremrangeByScore(String key, double start, double end) { - sendCommand("ZREMRANGEBYSCORE", key, String.valueOf(start), String - .valueOf(end)); - } - - public void zunionstore(String dstkey, String... sets) { - String[] params = new String[sets.length + 2]; - params[0] = dstkey; - params[1] = String.valueOf(sets.length); - System.arraycopy(sets, 0, params, 2, sets.length); - sendCommand("ZUNIONSTORE", params); - } - - public void zunionstore(String dstkey, ZParams params, String... sets) { - List args = new ArrayList(); - args.add(dstkey); - args.add(String.valueOf(sets.length)); - for (String set : sets) { - args.add(set); + public void mget(final String... keys) { + final byte[][] bkeys = new byte[keys.length][]; + for (int i = 0; i < bkeys.length; i++) { + bkeys[i] = keys[i].getBytes(Protocol.UTF8); } - args.addAll(params.getParams()); - sendCommand("ZUNIONSTORE", args.toArray(new String[args.size()])); + mget(bkeys); } - public void zinterstore(String dstkey, String... sets) { - String[] params = new String[sets.length + 2]; - params[0] = dstkey; - params[1] = String.valueOf(sets.length); - System.arraycopy(sets, 0, params, 2, sets.length); - sendCommand("ZINTERSTORE", params); + public void setnx(final String key, final String value) { + setnx(key.getBytes(Protocol.UTF8), value.getBytes(Protocol.UTF8)); } - public void zinterstore(String dstkey, ZParams params, String... sets) { - List args = new ArrayList(); - args.add(dstkey); - args.add(String.valueOf(sets.length)); - for (String set : sets) { - args.add(set); + public void setex(final String key, final int seconds, final String value) { + setex(key.getBytes(Protocol.UTF8), seconds, value + .getBytes(Protocol.UTF8)); + } + + public void mset(final String... keysvalues) { + final byte[][] bkeysvalues = new byte[keysvalues.length][]; + for (int i = 0; i < keysvalues.length; i++) { + bkeysvalues[i] = keysvalues[i].getBytes(Protocol.UTF8); } - args.addAll(params.getParams()); - sendCommand("ZINTERSTORE", args.toArray(new String[args.size()])); + mset(bkeysvalues); } - public void save() { - sendCommand("SAVE"); + public void msetnx(final String... keysvalues) { + final byte[][] bkeysvalues = new byte[keysvalues.length][]; + for (int i = 0; i < keysvalues.length; i++) { + bkeysvalues[i] = keysvalues[i].getBytes(Protocol.UTF8); + } + msetnx(bkeysvalues); } - public void bgsave() { - sendCommand("BGSAVE"); + public void decrBy(final String key, final int integer) { + decrBy(key.getBytes(Protocol.UTF8), integer); } - public void bgrewriteaof() { - sendCommand("BGREWRITEAOF"); + public void decr(final String key) { + decr(key.getBytes(Protocol.UTF8)); } - public void lastsave() { - sendCommand("LASTSAVE"); + public void incrBy(final String key, final int integer) { + incrBy(key.getBytes(Protocol.UTF8), integer); } - public void shutdown() { - sendCommand("SHUTDOWN"); + public void incr(final String key) { + incr(key.getBytes(Protocol.UTF8)); } - public void info() { - sendCommand("INFO"); + public void append(final String key, final String value) { + append(key.getBytes(Protocol.UTF8), value.getBytes(Protocol.UTF8)); } - public void monitor() { - sendCommand("MONITOR"); + public void substr(final String key, final int start, final int end) { + substr(key.getBytes(Protocol.UTF8), start, end); } - public void slaveof(String host, int port) { - sendCommand("SLAVEOF", host, String.valueOf(port)); + public void hset(final String key, final String field, final String value) { + hset(key.getBytes(Protocol.UTF8), field.getBytes(Protocol.UTF8), value + .getBytes(Protocol.UTF8)); } - public void slaveofNoOne() { - sendCommand("SLAVEOF", "no", "one"); + public void hget(final String key, final String field) { + hget(key.getBytes(Protocol.UTF8), field.getBytes(Protocol.UTF8)); } - public void configGet(String pattern) { - sendCommand("CONFIG", "GET", pattern); + public void hsetnx(final String key, final String field, final String value) { + hsetnx(key.getBytes(Protocol.UTF8), field.getBytes(Protocol.UTF8), + value.getBytes(Protocol.UTF8)); } - public void configSet(String parameter, String value) { - sendCommand("CONFIG", "SET", parameter, value); + public void hmset(final String key, final Map hash) { + final Map bhash = new HashMap(hash + .size()); + for (final Entry entry : hash.entrySet()) { + bhash.put(entry.getKey().getBytes(Protocol.UTF8), entry.getValue() + .getBytes(Protocol.UTF8)); + } + hmset(key.getBytes(Protocol.UTF8), bhash); } - public void strlen(String key) { - sendCommand("STRLEN", key); + public void hmget(final String key, final String... fields) { + final byte[][] bfields = new byte[fields.length][]; + for (int i = 0; i < bfields.length; i++) { + bfields[i] = fields[i].getBytes(Protocol.UTF8); + } + hmget(key.getBytes(Protocol.UTF8), bfields); } - public void sync() { - sendCommand("SYNC"); + public void hincrBy(final String key, final String field, final int value) { + hincrBy(key.getBytes(Protocol.UTF8), field.getBytes(Protocol.UTF8), + value); } - public void lpushx(String key, String string) { - sendCommand("LPUSHX", key, string); + public void hexists(final String key, final String field) { + hexists(key.getBytes(Protocol.UTF8), field.getBytes(Protocol.UTF8)); } - public void persist(String key) { - sendCommand("PERSIST", key); + public void hdel(final String key, final String field) { + hdel(key.getBytes(Protocol.UTF8), field.getBytes(Protocol.UTF8)); } - public void rpushx(String key, String string) { - sendCommand("RPUSHX", key, string); + public void hlen(final String key) { + hlen(key.getBytes(Protocol.UTF8)); } - public void echo(String string) { - sendCommand("ECHO", string); + public void hkeys(final String key) { + hkeys(key.getBytes(Protocol.UTF8)); } - public void linsert(String key, LIST_POSITION where, String pivot, - String value) { - sendCommand("LINSERT", key, where.toString(), pivot, value); + public void hvals(final String key) { + hvals(key.getBytes(Protocol.UTF8)); } - public void debug(DebugParams params) { - sendCommand("DEBUG", params.getCommand()); + public void hgetAll(final String key) { + hgetAll(key.getBytes(Protocol.UTF8)); + } + + public void rpush(final String key, final String string) { + rpush(key.getBytes(Protocol.UTF8), string.getBytes(Protocol.UTF8)); + } + + public void lpush(final String key, final String string) { + lpush(key.getBytes(Protocol.UTF8), string.getBytes(Protocol.UTF8)); + } + + public void llen(final String key) { + llen(key.getBytes(Protocol.UTF8)); + } + + public void lrange(final String key, final int start, final int end) { + lrange(key.getBytes(Protocol.UTF8), start, end); + } + + public void ltrim(final String key, final int start, final int end) { + ltrim(key.getBytes(Protocol.UTF8), start, end); + } + + public void lindex(final String key, final int index) { + lindex(key.getBytes(Protocol.UTF8), index); + } + + public void lset(final String key, final int index, final String value) { + lset(key.getBytes(Protocol.UTF8), index, value.getBytes(Protocol.UTF8)); + } + + public void lrem(final String key, int count, final String value) { + lrem(key.getBytes(Protocol.UTF8), count, value.getBytes(Protocol.UTF8)); + } + + public void lpop(final String key) { + lpop(key.getBytes(Protocol.UTF8)); + } + + public void rpop(final String key) { + rpop(key.getBytes(Protocol.UTF8)); + } + + public void rpoplpush(final String srckey, final String dstkey) { + rpoplpush(srckey.getBytes(Protocol.UTF8), dstkey + .getBytes(Protocol.UTF8)); + } + + public void sadd(final String key, final String member) { + sadd(key.getBytes(Protocol.UTF8), member.getBytes(Protocol.UTF8)); + } + + public void smembers(final String key) { + smembers(key.getBytes(Protocol.UTF8)); + } + + public void srem(final String key, final String member) { + srem(key.getBytes(Protocol.UTF8), member.getBytes(Protocol.UTF8)); + } + + public void spop(final String key) { + spop(key.getBytes(Protocol.UTF8)); + } + + public void smove(final String srckey, final String dstkey, + final String member) { + smove(srckey.getBytes(Protocol.UTF8), dstkey.getBytes(Protocol.UTF8), + member.getBytes(Protocol.UTF8)); + } + + public void scard(final String key) { + scard(key.getBytes(Protocol.UTF8)); + } + + public void sismember(final String key, final String member) { + sismember(key.getBytes(Protocol.UTF8), member.getBytes(Protocol.UTF8)); + } + + public void sinter(final String... keys) { + final byte[][] bkeys = new byte[keys.length][]; + for (int i = 0; i < bkeys.length; i++) { + bkeys[i] = keys[i].getBytes(Protocol.UTF8); + } + sinter(bkeys); + } + + public void sinterstore(final String dstkey, final String... keys) { + final byte[][] bkeys = new byte[keys.length][]; + for (int i = 0; i < bkeys.length; i++) { + bkeys[i] = keys[i].getBytes(Protocol.UTF8); + } + sinterstore(dstkey.getBytes(Protocol.UTF8), bkeys); + } + + public void sunion(final String... keys) { + final byte[][] bkeys = new byte[keys.length][]; + for (int i = 0; i < bkeys.length; i++) { + bkeys[i] = keys[i].getBytes(Protocol.UTF8); + } + sunion(bkeys); + } + + public void sunionstore(final String dstkey, final String... keys) { + final byte[][] bkeys = new byte[keys.length][]; + for (int i = 0; i < bkeys.length; i++) { + bkeys[i] = keys[i].getBytes(Protocol.UTF8); + } + sunionstore(dstkey.getBytes(Protocol.UTF8), bkeys); + } + + public void sdiff(final String... keys) { + final byte[][] bkeys = new byte[keys.length][]; + for (int i = 0; i < bkeys.length; i++) { + bkeys[i] = keys[i].getBytes(Protocol.UTF8); + } + sdiff(bkeys); + } + + public void sdiffstore(final String dstkey, final String... keys) { + final byte[][] bkeys = new byte[keys.length][]; + for (int i = 0; i < bkeys.length; i++) { + bkeys[i] = keys[i].getBytes(Protocol.UTF8); + } + sdiffstore(dstkey.getBytes(Protocol.UTF8), bkeys); + } + + public void srandmember(final String key) { + srandmember(key.getBytes(Protocol.UTF8)); + } + + public void zadd(final String key, final double score, final String member) { + zadd(key.getBytes(Protocol.UTF8), score, member.getBytes(Protocol.UTF8)); + } + + public void zrange(final String key, final int start, final int end) { + zrange(key.getBytes(Protocol.UTF8), start, end); + } + + public void zrem(final String key, final String member) { + zrem(key.getBytes(Protocol.UTF8), member.getBytes(Protocol.UTF8)); + } + + public void zincrby(final String key, final double score, + final String member) { + zincrby(key.getBytes(Protocol.UTF8), score, member + .getBytes(Protocol.UTF8)); + } + + public void zrank(final String key, final String member) { + zrank(key.getBytes(Protocol.UTF8), member.getBytes(Protocol.UTF8)); + } + + public void zrevrank(final String key, final String member) { + zrevrank(key.getBytes(Protocol.UTF8), member.getBytes(Protocol.UTF8)); + } + + public void zrevrange(final String key, final int start, final int end) { + zrevrange(key.getBytes(Protocol.UTF8), start, end); + } + + public void zrangeWithScores(final String key, final int start, + final int end) { + zrangeWithScores(key.getBytes(Protocol.UTF8), start, end); + } + + public void zrevrangeWithScores(final String key, final int start, + final int end) { + zrevrangeWithScores(key.getBytes(Protocol.UTF8), start, end); + } + + public void zcard(final String key) { + zcard(key.getBytes(Protocol.UTF8)); + } + + public void zscore(final String key, final String member) { + zscore(key.getBytes(Protocol.UTF8), member.getBytes(Protocol.UTF8)); + } + + public void watch(final String key) { + watch(key.getBytes(Protocol.UTF8)); + } + + public void sort(final String key) { + sort(key.getBytes(Protocol.UTF8)); + } + + public void sort(final String key, final SortingParams sortingParameters) { + sort(key.getBytes(Protocol.UTF8), sortingParameters); + } + + public void blpop(final String[] args) { + final byte[][] bargs = new byte[args.length][]; + for (int i = 0; i < bargs.length; i++) { + bargs[i] = args[i].getBytes(Protocol.UTF8); + } + blpop(bargs); + } + + public void sort(final String key, final SortingParams sortingParameters, + final String dstkey) { + sort(key.getBytes(Protocol.UTF8), sortingParameters, dstkey + .getBytes(Protocol.UTF8)); + } + + public void sort(final String key, final String dstkey) { + sort(key.getBytes(Protocol.UTF8), dstkey.getBytes(Protocol.UTF8)); + } + + public void brpop(final String[] args) { + final byte[][] bargs = new byte[args.length][]; + for (int i = 0; i < bargs.length; i++) { + bargs[i] = args[i].getBytes(Protocol.UTF8); + } + brpop(bargs); + } + + public void zcount(final String key, final double min, final double max) { + zcount(key.getBytes(Protocol.UTF8), min, max); + } + + public void zrangeByScore(final String key, final double min, + final double max) { + zrangeByScore(key.getBytes(Protocol.UTF8), min, max); + } + + public void zrangeByScore(final String key, final String min, + final String max) { + zrangeByScore(key.getBytes(Protocol.UTF8), min.getBytes(Protocol.UTF8), + max.getBytes(Protocol.UTF8)); + } + + public void zrangeByScore(final String key, final double min, + final double max, final int offset, int count) { + zrangeByScore(key.getBytes(Protocol.UTF8), min, max, offset, count); + } + + public void zrangeByScoreWithScores(final String key, final double min, + final double max) { + zrangeByScoreWithScores(key.getBytes(Protocol.UTF8), min, max); + } + + public void zrangeByScoreWithScores(final String key, final double min, + final double max, final int offset, final int count) { + zrangeByScoreWithScores(key.getBytes(Protocol.UTF8), min, max, offset, + count); + } + + public void zremrangeByRank(final String key, final int start, final int end) { + zremrangeByRank(key.getBytes(Protocol.UTF8), start, end); + } + + public void zremrangeByScore(final String key, final double start, + final double end) { + zremrangeByScore(key.getBytes(Protocol.UTF8), start, end); + } + + public void zunionstore(final String dstkey, final String... sets) { + final byte[][] bsets = new byte[sets.length][]; + for (int i = 0; i < bsets.length; i++) { + bsets[i] = sets[i].getBytes(Protocol.UTF8); + } + zunionstore(dstkey.getBytes(Protocol.UTF8), bsets); + } + + public void zunionstore(final String dstkey, final ZParams params, + final String... sets) { + final byte[][] bsets = new byte[sets.length][]; + for (int i = 0; i < bsets.length; i++) { + bsets[i] = sets[i].getBytes(Protocol.UTF8); + } + zunionstore(dstkey.getBytes(Protocol.UTF8), params, bsets); + } + + public void zinterstore(final String dstkey, final String... sets) { + final byte[][] bsets = new byte[sets.length][]; + for (int i = 0; i < bsets.length; i++) { + bsets[i] = sets[i].getBytes(Protocol.UTF8); + } + zinterstore(dstkey.getBytes(Protocol.UTF8), bsets); + } + + public void zinterstore(final String dstkey, final ZParams params, + final String... sets) { + final byte[][] bsets = new byte[sets.length][]; + for (int i = 0; i < bsets.length; i++) { + bsets[i] = sets[i].getBytes(Protocol.UTF8); + } + zinterstore(dstkey.getBytes(Protocol.UTF8), params, bsets); + } + + public void strlen(final String key) { + strlen(key.getBytes(Protocol.UTF8)); + } + + public void lpushx(final String key, final String string) { + lpushx(key.getBytes(Protocol.UTF8), string.getBytes(Protocol.UTF8)); + } + + public void persist(final String key) { + persist(key.getBytes(Protocol.UTF8)); + } + + public void rpushx(final String key, final String string) { + rpushx(key.getBytes(Protocol.UTF8), string.getBytes(Protocol.UTF8)); + } + + public void echo(final String string) { + echo(string.getBytes(Protocol.UTF8)); + } + + public void linsert(final String key, final LIST_POSITION where, + final String pivot, final String value) { + linsert(key.getBytes(Protocol.UTF8), where, pivot + .getBytes(Protocol.UTF8), value.getBytes(Protocol.UTF8)); } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/Connection.java b/src/main/java/redis/clients/jedis/Connection.java index a9c9cd6..84f9579 100644 --- a/src/main/java/redis/clients/jedis/Connection.java +++ b/src/main/java/redis/clients/jedis/Connection.java @@ -7,6 +7,7 @@ import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; +import redis.clients.jedis.Protocol.Command; import redis.clients.util.RedisInputStream; import redis.clients.util.RedisOutputStream; @@ -24,7 +25,7 @@ public class Connection { return timeout; } - public void setTimeout(int timeout) { + public void setTimeout(final int timeout) { this.timeout = timeout; } @@ -44,18 +45,46 @@ public class Connection { } } - public Connection(String host) { + public Connection(final String host) { super(); this.host = host; } - protected Connection sendCommand(String name, String... args) { - protocol.sendCommand(outputStream, name, args); + protected Connection sendCommand(final Command cmd, final String... args) { + final byte[][] bargs = new byte[args.length][]; + for (int i = 0; i < args.length; i++) { + bargs[i] = args[i].getBytes(Protocol.UTF8); + } + return sendCommand(cmd, bargs); + } + + protected Connection sendCommand(final Command cmd, final byte[]... args) { + try { + connect(); + } catch (UnknownHostException e) { + throw new JedisException("Could not connect to redis-server", e); + } catch (IOException e) { + throw new JedisException("Could not connect to redis-server", e); + } + protocol.sendCommand(outputStream, cmd, args); pipelinedCommands++; return this; } - public Connection(String host, int port) { + protected Connection sendCommand(final Command cmd) { + try { + connect(); + } catch (UnknownHostException e) { + throw new JedisException("Could not connect to redis-server", e); + } catch (IOException e) { + throw new JedisException("Could not connect to redis-server", e); + } + protocol.sendCommand(outputStream, cmd, new byte[0][]); + pipelinedCommands++; + return this; + } + + public Connection(final String host, final int port) { super(); this.host = host; this.port = port; @@ -65,7 +94,7 @@ public class Connection { return host; } - public void setHost(String host) { + public void setHost(final String host) { this.host = host; } @@ -73,7 +102,7 @@ public class Connection { return port; } - public void setPort(int port) { + public void setPort(final int port) { this.port = port; } @@ -111,12 +140,26 @@ public class Connection { protected String getStatusCodeReply() { pipelinedCommands--; - return (String) protocol.read(inputStream); + final byte[] resp = (byte[]) protocol.read(inputStream); + if (null == resp) { + return null; + } else { + return new String(resp, Protocol.UTF8); + } } public String getBulkReply() { + final byte[] result = getBinaryBulkReply(); + if (null != result) { + return new String(result, Protocol.UTF8); + } else { + return null; + } + } + + public byte[] getBinaryBulkReply() { pipelinedCommands--; - return (String) protocol.read(inputStream); + return (byte[]) protocol.read(inputStream); } public Integer getIntegerReply() { @@ -124,10 +167,26 @@ public class Connection { return (Integer) protocol.read(inputStream); } - @SuppressWarnings("unchecked") public List getMultiBulkReply() { + final List bresult = getBinaryMultiBulkReply(); + if (null == bresult) { + return null; + } + final ArrayList result = new ArrayList(bresult.size()); + for (final byte[] barray : bresult) { + if (barray == null) { + result.add(null); + } else { + result.add(new String(barray, Protocol.UTF8)); + } + } + return result; + } + + @SuppressWarnings("unchecked") + public List getBinaryMultiBulkReply() { pipelinedCommands--; - return (List) protocol.read(inputStream); + return (List) protocol.read(inputStream); } @SuppressWarnings("unchecked") diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index d70c2ac..15fb1ec 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -4,35 +4,30 @@ import java.io.IOException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; -import redis.clients.jedis.Client.LIST_POSITION; +import redis.clients.jedis.BinaryClient.LIST_POSITION; -public class Jedis implements JedisCommands { - private Client client = null; - private String password = null; - - public Jedis(String host) { - client = new Client(host); +public class Jedis extends BinaryJedis implements JedisCommands { + public Jedis(final String host) { + super(host); } - public Jedis(String host, int port) { - client = new Client(host, port); + public Jedis(final String host, final int port) { + super(host, port); } - public Jedis(String host, int port, int timeout) { - client = new Client(host, port); - client.setTimeout(timeout); + public Jedis(final String host, final int port, final int timeout) { + super(host, port, timeout); } public Jedis(JedisShardInfo shardInfo) { - client = new Client(shardInfo.getHost(), shardInfo.getPort()); - client.setTimeout(shardInfo.getTimeout()); - this.password = shardInfo.getPassword(); + super(shardInfo); } public String ping() { @@ -51,7 +46,7 @@ public class Jedis implements JedisCommands { * @param value * @return Status code reply */ - public String set(String key, String value) { + public String set(final String key, String value) { runChecks(); client.set(key, value); return client.getStatusCodeReply(); @@ -67,9 +62,9 @@ public class Jedis implements JedisCommands { * @param key * @return Bulk reply */ - public String get(String key) { + public String get(final String key) { runChecks(); - client.sendCommand("GET", key); + client.sendCommand(Protocol.Command.GET, key); return client.getBulkReply(); } @@ -91,7 +86,7 @@ public class Jedis implements JedisCommands { * @param key * @return Integer reply, "0" if the key exists, otherwise "1" */ - public Integer exists(String key) { + public Integer exists(final String key) { runChecks(); client.exists(key); return client.getIntegerReply(); @@ -107,7 +102,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically: an integer greater than 0 if one or * more keys were removed 0 if none of the specified key existed */ - public Integer del(String... keys) { + public Integer del(final String... keys) { runChecks(); client.del(keys); return client.getIntegerReply(); @@ -127,7 +122,7 @@ public class Jedis implements JedisCommands { * "zset" if the key contains a Sorted Set value "hash" if the key * contains a Hash value */ - public String type(String key) { + public String type(final String key) { runChecks(); client.type(key); return client.getStatusCodeReply(); @@ -176,10 +171,12 @@ public class Jedis implements JedisCommands { * @param pattern * @return Multi bulk reply */ - public List keys(String pattern) { + public Set keys(final String pattern) { runChecks(); client.keys(pattern); - return client.getMultiBulkReply(); + final HashSet keySet = new HashSet(client + .getMultiBulkReply()); + return keySet; } /** @@ -207,7 +204,7 @@ public class Jedis implements JedisCommands { * @param newkey * @return Status code repy */ - public String rename(String oldkey, String newkey) { + public String rename(final String oldkey, final String newkey) { runChecks(); client.rename(oldkey, newkey); return client.getStatusCodeReply(); @@ -224,7 +221,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically: 1 if the key was renamed 0 if the * target key already exist */ - public Integer renamenx(String oldkey, String newkey) { + public Integer renamenx(final String oldkey, final String newkey) { runChecks(); client.renamenx(oldkey, newkey); return client.getIntegerReply(); @@ -269,7 +266,7 @@ public class Jedis implements JedisCommands { * 2.1.3 will happily update the timeout), or the key does not * exist. */ - public Integer expire(String key, int seconds) { + public Integer expire(final String key, final int seconds) { runChecks(); client.expire(key, seconds); return client.getIntegerReply(); @@ -305,7 +302,7 @@ public class Jedis implements JedisCommands { * 2.1.3 will happily update the timeout), or the key does not * exist. */ - public Integer expireAt(String key, long unixTime) { + public Integer expireAt(final String key, final long unixTime) { runChecks(); client.expireAt(key, unixTime); return client.getIntegerReply(); @@ -322,7 +319,7 @@ public class Jedis implements JedisCommands { * key that has an EXPIRE. If the Key does not exists or does not * have an associated expire, -1 is returned. */ - public Integer ttl(String key) { + public Integer ttl(final String key) { runChecks(); client.ttl(key); return client.getIntegerReply(); @@ -335,7 +332,7 @@ public class Jedis implements JedisCommands { * @param index * @return Status code reply */ - public String select(int index) { + public String select(final int index) { runChecks(); client.select(index); return client.getStatusCodeReply(); @@ -354,7 +351,7 @@ public class Jedis implements JedisCommands { * was not moved because already present on the target DB or was not * found in the current DB. */ - public Integer move(String key, int dbIndex) { + public Integer move(final String key, final int dbIndex) { runChecks(); client.move(key, dbIndex); return client.getIntegerReply(); @@ -383,7 +380,7 @@ public class Jedis implements JedisCommands { * @param value * @return Bulk reply */ - public String getSet(String key, String value) { + public String getSet(final String key, final String value) { runChecks(); client.getSet(key, value); return client.getBulkReply(); @@ -399,7 +396,7 @@ public class Jedis implements JedisCommands { * @param keys * @return Multi bulk reply */ - public List mget(String... keys) { + public List mget(final String... keys) { runChecks(); client.mget(keys); return client.getMultiBulkReply(); @@ -417,7 +414,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically: 1 if the key was set 0 if the key * was not set */ - public Integer setnx(String key, String value) { + public Integer setnx(final String key, final String value) { runChecks(); client.setnx(key, value); return client.getIntegerReply(); @@ -435,7 +432,7 @@ public class Jedis implements JedisCommands { * @param value * @return Status code reply */ - public String setex(String key, int seconds, String value) { + public String setex(final String key, final int seconds, final String value) { runChecks(); client.setex(key, seconds, value); return client.getStatusCodeReply(); @@ -461,7 +458,7 @@ public class Jedis implements JedisCommands { * @param keysvalues * @return Status code reply Basically +OK as MSET can't fail */ - public String mset(String... keysvalues) { + public String mset(final String... keysvalues) { runChecks(); client.mset(keysvalues); return client.getStatusCodeReply(); @@ -488,7 +485,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically: 1 if the all the keys were set 0 if * no key was set (at least one key already existed) */ - public Integer msetnx(String... keysvalues) { + public Integer msetnx(final String... keysvalues) { runChecks(); client.msetnx(keysvalues); return client.getIntegerReply(); @@ -516,7 +513,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, this commands will reply with the new value of key * after the increment. */ - public Integer decrBy(String key, int integer) { + public Integer decrBy(final String key, final int integer) { runChecks(); client.decrBy(key, integer); return client.getIntegerReply(); @@ -544,7 +541,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, this commands will reply with the new value of key * after the increment. */ - public Integer decr(String key) { + public Integer decr(final String key) { runChecks(); client.decr(key); return client.getIntegerReply(); @@ -572,7 +569,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, this commands will reply with the new value of key * after the increment. */ - public Integer incrBy(String key, int integer) { + public Integer incrBy(final String key, final int integer) { runChecks(); client.incrBy(key, integer); return client.getIntegerReply(); @@ -600,7 +597,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, this commands will reply with the new value of key * after the increment. */ - public Integer incr(String key) { + public Integer incr(final String key) { runChecks(); client.incr(key); return client.getIntegerReply(); @@ -622,7 +619,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically the total length of the string after * the append operation. */ - public Integer append(String key, String value) { + public Integer append(final String key, final String value) { runChecks(); client.append(key, value); return client.getIntegerReply(); @@ -646,7 +643,7 @@ public class Jedis implements JedisCommands { * @param end * @return Bulk reply */ - public String substr(String key, int start, int end) { + public String substr(final String key, final int start, final int end) { runChecks(); client.substr(key, start, end); return client.getBulkReply(); @@ -667,7 +664,7 @@ public class Jedis implements JedisCommands { * of the value, 0 is returned, otherwise if a new field is created * 1 is returned. */ - public Integer hset(String key, String field, String value) { + public Integer hset(final String key, final String field, final String value) { runChecks(); client.hset(key, field, value); return client.getIntegerReply(); @@ -686,7 +683,7 @@ public class Jedis implements JedisCommands { * @param field * @return Bulk reply */ - public String hget(String key, String field) { + public String hget(final String key, final String field) { runChecks(); client.hget(key, field); return client.getBulkReply(); @@ -703,7 +700,8 @@ public class Jedis implements JedisCommands { * @return If the field already exists, 0 is returned, otherwise if a new * field is created 1 is returned. */ - public Integer hsetnx(String key, String field, String value) { + public Integer hsetnx(final String key, final String field, + final String value) { runChecks(); client.hsetnx(key, field, value); return client.getIntegerReply(); @@ -721,7 +719,7 @@ public class Jedis implements JedisCommands { * @param hash * @return Always OK because HMSET can't fail */ - public String hmset(String key, Map hash) { + public String hmset(final String key, final Map hash) { runChecks(); client.hmset(key, hash); return client.getStatusCodeReply(); @@ -740,7 +738,7 @@ public class Jedis implements JedisCommands { * @return Multi Bulk Reply specifically a list of all the values associated * with the specified fields, in the same order of the request. */ - public List hmget(String key, String... fields) { + public List hmget(final String key, final String... fields) { runChecks(); client.hmget(key, fields); return client.getMultiBulkReply(); @@ -764,7 +762,7 @@ public class Jedis implements JedisCommands { * @return Integer reply The new value at field after the increment * operation. */ - public Integer hincrBy(String key, String field, int value) { + public Integer hincrBy(final String key, final String field, final int value) { runChecks(); client.hincrBy(key, field, value); return client.getIntegerReply(); @@ -780,7 +778,7 @@ public class Jedis implements JedisCommands { * @return Return 1 if the hash stored at key contains the specified field. * Return 0 if the key is not found or the field is not present. */ - public Integer hexists(String key, String field) { + public Integer hexists(final String key, final String field) { runChecks(); client.hexists(key, field); return client.getIntegerReply(); @@ -796,7 +794,7 @@ public class Jedis implements JedisCommands { * @return If the field was present in the hash it is deleted and 1 is * returned, otherwise 0 is returned and no operation is performed. */ - public Integer hdel(String key, String field) { + public Integer hdel(final String key, final String field) { runChecks(); client.hdel(key, field); return client.getIntegerReply(); @@ -812,7 +810,7 @@ public class Jedis implements JedisCommands { * key. If the specified key does not exist, 0 is returned assuming * an empty hash. */ - public Integer hlen(String key) { + public Integer hlen(final String key) { runChecks(); client.hlen(key); return client.getIntegerReply(); @@ -826,10 +824,11 @@ public class Jedis implements JedisCommands { * @param key * @return All the fields names contained into a hash. */ - public List hkeys(String key) { + public Set hkeys(final String key) { runChecks(); client.hkeys(key); - return client.getMultiBulkReply(); + final List lresult = client.getMultiBulkReply(); + return new HashSet(lresult); } /** @@ -840,10 +839,11 @@ public class Jedis implements JedisCommands { * @param key * @return All the fields values contained into a hash. */ - public List hvals(String key) { + public List hvals(final String key) { runChecks(); client.hvals(key); - return client.getMultiBulkReply(); + final List lresult = client.getMultiBulkReply(); + return lresult; } /** @@ -854,12 +854,12 @@ public class Jedis implements JedisCommands { * @param key * @return All the fields and values contained into a hash. */ - public Map hgetAll(String key) { + public Map hgetAll(final String key) { runChecks(); client.hgetAll(key); - List flatHash = client.getMultiBulkReply(); - Map hash = new HashMap(); - Iterator iterator = flatHash.iterator(); + final List flatHash = client.getMultiBulkReply(); + final Map hash = new HashMap(); + final Iterator iterator = flatHash.iterator(); while (iterator.hasNext()) { hash.put(iterator.next(), iterator.next()); } @@ -882,7 +882,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically, the number of elements inside the * list after the push operation. */ - public Integer rpush(String key, String string) { + public Integer rpush(final String key, final String string) { runChecks(); client.rpush(key, string); return client.getIntegerReply(); @@ -903,7 +903,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically, the number of elements inside the * list after the push operation. */ - public Integer lpush(String key, String string) { + public Integer lpush(final String key, final String string) { runChecks(); client.lpush(key, string); return client.getIntegerReply(); @@ -919,7 +919,7 @@ public class Jedis implements JedisCommands { * @param key * @return The length of the list. */ - public Integer llen(String key) { + public Integer llen(final String key) { runChecks(); client.llen(key); return client.getIntegerReply(); @@ -963,7 +963,7 @@ public class Jedis implements JedisCommands { * @return Multi bulk reply, specifically a list of elements in the * specified range. */ - public List lrange(String key, int start, int end) { + public List lrange(final String key, final int start, final int end) { runChecks(); client.lrange(key, start, end); return client.getMultiBulkReply(); @@ -1003,7 +1003,7 @@ public class Jedis implements JedisCommands { * @param end * @return Status code reply */ - public String ltrim(String key, int start, int end) { + public String ltrim(final String key, final int start, final int end) { runChecks(); client.ltrim(key, start, end); return client.getStatusCodeReply(); @@ -1027,7 +1027,7 @@ public class Jedis implements JedisCommands { * @param index * @return Bulk reply, specifically the requested element */ - public String lindex(String key, int index) { + public String lindex(final String key, final int index) { runChecks(); client.lindex(key, index); return client.getBulkReply(); @@ -1054,7 +1054,7 @@ public class Jedis implements JedisCommands { * @param value * @return Status code reply */ - public String lset(String key, int index, String value) { + public String lset(final String key, final int index, final String value) { runChecks(); client.lset(key, index, value); return client.getStatusCodeReply(); @@ -1079,7 +1079,7 @@ public class Jedis implements JedisCommands { * @return Integer Reply, specifically: The number of removed elements if * the operation succeeded */ - public Integer lrem(String key, int count, String value) { + public Integer lrem(final String key, final int count, final String value) { runChecks(); client.lrem(key, count, value); return client.getIntegerReply(); @@ -1098,7 +1098,7 @@ public class Jedis implements JedisCommands { * @param key * @return Bulk reply */ - public String lpop(String key) { + public String lpop(final String key) { runChecks(); client.lpop(key); return client.getBulkReply(); @@ -1117,7 +1117,7 @@ public class Jedis implements JedisCommands { * @param key * @return Bulk reply */ - public String rpop(String key) { + public String rpop(final String key) { runChecks(); client.rpop(key); return client.getBulkReply(); @@ -1141,7 +1141,7 @@ public class Jedis implements JedisCommands { * @param dstkey * @return Bulk reply */ - public String rpoplpush(String srckey, String dstkey) { + public String rpoplpush(final String srckey, final String dstkey) { runChecks(); client.rpoplpush(srckey, dstkey); return client.getBulkReply(); @@ -1160,7 +1160,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically: 1 if the new element was added 0 if * the element was already a member of the set */ - public Integer sadd(String key, String member) { + public Integer sadd(final String key, final String member) { runChecks(); client.sadd(key, member); return client.getIntegerReply(); @@ -1175,10 +1175,10 @@ public class Jedis implements JedisCommands { * @param key * @return Multi bulk reply */ - public Set smembers(String key) { + public Set smembers(final String key) { runChecks(); client.smembers(key); - List members = client.getMultiBulkReply(); + final List members = client.getMultiBulkReply(); return new LinkedHashSet(members); } @@ -1194,7 +1194,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically: 1 if the new element was removed 0 * if the new element was not a member of the set */ - public Integer srem(String key, String member) { + public Integer srem(final String key, final String member) { runChecks(); client.srem(key, member); return client.getIntegerReply(); @@ -1212,7 +1212,7 @@ public class Jedis implements JedisCommands { * @param key * @return Bulk reply */ - public String spop(String key) { + public String spop(final String key) { runChecks(); client.spop(key); return client.getBulkReply(); @@ -1241,7 +1241,8 @@ public class Jedis implements JedisCommands { * element was not found on the first set and no operation was * performed */ - public Integer smove(String srckey, String dstkey, String member) { + public Integer smove(final String srckey, final String dstkey, + final String member) { runChecks(); client.smove(srckey, dstkey, member); return client.getIntegerReply(); @@ -1255,7 +1256,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically: the cardinality (number of elements) * of the set as an integer. */ - public Integer scard(String key) { + public Integer scard(final String key) { runChecks(); client.scard(key); return client.getIntegerReply(); @@ -1273,7 +1274,7 @@ public class Jedis implements JedisCommands { * set 0 if the element is not a member of the set OR if the key * does not exist */ - public Integer sismember(String key, String member) { + public Integer sismember(final String key, final String member) { runChecks(); client.sismember(key, member); return client.getIntegerReply(); @@ -1298,10 +1299,10 @@ public class Jedis implements JedisCommands { * @param keys * @return Multi bulk reply, specifically the list of common elements. */ - public Set sinter(String... keys) { + public Set sinter(final String... keys) { runChecks(); client.sinter(keys); - List members = client.getMultiBulkReply(); + final List members = client.getMultiBulkReply(); return new LinkedHashSet(members); } @@ -1316,7 +1317,7 @@ public class Jedis implements JedisCommands { * @param keys * @return Status code reply */ - public Integer sinterstore(String dstkey, String... keys) { + public Integer sinterstore(final String dstkey, final String... keys) { runChecks(); client.sinterstore(dstkey, keys); return client.getIntegerReply(); @@ -1338,10 +1339,10 @@ public class Jedis implements JedisCommands { * @param keys * @return Multi bulk reply, specifically the list of common elements. */ - public Set sunion(String... keys) { + public Set sunion(final String... keys) { runChecks(); client.sunion(keys); - List members = client.getMultiBulkReply(); + final List members = client.getMultiBulkReply(); return new LinkedHashSet(members); } @@ -1357,7 +1358,7 @@ public class Jedis implements JedisCommands { * @param keys * @return Status code reply */ - public Integer sunionstore(String dstkey, String... keys) { + public Integer sunionstore(final String dstkey, final String... keys) { runChecks(); client.sunionstore(dstkey, keys); return client.getIntegerReply(); @@ -1386,10 +1387,10 @@ public class Jedis implements JedisCommands { * @return Return the members of a set resulting from the difference between * the first set provided and all the successive sets. */ - public Set sdiff(String... keys) { + public Set sdiff(final String... keys) { runChecks(); client.sdiff(keys); - List members = client.getMultiBulkReply(); + final List members = client.getMultiBulkReply(); return new LinkedHashSet(members); } @@ -1401,7 +1402,7 @@ public class Jedis implements JedisCommands { * @param keys * @return Status code reply */ - public Integer sdiffstore(String dstkey, String... keys) { + public Integer sdiffstore(final String dstkey, final String... keys) { runChecks(); client.sdiffstore(dstkey, keys); return client.getIntegerReply(); @@ -1419,7 +1420,7 @@ public class Jedis implements JedisCommands { * @param key * @return Bulk reply */ - public String srandmember(String key) { + public String srandmember(final String key) { runChecks(); client.srandmember(key); return client.getBulkReply(); @@ -1446,16 +1447,17 @@ public class Jedis implements JedisCommands { * the element was already a member of the sorted set and the score * was updated */ - public Integer zadd(String key, double score, String member) { + public Integer zadd(final String key, final double score, + final String member) { runChecks(); client.zadd(key, score, member); return client.getIntegerReply(); } - public Set zrange(String key, int start, int end) { + public Set zrange(final String key, final int start, final int end) { runChecks(); client.zrange(key, start, end); - List members = client.getMultiBulkReply(); + final List members = client.getMultiBulkReply(); return new LinkedHashSet(members); } @@ -1474,7 +1476,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically: 1 if the new element was removed 0 * if the new element was not a member of the set */ - public Integer zrem(String key, String member) { + public Integer zrem(final String key, final String member) { runChecks(); client.zrem(key, member); return client.getIntegerReply(); @@ -1504,7 +1506,8 @@ public class Jedis implements JedisCommands { * @param member * @return The new score */ - public Double zincrby(String key, double score, String member) { + public Double zincrby(final String key, final double score, + final String member) { runChecks(); client.zincrby(key, score, member); String newscore = client.getBulkReply(); @@ -1531,7 +1534,7 @@ public class Jedis implements JedisCommands { * element as an integer reply if the element exists. A nil bulk * reply if there is no such element. */ - public Integer zrank(String key, String member) { + public Integer zrank(final String key, final String member) { runChecks(); client.zrank(key, member); return client.getIntegerReply(); @@ -1557,27 +1560,30 @@ public class Jedis implements JedisCommands { * element as an integer reply if the element exists. A nil bulk * reply if there is no such element. */ - public Integer zrevrank(String key, String member) { + public Integer zrevrank(final String key, final String member) { runChecks(); client.zrevrank(key, member); return client.getIntegerReply(); } - public Set zrevrange(String key, int start, int end) { + public Set zrevrange(final String key, final int start, + final int end) { runChecks(); client.zrevrange(key, start, end); - List members = client.getMultiBulkReply(); + final List members = client.getMultiBulkReply(); return new LinkedHashSet(members); } - public Set zrangeWithScores(String key, int start, int end) { + public Set zrangeWithScores(final String key, final int start, + final int end) { runChecks(); client.zrangeWithScores(key, start, end); Set set = getTupledSet(); return set; } - public Set zrevrangeWithScores(String key, int start, int end) { + public Set zrevrangeWithScores(final String key, final int start, + final int end) { runChecks(); client.zrevrangeWithScores(key, start, end); Set set = getTupledSet(); @@ -1593,7 +1599,7 @@ public class Jedis implements JedisCommands { * @param key * @return the cardinality (number of elements) of the set as an integer. */ - public Integer zcard(String key) { + public Integer zcard(final String key) { runChecks(); client.zcard(key); return client.getIntegerReply(); @@ -1610,10 +1616,10 @@ public class Jedis implements JedisCommands { * @param member * @return the score */ - public Double zscore(String key, String member) { + public Double zscore(final String key, final String member) { runChecks(); client.zscore(key, member); - String score = client.getBulkReply(); + final String score = client.getBulkReply(); return (score != null ? new Double(score) : null); } @@ -1663,16 +1669,11 @@ public class Jedis implements JedisCommands { client.disconnect(); } - public String watch(String key) { + public String watch(final String key) { client.watch(key); return client.getStatusCodeReply(); } - public String unwatch() { - client.unwatch(); - return client.getStatusCodeReply(); - } - /** * Sort a Set or a List. *

@@ -1690,7 +1691,7 @@ public class Jedis implements JedisCommands { * return value will be the list of numbers ordered from the * smallest to the biggest number. */ - public List sort(String key) { + public List sort(final String key) { runChecks(); client.sort(key); return client.getMultiBulkReply(); @@ -1772,7 +1773,8 @@ public class Jedis implements JedisCommands { * @param sortingParameters * @return a list of sorted elements. */ - public List sort(String key, SortingParams sortingParameters) { + public List sort(final String key, + final SortingParams sortingParameters) { runChecks(); client.sort(key, sortingParameters); return client.getMultiBulkReply(); @@ -1850,7 +1852,7 @@ public class Jedis implements JedisCommands { * client values will return false or nil accordingly to the * programming language used. */ - public List blpop(int timeout, String... keys) { + public List blpop(final int timeout, final String... keys) { runChecks(); List args = new ArrayList(); for (String arg : keys) { @@ -1860,7 +1862,7 @@ public class Jedis implements JedisCommands { client.blpop(args.toArray(new String[args.size()])); client.setTimeoutInfinite(); - List multiBulkReply = client.getMultiBulkReply(); + final List multiBulkReply = client.getMultiBulkReply(); client.rollbackTimeout(); return multiBulkReply; } @@ -1878,8 +1880,8 @@ public class Jedis implements JedisCommands { * @param dstkey * @return The number of elements of the list at dstkey. */ - public Integer sort(String key, SortingParams sortingParameters, - String dstkey) { + public Integer sort(final String key, + final SortingParams sortingParameters, final String dstkey) { runChecks(); client.sort(key, sortingParameters, dstkey); return client.getIntegerReply(); @@ -1901,7 +1903,7 @@ public class Jedis implements JedisCommands { * @param dstkey * @return The number of elements of the list at dstkey. */ - public Integer sort(String key, String dstkey) { + public Integer sort(final String key, final String dstkey) { runChecks(); client.sort(key, dstkey); return client.getIntegerReply(); @@ -1979,7 +1981,7 @@ public class Jedis implements JedisCommands { * client values will return false or nil accordingly to the * programming language used. */ - public List brpop(int timeout, String... keys) { + public List brpop(final int timeout, final String... keys) { runChecks(); List args = new ArrayList(); for (String arg : keys) { @@ -2010,7 +2012,7 @@ public class Jedis implements JedisCommands { * @param password * @return Status code reply */ - public String auth(String password) { + public String auth(final String password) { runChecks(); client.auth(password); return client.getStatusCodeReply(); @@ -2039,7 +2041,7 @@ public class Jedis implements JedisCommands { client.rollbackTimeout(); } - public Integer zcount(String key, double min, double max) { + public Integer zcount(final String key, final double min, final double max) { runChecks(); client.zcount(key, min, max); return client.getIntegerReply(); @@ -2102,13 +2104,15 @@ public class Jedis implements JedisCommands { * @return Multi bulk reply specifically a list of elements in the specified * score range. */ - public Set zrangeByScore(String key, double min, double max) { + public Set zrangeByScore(final String key, final double min, + final double max) { runChecks(); client.zrangeByScore(key, min, max); return new LinkedHashSet(client.getMultiBulkReply()); } - public Set zrangeByScore(String key, String min, String max) { + public Set zrangeByScore(final String key, final String min, + final String max) { runChecks(); client.zrangeByScore(key, min, max); return new LinkedHashSet(client.getMultiBulkReply()); @@ -2170,8 +2174,8 @@ public class Jedis implements JedisCommands { * @return Multi bulk reply specifically a list of elements in the specified * score range. */ - public Set zrangeByScore(String key, double min, double max, - int offset, int count) { + public Set zrangeByScore(final String key, final double min, + final double max, final int offset, final int count) { runChecks(); client.zrangeByScore(key, min, max, offset, count); return new LinkedHashSet(client.getMultiBulkReply()); @@ -2233,7 +2237,8 @@ public class Jedis implements JedisCommands { * @return Multi bulk reply specifically a list of elements in the specified * score range. */ - public Set zrangeByScoreWithScores(String key, double min, double max) { + public Set zrangeByScoreWithScores(final String key, + final double min, final double max) { runChecks(); client.zrangeByScoreWithScores(key, min, max); Set set = getTupledSet(); @@ -2296,8 +2301,9 @@ public class Jedis implements JedisCommands { * @return Multi bulk reply specifically a list of elements in the specified * score range. */ - public Set zrangeByScoreWithScores(String key, double min, - double max, int offset, int count) { + public Set zrangeByScoreWithScores(final String key, + final double min, final double max, final int offset, + final int count) { runChecks(); client.zrangeByScoreWithScores(key, min, max, offset, count); Set set = getTupledSet(); @@ -2330,7 +2336,8 @@ public class Jedis implements JedisCommands { * operation * */ - public Integer zremrangeByRank(String key, int start, int end) { + public Integer zremrangeByRank(final String key, final int start, + final int end) { runChecks(); client.zremrangeByRank(key, start, end); return client.getIntegerReply(); @@ -2350,7 +2357,8 @@ public class Jedis implements JedisCommands { * @param end * @return Integer reply, specifically the number of elements removed. */ - public Integer zremrangeByScore(String key, double start, double end) { + public Integer zremrangeByScore(final String key, final double start, + final double end) { runChecks(); client.zremrangeByScore(key, start, end); return client.getIntegerReply(); @@ -2394,7 +2402,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically the number of elements in the sorted * set at dstkey */ - public Integer zunionstore(String dstkey, String... sets) { + public Integer zunionstore(final String dstkey, final String... sets) { runChecks(); client.zunionstore(dstkey, sets); return client.getIntegerReply(); @@ -2439,7 +2447,8 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically the number of elements in the sorted * set at dstkey */ - public Integer zunionstore(String dstkey, ZParams params, String... sets) { + public Integer zunionstore(final String dstkey, final ZParams params, + final String... sets) { runChecks(); client.zunionstore(dstkey, params, sets); return client.getIntegerReply(); @@ -2483,7 +2492,7 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically the number of elements in the sorted * set at dstkey */ - public Integer zinterstore(String dstkey, String... sets) { + public Integer zinterstore(final String dstkey, final String... sets) { runChecks(); client.zinterstore(dstkey, sets); return client.getIntegerReply(); @@ -2528,299 +2537,19 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically the number of elements in the sorted * set at dstkey */ - public Integer zinterstore(String dstkey, ZParams params, String... sets) { + public Integer zinterstore(final String dstkey, final ZParams params, + final String... sets) { runChecks(); client.zinterstore(dstkey, params, sets); return client.getIntegerReply(); } - /** - * Synchronously save the DB on disk. - *

- * Save the whole dataset on disk (this means that all the databases are - * saved, as well as keys with an EXPIRE set (the expire is preserved). The - * server hangs while the saving is not completed, no connection is served - * in the meanwhile. An OK code is returned when the DB was fully stored in - * disk. - *

- * The background variant of this command is {@link #bgsave() BGSAVE} that - * is able to perform the saving in the background while the server - * continues serving other clients. - *

- * - * @return Status code reply - */ - public String save() { - client.save(); - return client.getStatusCodeReply(); - } - - /** - * Asynchronously save the DB on disk. - *

- * Save the DB in background. The OK code is immediately returned. Redis - * forks, the parent continues to server the clients, the child saves the DB - * on disk then exit. A client my be able to check if the operation - * succeeded using the LASTSAVE command. - * - * @return Status code reply - */ - public String bgsave() { - client.bgsave(); - return client.getStatusCodeReply(); - } - - /** - * Rewrite the append only file in background when it gets too big. Please - * for detailed information about the Redis Append Only File check the Append - * Only File Howto. - *

- * BGREWRITEAOF rewrites the Append Only File in background when it gets too - * big. The Redis Append Only File is a Journal, so every operation - * modifying the dataset is logged in the Append Only File (and replayed at - * startup). This means that the Append Only File always grows. In order to - * rebuild its content the BGREWRITEAOF creates a new version of the append - * only file starting directly form the dataset in memory in order to - * guarantee the generation of the minimal number of commands needed to - * rebuild the database. - *

- * - * @return Status code reply - */ - public String bgrewriteaof() { - client.bgrewriteaof(); - return client.getStatusCodeReply(); - } - - /** - * Return the UNIX time stamp of the last successfully saving of the dataset - * on disk. - *

- * Return the UNIX TIME of the last DB save executed with success. A client - * may check if a {@link #bgsave() BGSAVE} command succeeded reading the - * LASTSAVE value, then issuing a BGSAVE command and checking at regular - * intervals every N seconds if LASTSAVE changed. - * - * @return Integer reply, specifically an UNIX time stamp. - */ - public Integer lastsave() { - client.lastsave(); - return client.getIntegerReply(); - } - - /** - * Synchronously save the DB on disk, then shutdown the server. - *

- * Stop all the clients, save the DB, then quit the server. This commands - * makes sure that the DB is switched off without the lost of any data. This - * is not guaranteed if the client uses simply {@link #save() SAVE} and then - * {@link #quit() QUIT} because other clients may alter the DB data between - * the two commands. - * - * @return Status code reply on error. On success nothing is returned since - * the server quits and the connection is closed. - */ - public String shutdown() { - client.shutdown(); - String status = null; - try { - status = client.getStatusCodeReply(); - } catch (JedisException ex) { - status = null; - } - return status; - } - - /** - * Provide information and statistics about the server. - *

- * The info command returns different information and statistics about the - * server in an format that's simple to parse by computers and easy to read - * by humans. - *

- * Format of the returned String: - *

- * All the fields are in the form field:value - * - *

-     * edis_version:0.07
-     * connected_clients:1
-     * connected_slaves:0
-     * used_memory:3187
-     * changes_since_last_save:0
-     * last_save_time:1237655729
-     * total_connections_received:1
-     * total_commands_processed:1
-     * uptime_in_seconds:25
-     * uptime_in_days:0
-     * 
- * - * Notes - *

- * used_memory is returned in bytes, and is the total number of bytes - * allocated by the program using malloc. - *

- * uptime_in_days is redundant since the uptime in seconds contains already - * the full uptime information, this field is only mainly present for - * humans. - *

- * changes_since_last_save does not refer to the number of key changes, but - * to the number of operations that produced some kind of change in the - * dataset. - *

- * - * @return Bulk reply - */ - public String info() { - client.info(); - return client.getBulkReply(); - } - - /** - * Dump all the received requests in real time. - *

- * MONITOR is a debugging command that outputs the whole sequence of - * commands received by the Redis server. is very handy in order to - * understand what is happening into the database. This command is used - * directly via telnet. - * - * @param jedisMonitor - */ - public void monitor(JedisMonitor jedisMonitor) { - client.monitor(); - jedisMonitor.proceed(client); - } - - /** - * Change the replication settings. - *

- * The SLAVEOF command can change the replication settings of a slave on the - * fly. If a Redis server is arleady acting as slave, the command SLAVEOF NO - * ONE will turn off the replicaiton turning the Redis server into a MASTER. - * In the proper form SLAVEOF hostname port will make the server a slave of - * the specific server listening at the specified hostname and port. - *

- * If a server is already a slave of some master, SLAVEOF hostname port will - * stop the replication against the old server and start the - * synchrnonization against the new one discarding the old dataset. - *

- * The form SLAVEOF no one will stop replication turning the server into a - * MASTER but will not discard the replication. So if the old master stop - * working it is possible to turn the slave into a master and set the - * application to use the new master in read/write. Later when the other - * Redis server will be fixed it can be configured in order to work as - * slave. - *

- * - * @param host - * @param port - * @return Status code reply - */ - public String slaveof(String host, int port) { - client.slaveof(host, port); - return client.getStatusCodeReply(); - } - - public String slaveofNoOne() { - client.slaveofNoOne(); - return client.getStatusCodeReply(); - } - - /** - * Retrieve the configuration of a running Redis server. Not all the - * configuration parameters are supported. - *

- * CONFIG GET returns the current configuration parameters. This sub command - * only accepts a single argument, that is glob style pattern. All the - * configuration parameters matching this parameter are reported as a list - * of key-value pairs. - *

- * Example: - * - *

-     * $ redis-cli config get '*'
-     * 1. "dbfilename"
-     * 2. "dump.rdb"
-     * 3. "requirepass"
-     * 4. (nil)
-     * 5. "masterauth"
-     * 6. (nil)
-     * 7. "maxmemory"
-     * 8. "0\n"
-     * 9. "appendfsync"
-     * 10. "everysec"
-     * 11. "save"
-     * 12. "3600 1 300 100 60 10000"
-     * 
-     * $ redis-cli config get 'm*'
-     * 1. "masterauth"
-     * 2. (nil)
-     * 3. "maxmemory"
-     * 4. "0\n"
-     * 
- * - * @param pattern - * @return Bulk reply. - */ - public List configGet(String pattern) { - client.configGet(pattern); - return client.getMultiBulkReply(); - } - - /** - * Alter the configuration of a running Redis server. Not all the - * configuration parameters are supported. - *

- * The list of configuration parameters supported by CONFIG SET can be - * obtained issuing a {@link #configGet(String) CONFIG GET *} command. - *

- * The configuration set using CONFIG SET is immediately loaded by the Redis - * server that will start acting as specified starting from the next - * command. - *

- * - * Parameters value format - *

- * The value of the configuration parameter is the same as the one of the - * same parameter in the Redis configuration file, with the following - * exceptions: - *

- *

    - *
  • The save paramter is a list of space-separated integers. Every pair - * of integers specify the time and number of changes limit to trigger a - * save. For instance the command CONFIG SET save "3600 10 60 10000" will - * configure the server to issue a background saving of the RDB file every - * 3600 seconds if there are at least 10 changes in the dataset, and every - * 60 seconds if there are at least 10000 changes. To completely disable - * automatic snapshots just set the parameter as an empty string. - *
  • All the integer parameters representing memory are returned and - * accepted only using bytes as unit. - *
- * - * @param parameter - * @param value - * @return Status code reply - */ - public String configSet(String parameter, String value) { - client.configSet(parameter, value); - return client.getStatusCodeReply(); - } - - public boolean isConnected() { - return client.isConnected(); - } - - public Integer strlen(String key) { + public Integer strlen(final String key) { client.strlen(key); return client.getIntegerReply(); } - public void sync() { - client.sync(); - } - - public Integer lpushx(String key, String string) { + public Integer lpushx(final String key, final String string) { client.lpushx(key, string); return client.getIntegerReply(); } @@ -2835,33 +2564,24 @@ public class Jedis implements JedisCommands { * @return Integer reply, specifically: 1: the key is now persist. 0: the * key is not persist (only happens when key not set). */ - public Integer persist(String key) { + public Integer persist(final String key) { client.persist(key); return client.getIntegerReply(); } - public Integer rpushx(String key, String string) { + public Integer rpushx(final String key, final String string) { client.rpushx(key, string); return client.getIntegerReply(); } - public String echo(String string) { + public String echo(final String string) { client.echo(string); return client.getBulkReply(); } - public Integer linsert(String key, LIST_POSITION where, String pivot, - String value) { + public Integer linsert(final String key, final LIST_POSITION where, + final String pivot, final String value) { client.linsert(key, where, pivot, value); return client.getIntegerReply(); } - - public String debug(DebugParams params) { - client.debug(params); - return client.getStatusCodeReply(); - } - - public Client getClient() { - return client; - } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/JedisCommands.java b/src/main/java/redis/clients/jedis/JedisCommands.java index 126e28d..a821519 100644 --- a/src/main/java/redis/clients/jedis/JedisCommands.java +++ b/src/main/java/redis/clients/jedis/JedisCommands.java @@ -1,5 +1,6 @@ package redis.clients.jedis; +import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; @@ -58,9 +59,9 @@ public interface JedisCommands { Integer hlen(String key); - List hkeys(String key); + Set hkeys(String key); - List hvals(String key); + Collection hvals(String key); Map hgetAll(String key); diff --git a/src/main/java/redis/clients/jedis/JedisPubSub.java b/src/main/java/redis/clients/jedis/JedisPubSub.java index ac6918d..e0c5dec 100644 --- a/src/main/java/redis/clients/jedis/JedisPubSub.java +++ b/src/main/java/redis/clients/jedis/JedisPubSub.java @@ -1,7 +1,10 @@ package redis.clients.jedis; +import java.util.Arrays; import java.util.List; +import static redis.clients.jedis.Protocol.Keyword.*; + public abstract class JedisPubSub { private int subscribedChannels = 0; private Client client; @@ -62,26 +65,78 @@ public abstract class JedisPubSub { private void process(Client client) { do { List reply = client.getObjectMultiBulkReply(); - if (reply.get(0).equals("subscribe")) { + final Object firstObj = reply.get(0); + if (!(firstObj instanceof byte[])) { + throw + new JedisException("Unknown message type: "+ firstObj); + } + final byte[] resp = (byte[]) firstObj; + if(Arrays.equals(SUBSCRIBE.raw, resp)) { subscribedChannels = ((Integer) reply.get(2)).intValue(); - onSubscribe((String) reply.get(1), subscribedChannels); - } else if (reply.get(0).equals("unsubscribe")) { + final byte[] bchannel = (byte[]) reply.get(1); + final String strchannel = + (bchannel == null) ? + null : + new String(bchannel, Protocol.UTF8); + onSubscribe(strchannel, subscribedChannels); + } else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) { subscribedChannels = ((Integer) reply.get(2)).intValue(); - onUnsubscribe((String) reply.get(1), subscribedChannels); - } else if (reply.get(0).equals("message")) { - onMessage((String) reply.get(1), (String) reply.get(2)); - } else if (reply.get(0).equals("pmessage")) { - onPMessage((String) reply.get(1), (String) reply.get(2), - (String) reply.get(3)); - } else if (reply.get(0).equals("psubscribe")) { + final byte[] bchannel = (byte[]) reply.get(1); + final String strchannel = + (bchannel == null) ? + null : + new String(bchannel, Protocol.UTF8); + onUnsubscribe(strchannel, subscribedChannels); + } else if (Arrays.equals(MESSAGE.raw, resp)) { + final byte[] bchannel = (byte[]) reply.get(1); + final byte[] bmesg = (byte[]) reply.get(2); + final String strchannel = + (bchannel == null) ? + null : + new String(bchannel, Protocol.UTF8); + final String strmesg = + (bmesg == null) ? + null : + new String(bmesg, Protocol.UTF8); + onMessage(strchannel, strmesg); + } else if (Arrays.equals(PMESSAGE.raw, resp)) { + final byte[] bpattern = (byte[]) reply.get(1); + final byte[] bchannel = (byte[]) reply.get(2); + final byte[] bmesg = (byte[]) reply.get(3); + final String strpattern = + (bpattern == null) ? + null : + new String(bpattern, Protocol.UTF8); + final String strchannel = + (bchannel == null) ? + null : + new String(bchannel, Protocol.UTF8); + final String strmesg = + (bmesg == null) ? + null : + new String(bmesg, Protocol.UTF8); + onPMessage( + strpattern, + strchannel, + strmesg); + } else if (Arrays.equals(PSUBSCRIBE.raw, resp)) { subscribedChannels = ((Integer) reply.get(2)).intValue(); - onPSubscribe((String) reply.get(1), subscribedChannels); - } else if (reply.get(0).equals("punsubscribe")) { + final byte[] bpattern = (byte[]) reply.get(1); + final String strpattern = + (bpattern == null) ? + null : + new String(bpattern, Protocol.UTF8); + onPSubscribe(strpattern, subscribedChannels); + } else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) { subscribedChannels = ((Integer) reply.get(2)).intValue(); - onPUnsubscribe((String) reply.get(1), subscribedChannels); + final byte[] bpattern = (byte[]) reply.get(1); + final String strpattern = + (bpattern == null) ? + null : + new String(bpattern, Protocol.UTF8); + onPUnsubscribe(strpattern, subscribedChannels); } else { - throw new JedisException("Unknown message type: " - + reply.get(0)); + throw new JedisException("Unknown message type: "+ firstObj); } } while (isSubscribed()); } diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index e9e6211..00b9cae 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -1,41 +1,45 @@ package redis.clients.jedis; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; + import redis.clients.util.RedisInputStream; import redis.clients.util.RedisOutputStream; -import java.io.*; -import java.util.ArrayList; -import java.util.List; - -import static redis.clients.util.RedisOutputStream.CHARSET; - public final class Protocol { public static final int DEFAULT_PORT = 6379; + public static final Charset UTF8 = Charset.forName("UTF-8"); + public static final byte DOLLAR_BYTE = '$'; public static final byte ASTERISK_BYTE = '*'; public static final byte PLUS_BYTE = '+'; public static final byte MINUS_BYTE = '-'; public static final byte COLON_BYTE = ':'; - public void sendCommand(RedisOutputStream os, String name, String... args) { + public void sendCommand(final RedisOutputStream os, final Command command, + final byte[]... args) { + sendCommand(os, command.raw, args); + } + + private void sendCommand(final RedisOutputStream os, final byte[] command, + final byte[]... args) { try { os.write(ASTERISK_BYTE); os.writeIntCrLf(args.length + 1); os.write(DOLLAR_BYTE); - os.writeIntCrLf(name.length()); - os.writeAsciiCrLf(name); + os.writeIntCrLf(command.length); + os.write(command); + os.writeCrLf(); - for (String str : args) { + for (final byte[] arg : args) { os.write(DOLLAR_BYTE); - final int size = RedisOutputStream.utf8Length(str); - os.writeIntCrLf(size); - if (size == str.length()) - os.writeAsciiCrLf(str); - else { - os.writeUtf8CrLf(str); - } + os.writeIntCrLf(arg.length); + os.write(arg); + os.writeCrLf(); } os.flush(); } catch (IOException e) { @@ -43,12 +47,12 @@ public final class Protocol { } } - private void processError(RedisInputStream is) { + private void processError(final RedisInputStream is) { String message = is.readLine(); throw new JedisException(message); } - private Object process(RedisInputStream is) { + private Object process(final RedisInputStream is) { try { byte b = is.readByte(); if (b == MINUS_BYTE) { @@ -70,11 +74,11 @@ public final class Protocol { return null; } - private String processStatusCodeReply(RedisInputStream is) { - return is.readLine(); + private byte[] processStatusCodeReply(final RedisInputStream is) { + return is.readLine().getBytes(UTF8); } - private String processBulkReply(RedisInputStream is) { + private byte[] processBulkReply(final RedisInputStream is) { int len = Integer.parseInt(is.readLine()); if (len == -1) { return null; @@ -92,15 +96,15 @@ public final class Protocol { throw new JedisException(e); } - return new String(read, CHARSET); + return read; } - private Integer processInteger(RedisInputStream is) { + private Integer processInteger(final RedisInputStream is) { String num = is.readLine(); return Integer.valueOf(num); } - private List processMultiBulkReply(RedisInputStream is) { + private List processMultiBulkReply(final RedisInputStream is) { int num = Integer.parseInt(is.readLine()); if (num == -1) { return null; @@ -112,7 +116,39 @@ public final class Protocol { return ret; } - public Object read(RedisInputStream is) { + public Object read(final RedisInputStream is) { return process(is); } + + public static final byte[] toByteArray(final int value) { + return String.valueOf(value).getBytes(Protocol.UTF8); + } + + public static final byte[] toByteArray(final long value) { + return String.valueOf(value).getBytes(Protocol.UTF8); + } + + public static final byte[] toByteArray(final double value) { + return String.valueOf(value).getBytes(Protocol.UTF8); + } + + public static enum Command { + PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, ZCOUNT, ZRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG; + + public final byte[] raw; + + Command() { + raw = this.name().getBytes(UTF8); + } + } + + public static enum Keyword { + AGGREGATE, ALPHA, ASC, BY, DESC, GET, LIMIT, MESSAGE, NO, NOSORT, PMESSAGE, PSUBSCRIBE, PUNSUBSCRIBE, OK, ONE, QUEUED, SET, STORE, SUBSCRIBE, UNSUBSCRIBE, WEIGHTS, WITHSCORES; + public final byte[] raw; + + Keyword() { + raw = this.name().toLowerCase().getBytes(UTF8); + } + + } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/ShardedJedis.java b/src/main/java/redis/clients/jedis/ShardedJedis.java index a14b0a8..719e7de 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedis.java +++ b/src/main/java/redis/clients/jedis/ShardedJedis.java @@ -1,17 +1,16 @@ package redis.clients.jedis; import java.io.IOException; +import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; -import redis.clients.jedis.Client.LIST_POSITION; +import redis.clients.jedis.BinaryClient.LIST_POSITION; import redis.clients.util.Hashing; -import redis.clients.util.Sharded; -public class ShardedJedis extends Sharded implements - JedisCommands { +public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { public ShardedJedis(List shards) { super(shards); } @@ -161,12 +160,12 @@ public class ShardedJedis extends Sharded implements return j.hlen(key); } - public List hkeys(String key) { + public Set hkeys(String key) { Jedis j = getShard(key); return j.hkeys(key); } - public List hvals(String key) { + public Collection hvals(String key) { Jedis j = getShard(key); return j.hvals(key); } @@ -368,10 +367,4 @@ public class ShardedJedis extends Sharded implements Jedis j = getShard(key); return j.linsert(key, where, pivot, value); } - - public List pipelined(ShardedJedisPipeline shardedJedisPipeline) { - shardedJedisPipeline.setShardedJedis(this); - shardedJedisPipeline.execute(); - return shardedJedisPipeline.getResults(); - } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/ShardedJedisPipeline.java b/src/main/java/redis/clients/jedis/ShardedJedisPipeline.java index c4e4881..ad57c0f 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedisPipeline.java +++ b/src/main/java/redis/clients/jedis/ShardedJedisPipeline.java @@ -4,10 +4,10 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import redis.clients.jedis.Client.LIST_POSITION; +import redis.clients.jedis.BinaryClient.LIST_POSITION; public abstract class ShardedJedisPipeline { - private ShardedJedis jedis; + private BinaryShardedJedis jedis; private List results = new ArrayList(); private class FutureResult { @@ -22,7 +22,7 @@ public abstract class ShardedJedisPipeline { } } - public void setShardedJedis(ShardedJedis jedis) { + public void setShardedJedis(BinaryShardedJedis jedis) { this.jedis = jedis; } diff --git a/src/main/java/redis/clients/jedis/SortingParams.java b/src/main/java/redis/clients/jedis/SortingParams.java index dcd415d..2129025 100644 --- a/src/main/java/redis/clients/jedis/SortingParams.java +++ b/src/main/java/redis/clients/jedis/SortingParams.java @@ -4,13 +4,13 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; - +import static redis.clients.jedis.Protocol.Keyword.*; /** * Builder Class for {@link Jedis#sort(String, SortingParams) SORT} Parameters. * */ public class SortingParams { - private List params = new ArrayList(); + private List params = new ArrayList(); /** * Sort by weight in keys. @@ -25,8 +25,25 @@ public class SortingParams { * @param pattern * @return the SortingParams Object */ - public SortingParams by(String pattern) { - params.add("BY"); + public SortingParams by(final String pattern) { + return by(pattern.getBytes(Protocol.UTF8)); + } + + /** + * Sort by weight in keys. + *

+ * Takes a pattern that is used in order to generate the key names of the + * weights used for sorting. Weight key names are obtained substituting the + * first occurrence of * with the actual value of the elements on the list. + *

+ * The pattern for a normal key/value pair is "keyname*" and for a value in + * a hash "keyname*->fieldname". + * + * @param pattern + * @return the SortingParams Object + */ + public SortingParams by(final byte[] pattern) { + params.add(BY.raw); params.add(pattern); return this; } @@ -40,11 +57,12 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams nosort() { - params.add("BY nosort"); + params.add(BY.raw); + params.add(NOSORT.raw); return this; } - public Collection getParams() { + public Collection getParams() { return Collections.unmodifiableCollection(params); } @@ -54,7 +72,7 @@ public class SortingParams { * @return the sortingParams Object */ public SortingParams desc() { - params.add("DESC"); + params.add(DESC.raw); return this; } @@ -64,7 +82,7 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams asc() { - params.add("ASC"); + params.add(ASC.raw); return this; } @@ -76,10 +94,10 @@ public class SortingParams { * @param count * @return the SortingParams Object */ - public SortingParams limit(int start, int count) { - params.add("LIMIT"); - params.add(String.valueOf(start)); - params.add(String.valueOf(count)); + public SortingParams limit(final int start, final int count) { + params.add(LIMIT.raw); + params.add(Protocol.toByteArray(start)); + params.add(Protocol.toByteArray(count)); return this; } @@ -90,7 +108,7 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams alpha() { - params.add("ALPHA"); + params.add(ALPHA.raw); return this; } @@ -110,8 +128,31 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams get(String... patterns) { - for (String pattern : patterns) { - params.add("GET"); + for (final String pattern : patterns) { + params.add(GET.raw); + params.add(pattern.getBytes(Protocol.UTF8)); + } + return this; + } + + /** + * Retrieving external keys from the result of the search. + *

+ * Takes a pattern that is used in order to generate the key names of the + * result of sorting. The key names are obtained substituting the first + * occurrence of * with the actual value of the elements on the list. + *

+ * The pattern for a normal key/value pair is "keyname*" and for a value in + * a hash "keyname*->fieldname". + *

+ * To get the list itself use the char # as pattern. + * + * @param patterns + * @return the SortingParams Object + */ + public SortingParams get(byte[]... patterns) { + for (final byte[] pattern : patterns) { + params.add(GET.raw); params.add(pattern); } return this; diff --git a/src/main/java/redis/clients/jedis/Transaction.java b/src/main/java/redis/clients/jedis/Transaction.java index 51a7fe3..f0ddbe1 100644 --- a/src/main/java/redis/clients/jedis/Transaction.java +++ b/src/main/java/redis/clients/jedis/Transaction.java @@ -1,425 +1,392 @@ package redis.clients.jedis; -import java.util.List; import java.util.Map; -public class Transaction { - protected Client client = null; - - public Transaction() { - } - - public Transaction(Client client) { - this.client = client; - } - - public String ping() { - client.ping(); - return client.getStatusCodeReply(); - } - - public String set(String key, String value) { - client.set(key, value); - return client.getStatusCodeReply(); - } - - public String get(String key) { - client.sendCommand("GET", key); - return client.getStatusCodeReply(); - } - - public String exists(String key) { - client.exists(key); - return client.getStatusCodeReply(); - } - - public String del(String... keys) { - client.del(keys); - return client.getStatusCodeReply(); - } - - public String type(String key) { - client.type(key); - return client.getStatusCodeReply(); - } - - public String flushDB() { - client.flushDB(); - return client.getStatusCodeReply(); - } - - public String keys(String pattern) { - client.keys(pattern); - return client.getStatusCodeReply(); - } - - public String randomKey() { - client.randomKey(); - return client.getStatusCodeReply(); - } - - public String rename(String oldkey, String newkey) { - client.rename(oldkey, newkey); - return client.getStatusCodeReply(); - } - - public String renamenx(String oldkey, String newkey) { - client.renamenx(oldkey, newkey); - return client.getStatusCodeReply(); - } - - public String dbSize() { - client.dbSize(); - return client.getStatusCodeReply(); - } - - public String expire(String key, int seconds) { - client.expire(key, seconds); - return client.getStatusCodeReply(); - } - - public String expireAt(String key, long unixTime) { - client.expireAt(key, unixTime); - return client.getStatusCodeReply(); - } - - public String ttl(String key) { - client.ttl(key); - return client.getStatusCodeReply(); - } - - public String select(int index) { - client.select(index); - return client.getStatusCodeReply(); - } - - public String move(String key, int dbIndex) { - client.move(key, dbIndex); - return client.getStatusCodeReply(); - } - - public String flushAll() { - client.flushAll(); - return client.getStatusCodeReply(); - } - - public String getSet(String key, String value) { - client.getSet(key, value); - return client.getStatusCodeReply(); - } - - public String mget(String... keys) { - client.mget(keys); - return client.getStatusCodeReply(); - } - - public String setnx(String key, String value) { - client.setnx(key, value); - return client.getStatusCodeReply(); - } - - public String setex(String key, int seconds, String value) { - client.setex(key, seconds, value); - return client.getStatusCodeReply(); - } - - public String mset(String... keysvalues) { - client.mset(keysvalues); - return client.getStatusCodeReply(); - } - - public String msetnx(String... keysvalues) { - client.msetnx(keysvalues); - return client.getStatusCodeReply(); - } - - public String decrBy(String key, int integer) { - client.decrBy(key, integer); - return client.getStatusCodeReply(); - } - - public String decr(String key) { - client.decr(key); - return client.getStatusCodeReply(); - } - - public String incrBy(String key, int integer) { - client.incrBy(key, integer); - return client.getStatusCodeReply(); - } - - public String incr(String key) { - client.incr(key); - return client.getStatusCodeReply(); - } - - public String append(String key, String value) { - client.append(key, value); - return client.getStatusCodeReply(); - } - - public String substr(String key, int start, int end) { - client.substr(key, start, end); - return client.getStatusCodeReply(); - } - - public String hset(String key, String field, String value) { - client.hset(key, field, value); - return client.getStatusCodeReply(); - } - - public String hget(String key, String field) { - client.hget(key, field); - return client.getStatusCodeReply(); - } - - public String hsetnx(String key, String field, String value) { - client.hsetnx(key, field, value); - return client.getStatusCodeReply(); - } - - public String hmset(String key, Map hash) { - client.hmset(key, hash); - return client.getStatusCodeReply(); - } - - public String hmget(String key, String... fields) { - client.hmget(key, fields); - return client.getStatusCodeReply(); - } - - public String hincrBy(String key, String field, int value) { - client.hincrBy(key, field, value); - return client.getStatusCodeReply(); - } - - public String hexists(String key, String field) { - client.hexists(key, field); - return client.getStatusCodeReply(); - } - - public String hdel(String key, String field) { - client.hdel(key, field); - return client.getStatusCodeReply(); - } - - public String hlen(String key) { - client.hlen(key); - return client.getStatusCodeReply(); - } - - public String hkeys(String key) { - client.hkeys(key); - return client.getStatusCodeReply(); - } - - public String hvals(String key) { - client.hvals(key); - return client.getStatusCodeReply(); - } - - public String hgetAll(String key) { - client.hgetAll(key); - return client.getStatusCodeReply(); - } - - public String rpush(String key, String string) { - client.rpush(key, string); - return client.getStatusCodeReply(); - } - - public String lpush(String key, String string) { - client.lpush(key, string); - return client.getStatusCodeReply(); - } - - public String llen(String key) { - client.llen(key); - return client.getStatusCodeReply(); - } - - public String lrange(String key, int start, int end) { - client.lrange(key, start, end); - return client.getStatusCodeReply(); - } - - public String ltrim(String key, int start, int end) { - client.ltrim(key, start, end); - return client.getStatusCodeReply(); - } - - public String lindex(String key, int index) { - client.lindex(key, index); - return client.getStatusCodeReply(); - } - - public String lset(String key, int index, String value) { - client.lset(key, index, value); - return client.getStatusCodeReply(); - } - - public String lrem(String key, int count, String value) { - client.lrem(key, count, value); - return client.getStatusCodeReply(); - } - - public String lpop(String key) { - client.lpop(key); - return client.getStatusCodeReply(); - } - - public String rpop(String key) { - client.rpop(key); - return client.getStatusCodeReply(); - } - - public String rpoplpush(String srckey, String dstkey) { - client.rpoplpush(srckey, dstkey); - return client.getStatusCodeReply(); - } - - public String sadd(String key, String member) { - client.sadd(key, member); - return client.getStatusCodeReply(); - } - - public String smembers(String key) { - client.smembers(key); - return client.getStatusCodeReply(); - } - - public String srem(String key, String member) { - client.srem(key, member); - return client.getStatusCodeReply(); - } - - public String spop(String key) { - client.spop(key); - return client.getStatusCodeReply(); - } - - public String smove(String srckey, String dstkey, String member) { - client.smove(srckey, dstkey, member); - return client.getStatusCodeReply(); - } - - public String scard(String key) { - client.scard(key); - return client.getStatusCodeReply(); - } - - public String sismember(String key, String member) { - client.sismember(key, member); - return client.getStatusCodeReply(); - } - - public String sinter(String... keys) { - client.sinter(keys); - return client.getStatusCodeReply(); - } - - public String sinterstore(String dstkey, String... keys) { - client.sinterstore(dstkey, keys); - return client.getStatusCodeReply(); - } - - public String sunion(String... keys) { - client.sunion(keys); - return client.getStatusCodeReply(); - } - - public String sunionstore(String dstkey, String... keys) { - client.sunionstore(dstkey, keys); - return client.getStatusCodeReply(); - } - - public String sdiff(String... keys) { - client.sdiff(keys); - return client.getStatusCodeReply(); - } - - public String sdiffstore(String dstkey, String... keys) { - client.sdiffstore(dstkey, keys); - return client.getStatusCodeReply(); - } - - public String srandmember(String key) { - client.srandmember(key); - return client.getStatusCodeReply(); - } - - public String zadd(String key, double score, String member) { - client.zadd(key, score, member); - return client.getStatusCodeReply(); - } - - public String zrange(String key, int start, int end) { - client.zrange(key, start, end); - return client.getStatusCodeReply(); - } - - public String zrem(String key, String member) { - client.zrem(key, member); - return client.getStatusCodeReply(); - } - - public String zincrby(String key, double score, String member) { - client.zincrby(key, score, member); - return client.getStatusCodeReply(); - } - - public String zrank(String key, String member) { - client.zrank(key, member); - return client.getStatusCodeReply(); - } - - public String zrevrank(String key, String member) { - client.zrevrank(key, member); - return client.getStatusCodeReply(); - } - - public String zrevrange(String key, int start, int end) { - client.zrevrange(key, start, end); - return client.getStatusCodeReply(); - } - - public String zrangeWithScores(String key, int start, int end) { - client.zrangeWithScores(key, start, end); - return client.getStatusCodeReply(); - } - - public String zrevrangeWithScores(String key, int start, int end) { - client.zrevrangeWithScores(key, start, end); - return client.getStatusCodeReply(); - } - - public String zcard(String key) { - client.zcard(key); - return client.getStatusCodeReply(); - } - - public String zscore(String key, String member) { - client.zscore(key, member); - return client.getStatusCodeReply(); - } - - public List exec() { - client.exec(); - - return client.getObjectMultiBulkReply(); - } - - public String sort(String key) { - client.sort(key); - return client.getStatusCodeReply(); - } - - public String sort(String key, SortingParams sortingParameters) { - client.sort(key, sortingParameters); - return client.getStatusCodeReply(); - } - - public void discard() { - client.discard(); - } +public class Transaction extends BinaryTransaction { + public Transaction() { + } + + public Transaction(final Client client) { + super(client); + } + + public String set(final String key, final String value) { + client.set(key, value); + return client.getStatusCodeReply(); + } + + public String get(final String key) { + client.get(key); + return client.getStatusCodeReply(); + } + + public String exists(final String key) { + client.exists(key); + return client.getStatusCodeReply(); + } + + public String del(final String... keys) { + client.del(keys); + return client.getStatusCodeReply(); + } + + public String type(final String key) { + client.type(key); + return client.getStatusCodeReply(); + } + + public String keys(final String pattern) { + client.keys(pattern); + return client.getStatusCodeReply(); + } + + public String randomKey() { + client.randomKey(); + return client.getBulkReply(); + } + + public String rename(final String oldkey, final String newkey) { + client.rename(oldkey, newkey); + return client.getStatusCodeReply(); + } + + public String renamenx(final String oldkey, final String newkey) { + client.renamenx(oldkey, newkey); + return client.getStatusCodeReply(); + } + + public String expire(final String key, final int seconds) { + client.expire(key, seconds); + return client.getStatusCodeReply(); + } + + public String expireAt(final String key, final long unixTime) { + client.expireAt(key, unixTime); + return client.getStatusCodeReply(); + } + + public String ttl(final String key) { + client.ttl(key); + return client.getStatusCodeReply(); + } + + public String move(final String key, final int dbIndex) { + client.move(key, dbIndex); + return client.getStatusCodeReply(); + } + + public String getSet(final String key, final String value) { + client.getSet(key, value); + return client.getStatusCodeReply(); + } + + public String mget(final String... keys) { + client.mget(keys); + return client.getStatusCodeReply(); + } + + public String setnx(final String key, final String value) { + client.setnx(key, value); + return client.getStatusCodeReply(); + } + + public String setex(final String key, final int seconds, final String value) { + client.setex(key, seconds, value); + return client.getStatusCodeReply(); + } + + public String mset(final String... keysvalues) { + client.mset(keysvalues); + return client.getStatusCodeReply(); + } + + public String msetnx(final String... keysvalues) { + client.msetnx(keysvalues); + return client.getStatusCodeReply(); + } + + public String decrBy(final String key, final int integer) { + client.decrBy(key, integer); + return client.getStatusCodeReply(); + } + + public String decr(final String key) { + client.decr(key); + return client.getStatusCodeReply(); + } + + public String incrBy(final String key, final int integer) { + client.incrBy(key, integer); + return client.getStatusCodeReply(); + } + + public String incr(final String key) { + client.incr(key); + return client.getStatusCodeReply(); + } + + public String append(final String key, final String value) { + client.append(key, value); + return client.getStatusCodeReply(); + } + + public String substr(final String key, final int start, final int end) { + client.substr(key, start, end); + return client.getStatusCodeReply(); + } + + public String hset(final String key, final String field, final String value) { + client.hset(key, field, value); + return client.getStatusCodeReply(); + } + + public String hget(final String key, final String field) { + client.hget(key, field); + return client.getStatusCodeReply(); + } + + public String hsetnx(final String key, final String field, + final String value) { + client.hsetnx(key, field, value); + return client.getStatusCodeReply(); + } + + public String hmset(final String key, final Map hash) { + client.hmset(key, hash); + return client.getStatusCodeReply(); + } + + public String hmget(final String key, final String... fields) { + client.hmget(key, fields); + return client.getStatusCodeReply(); + } + + public String hincrBy(final String key, final String field, final int value) { + client.hincrBy(key, field, value); + return client.getStatusCodeReply(); + } + + public String hexists(final String key, final String field) { + client.hexists(key, field); + return client.getStatusCodeReply(); + } + + public String hdel(final String key, final String field) { + client.hdel(key, field); + return client.getStatusCodeReply(); + } + + public String hlen(final String key) { + client.hlen(key); + return client.getStatusCodeReply(); + } + + public String hkeys(final String key) { + client.hkeys(key); + return client.getStatusCodeReply(); + } + + public String hvals(final String key) { + client.hvals(key); + return client.getStatusCodeReply(); + } + + public String hgetAll(final String key) { + client.hgetAll(key); + return client.getStatusCodeReply(); + } + + public String rpush(final String key, final String string) { + client.rpush(key, string); + return client.getStatusCodeReply(); + } + + public String lpush(final String key, final String string) { + client.lpush(key, string); + return client.getStatusCodeReply(); + } + + public String llen(final String key) { + client.llen(key); + return client.getStatusCodeReply(); + } + + public String lrange(final String key, final int start, final int end) { + client.lrange(key, start, end); + return client.getStatusCodeReply(); + } + + public String ltrim(String key, final int start, final int end) { + client.ltrim(key, start, end); + return client.getStatusCodeReply(); + } + + public String lindex(final String key, final int index) { + client.lindex(key, index); + return client.getStatusCodeReply(); + } + + public String lset(final String key, final int index, final String value) { + client.lset(key, index, value); + return client.getStatusCodeReply(); + } + + public String lrem(final String key, final int count, final String value) { + client.lrem(key, count, value); + return client.getStatusCodeReply(); + } + + public String lpop(final String key) { + client.lpop(key); + return client.getStatusCodeReply(); + } + + public String rpop(final String key) { + client.rpop(key); + return client.getStatusCodeReply(); + } + + public String rpoplpush(final String srckey, final String dstkey) { + client.rpoplpush(srckey, dstkey); + return client.getStatusCodeReply(); + } + + public String sadd(final String key, final String member) { + client.sadd(key, member); + return client.getStatusCodeReply(); + } + + public String smembers(final String key) { + client.smembers(key); + return client.getStatusCodeReply(); + } + + public String srem(final String key, final String member) { + client.srem(key, member); + return client.getStatusCodeReply(); + } + + public String spop(final String key) { + client.spop(key); + return client.getStatusCodeReply(); + } + + public String smove(final String srckey, final String dstkey, + final String member) { + client.smove(srckey, dstkey, member); + return client.getStatusCodeReply(); + } + + public String scard(final String key) { + client.scard(key); + return client.getStatusCodeReply(); + } + + public String sismember(final String key, final String member) { + client.sismember(key, member); + return client.getStatusCodeReply(); + } + + public String sinter(final String... keys) { + client.sinter(keys); + return client.getStatusCodeReply(); + } + + public String sinterstore(final String dstkey, final String... keys) { + client.sinterstore(dstkey, keys); + return client.getStatusCodeReply(); + } + + public String sunion(final String... keys) { + client.sunion(keys); + return client.getStatusCodeReply(); + } + + public String sunionstore(final String dstkey, final String... keys) { + client.sunionstore(dstkey, keys); + return client.getStatusCodeReply(); + } + + public String sdiff(final String... keys) { + client.sdiff(keys); + return client.getStatusCodeReply(); + } + + public String sdiffstore(final String dstkey, final String... keys) { + client.sdiffstore(dstkey, keys); + return client.getStatusCodeReply(); + } + + public String srandmember(final String key) { + client.srandmember(key); + return client.getStatusCodeReply(); + } + + public String zadd(final String key, final double score, final String member) { + client.zadd(key, score, member); + return client.getStatusCodeReply(); + } + + public String zrange(final String key, final int start, final int end) { + client.zrange(key, start, end); + return client.getStatusCodeReply(); + } + + public String zrem(final String key, final String member) { + client.zrem(key, member); + return client.getStatusCodeReply(); + } + + public String zincrby(final String key, final double score, + final String member) { + client.zincrby(key, score, member); + return client.getStatusCodeReply(); + } + + public String zrank(final String key, final String member) { + client.zrank(key, member); + return client.getStatusCodeReply(); + } + + public String zrevrank(final String key, final String member) { + client.zrevrank(key, member); + return client.getStatusCodeReply(); + } + + public String zrevrange(final String key, final int start, final int end) { + client.zrevrange(key, start, end); + return client.getStatusCodeReply(); + } + + public String zrangeWithScores(final String key, final int start, + final int end) { + client.zrangeWithScores(key, start, end); + return client.getStatusCodeReply(); + } + + public String zrevrangeWithScores(final String key, final int start, + final int end) { + client.zrevrangeWithScores(key, start, end); + return client.getStatusCodeReply(); + } + + public String zcard(final String key) { + client.zcard(key); + return client.getStatusCodeReply(); + } + + public String zscore(final String key, final String member) { + client.zscore(key, member); + return client.getStatusCodeReply(); + } + + public String sort(final String key) { + client.sort(key); + return client.getStatusCodeReply(); + } + + public String sort(final String key, final SortingParams sortingParameters) { + client.sort(key, sortingParameters); + return client.getStatusCodeReply(); + } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/Tuple.java b/src/main/java/redis/clients/jedis/Tuple.java index 30e4e53..425748d 100644 --- a/src/main/java/redis/clients/jedis/Tuple.java +++ b/src/main/java/redis/clients/jedis/Tuple.java @@ -1,14 +1,21 @@ package redis.clients.jedis; +import java.util.Arrays; + public class Tuple { - private String element; + private byte[] element; private Double score; @Override public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((element == null) ? 0 : element.hashCode()); + result = prime * result; + if (null != element) { + for(final byte b : element) { + result = prime * result + b; + } + } long temp; temp = Double.doubleToLongBits(score); result = prime * result + (int) (temp ^ (temp >>> 32)); @@ -27,7 +34,7 @@ public class Tuple { if (element == null) { if (other.element != null) return false; - } else if (!element.equals(other.element)) + } else if (!Arrays.equals(element, other.element)) return false; if (Double.doubleToLongBits(score) != Double .doubleToLongBits(other.score)) @@ -37,15 +44,33 @@ public class Tuple { public Tuple(String element, Double score) { super(); - this.element = element; + this.element = element.getBytes(Protocol.UTF8); this.score = score; } + public Tuple(byte[] element, Double score) { + super(); + this.element = element; + this.score = score; + } + public String getElement() { - return element; + if(null != element) { + return new String(element, Protocol.UTF8); + } else { + return null; + } + } + + public byte[] getBinaryElement() { + return element; } public double getScore() { return score; } + + public String toString() { + return '['+Arrays.toString(element)+','+score+']'; + } } diff --git a/src/main/java/redis/clients/jedis/ZParams.java b/src/main/java/redis/clients/jedis/ZParams.java index 86d9078..a260397 100644 --- a/src/main/java/redis/clients/jedis/ZParams.java +++ b/src/main/java/redis/clients/jedis/ZParams.java @@ -5,29 +5,36 @@ import java.util.Collection; import java.util.Collections; import java.util.List; +import static redis.clients.jedis.Protocol.Keyword.*; + public class ZParams { public enum Aggregate { - SUM, MIN, MAX + SUM, MIN, MAX; + + public final byte[] raw; + Aggregate() { + raw = name().getBytes(Protocol.UTF8); + } } - private List params = new ArrayList(); + private List params = new ArrayList(); - public ZParams weights(int... weights) { - params.add("WEIGHTS"); - for (int weight : weights) { - params.add(String.valueOf(weight)); + public ZParams weights(final int... weights) { + params.add(WEIGHTS.raw); + for (final int weight : weights) { + params.add(Protocol.toByteArray(weight)); } return this; } - public Collection getParams() { - return Collections.unmodifiableCollection(params); + public Collection getParams() { + return Collections.unmodifiableCollection(params); } - public ZParams aggregate(Aggregate aggregate) { - params.add("AGGREGATE"); - params.add(aggregate.name()); + public ZParams aggregate(final Aggregate aggregate) { + params.add(AGGREGATE.raw); + params.add(aggregate.raw); return this; } } diff --git a/src/main/java/redis/clients/util/Hashing.java b/src/main/java/redis/clients/util/Hashing.java index 291416f..5eaa023 100644 --- a/src/main/java/redis/clients/util/Hashing.java +++ b/src/main/java/redis/clients/util/Hashing.java @@ -3,13 +3,19 @@ package redis.clients.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import redis.clients.jedis.Protocol; + public interface Hashing { public static final Hashing MURMUR_HASH = new MurmurHash(); public static final Hashing MD5 = new Hashing() { private MessageDigest md5 = null; // avoid recurring construction - + public long hash(String key) { + return hash(key.getBytes(Protocol.UTF8)); + } + + public long hash(byte[] key) { if (md5 == null) { try { md5 = MessageDigest.getInstance("MD5"); @@ -20,7 +26,7 @@ public interface Hashing { } md5.reset(); - md5.update(key.getBytes()); + md5.update(key); byte[] bKey = md5.digest(); long res = ((long) (bKey[3] & 0xFF) << 24) | ((long) (bKey[2] & 0xFF) << 16) @@ -30,4 +36,5 @@ public interface Hashing { }; public long hash(String key); + public long hash(byte[] key); } \ No newline at end of file diff --git a/src/main/java/redis/clients/util/JedisByteHashMap.java b/src/main/java/redis/clients/util/JedisByteHashMap.java new file mode 100644 index 0000000..a089d75 --- /dev/null +++ b/src/main/java/redis/clients/util/JedisByteHashMap.java @@ -0,0 +1,148 @@ +package redis.clients.util; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +public class JedisByteHashMap implements Map, Cloneable, + Serializable { + private static final long serialVersionUID = -6971431362627219416L; + private Map internalMap = new HashMap(); + + public void clear() { + internalMap.clear(); + } + + public boolean containsKey(Object key) { + if (key instanceof byte[]) + return internalMap.containsKey(new ByteArrayWrapper((byte[]) key)); + return internalMap.containsKey(key); + } + + public boolean containsValue(Object value) { + return internalMap.containsValue(value); + } + + public Set> entrySet() { + Iterator> iterator = internalMap + .entrySet().iterator(); + HashSet> hashSet = new HashSet>(); + while (iterator.hasNext()) { + Entry entry = iterator.next(); + hashSet.add(new JedisByteEntry(entry.getKey().data, entry + .getValue())); + } + return hashSet; + } + + @Override + public byte[] get(Object key) { + if (key instanceof byte[]) + return internalMap.get(new ByteArrayWrapper((byte[]) key)); + return internalMap.get(key); + } + + @Override + public boolean isEmpty() { + return internalMap.isEmpty(); + } + + @Override + public Set keySet() { + Set keySet = new HashSet(); + Iterator iterator = internalMap.keySet().iterator(); + while (iterator.hasNext()) { + keySet.add(iterator.next().data); + } + return keySet; + } + + @Override + public byte[] put(byte[] key, byte[] value) { + return internalMap.put(new ByteArrayWrapper(key), value); + } + + @SuppressWarnings("unchecked") + @Override + public void putAll(Map m) { + Iterator iterator = m.entrySet().iterator(); + while (iterator.hasNext()) { + Entry next = (Entry) iterator + .next(); + internalMap.put(new ByteArrayWrapper(next.getKey()), next + .getValue()); + } + } + + @Override + public byte[] remove(Object key) { + if (key instanceof byte[]) + return internalMap.remove(new ByteArrayWrapper((byte[]) key)); + return internalMap.remove(key); + } + + @Override + public int size() { + return internalMap.size(); + } + + @Override + public Collection values() { + return internalMap.values(); + } + + private final class ByteArrayWrapper { + private final byte[] data; + + public ByteArrayWrapper(byte[] data) { + if (data == null) { + throw new NullPointerException(); + } + this.data = data; + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof ByteArrayWrapper)) { + return false; + } + return Arrays.equals(data, ((ByteArrayWrapper) other).data); + } + + @Override + public int hashCode() { + return Arrays.hashCode(data); + } + } + + private final class JedisByteEntry implements Entry { + private byte[] value; + private byte[] key; + + public JedisByteEntry(byte[] key, byte[] value) { + this.key = key; + this.value = value; + } + + public byte[] getKey() { + return this.key; + } + + @Override + public byte[] getValue() { + return this.value; + } + + @Override + public byte[] setValue(byte[] value) { + this.value = value; + return value; + } + + } +} \ No newline at end of file diff --git a/src/main/java/redis/clients/util/MurmurHash.java b/src/main/java/redis/clients/util/MurmurHash.java index 0294a25..934f7cd 100644 --- a/src/main/java/redis/clients/util/MurmurHash.java +++ b/src/main/java/redis/clients/util/MurmurHash.java @@ -20,6 +20,8 @@ package redis.clients.util; import java.nio.ByteBuffer; import java.nio.ByteOrder; +import redis.clients.jedis.Protocol; + /** * This is a very fast, non-cryptographic hash suitable for general hash-based * lookup. See http://murmurhash.googlepages.com/ for more details. @@ -156,7 +158,11 @@ public class MurmurHash implements Hashing { return h; } + public long hash(byte[] key) { + return hash64A(key, 0x1234ABCD); + } + public long hash(String key) { - return hash64A(key.getBytes(), 0x1234ABCD); + return hash(key.getBytes(Protocol.UTF8)); } } \ No newline at end of file diff --git a/src/main/java/redis/clients/util/RedisOutputStream.java b/src/main/java/redis/clients/util/RedisOutputStream.java index c366e02..5708d43 100644 --- a/src/main/java/redis/clients/util/RedisOutputStream.java +++ b/src/main/java/redis/clients/util/RedisOutputStream.java @@ -1,7 +1,6 @@ package redis.clients.util; import java.io.*; -import java.nio.charset.Charset; /** * The class implements a buffered output stream without synchronization @@ -12,13 +11,12 @@ public final class RedisOutputStream extends FilterOutputStream { protected final byte buf[]; protected int count; - public static final Charset CHARSET = Charset.forName("UTF-8"); - public RedisOutputStream(OutputStream out) { + public RedisOutputStream(final OutputStream out) { this(out, 8192); } - public RedisOutputStream(OutputStream out, int size) { + public RedisOutputStream(final OutputStream out, final int size) { super(out); if (size <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); @@ -33,14 +31,18 @@ public final class RedisOutputStream extends FilterOutputStream { } } - public void write(int b) throws IOException { - buf[count++] = (byte) b; + public void write(final byte b) throws IOException { + buf[count++] = b; if (count == buf.length) { flushBuffer(); } } + + public void write(final byte[] b) throws IOException { + write(b, 0, b.length); + } - public void write(byte b[], int off, int len) throws IOException { + public void write(final byte b[], final int off, final int len) throws IOException { if (len >= buf.length) { flushBuffer(); out.write(b, off, len); @@ -54,7 +56,7 @@ public final class RedisOutputStream extends FilterOutputStream { } } - public void writeAsciiCrLf(String in) throws IOException { + public void writeAsciiCrLf(final String in) throws IOException { final int size = in.length(); for (int i = 0; i != size; ++i) { @@ -67,11 +69,11 @@ public final class RedisOutputStream extends FilterOutputStream { writeCrLf(); } - public static boolean isSurrogate(char ch) { + public static boolean isSurrogate(final char ch) { return ch >= Character.MIN_SURROGATE && ch <= Character.MAX_SURROGATE; } - public static int utf8Length (String str) { + public static int utf8Length (final String str) { int strLen = str.length(), utfLen = 0; for(int i = 0; i != strLen; ++i) { char c = str.charAt(i); @@ -98,7 +100,7 @@ public final class RedisOutputStream extends FilterOutputStream { buf[count++] = '\n'; } - public void writeUtf8CrLf(String str) throws IOException { + public void writeUtf8CrLf(final String str) throws IOException { int strLen = str.length(); int i; diff --git a/src/main/java/redis/clients/util/Sharded.java b/src/main/java/redis/clients/util/Sharded.java index 9a4d7b7..d0f4f75 100644 --- a/src/main/java/redis/clients/util/Sharded.java +++ b/src/main/java/redis/clients/util/Sharded.java @@ -69,10 +69,19 @@ public class Sharded> { } } - public R getShard(String key) { - return nodes.floorEntry(algo.hash(getKeyTag(key))).getValue() - .getResource(); - } + public R getShard(byte[] key) { + return nodes + .floorEntry(algo.hash(key)) + .getValue() + .getResource(); + } + + public R getShard(String key) { + return nodes + .floorEntry(algo.hash(getKeyTag(key))) + .getValue() + .getResource(); + } public S getShardInfo(String key) { return nodes.floorEntry(algo.hash(getKeyTag(key))).getValue(); diff --git a/src/test/java/redis/clients/jedis/tests/JedisNewCommandsCheckTest.java b/src/test/java/redis/clients/jedis/tests/JedisNewCommandsCheckTest.java index 3fd5cb6..ec3f32c 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisNewCommandsCheckTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisNewCommandsCheckTest.java @@ -4,7 +4,6 @@ import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; -import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.HashSet; @@ -13,58 +12,61 @@ import java.util.Set; import org.junit.Assert; import org.junit.Test; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPubSub; -import redis.clients.jedis.Transaction; +import redis.clients.jedis.Protocol.Command; public class JedisNewCommandsCheckTest extends Assert { @Test public void checkJedisIsUpdated() throws IOException { - String[] commands = getAvailableCommands(); - Set implementedCommands = getImplementedCommands(); + String[] commands = getAvailableCommands(); + Set implementedCommands = getImplementedCommands(); - Set missingCommands = new HashSet(); - for (String command : commands) { - if (!implementedCommands.contains(command.trim())) { - missingCommands.add(command); - } - } + Set missingCommands = new HashSet(); + for (String command : commands) { + if (!implementedCommands.contains(command.trim())) { + missingCommands.add(command); + } + } - if (!missingCommands.isEmpty()) { - fail("There are missing commands: " + missingCommands.toString()); - } + if (!missingCommands.isEmpty()) { + fail("There are missing commands: " + missingCommands.toString()); + } } private Set getImplementedCommands() { - Method[] methods = Jedis.class.getDeclaredMethods(); - Set implementedCommands = new HashSet(); - for (Method method : methods) { - implementedCommands.add(method.getName().trim().toLowerCase()); - } - - methods = JedisPubSub.class.getDeclaredMethods(); - for (Method method : methods) { - implementedCommands.add(method.getName().trim().toLowerCase()); - } - - methods = Transaction.class.getDeclaredMethods(); - for (Method method : methods) { - implementedCommands.add(method.getName().trim().toLowerCase()); - } - implementedCommands.add("config"); - return implementedCommands; + // Method[] methods = Jedis.class.getDeclaredMethods(); + // Set implementedCommands = new HashSet(); + // for (Method method : methods) { + // implementedCommands.add(method.getName().trim().toLowerCase()); + // } + // + // methods = JedisPubSub.class.getDeclaredMethods(); + // for (Method method : methods) { + // implementedCommands.add(method.getName().trim().toLowerCase()); + // } + // + // methods = Transaction.class.getDeclaredMethods(); + // for (Method method : methods) { + // implementedCommands.add(method.getName().trim().toLowerCase()); + // } + // implementedCommands.add("config"); + // return implementedCommands; + Set implementedCommands = new HashSet(); + for (Command cmd : Command.values()) { + implementedCommands.add(cmd.name().toLowerCase()); + } + return implementedCommands; } private String[] getAvailableCommands() throws MalformedURLException, - IOException { - URL url = new URL("http://dimaion.com/redis/master"); - InputStream openStream = url.openStream(); - DataInputStream dis = new DataInputStream(new BufferedInputStream( - openStream)); - byte[] all = new byte[dis.available()]; - dis.readFully(all); - String commandList = new String(all); - String[] commands = commandList.split("\n"); - return commands; + IOException { + URL url = new URL("http://dimaion.com/redis/master"); + InputStream openStream = url.openStream(); + DataInputStream dis = new DataInputStream(new BufferedInputStream( + openStream)); + byte[] all = new byte[dis.available()]; + dis.readFully(all); + String commandList = new String(all); + String[] commands = commandList.split("\n"); + return commands; } } diff --git a/src/test/java/redis/clients/jedis/tests/JedisTest.java b/src/test/java/redis/clients/jedis/tests/JedisTest.java index 851c796..441fb6a 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisTest.java @@ -9,36 +9,35 @@ import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.Protocol; import redis.clients.jedis.tests.commands.JedisCommandTestBase; -import redis.clients.util.RedisOutputStream; public class JedisTest extends JedisCommandTestBase { @Test public void useWithoutConnecting() { - Jedis jedis = new Jedis("localhost"); - jedis.auth("foobared"); - jedis.dbSize(); + Jedis jedis = new Jedis("localhost"); + jedis.auth("foobared"); + jedis.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", new String(bigdata, RedisOutputStream.CHARSET)); + 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", new String(bigdata, Protocol.UTF8)); - String status = jedis.hmset("foo", hash); - assertEquals("OK", status); - assertEquals(hash, jedis.hgetAll("foo")); + String status = jedis.hmset("foo", hash); + assertEquals("OK", status); + assertEquals(hash, jedis.hgetAll("foo")); } @Test public void connectWithShardInfo() { - JedisShardInfo shardInfo = new JedisShardInfo("localhost", - Protocol.DEFAULT_PORT); - shardInfo.setPassword("foobared"); - Jedis jedis = new Jedis(shardInfo); - jedis.get("foo"); + JedisShardInfo shardInfo = new JedisShardInfo("localhost", + Protocol.DEFAULT_PORT); + shardInfo.setPassword("foobared"); + Jedis jedis = new Jedis(shardInfo); + jedis.get("foo"); } } diff --git a/src/test/java/redis/clients/jedis/tests/JedisTestBase.java b/src/test/java/redis/clients/jedis/tests/JedisTestBase.java new file mode 100644 index 0000000..74ce5bd --- /dev/null +++ b/src/test/java/redis/clients/jedis/tests/JedisTestBase.java @@ -0,0 +1,25 @@ +package redis.clients.jedis.tests; + +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.junit.Assert; + +public abstract class JedisTestBase extends Assert { + protected void assertEquals(List expected, List actual) { + assertEquals(expected.size(), actual.size()); + for (int n = 0; n < expected.size(); n++) { + assertArrayEquals(expected.get(n), actual.get(n)); + } + } + + protected void assertEquals(Set expected, Set actual) { + assertEquals(expected.size(), actual.size()); + Iterator iterator = expected.iterator(); + Iterator iterator2 = actual.iterator(); + while (iterator.hasNext() || iterator2.hasNext()) { + assertArrayEquals(iterator.next(), iterator2.next()); + } + } +} \ 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 eacecee..8df99d6 100644 --- a/src/test/java/redis/clients/jedis/tests/PipeliningTest.java +++ b/src/test/java/redis/clients/jedis/tests/PipeliningTest.java @@ -4,13 +4,14 @@ import java.io.IOException; import java.net.UnknownHostException; import java.util.List; -import junit.framework.Assert; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPipeline; +import redis.clients.jedis.Protocol; import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort; public class PipeliningTest extends Assert { @@ -36,7 +37,7 @@ public class PipeliningTest extends Assert { }); assertEquals(2, results.size()); - assertEquals("OK", results.get(0)); - assertEquals("bar", results.get(1)); + assertArrayEquals("OK".getBytes(Protocol.UTF8), (byte[])results.get(0)); + assertArrayEquals("bar".getBytes(Protocol.UTF8), (byte[])results.get(1)); } } diff --git a/src/test/java/redis/clients/jedis/tests/ProtocolTest.java b/src/test/java/redis/clients/jedis/tests/ProtocolTest.java index f8f4723..425c465 100644 --- a/src/test/java/redis/clients/jedis/tests/ProtocolTest.java +++ b/src/test/java/redis/clients/jedis/tests/ProtocolTest.java @@ -9,119 +9,102 @@ import java.io.PipedOutputStream; import java.util.ArrayList; import java.util.List; -import junit.framework.Assert; - import org.junit.Test; import redis.clients.jedis.Protocol; import redis.clients.util.RedisInputStream; import redis.clients.util.RedisOutputStream; -public class ProtocolTest extends Assert { +public class ProtocolTest extends JedisTestBase { @Test public void buildACommand() throws IOException { - PipedInputStream pis = new PipedInputStream(); - BufferedInputStream bis = new BufferedInputStream(pis); - PipedOutputStream pos = new PipedOutputStream(pis); + PipedInputStream pis = new PipedInputStream(); + BufferedInputStream bis = new BufferedInputStream(pis); + PipedOutputStream pos = new PipedOutputStream(pis); - Protocol protocol = new Protocol(); - protocol.sendCommand(new RedisOutputStream(pos), "GET", "SOMEKEY"); + Protocol protocol = new Protocol(); + protocol.sendCommand(new RedisOutputStream(pos), Protocol.Command.GET, + "SOMEKEY".getBytes(Protocol.UTF8)); - pos.close(); - String expectedCommand = "*2\r\n$3\r\nGET\r\n$7\r\nSOMEKEY\r\n"; + pos.close(); + String expectedCommand = "*2\r\n$3\r\nGET\r\n$7\r\nSOMEKEY\r\n"; - int b; - StringBuilder sb = new StringBuilder(); - while ((b = bis.read()) != -1) { - sb.append((char) b); - } + int b; + StringBuilder sb = new StringBuilder(); + while ((b = bis.read()) != -1) { + sb.append((char) b); + } - assertEquals(expectedCommand, sb.toString()); + assertEquals(expectedCommand, sb.toString()); } @Test public void bulkReply() { - InputStream is = new ByteArrayInputStream("$6\r\nfoobar\r\n".getBytes()); - Protocol protocol = new Protocol(); - String response = (String) protocol.read(new RedisInputStream(is)); - assertEquals("foobar", response); + InputStream is = new ByteArrayInputStream("$6\r\nfoobar\r\n".getBytes()); + Protocol protocol = new Protocol(); + byte[] response = (byte[]) protocol.read(new RedisInputStream(is)); + assertArrayEquals("foobar".getBytes(Protocol.UTF8), response); } @Test public void fragmentedBulkReply() { - FragmentedByteArrayInputStream fis = new FragmentedByteArrayInputStream( - "$30\r\n012345678901234567890123456789\r\n".getBytes()); - Protocol protocol = new Protocol(); - String response = (String) protocol.read(new RedisInputStream(fis)); - assertEquals("012345678901234567890123456789", response); + FragmentedByteArrayInputStream fis = new FragmentedByteArrayInputStream( + "$30\r\n012345678901234567890123456789\r\n".getBytes()); + Protocol protocol = new Protocol(); + byte[] response = (byte[]) protocol.read(new RedisInputStream(fis)); + assertArrayEquals("012345678901234567890123456789" + .getBytes(Protocol.UTF8), response); } @Test public void nullBulkReply() { - InputStream is = new ByteArrayInputStream("$-1\r\n".getBytes()); - Protocol protocol = new Protocol(); - String response = (String) protocol.read(new RedisInputStream(is)); - assertEquals(null, response); + InputStream is = new ByteArrayInputStream("$-1\r\n".getBytes()); + Protocol protocol = new Protocol(); + String response = (String) protocol.read(new RedisInputStream(is)); + assertEquals(null, response); } @Test public void singleLineReply() { - InputStream is = new ByteArrayInputStream("+OK\r\n".getBytes()); - Protocol protocol = new Protocol(); - String response = (String) protocol.read(new RedisInputStream(is)); - assertEquals("OK", response); + InputStream is = new ByteArrayInputStream("+OK\r\n".getBytes()); + Protocol protocol = new Protocol(); + byte[] response = (byte[]) protocol.read(new RedisInputStream(is)); + assertArrayEquals("OK".getBytes(Protocol.UTF8), response); } @Test public void integerReply() { - InputStream is = new ByteArrayInputStream(":123\r\n".getBytes()); - Protocol protocol = new Protocol(); - int response = (Integer) protocol.read(new RedisInputStream(is)); - assertEquals(123, response); + InputStream is = new ByteArrayInputStream(":123\r\n".getBytes()); + Protocol protocol = new Protocol(); + int response = (Integer) protocol.read(new RedisInputStream(is)); + assertEquals(123, response); } @SuppressWarnings("unchecked") @Test public void multiBulkReply() { - InputStream is = new ByteArrayInputStream( - "*4\r\n$3\r\nfoo\r\n$3\r\nbar\r\n$5\r\nHello\r\n$5\r\nWorld\r\n" - .getBytes()); - Protocol protocol = new Protocol(); - List response = (List) (List) protocol - .read(new RedisInputStream(is)); - List expected = new ArrayList(); - expected.add("foo"); - expected.add("bar"); - expected.add("Hello"); - expected.add("World"); + InputStream is = new ByteArrayInputStream( + "*4\r\n$3\r\nfoo\r\n$3\r\nbar\r\n$5\r\nHello\r\n$5\r\nWorld\r\n" + .getBytes()); + Protocol protocol = new Protocol(); + List response = (List) protocol + .read(new RedisInputStream(is)); + List expected = new ArrayList(); + expected.add("foo".getBytes(Protocol.UTF8)); + expected.add("bar".getBytes(Protocol.UTF8)); + expected.add("Hello".getBytes(Protocol.UTF8)); + expected.add("World".getBytes(Protocol.UTF8)); - assertEquals(expected, response); - - is = new ByteArrayInputStream( - "*4\r\n$3\r\nfoo\r\n+OK\r\n:1000\r\n*2\r\n$3\r\nfoo\r\n$3\r\nbar" - .getBytes()); - protocol = new Protocol(); - List response2 = (List) protocol - .read(new RedisInputStream(is)); - List expected2 = new ArrayList(); - expected2.add("foo"); - expected2.add("OK"); - expected2.add(1000); - List sub = new ArrayList(); - sub.add("foo"); - sub.add("bar"); - expected2.add(sub); - - assertEquals(expected2, response2); + assertEquals(expected, response); } @SuppressWarnings("unchecked") @Test public void nullMultiBulkReply() { - InputStream is = new ByteArrayInputStream("*-1\r\n".getBytes()); - Protocol protocol = new Protocol(); - List response = (List) protocol - .read(new RedisInputStream(is)); - assertNull(response); + InputStream is = new ByteArrayInputStream("*-1\r\n".getBytes()); + Protocol protocol = new Protocol(); + List response = (List) protocol + .read(new RedisInputStream(is)); + assertNull(response); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java b/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java index fca100d..b63eab1 100644 --- a/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java @@ -57,7 +57,7 @@ public class ShardedJedisPoolTest extends Assert { @Test public void checkConnectionWithDefaultPort() throws TimeoutException { ShardedJedisPool pool = new ShardedJedisPool(shards); - pool.setResourcesNumber(10); + pool.setResourcesNumber(1); pool.init(); ShardedJedis jedis = pool.getResource(200); diff --git a/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java b/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java index 5190306..2c23847 100644 --- a/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java +++ b/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java @@ -9,6 +9,7 @@ import org.junit.Test; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisShardInfo; +import redis.clients.jedis.Protocol; import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.ShardedJedisPipeline; import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort; @@ -141,7 +142,12 @@ public class ShardedJedisTest extends Assert { } }); - assertEquals("a", results.get(0)); - assertEquals("b", results.get(1)); + List expected = new ArrayList(2); + expected.add("a".getBytes(Protocol.UTF8)); + expected.add("b".getBytes(Protocol.UTF8)); + + assertEquals(2, results.size()); + assertArrayEquals("a".getBytes(Protocol.UTF8), (byte[]) results.get(0)); + assertArrayEquals("b".getBytes(Protocol.UTF8), (byte[]) results.get(1)); } } \ No newline at end of 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 8ee7691..0375080 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java @@ -1,238 +1,454 @@ package redis.clients.jedis.tests.commands; -import java.util.ArrayList; -import java.util.List; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; import org.junit.Test; import redis.clients.jedis.JedisException; +import redis.clients.jedis.Protocol; public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { + final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + final byte[] bfoo1 = { 0x01, 0x02, 0x03, 0x04, 0x0A }; + final byte[] bfoo2 = { 0x01, 0x02, 0x03, 0x04, 0x0B }; + final byte[] bfoo3 = { 0x01, 0x02, 0x03, 0x04, 0x0C }; + final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, 0x0A }; + final byte[] bbar2 = { 0x05, 0x06, 0x07, 0x08, 0x0B }; + final byte[] bbar3 = { 0x05, 0x06, 0x07, 0x08, 0x0C }; + + final byte[] bfoobar = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; + final byte[] bfoostar = { 0x01, 0x02, 0x03, 0x04, '*' }; + final byte[] bbarstar = { 0x05, 0x06, 0x07, 0x08, '*' }; + @Test public void ping() { - String status = jedis.ping(); - assertEquals("PONG", status); + String status = jedis.ping(); + assertEquals("PONG", status); } @Test public void exists() { - String status = jedis.set("foo", "bar"); - assertEquals("OK", status); + String status = jedis.set("foo", "bar"); + assertEquals("OK", status); - int reply = jedis.exists("foo"); - assertEquals(1, reply); + status = jedis.set(bfoo, bbar); + assertEquals("OK", status); - reply = jedis.del("foo"); - assertEquals(1, reply); + int reply = jedis.exists("foo"); + assertEquals(1, reply); - reply = jedis.exists("foo"); - assertEquals(0, reply); + reply = jedis.exists(bfoo); + assertEquals(1, reply); + + reply = jedis.del("foo"); + assertEquals(1, reply); + + reply = jedis.del(bfoo); + assertEquals(1, reply); + + reply = jedis.exists("foo"); + assertEquals(0, reply); + + reply = jedis.exists(bfoo); + assertEquals(0, reply); } @Test public void del() { - jedis.set("foo1", "bar1"); - jedis.set("foo2", "bar2"); - jedis.set("foo3", "bar3"); + jedis.set("foo1", "bar1"); + jedis.set("foo2", "bar2"); + jedis.set("foo3", "bar3"); - int reply = jedis.del("foo1", "foo2", "foo3"); - assertEquals(3, reply); + int reply = jedis.del("foo1", "foo2", "foo3"); + assertEquals(3, reply); - reply = jedis.exists("foo1"); - assertEquals(0, reply); - reply = jedis.exists("foo2"); - assertEquals(0, reply); - reply = jedis.exists("foo3"); - assertEquals(0, reply); + reply = jedis.exists("foo1"); + assertEquals(0, reply); + reply = jedis.exists("foo2"); + assertEquals(0, reply); + reply = jedis.exists("foo3"); + assertEquals(0, reply); - jedis.set("foo1", "bar1"); + jedis.set("foo1", "bar1"); - reply = jedis.del("foo1", "foo2"); - assertEquals(1, reply); + reply = jedis.del("foo1", "foo2"); + assertEquals(1, reply); - reply = jedis.del("foo1", "foo2"); - assertEquals(0, reply); + reply = jedis.del("foo1", "foo2"); + assertEquals(0, reply); + + // Binary ... + jedis.set(bfoo1, bbar1); + jedis.set(bfoo2, bbar2); + jedis.set(bfoo3, bbar3); + + reply = jedis.del(bfoo1, bfoo2, bfoo3); + assertEquals(3, reply); + + reply = jedis.exists(bfoo1); + assertEquals(0, reply); + reply = jedis.exists(bfoo2); + assertEquals(0, reply); + reply = jedis.exists(bfoo3); + assertEquals(0, reply); + + jedis.set(bfoo1, bbar1); + + reply = jedis.del(bfoo1, bfoo2); + assertEquals(1, reply); + + reply = jedis.del(bfoo1, bfoo2); + assertEquals(0, reply); } @Test public void type() { - jedis.set("foo", "bar"); - String status = jedis.type("foo"); - assertEquals("string", status); + jedis.set("foo", "bar"); + String status = jedis.type("foo"); + assertEquals("string", status); + + // Binary + jedis.set(bfoo, bbar); + status = jedis.type(bfoo); + assertEquals("string", status); } @Test public void keys() { - jedis.set("foo", "bar"); - jedis.set("foobar", "bar"); + jedis.set("foo", "bar"); + jedis.set("foobar", "bar"); - List keys = jedis.keys("foo*"); - List expected = new ArrayList(); - expected.add("foo"); - expected.add("foobar"); - assertEquals(expected, keys); + Set keys = jedis.keys("foo*"); + Set expected = new HashSet(); + expected.add("foo"); + expected.add("foobar"); + assertEquals(expected, keys); - expected = new ArrayList(); - keys = jedis.keys("bar*"); + expected = new HashSet(); + keys = jedis.keys("bar*"); - assertEquals(expected, keys); + assertEquals(expected, keys); + + // Binary + jedis.set(bfoo, bbar); + jedis.set(bfoobar, bbar); + + Set bkeys = jedis.keys(bfoostar); + assertEquals(2, bkeys.size()); + assertTrue(setContains(bkeys, bfoo)); + assertTrue(setContains(bkeys, bfoobar)); + + bkeys = jedis.keys(bbarstar); + + assertEquals(0, bkeys.size()); } @Test public void randomKey() { - assertEquals(null, jedis.randomKey()); + assertEquals(null, jedis.randomKey()); - jedis.set("foo", "bar"); + jedis.set("foo", "bar"); - assertEquals("foo", jedis.randomKey()); + assertEquals("foo", jedis.randomKey()); - jedis.set("bar", "foo"); + jedis.set("bar", "foo"); + + String randomkey = jedis.randomKey(); + assertTrue(randomkey.equals("foo") || randomkey.equals("bar")); + + // Binary + jedis.del("foo"); + jedis.del("bar"); + assertEquals(null, jedis.randomKey()); + + jedis.set(bfoo, bbar); + + assertArrayEquals(bfoo, jedis.randomBinaryKey()); + + jedis.set(bbar, bfoo); + + byte[] randomBkey = jedis.randomBinaryKey(); + assertTrue(Arrays.equals(randomBkey, bfoo) + || Arrays.equals(randomBkey, bbar)); - String randomkey = jedis.randomKey(); - assertTrue(randomkey.equals("foo") || randomkey.equals("bar")); } @Test public void rename() { - jedis.set("foo", "bar"); - String status = jedis.rename("foo", "bar"); - assertEquals("OK", status); + jedis.set("foo", "bar"); + String status = jedis.rename("foo", "bar"); + assertEquals("OK", status); - String value = jedis.get("foo"); - assertEquals(null, value); + String value = jedis.get("foo"); + assertEquals(null, value); - value = jedis.get("bar"); - assertEquals("bar", value); + value = jedis.get("bar"); + assertEquals("bar", value); + + // Binary + jedis.set(bfoo, bbar); + String bstatus = jedis.rename(bfoo, bbar); + assertEquals("OK", bstatus); + + byte[] bvalue = jedis.get(bfoo); + assertEquals(null, bvalue); + + bvalue = jedis.get(bbar); + assertArrayEquals(bbar, bvalue); } - @Test(expected = JedisException.class) + @Test public void renameOldAndNewAreTheSame() { - jedis.set("foo", "bar"); - jedis.rename("foo", "foo"); + try { + jedis.set("foo", "bar"); + jedis.rename("foo", "foo"); + fail("JedisException expected"); + } catch (final JedisException e) { + } + + // Binary + try { + jedis.set(bfoo, bbar); + jedis.rename(bfoo, bfoo); + fail("JedisException expected"); + } catch (final JedisException e) { + } + } @Test public void renamenx() { - jedis.set("foo", "bar"); - int status = jedis.renamenx("foo", "bar"); - assertEquals(1, status); + jedis.set("foo", "bar"); + int status = jedis.renamenx("foo", "bar"); + assertEquals(1, status); + + jedis.set("foo", "bar"); + status = jedis.renamenx("foo", "bar"); + assertEquals(0, status); + + // Binary + jedis.set(bfoo, bbar); + int bstatus = jedis.renamenx(bfoo, bbar); + assertEquals(1, bstatus); + + jedis.set(bfoo, bbar); + bstatus = jedis.renamenx(bfoo, bbar); + assertEquals(0, bstatus); - jedis.set("foo", "bar"); - status = jedis.renamenx("foo", "bar"); - assertEquals(0, status); } @Test public void dbSize() { - int size = jedis.dbSize(); - assertEquals(0, size); + int size = jedis.dbSize(); + assertEquals(0, size); - jedis.set("foo", "bar"); - size = jedis.dbSize(); - assertEquals(1, size); + jedis.set("foo", "bar"); + size = jedis.dbSize(); + assertEquals(1, size); + + // Binary + jedis.set(bfoo, bbar); + size = jedis.dbSize(); + assertEquals(2, size); } @Test public void expire() { - int status = jedis.expire("foo", 20); - assertEquals(0, status); + int status = jedis.expire("foo", 20); + assertEquals(0, status); + + jedis.set("foo", "bar"); + status = jedis.expire("foo", 20); + assertEquals(1, status); + + // Binary + int bstatus = jedis.expire(bfoo, 20); + assertEquals(0, bstatus); + + jedis.set(bfoo, bbar); + bstatus = jedis.expire(bfoo, 20); + assertEquals(1, bstatus); - jedis.set("foo", "bar"); - status = jedis.expire("foo", 20); - assertEquals(1, status); } @Test public void expireAt() { - long unixTime = (System.currentTimeMillis() / 1000L) + 20; + long unixTime = (System.currentTimeMillis() / 1000L) + 20; - int status = jedis.expireAt("foo", unixTime); - assertEquals(0, status); + int status = jedis.expireAt("foo", unixTime); + assertEquals(0, status); + + jedis.set("foo", "bar"); + unixTime = (System.currentTimeMillis() / 1000L) + 20; + status = jedis.expireAt("foo", unixTime); + assertEquals(1, status); + + // Binary + int bstatus = jedis.expireAt(bfoo, unixTime); + assertEquals(0, bstatus); + + jedis.set(bfoo, bbar); + unixTime = (System.currentTimeMillis() / 1000L) + 20; + bstatus = jedis.expireAt(bfoo, unixTime); + assertEquals(1, bstatus); - jedis.set("foo", "bar"); - unixTime = (System.currentTimeMillis() / 1000L) + 20; - status = jedis.expireAt("foo", unixTime); - assertEquals(1, status); } @Test public void ttl() { - int ttl = jedis.ttl("foo"); - assertEquals(-1, ttl); + int ttl = jedis.ttl("foo"); + assertEquals(-1, ttl); - jedis.set("foo", "bar"); - ttl = jedis.ttl("foo"); - assertEquals(-1, ttl); + jedis.set("foo", "bar"); + ttl = jedis.ttl("foo"); + assertEquals(-1, ttl); + + jedis.expire("foo", 20); + ttl = jedis.ttl("foo"); + assertTrue(ttl >= 0 && ttl <= 20); + + // Binary + int bttl = jedis.ttl(bfoo); + assertEquals(-1, bttl); + + jedis.set(bfoo, bbar); + bttl = jedis.ttl(bfoo); + assertEquals(-1, bttl); + + jedis.expire(bfoo, 20); + bttl = jedis.ttl(bfoo); + assertTrue(bttl >= 0 && bttl <= 20); - jedis.expire("foo", 20); - ttl = jedis.ttl("foo"); - assertTrue(ttl >= 0 && ttl <= 20); } @Test public void select() { - jedis.set("foo", "bar"); - String status = jedis.select(1); - assertEquals("OK", status); - assertEquals(null, jedis.get("foo")); - status = jedis.select(0); - assertEquals("OK", status); - assertEquals("bar", jedis.get("foo")); + jedis.set("foo", "bar"); + String status = jedis.select(1); + assertEquals("OK", status); + assertEquals(null, 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); + assertEquals(null, jedis.get(bfoo)); + bstatus = jedis.select(0); + assertEquals("OK", bstatus); + assertArrayEquals(bbar, jedis.get(bfoo)); } @Test public void move() { - int status = jedis.move("foo", 1); - assertEquals(0, status); + int status = jedis.move("foo", 1); + assertEquals(0, status); - jedis.set("foo", "bar"); - status = jedis.move("foo", 1); - assertEquals(1, status); - assertEquals(null, jedis.get("foo")); + jedis.set("foo", "bar"); + status = jedis.move("foo", 1); + assertEquals(1, status); + assertEquals(null, jedis.get("foo")); + + jedis.select(1); + assertEquals("bar", jedis.get("foo")); + + // Binary + jedis.select(0); + int bstatus = jedis.move(bfoo, 1); + assertEquals(0, bstatus); + + jedis.set(bfoo, bbar); + bstatus = jedis.move(bfoo, 1); + assertEquals(1, bstatus); + assertEquals(null, jedis.get(bfoo)); + + jedis.select(1); + assertArrayEquals(bbar, jedis.get(bfoo)); - jedis.select(1); - assertEquals("bar", jedis.get("foo")); } @Test public void flushDB() { - jedis.set("foo", "bar"); - assertEquals(1, jedis.dbSize().intValue()); - jedis.set("bar", "foo"); - jedis.move("bar", 1); - String status = jedis.flushDB(); - assertEquals("OK", status); - assertEquals(0, jedis.dbSize().intValue()); - jedis.select(1); - assertEquals(1, jedis.dbSize().intValue()); + jedis.set("foo", "bar"); + assertEquals(1, jedis.dbSize().intValue()); + jedis.set("bar", "foo"); + jedis.move("bar", 1); + String status = jedis.flushDB(); + assertEquals("OK", status); + assertEquals(0, jedis.dbSize().intValue()); + jedis.select(1); + assertEquals(1, jedis.dbSize().intValue()); + jedis.del("bar"); + + // Binary + jedis.select(0); + jedis.set(bfoo, bbar); + assertEquals(1, jedis.dbSize().intValue()); + jedis.set(bbar, bfoo); + jedis.move(bbar, 1); + String bstatus = jedis.flushDB(); + assertEquals("OK", bstatus); + assertEquals(0, jedis.dbSize().intValue()); + jedis.select(1); + assertEquals(1, jedis.dbSize().intValue()); + } @Test public void flushAll() { - jedis.set("foo", "bar"); - assertEquals(1, jedis.dbSize().intValue()); - jedis.set("bar", "foo"); - jedis.move("bar", 1); - String status = jedis.flushAll(); - assertEquals("OK", status); - assertEquals(0, jedis.dbSize().intValue()); - jedis.select(1); - assertEquals(0, jedis.dbSize().intValue()); + jedis.set("foo", "bar"); + assertEquals(1, jedis.dbSize().intValue()); + jedis.set("bar", "foo"); + jedis.move("bar", 1); + String status = jedis.flushAll(); + assertEquals("OK", status); + assertEquals(0, jedis.dbSize().intValue()); + jedis.select(1); + assertEquals(0, jedis.dbSize().intValue()); + + // Binary + jedis.select(0); + jedis.set(bfoo, bbar); + assertEquals(1, jedis.dbSize().intValue()); + jedis.set(bbar, bfoo); + jedis.move(bbar, 1); + String bstatus = jedis.flushAll(); + assertEquals("OK", bstatus); + assertEquals(0, jedis.dbSize().intValue()); + jedis.select(1); + assertEquals(0, jedis.dbSize().intValue()); + } @Test public void persist() { - jedis.setex("foo", 60 * 60, "bar"); - assertTrue(jedis.ttl("foo") > 0); - int status = jedis.persist("foo"); - assertEquals(1, status); - assertEquals(-1, jedis.ttl("foo").intValue()); + jedis.setex("foo", 60 * 60, "bar"); + assertTrue(jedis.ttl("foo") > 0); + int status = jedis.persist("foo"); + assertEquals(1, status); + assertEquals(-1, jedis.ttl("foo").intValue()); + + // Binary + jedis.setex(bfoo, 60 * 60, bbar); + assertTrue(jedis.ttl(bfoo) > 0); + int bstatus = jedis.persist(bfoo); + assertEquals(1, bstatus); + assertEquals(-1, jedis.ttl(bfoo).intValue()); + } @Test public void echo() { - String result = jedis.echo("hello world"); - assertEquals("hello world", result); + String result = jedis.echo("hello world"); + assertEquals("hello world", result); + + // Binary + byte[] bresult = jedis.echo("hello world".getBytes(Protocol.UTF8)); + assertArrayEquals("hello world".getBytes(Protocol.UTF8), bresult); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/BinaryValuesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/BinaryValuesCommandsTest.java new file mode 100644 index 0000000..001e2d3 --- /dev/null +++ b/src/test/java/redis/clients/jedis/tests/commands/BinaryValuesCommandsTest.java @@ -0,0 +1,214 @@ +package redis.clients.jedis.tests.commands; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +import redis.clients.jedis.JedisException; +import redis.clients.jedis.Protocol.Keyword; + +public class BinaryValuesCommandsTest extends JedisCommandTestBase { + byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + byte[] binaryValue; + + @Before + public void startUp() { + StringBuilder sb = new StringBuilder(); + + for (int n = 0; n < 1000; n++) { + sb.append("A"); + } + + binaryValue = sb.toString().getBytes(); + } + + @Test + public void setAndGet() { + String status = jedis.set(bfoo, binaryValue); + assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); + + byte[] value = jedis.get(bfoo); + assertTrue(Arrays.equals(binaryValue, value)); + + assertNull(jedis.get(bbar)); + } + + @Test + public void getSet() { + byte[] value = jedis.getSet(bfoo, binaryValue); + assertNull(value); + value = jedis.get(bfoo); + assertTrue(Arrays.equals(binaryValue, value)); + } + + @Test + public void mget() { + List values = jedis.mget(bfoo, bbar); + List expected = new ArrayList(); + expected.add(null); + expected.add(null); + + assertEquals(expected, values); + + jedis.set(bfoo, binaryValue); + + expected = new ArrayList(); + expected.add(binaryValue); + expected.add(null); + values = jedis.mget(bfoo, bbar); + + assertEquals(expected, values); + + jedis.set(bbar, bfoo); + + expected = new ArrayList(); + expected.add(binaryValue); + expected.add(bfoo); + values = jedis.mget(bfoo, bbar); + + assertEquals(expected, values); + } + + @Test + public void setnx() { + int status = jedis.setnx(bfoo, binaryValue); + assertEquals(1, status); + assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); + + status = jedis.setnx(bfoo, bbar); + assertEquals(0, status); + assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); + } + + @Test + public void setex() { + String status = jedis.setex(bfoo, 20, binaryValue); + assertEquals(Keyword.OK.name(), status); + int ttl = jedis.ttl(bfoo); + assertTrue(ttl > 0 && ttl <= 20); + } + + @Test + public void mset() { + String status = jedis.mset(bfoo, binaryValue, bbar, bfoo); + assertEquals(Keyword.OK.name(), status); + assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); + assertTrue(Arrays.equals(bfoo, jedis.get(bbar))); + } + + @Test + public void msetnx() { + int status = jedis.msetnx(bfoo, binaryValue, bbar, bfoo); + assertEquals(1, status); + assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); + assertTrue(Arrays.equals(bfoo, jedis.get(bbar))); + + status = jedis.msetnx(bfoo, bbar, "bar2".getBytes(), "foo2".getBytes()); + assertEquals(0, status); + assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); + assertTrue(Arrays.equals(bfoo, jedis.get(bbar))); + } + + @Test(expected = JedisException.class) + public void incrWrongValue() { + jedis.set(bfoo, binaryValue); + jedis.incr(bfoo); + } + + @Test + public void incr() { + int value = jedis.incr(bfoo); + assertEquals(1, value); + value = jedis.incr(bfoo); + assertEquals(2, value); + } + + @Test(expected = JedisException.class) + public void incrByWrongValue() { + jedis.set(bfoo, binaryValue); + jedis.incrBy(bfoo, 2); + } + + @Test + public void incrBy() { + int value = jedis.incrBy(bfoo, 2); + assertEquals(2, value); + value = jedis.incrBy(bfoo, 2); + assertEquals(4, value); + } + + @Test(expected = JedisException.class) + public void decrWrongValue() { + jedis.set(bfoo, binaryValue); + jedis.decr(bfoo); + } + + @Test + public void decr() { + int value = jedis.decr(bfoo); + assertEquals(-1, value); + value = jedis.decr(bfoo); + assertEquals(-2, value); + } + + @Test(expected = JedisException.class) + public void decrByWrongValue() { + jedis.set(bfoo, binaryValue); + jedis.decrBy(bfoo, 2); + } + + @Test + public void decrBy() { + int value = jedis.decrBy(bfoo, 2); + assertEquals(-2, value); + value = jedis.decrBy(bfoo, 2); + assertEquals(-4, value); + } + + @Test + public void append() { + byte[] first512 = new byte[512]; + System.arraycopy(binaryValue, 0, first512, 0, 512); + int value = jedis.append(bfoo, first512); + assertEquals(512, value); + assertTrue(Arrays.equals(first512, jedis.get(bfoo))); + + byte[] rest = new byte[binaryValue.length - 512]; + System.arraycopy(binaryValue, 512, rest, 0, binaryValue.length - 512); + value = jedis.append(bfoo, rest); + assertEquals(binaryValue.length, value); + + assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); + } + + @Test + public void substr() { + jedis.set(bfoo, binaryValue); + + byte[] first512 = new byte[512]; + System.arraycopy(binaryValue, 0, first512, 0, 512); + byte[] rfirst512 = jedis.substr(bfoo, 0, 511); + assertTrue(Arrays.equals(first512, rfirst512)); + + byte[] last512 = new byte[512]; + System + .arraycopy(binaryValue, binaryValue.length - 512, last512, 0, + 512); + assertTrue(Arrays.equals(last512, jedis.substr(bfoo, -512, -1))); + + assertTrue(Arrays.equals(binaryValue, jedis.substr(bfoo, 0, -1))); + + assertTrue(Arrays.equals(last512, jedis.substr(bfoo, + binaryValue.length - 512, 100000))); + } + + @Test + public void strlen() { + jedis.set(bfoo, binaryValue); + assertEquals(binaryValue.length, jedis.strlen(bfoo).intValue()); + } +} \ 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 0bc4020..68be673 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java @@ -21,8 +21,9 @@ public class ControlCommandsTest extends JedisCommandTestBase { String status = jedis.bgsave(); assertEquals("Background saving started", status); } catch (JedisException e) { - assertEquals("ERR Background save already in progress", e - .getMessage()); + assertTrue( + "ERR Background save already in progress" + .equalsIgnoreCase(e.getMessage())); } } 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 6355b03..f7f4fd1 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java @@ -3,155 +3,287 @@ package redis.clients.jedis.tests.commands; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Set; import org.junit.Test; public class HashesCommandsTest extends JedisCommandTestBase { + final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; + @Test public void hset() { - int status = jedis.hset("foo", "bar", "car"); - assertEquals(1, status); - status = jedis.hset("foo", "bar", "foo"); - assertEquals(0, status); + int status = jedis.hset("foo", "bar", "car"); + assertEquals(1, status); + status = jedis.hset("foo", "bar", "foo"); + assertEquals(0, status); + + // Binary + int bstatus = jedis.hset(bfoo, bbar, bcar); + assertEquals(1, bstatus); + bstatus = jedis.hset(bfoo, bbar, bfoo); + assertEquals(0, bstatus); + } @Test public void hget() { - jedis.hset("foo", "bar", "car"); - assertEquals(null, jedis.hget("bar", "foo")); - assertEquals(null, jedis.hget("foo", "car")); - assertEquals("car", jedis.hget("foo", "bar")); + jedis.hset("foo", "bar", "car"); + assertEquals(null, jedis.hget("bar", "foo")); + assertEquals(null, jedis.hget("foo", "car")); + assertEquals("car", jedis.hget("foo", "bar")); + + // Binary + jedis.hset(bfoo, bbar, bcar); + assertEquals(null, jedis.hget(bbar, bfoo)); + assertEquals(null, jedis.hget(bfoo, bcar)); + assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); } @Test public void hsetnx() { - int status = jedis.hsetnx("foo", "bar", "car"); - assertEquals(1, status); - assertEquals("car", jedis.hget("foo", "bar")); + int status = jedis.hsetnx("foo", "bar", "car"); + assertEquals(1, status); + assertEquals("car", jedis.hget("foo", "bar")); - status = jedis.hsetnx("foo", "bar", "foo"); - assertEquals(0, status); - assertEquals("car", jedis.hget("foo", "bar")); + status = jedis.hsetnx("foo", "bar", "foo"); + assertEquals(0, status); + assertEquals("car", jedis.hget("foo", "bar")); + + status = jedis.hsetnx("foo", "car", "bar"); + assertEquals(1, status); + assertEquals("bar", jedis.hget("foo", "car")); + + // Binary + int bstatus = jedis.hsetnx(bfoo, bbar, bcar); + assertEquals(1, bstatus); + assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); + + bstatus = jedis.hsetnx(bfoo, bbar, bfoo); + assertEquals(0, bstatus); + assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); + + bstatus = jedis.hsetnx(bfoo, bcar, bbar); + assertEquals(1, bstatus); + assertArrayEquals(bbar, jedis.hget(bfoo, bcar)); - status = jedis.hsetnx("foo", "car", "bar"); - assertEquals(1, status); - assertEquals("bar", jedis.hget("foo", "car")); } @Test public void hmset() { - Map hash = new HashMap(); - hash.put("bar", "car"); - hash.put("car", "bar"); - String status = jedis.hmset("foo", hash); - assertEquals("OK", status); - assertEquals("car", jedis.hget("foo", "bar")); - assertEquals("bar", jedis.hget("foo", "car")); + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + String status = jedis.hmset("foo", hash); + assertEquals("OK", status); + assertEquals("car", jedis.hget("foo", "bar")); + assertEquals("bar", jedis.hget("foo", "car")); + + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + String bstatus = jedis.hmset(bfoo, bhash); + assertEquals("OK", bstatus); + assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); + assertArrayEquals(bbar, jedis.hget(bfoo, bcar)); + } @Test public void hmget() { - Map hash = new HashMap(); - hash.put("bar", "car"); - hash.put("car", "bar"); - jedis.hmset("foo", hash); + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); - List values = jedis.hmget("foo", "bar", "car", "foo"); - List expected = new ArrayList(); - expected.add("car"); - expected.add("bar"); - expected.add(null); + List values = jedis.hmget("foo", "bar", "car", "foo"); + List expected = new ArrayList(); + expected.add("car"); + expected.add("bar"); + expected.add(null); - assertEquals(expected, values); + assertEquals(expected, values); + + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); + + List bvalues = jedis.hmget(bfoo, bbar, bcar, bfoo); + List bexpected = new ArrayList(); + bexpected.add(bcar); + bexpected.add(bbar); + bexpected.add(null); + + assertEquals(bexpected, bvalues); } @Test public void hincrBy() { - int value = jedis.hincrBy("foo", "bar", 1); - assertEquals(1, value); - value = jedis.hincrBy("foo", "bar", -1); - assertEquals(0, value); - value = jedis.hincrBy("foo", "bar", -10); - assertEquals(-10, value); + int value = jedis.hincrBy("foo", "bar", 1); + assertEquals(1, value); + value = jedis.hincrBy("foo", "bar", -1); + assertEquals(0, value); + value = jedis.hincrBy("foo", "bar", -10); + assertEquals(-10, value); + + // Binary + int bvalue = jedis.hincrBy(bfoo, bbar, 1); + assertEquals(1, bvalue); + bvalue = jedis.hincrBy(bfoo, bbar, -1); + assertEquals(0, bvalue); + bvalue = jedis.hincrBy(bfoo, bbar, -10); + assertEquals(-10, bvalue); + } @Test public void hexists() { - Map hash = new HashMap(); - hash.put("bar", "car"); - hash.put("car", "bar"); - jedis.hmset("foo", hash); + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); + + assertEquals(0, jedis.hexists("bar", "foo").intValue()); + assertEquals(0, jedis.hexists("foo", "foo").intValue()); + assertEquals(1, jedis.hexists("foo", "bar").intValue()); + + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); + + assertEquals(0, jedis.hexists(bbar, bfoo).intValue()); + assertEquals(0, jedis.hexists(bfoo, bfoo).intValue()); + assertEquals(1, jedis.hexists(bfoo, bbar).intValue()); - assertEquals(0, jedis.hexists("bar", "foo").intValue()); - assertEquals(0, jedis.hexists("foo", "foo").intValue()); - assertEquals(1, jedis.hexists("foo", "bar").intValue()); } @Test public void hdel() { - Map hash = new HashMap(); - hash.put("bar", "car"); - hash.put("car", "bar"); - jedis.hmset("foo", hash); + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); + + assertEquals(0, jedis.hdel("bar", "foo").intValue()); + assertEquals(0, jedis.hdel("foo", "foo").intValue()); + assertEquals(1, jedis.hdel("foo", "bar").intValue()); + assertEquals(null, jedis.hget("foo", "bar")); + + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); + + assertEquals(0, jedis.hdel(bbar, bfoo).intValue()); + assertEquals(0, jedis.hdel(bfoo, bfoo).intValue()); + assertEquals(1, jedis.hdel(bfoo, bbar).intValue()); + assertEquals(null, jedis.hget(bfoo, bbar)); - assertEquals(0, jedis.hdel("bar", "foo").intValue()); - assertEquals(0, jedis.hdel("foo", "foo").intValue()); - assertEquals(1, jedis.hdel("foo", "bar").intValue()); - assertEquals(null, jedis.hget("foo", "bar")); } @Test public void hlen() { - Map hash = new HashMap(); - hash.put("bar", "car"); - hash.put("car", "bar"); - jedis.hmset("foo", hash); + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); + + assertEquals(0, jedis.hlen("bar").intValue()); + assertEquals(2, jedis.hlen("foo").intValue()); + + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); + + assertEquals(0, jedis.hlen(bbar).intValue()); + assertEquals(2, jedis.hlen(bfoo).intValue()); - assertEquals(0, jedis.hlen("bar").intValue()); - assertEquals(2, jedis.hlen("foo").intValue()); } @Test public void hkeys() { - Map hash = new LinkedHashMap(); - hash.put("bar", "car"); - hash.put("car", "bar"); - jedis.hmset("foo", hash); + Map hash = new LinkedHashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); - List keys = jedis.hkeys("foo"); - List expected = new ArrayList(); - expected.add("bar"); - expected.add("car"); - assertEquals(expected, keys); + Set keys = jedis.hkeys("foo"); + Set expected = new LinkedHashSet(); + expected.add("bar"); + expected.add("car"); + assertEquals(expected, keys); + + // Binary + Map bhash = new LinkedHashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); + + Set bkeys = jedis.hkeys(bfoo); + Set bexpected = new LinkedHashSet(); + bexpected.add(bbar); + bexpected.add(bcar); + assertEquals(bexpected, bkeys); } @Test public void hvals() { - Map hash = new LinkedHashMap(); - hash.put("bar", "car"); - hash.put("car", "bar"); - jedis.hmset("foo", hash); + Map hash = new LinkedHashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); - List vals = jedis.hvals("foo"); - List expected = new ArrayList(); - expected.add("car"); - expected.add("bar"); - assertEquals(expected, vals); + List vals = jedis.hvals("foo"); + assertEquals(2, vals.size()); + assertTrue(vals.contains("bar")); + assertTrue(vals.contains("car")); + + // Binary + Map bhash = new LinkedHashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); + + List bvals = jedis.hvals(bfoo); + + assertEquals(2, bvals.size()); + assertTrue(arrayContains(bvals, bbar)); + assertTrue(arrayContains(bvals, bcar)); } @Test public void hgetAll() { - Map h = new HashMap(); - h.put("bar", "car"); - h.put("car", "bar"); - jedis.hmset("foo", h); + Map h = new HashMap(); + h.put("bar", "car"); + h.put("car", "bar"); + jedis.hmset("foo", h); - Map hash = jedis.hgetAll("foo"); - Map expected = new HashMap(); - expected.put("bar", "car"); - expected.put("car", "bar"); - assertEquals(expected, hash); + Map hash = jedis.hgetAll("foo"); + assertEquals(2, hash.size()); + assertEquals("car", hash.get("bar")); + assertEquals("bar", hash.get("car")); + + // Binary + Map bh = new HashMap(); + bh.put(bbar, bcar); + bh.put(bcar, bbar); + jedis.hmset(bfoo, bh); + Map bhash = jedis.hgetAll(bfoo); + + assertEquals(2, bhash.size()); + assertArrayEquals(bcar, bhash.get(bbar)); + assertArrayEquals(bbar, bhash.get(bcar)); } } 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 f7150f3..4e05fb0 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java +++ b/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java @@ -2,43 +2,85 @@ package redis.clients.jedis.tests.commands; import java.io.IOException; import java.net.UnknownHostException; - -import junit.framework.Assert; +import java.util.Iterator; +import java.util.List; +import java.util.Set; import org.junit.After; import org.junit.Before; import redis.clients.jedis.Jedis; import redis.clients.jedis.tests.HostAndPortUtil; +import redis.clients.jedis.tests.JedisTestBase; import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort; -public abstract class JedisCommandTestBase extends Assert { - protected static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); +public abstract class JedisCommandTestBase extends JedisTestBase { + protected static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); - protected Jedis jedis; + protected Jedis jedis; - public JedisCommandTestBase() { - super(); - } + public JedisCommandTestBase() { + super(); + } - @Before - public void setUp() throws Exception { - jedis = new Jedis(hnp.host, hnp.port, 500); - jedis.connect(); - jedis.auth("foobared"); - jedis.flushAll(); - } + @Before + public void setUp() throws Exception { + jedis = new Jedis(hnp.host, hnp.port, 500); + jedis.connect(); + jedis.auth("foobared"); + jedis.flushAll(); + } - @After - public void tearDown() throws Exception { - jedis.disconnect(); - } + @After + public void tearDown() throws Exception { + jedis.disconnect(); + } - protected Jedis createJedis() throws UnknownHostException, IOException { - Jedis j = new Jedis(hnp.host, hnp.port); - j.connect(); - j.auth("foobared"); - j.flushAll(); - return j; - } + protected Jedis createJedis() throws UnknownHostException, IOException { + Jedis j = new Jedis(hnp.host, hnp.port); + j.connect(); + j.auth("foobared"); + j.flushAll(); + return j; + } + + protected void assertEquals(List expected, List actual) { + assertEquals(expected.size(), actual.size()); + for (int n = 0; n < expected.size(); n++) { + assertArrayEquals(expected.get(n), actual.get(n)); + } + } + + protected void assertEquals(Set expected, Set actual) { + assertEquals(expected.size(), actual.size()); + Iterator iterator = expected.iterator(); + Iterator iterator2 = actual.iterator(); + while (iterator.hasNext() || iterator2.hasNext()) { + assertArrayEquals(iterator.next(), iterator2.next()); + } + } + + protected boolean arrayContains(List array, byte[] expected) { + for (byte[] a : array) { + try { + assertArrayEquals(a, expected); + return true; + } catch (AssertionError e) { + + } + } + return false; + } + + protected boolean setContains(Set set, byte[] expected) { + for (byte[] a : set) { + try { + assertArrayEquals(a, expected); + return true; + } catch (AssertionError e) { + + } + } + return false; + } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java index b861a59..25ae7c9 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java @@ -10,287 +10,572 @@ import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisException; public class ListCommandsTest extends JedisCommandTestBase { + final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; + final byte[] bA = { 0x0A }; + final byte[] bB = { 0x0B }; + final byte[] bC = { 0x0C }; + final byte[] b1 = { 0x01 }; + final byte[] b2 = { 0x02 }; + final byte[] b3 = { 0x03 }; + final byte[] bhello = { 0x04, 0x02 }; + final byte[] bx = { 0x02, 0x04 }; + final byte[] bdst = { 0x11, 0x12, 0x13, 0x14 }; + @Test public void rpush() { - int size = jedis.rpush("foo", "bar"); - assertEquals(1, size); - size = jedis.rpush("foo", "foo"); - assertEquals(2, size); + int size = jedis.rpush("foo", "bar"); + assertEquals(1, size); + size = jedis.rpush("foo", "foo"); + assertEquals(2, size); + + // Binary + int bsize = jedis.rpush(bfoo, bbar); + assertEquals(1, bsize); + bsize = jedis.rpush(bfoo, bfoo); + assertEquals(2, bsize); + } @Test public void lpush() { - int size = jedis.lpush("foo", "bar"); - assertEquals(1, size); - size = jedis.lpush("foo", "foo"); - assertEquals(2, size); + int size = jedis.lpush("foo", "bar"); + assertEquals(1, size); + size = jedis.lpush("foo", "foo"); + assertEquals(2, size); + + // Binary + int bsize = jedis.lpush(bfoo, bbar); + assertEquals(1, bsize); + bsize = jedis.lpush(bfoo, bfoo); + assertEquals(2, bsize); + } @Test public void llen() { - assertEquals(0, jedis.llen("foo").intValue()); - jedis.lpush("foo", "bar"); - jedis.lpush("foo", "car"); - assertEquals(2, jedis.llen("foo").intValue()); + assertEquals(0, jedis.llen("foo").intValue()); + jedis.lpush("foo", "bar"); + jedis.lpush("foo", "car"); + assertEquals(2, jedis.llen("foo").intValue()); + + // Binary + assertEquals(0, jedis.llen(bfoo).intValue()); + jedis.lpush(bfoo, bbar); + jedis.lpush(bfoo, bcar); + assertEquals(2, jedis.llen(bfoo).intValue()); + } - @Test(expected = JedisException.class) + @Test public void llenNotOnList() { - jedis.set("foo", "bar"); - jedis.llen("foo"); + try { + jedis.set("foo", "bar"); + jedis.llen("foo"); + fail("JedisException expected"); + } catch (final JedisException e) { + } + + // Binary + try { + jedis.set(bfoo, bbar); + jedis.llen(bfoo); + fail("JedisException expected"); + } catch (final JedisException e) { + } + } @Test public void lrange() { - jedis.rpush("foo", "a"); - jedis.rpush("foo", "b"); - jedis.rpush("foo", "c"); + jedis.rpush("foo", "a"); + jedis.rpush("foo", "b"); + jedis.rpush("foo", "c"); - List expected = new ArrayList(); - expected.add("a"); - expected.add("b"); - expected.add("c"); + List expected = new ArrayList(); + expected.add("a"); + expected.add("b"); + expected.add("c"); - List range = jedis.lrange("foo", 0, 2); - assertEquals(expected, range); + List range = jedis.lrange("foo", 0, 2); + assertEquals(expected, range); - range = jedis.lrange("foo", 0, 20); - assertEquals(expected, range); + range = jedis.lrange("foo", 0, 20); + assertEquals(expected, range); - expected = new ArrayList(); - expected.add("b"); - expected.add("c"); + expected = new ArrayList(); + expected.add("b"); + expected.add("c"); - range = jedis.lrange("foo", 1, 2); - assertEquals(expected, range); + range = jedis.lrange("foo", 1, 2); + assertEquals(expected, range); + + expected = new ArrayList(); + range = jedis.lrange("foo", 2, 1); + assertEquals(expected, range); + + // Binary + jedis.rpush(bfoo, bA); + jedis.rpush(bfoo, bB); + jedis.rpush(bfoo, bC); + + List bexpected = new ArrayList(); + bexpected.add(bA); + bexpected.add(bB); + bexpected.add(bC); + + List brange = jedis.lrange(bfoo, 0, 2); + assertEquals(bexpected, brange); + + brange = jedis.lrange(bfoo, 0, 20); + assertEquals(bexpected, brange); + + bexpected = new ArrayList(); + bexpected.add(bB); + bexpected.add(bC); + + brange = jedis.lrange(bfoo, 1, 2); + assertEquals(bexpected, brange); + + bexpected = new ArrayList(); + brange = jedis.lrange(bfoo, 2, 1); + assertEquals(bexpected, brange); - expected = new ArrayList(); - range = jedis.lrange("foo", 2, 1); - assertEquals(expected, range); } @Test public void ltrim() { - jedis.lpush("foo", "1"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "3"); - String status = jedis.ltrim("foo", 0, 1); + jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "3"); + String status = jedis.ltrim("foo", 0, 1); - List expected = new ArrayList(); - expected.add("3"); - expected.add("2"); + List expected = new ArrayList(); + expected.add("3"); + expected.add("2"); + + assertEquals("OK", status); + assertEquals(2, jedis.llen("foo").intValue()); + assertEquals(expected, jedis.lrange("foo", 0, 100)); + + // Binary + jedis.lpush(bfoo, b1); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b3); + String bstatus = jedis.ltrim(bfoo, 0, 1); + + List bexpected = new ArrayList(); + bexpected.add(b3); + bexpected.add(b2); + + assertEquals("OK", bstatus); + assertEquals(2, jedis.llen(bfoo).intValue()); + assertEquals(bexpected, jedis.lrange(bfoo, 0, 100)); - assertEquals("OK", status); - assertEquals(2, jedis.llen("foo").intValue()); - assertEquals(expected, jedis.lrange("foo", 0, 100)); } @Test public void lindex() { - jedis.lpush("foo", "1"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "3"); + jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "3"); - List expected = new ArrayList(); - expected.add("3"); - expected.add("bar"); - expected.add("1"); + List expected = new ArrayList(); + expected.add("3"); + expected.add("bar"); + expected.add("1"); - String status = jedis.lset("foo", 1, "bar"); + String status = jedis.lset("foo", 1, "bar"); - assertEquals("OK", status); - assertEquals(expected, jedis.lrange("foo", 0, 100)); + assertEquals("OK", status); + assertEquals(expected, jedis.lrange("foo", 0, 100)); + + // Binary + jedis.lpush(bfoo, b1); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b3); + + List bexpected = new ArrayList(); + bexpected.add(b3); + bexpected.add(bbar); + bexpected.add(b1); + + String bstatus = jedis.lset(bfoo, 1, bbar); + + assertEquals("OK", bstatus); + assertEquals(bexpected, jedis.lrange(bfoo, 0, 100)); } @Test public void lset() { - jedis.lpush("foo", "1"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "3"); + jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "3"); + + assertEquals("3", jedis.lindex("foo", 0)); + assertEquals(null, jedis.lindex("foo", 100)); + + // Binary + jedis.lpush(bfoo, b1); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b3); + + assertArrayEquals(b3, jedis.lindex(bfoo, 0)); + assertEquals(null, jedis.lindex(bfoo, 100)); - assertEquals("3", jedis.lindex("foo", 0)); - assertEquals(null, jedis.lindex("foo", 100)); } @Test public void lrem() { - jedis.lpush("foo", "hello"); - jedis.lpush("foo", "hello"); - jedis.lpush("foo", "x"); - jedis.lpush("foo", "hello"); - jedis.lpush("foo", "c"); - jedis.lpush("foo", "b"); - jedis.lpush("foo", "a"); + jedis.lpush("foo", "hello"); + jedis.lpush("foo", "hello"); + jedis.lpush("foo", "x"); + jedis.lpush("foo", "hello"); + jedis.lpush("foo", "c"); + jedis.lpush("foo", "b"); + jedis.lpush("foo", "a"); - int count = jedis.lrem("foo", -2, "hello"); + int count = jedis.lrem("foo", -2, "hello"); - List expected = new ArrayList(); - expected.add("a"); - expected.add("b"); - expected.add("c"); - expected.add("hello"); - expected.add("x"); + List expected = new ArrayList(); + expected.add("a"); + expected.add("b"); + expected.add("c"); + expected.add("hello"); + expected.add("x"); + + assertEquals(2, count); + assertEquals(expected, jedis.lrange("foo", 0, 1000)); + assertEquals(0, jedis.lrem("bar", 100, "foo").intValue()); + + // Binary + jedis.lpush(bfoo, bhello); + jedis.lpush(bfoo, bhello); + jedis.lpush(bfoo, bx); + jedis.lpush(bfoo, bhello); + jedis.lpush(bfoo, bC); + jedis.lpush(bfoo, bB); + jedis.lpush(bfoo, bA); + + int bcount = jedis.lrem(bfoo, -2, bhello); + + List bexpected = new ArrayList(); + bexpected.add(bA); + bexpected.add(bB); + bexpected.add(bC); + bexpected.add(bhello); + bexpected.add(bx); + + assertEquals(2, bcount); + assertEquals(bexpected, jedis.lrange(bfoo, 0, 1000)); + assertEquals(0, jedis.lrem(bbar, 100, bfoo).intValue()); - assertEquals(2, count); - assertEquals(expected, jedis.lrange("foo", 0, 1000)); - assertEquals(0, jedis.lrem("bar", 100, "foo").intValue()); } @Test public void lpop() { - jedis.rpush("foo", "a"); - jedis.rpush("foo", "b"); - jedis.rpush("foo", "c"); + jedis.rpush("foo", "a"); + jedis.rpush("foo", "b"); + jedis.rpush("foo", "c"); - String element = jedis.lpop("foo"); - assertEquals("a", element); + String element = jedis.lpop("foo"); + assertEquals("a", element); - List expected = new ArrayList(); - expected.add("b"); - expected.add("c"); + List expected = new ArrayList(); + expected.add("b"); + expected.add("c"); - assertEquals(expected, jedis.lrange("foo", 0, 1000)); - jedis.lpop("foo"); - jedis.lpop("foo"); + assertEquals(expected, jedis.lrange("foo", 0, 1000)); + jedis.lpop("foo"); + jedis.lpop("foo"); + + element = jedis.lpop("foo"); + assertEquals(null, element); + + // Binary + jedis.rpush(bfoo, bA); + jedis.rpush(bfoo, bB); + jedis.rpush(bfoo, bC); + + byte[] belement = jedis.lpop(bfoo); + assertArrayEquals(bA, belement); + + List bexpected = new ArrayList(); + bexpected.add(bB); + bexpected.add(bC); + + assertEquals(bexpected, jedis.lrange(bfoo, 0, 1000)); + jedis.lpop(bfoo); + jedis.lpop(bfoo); + + belement = jedis.lpop(bfoo); + assertEquals(null, belement); - element = jedis.lpop("foo"); - assertEquals(null, element); } @Test public void rpop() { - jedis.rpush("foo", "a"); - jedis.rpush("foo", "b"); - jedis.rpush("foo", "c"); + jedis.rpush("foo", "a"); + jedis.rpush("foo", "b"); + jedis.rpush("foo", "c"); - String element = jedis.rpop("foo"); - assertEquals("c", element); + String element = jedis.rpop("foo"); + assertEquals("c", element); - List expected = new ArrayList(); - expected.add("a"); - expected.add("b"); + List expected = new ArrayList(); + expected.add("a"); + expected.add("b"); - assertEquals(expected, jedis.lrange("foo", 0, 1000)); - jedis.rpop("foo"); - jedis.rpop("foo"); + assertEquals(expected, jedis.lrange("foo", 0, 1000)); + jedis.rpop("foo"); + jedis.rpop("foo"); + + element = jedis.rpop("foo"); + assertEquals(null, element); + + // Binary + jedis.rpush(bfoo, bA); + jedis.rpush(bfoo, bB); + jedis.rpush(bfoo, bC); + + byte[] belement = jedis.rpop(bfoo); + assertArrayEquals(bC, belement); + + List bexpected = new ArrayList(); + bexpected.add(bA); + bexpected.add(bB); + + assertEquals(bexpected, jedis.lrange(bfoo, 0, 1000)); + jedis.rpop(bfoo); + jedis.rpop(bfoo); + + belement = jedis.rpop(bfoo); + assertEquals(null, belement); - element = jedis.rpop("foo"); - assertEquals(null, element); } @Test public void rpoplpush() { - jedis.rpush("foo", "a"); - jedis.rpush("foo", "b"); - jedis.rpush("foo", "c"); + jedis.rpush("foo", "a"); + jedis.rpush("foo", "b"); + jedis.rpush("foo", "c"); - jedis.rpush("dst", "foo"); - jedis.rpush("dst", "bar"); + jedis.rpush("dst", "foo"); + jedis.rpush("dst", "bar"); - String element = jedis.rpoplpush("foo", "dst"); + String element = jedis.rpoplpush("foo", "dst"); - assertEquals("c", element); + assertEquals("c", element); - List srcExpected = new ArrayList(); - srcExpected.add("a"); - srcExpected.add("b"); + List srcExpected = new ArrayList(); + srcExpected.add("a"); + srcExpected.add("b"); - List dstExpected = new ArrayList(); - dstExpected.add("c"); - dstExpected.add("foo"); - dstExpected.add("bar"); + List dstExpected = new ArrayList(); + dstExpected.add("c"); + dstExpected.add("foo"); + dstExpected.add("bar"); + + assertEquals(srcExpected, jedis.lrange("foo", 0, 1000)); + assertEquals(dstExpected, jedis.lrange("dst", 0, 1000)); + + // Binary + jedis.rpush(bfoo, bA); + jedis.rpush(bfoo, bB); + jedis.rpush(bfoo, bC); + + jedis.rpush(bdst, bfoo); + jedis.rpush(bdst, bbar); + + byte[] belement = jedis.rpoplpush(bfoo, bdst); + + assertArrayEquals(bC, belement); + + List bsrcExpected = new ArrayList(); + bsrcExpected.add(bA); + bsrcExpected.add(bB); + + List bdstExpected = new ArrayList(); + bdstExpected.add(bC); + bdstExpected.add(bfoo); + bdstExpected.add(bbar); + + assertEquals(bsrcExpected, jedis.lrange(bfoo, 0, 1000)); + assertEquals(bdstExpected, jedis.lrange(bdst, 0, 1000)); - assertEquals(srcExpected, jedis.lrange("foo", 0, 1000)); - assertEquals(dstExpected, jedis.lrange("dst", 0, 1000)); } @Test public void blpop() throws InterruptedException { - List result = jedis.blpop(1, "foo"); - assertNull(result); + List result = jedis.blpop(1, "foo"); + assertNull(result); - new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - j.lpush("foo", "bar"); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }).start(); + new Thread(new Runnable() { + public void run() { + try { + Jedis j = createJedis(); + j.lpush("foo", "bar"); + j.disconnect(); + } catch (Exception ex) { + fail(ex.getMessage()); + } + } + }).start(); + + result = jedis.blpop(1, "foo"); + assertNotNull(result); + assertEquals(2, result.size()); + assertEquals("foo", result.get(0)); + assertEquals("bar", result.get(1)); + + // Binary + List bresult = jedis.blpop(1, bfoo); + assertNull(bresult); + + new Thread(new Runnable() { + public void run() { + try { + Jedis j = createJedis(); + j.lpush(bfoo, bbar); + j.disconnect(); + } catch (Exception ex) { + fail(ex.getMessage()); + } + } + }).start(); + + bresult = jedis.blpop(1, bfoo); + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); - result = jedis.blpop(1, "foo"); - assertNotNull(result); - assertEquals(2, result.size()); - assertEquals("foo", result.get(0)); - assertEquals("bar", result.get(1)); } @Test public void brpop() throws InterruptedException { - List result = jedis.brpop(1, "foo"); - assertNull(result); + List result = jedis.brpop(1, "foo"); + assertNull(result); - new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - j.lpush("foo", "bar"); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }).start(); + new Thread(new Runnable() { + public void run() { + try { + Jedis j = createJedis(); + j.lpush("foo", "bar"); + j.disconnect(); + } catch (Exception ex) { + fail(ex.getMessage()); + } + } + }).start(); + + result = jedis.brpop(1, "foo"); + assertNotNull(result); + assertEquals(2, result.size()); + assertEquals("foo", result.get(0)); + assertEquals("bar", result.get(1)); + + // Binary + List bresult = jedis.brpop(1, bfoo); + assertNull(bresult); + + new Thread(new Runnable() { + public void run() { + try { + Jedis j = createJedis(); + j.lpush(bfoo, bbar); + j.disconnect(); + } catch (Exception ex) { + fail(ex.getMessage()); + } + } + }).start(); + + bresult = jedis.brpop(1, bfoo); + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); - result = jedis.brpop(1, "foo"); - assertNotNull(result); - assertEquals(2, result.size()); - assertEquals("foo", result.get(0)); - assertEquals("bar", result.get(1)); } @Test public void lpushx() { - int status = jedis.lpushx("foo", "bar"); - assertEquals(0, status); + int status = jedis.lpushx("foo", "bar"); + assertEquals(0, status); + + jedis.lpush("foo", "a"); + status = jedis.lpushx("foo", "b"); + assertEquals(2, status); + + // Binary + int bstatus = jedis.lpushx(bfoo, bbar); + assertEquals(0, bstatus); + + jedis.lpush(bfoo, bA); + bstatus = jedis.lpushx(bfoo, bB); + assertEquals(2, bstatus); - jedis.lpush("foo", "a"); - status = jedis.lpushx("foo", "b"); - assertEquals(2, status); } @Test public void rpushx() { - int status = jedis.rpushx("foo", "bar"); - assertEquals(0, status); + int status = jedis.rpushx("foo", "bar"); + assertEquals(0, status); - jedis.lpush("foo", "a"); - status = jedis.rpushx("foo", "b"); - assertEquals(2, status); + jedis.lpush("foo", "a"); + status = jedis.rpushx("foo", "b"); + assertEquals(2, status); + + // Binary + int bstatus = jedis.rpushx(bfoo, bbar); + assertEquals(0, bstatus); + + jedis.lpush(bfoo, bA); + bstatus = jedis.rpushx(bfoo, bB); + assertEquals(2, bstatus); } @Test public void linsert() { - int status = jedis.linsert("foo", Client.LIST_POSITION.BEFORE, "bar", - "car"); - assertEquals(0, status); + int status = jedis.linsert("foo", Client.LIST_POSITION.BEFORE, "bar", + "car"); + assertEquals(0, status); - jedis.lpush("foo", "a"); - status = jedis.linsert("foo", Client.LIST_POSITION.AFTER, "a", "b"); - assertEquals(2, status); + jedis.lpush("foo", "a"); + status = jedis.linsert("foo", Client.LIST_POSITION.AFTER, "a", "b"); + assertEquals(2, status); - List actual = jedis.lrange("foo", 0, 100); - List expected = new ArrayList(); - expected.add("a"); - expected.add("b"); + List actual = jedis.lrange("foo", 0, 100); + List expected = new ArrayList(); + expected.add("a"); + expected.add("b"); - assertEquals(expected, actual); + assertEquals(expected, actual); + + status = jedis + .linsert("foo", Client.LIST_POSITION.BEFORE, "bar", "car"); + assertEquals(-1, status); + + // Binary + int bstatus = jedis.linsert(bfoo, Client.LIST_POSITION.BEFORE, bbar, + bcar); + assertEquals(0, bstatus); + + jedis.lpush(bfoo, bA); + bstatus = jedis.linsert(bfoo, Client.LIST_POSITION.AFTER, bA, bB); + assertEquals(2, bstatus); + + List bactual = jedis.lrange(bfoo, 0, 100); + List bexpected = new ArrayList(); + bexpected.add(bA); + bexpected.add(bB); + + assertEquals(bexpected, bactual); + + bstatus = jedis.linsert(bfoo, Client.LIST_POSITION.BEFORE, bbar, bcar); + assertEquals(-1, bstatus); - status = jedis - .linsert("foo", Client.LIST_POSITION.BEFORE, "bar", "car"); - assertEquals(-1, status); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java index d9126c5..f8add85 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java @@ -1,236 +1,458 @@ package redis.clients.jedis.tests.commands; +import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; import org.junit.Test; public class SetCommandsTest extends JedisCommandTestBase { + final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; + final byte[] ba = { 0x0A }; + final byte[] bb = { 0x0B }; + final byte[] bc = { 0x0C }; + final byte[] bd = { 0x0D }; + final byte[] bx = { 0x42 }; + @Test public void sadd() { - int status = jedis.sadd("foo", "a"); - assertEquals(1, status); + int status = jedis.sadd("foo", "a"); + assertEquals(1, status); + + status = jedis.sadd("foo", "a"); + assertEquals(0, status); + + int bstatus = jedis.sadd(bfoo, ba); + assertEquals(1, bstatus); + + bstatus = jedis.sadd(bfoo, ba); + assertEquals(0, bstatus); - status = jedis.sadd("foo", "a"); - assertEquals(0, status); } @Test public void smembers() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - Set expected = new LinkedHashSet(); - expected.add("a"); - expected.add("b"); + Set expected = new LinkedHashSet(); + expected.add("a"); + expected.add("b"); - Set members = jedis.smembers("foo"); + Set members = jedis.smembers("foo"); - assertEquals(expected, members); + assertEquals(expected, members); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + Set bexpected = new LinkedHashSet(); + bexpected.add(bb); + bexpected.add(ba); + + Set bmembers = jedis.smembers(bfoo); + + assertEquals(bexpected, bmembers); } @Test public void srem() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - int status = jedis.srem("foo", "a"); + int status = jedis.srem("foo", "a"); - Set expected = new LinkedHashSet(); - expected.add("b"); + Set expected = new LinkedHashSet(); + expected.add("b"); - assertEquals(1, status); - assertEquals(expected, jedis.smembers("foo")); + assertEquals(1, status); + assertEquals(expected, jedis.smembers("foo")); - status = jedis.srem("foo", "bar"); + status = jedis.srem("foo", "bar"); + + assertEquals(0, status); + + // Binary + + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + int bstatus = jedis.srem(bfoo, ba); + + Set bexpected = new LinkedHashSet(); + bexpected.add(bb); + + assertEquals(1, bstatus); + assertEquals(bexpected, jedis.smembers(bfoo)); + + bstatus = jedis.srem(bfoo, bbar); + + assertEquals(0, bstatus); - assertEquals(0, status); } @Test public void spop() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - String member = jedis.spop("foo"); + String member = jedis.spop("foo"); - assertTrue("a".equals(member) || "b".equals(member)); - assertEquals(1, jedis.smembers("foo").size()); + assertTrue("a".equals(member) || "b".equals(member)); + assertEquals(1, jedis.smembers("foo").size()); + + member = jedis.spop("bar"); + assertNull(member); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + byte[] bmember = jedis.spop(bfoo); + + assertTrue(Arrays.equals(ba, bmember) || Arrays.equals(bb, bmember)); + assertEquals(1, jedis.smembers(bfoo).size()); + + bmember = jedis.spop(bbar); + assertNull(bmember); - member = jedis.spop("bar"); - assertNull(member); } @Test public void smove() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - jedis.sadd("bar", "c"); + jedis.sadd("bar", "c"); - int status = jedis.smove("foo", "bar", "a"); + int status = jedis.smove("foo", "bar", "a"); - Set expectedSrc = new LinkedHashSet(); - expectedSrc.add("b"); + Set expectedSrc = new LinkedHashSet(); + expectedSrc.add("b"); - Set expectedDst = new LinkedHashSet(); - expectedDst.add("c"); - expectedDst.add("a"); + Set expectedDst = new LinkedHashSet(); + expectedDst.add("c"); + expectedDst.add("a"); - assertEquals(status, 1); - assertEquals(expectedSrc, jedis.smembers("foo")); - assertEquals(expectedDst, jedis.smembers("bar")); + assertEquals(status, 1); + assertEquals(expectedSrc, jedis.smembers("foo")); + assertEquals(expectedDst, jedis.smembers("bar")); + + status = jedis.smove("foo", "bar", "a"); + + assertEquals(status, 0); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + jedis.sadd(bbar, bc); + + int bstatus = jedis.smove(bfoo, bbar, ba); + + Set bexpectedSrc = new LinkedHashSet(); + bexpectedSrc.add(bb); + + Set bexpectedDst = new LinkedHashSet(); + bexpectedDst.add(bc); + bexpectedDst.add(ba); + + assertEquals(bstatus, 1); + assertEquals(bexpectedSrc, jedis.smembers(bfoo)); + assertEquals(bexpectedDst, jedis.smembers(bbar)); + + bstatus = jedis.smove(bfoo, bbar, ba); + assertEquals(bstatus, 0); - status = jedis.smove("foo", "bar", "a"); - assertEquals(status, 0); } @Test public void scard() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - int card = jedis.scard("foo"); + int card = jedis.scard("foo"); - assertEquals(2, card); + assertEquals(2, card); + + card = jedis.scard("bar"); + assertEquals(0, card); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + int bcard = jedis.scard(bfoo); + + assertEquals(2, bcard); + + bcard = jedis.scard(bbar); + assertEquals(0, bcard); - card = jedis.scard("bar"); - assertEquals(0, card); } @Test public void sismember() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - int status = jedis.sismember("foo", "a"); - assertEquals(1, status); + int status = jedis.sismember("foo", "a"); + assertEquals(1, status); + + status = jedis.sismember("foo", "c"); + assertEquals(0, status); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + int bstatus = jedis.sismember(bfoo, ba); + assertEquals(1, bstatus); + + bstatus = jedis.sismember(bfoo, bc); + assertEquals(0, bstatus); - status = jedis.sismember("foo", "c"); - assertEquals(0, status); } @Test public void sinter() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - jedis.sadd("bar", "b"); - jedis.sadd("bar", "c"); + jedis.sadd("bar", "b"); + jedis.sadd("bar", "c"); - Set expected = new LinkedHashSet(); - expected.add("b"); + Set expected = new LinkedHashSet(); + expected.add("b"); - Set intersection = jedis.sinter("foo", "bar"); - assertEquals(expected, intersection); + Set intersection = jedis.sinter("foo", "bar"); + assertEquals(expected, intersection); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + jedis.sadd(bbar, bb); + jedis.sadd(bbar, bc); + + Set bexpected = new LinkedHashSet(); + bexpected.add(bb); + + Set bintersection = jedis.sinter(bfoo, bbar); + assertEquals(bexpected, bintersection); } @Test public void sinterstore() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - jedis.sadd("bar", "b"); - jedis.sadd("bar", "c"); + jedis.sadd("bar", "b"); + jedis.sadd("bar", "c"); - Set expected = new LinkedHashSet(); - expected.add("b"); + Set expected = new LinkedHashSet(); + expected.add("b"); - int status = jedis.sinterstore("car", "foo", "bar"); - assertEquals(1, status); + int status = jedis.sinterstore("car", "foo", "bar"); + assertEquals(1, status); + + assertEquals(expected, jedis.smembers("car")); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + jedis.sadd(bbar, bb); + jedis.sadd(bbar, bc); + + Set bexpected = new LinkedHashSet(); + bexpected.add(bb); + + int bstatus = jedis.sinterstore(bcar, bfoo, bbar); + assertEquals(1, bstatus); + + assertEquals(bexpected, jedis.smembers(bcar)); - assertEquals(expected, jedis.smembers("car")); } @Test public void sunion() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - jedis.sadd("bar", "b"); - jedis.sadd("bar", "c"); + jedis.sadd("bar", "b"); + jedis.sadd("bar", "c"); - Set expected = new LinkedHashSet(); - expected.add("a"); - expected.add("b"); - expected.add("c"); + Set expected = new LinkedHashSet(); + expected.add("a"); + expected.add("b"); + expected.add("c"); + + Set union = jedis.sunion("foo", "bar"); + assertEquals(expected, union); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + jedis.sadd(bbar, bb); + jedis.sadd(bbar, bc); + + Set bexpected = new LinkedHashSet(); + bexpected.add(bb); + bexpected.add(bc); + bexpected.add(ba); + + Set bunion = jedis.sunion(bfoo, bbar); + assertEquals(bexpected, bunion); - Set union = jedis.sunion("foo", "bar"); - assertEquals(expected, union); } @Test public void sunionstore() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - jedis.sadd("bar", "b"); - jedis.sadd("bar", "c"); + jedis.sadd("bar", "b"); + jedis.sadd("bar", "c"); - Set expected = new LinkedHashSet(); - expected.add("a"); - expected.add("b"); - expected.add("c"); + Set expected = new LinkedHashSet(); + expected.add("a"); + expected.add("b"); + expected.add("c"); - int status = jedis.sunionstore("car", "foo", "bar"); - assertEquals(3, status); + int status = jedis.sunionstore("car", "foo", "bar"); + assertEquals(3, status); + + assertEquals(expected, jedis.smembers("car")); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + jedis.sadd(bbar, bb); + jedis.sadd(bbar, bc); + + Set bexpected = new LinkedHashSet(); + bexpected.add(bb); + bexpected.add(bc); + bexpected.add(ba); + + int bstatus = jedis.sunionstore(bcar, bfoo, bbar); + assertEquals(3, bstatus); + + assertEquals(bexpected, jedis.smembers(bcar)); - assertEquals(expected, jedis.smembers("car")); } @Test public void sdiff() { - jedis.sadd("foo", "x"); - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); - jedis.sadd("foo", "c"); + jedis.sadd("foo", "x"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + jedis.sadd("foo", "c"); - jedis.sadd("bar", "c"); + jedis.sadd("bar", "c"); - jedis.sadd("car", "a"); - jedis.sadd("car", "d"); + jedis.sadd("car", "a"); + jedis.sadd("car", "d"); - Set expected = new LinkedHashSet(); - expected.add("x"); - expected.add("b"); + Set expected = new LinkedHashSet(); + expected.add("x"); + expected.add("b"); + + Set diff = jedis.sdiff("foo", "bar", "car"); + assertEquals(expected, diff); + + // Binary + jedis.sadd(bfoo, bx); + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + jedis.sadd(bfoo, bc); + + jedis.sadd(bbar, bc); + + jedis.sadd(bcar, ba); + jedis.sadd(bcar, bd); + + Set bexpected = new LinkedHashSet(); + bexpected.add(bb); + bexpected.add(bx); + + Set bdiff = jedis.sdiff(bfoo, bbar, bcar); + assertEquals(bexpected, bdiff); - Set diff = jedis.sdiff("foo", "bar", "car"); - assertEquals(expected, diff); } @Test public void sdiffstore() { - jedis.sadd("foo", "x"); - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); - jedis.sadd("foo", "c"); + jedis.sadd("foo", "x"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + jedis.sadd("foo", "c"); - jedis.sadd("bar", "c"); + jedis.sadd("bar", "c"); - jedis.sadd("car", "a"); - jedis.sadd("car", "d"); + jedis.sadd("car", "a"); + jedis.sadd("car", "d"); - Set expected = new LinkedHashSet(); - expected.add("d"); - expected.add("a"); + Set expected = new LinkedHashSet(); + expected.add("d"); + expected.add("a"); + + int status = jedis.sdiffstore("tar", "foo", "bar", "car"); + assertEquals(2, status); + assertEquals(expected, jedis.smembers("car")); + + // Binary + jedis.sadd(bfoo, bx); + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + jedis.sadd(bfoo, bc); + + jedis.sadd(bbar, bc); + + jedis.sadd(bcar, ba); + jedis.sadd(bcar, bd); + + Set bexpected = new LinkedHashSet(); + bexpected.add(bd); + bexpected.add(ba); + + int bstatus = jedis.sdiffstore("tar".getBytes(), bfoo, bbar, bcar); + assertEquals(2, bstatus); + assertEquals(bexpected, jedis.smembers(bcar)); - int status = jedis.sdiffstore("tar", "foo", "bar", "car"); - assertEquals(2, status); - assertEquals(expected, jedis.smembers("car")); } @Test public void srandmember() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - String member = jedis.srandmember("foo"); + String member = jedis.srandmember("foo"); - assertTrue("a".equals(member) || "b".equals(member)); - assertEquals(2, jedis.smembers("foo").size()); + assertTrue("a".equals(member) || "b".equals(member)); + assertEquals(2, jedis.smembers("foo").size()); + + member = jedis.srandmember("bar"); + assertNull(member); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + byte[] bmember = jedis.srandmember(bfoo); + + assertTrue(Arrays.equals(ba, bmember) || Arrays.equals(bb, bmember)); + assertEquals(2, jedis.smembers(bfoo).size()); + + bmember = jedis.srandmember(bbar); + assertNull(bmember); - member = jedis.srandmember("bar"); - assertNull(member); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java index ad238fc..7f45f21 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java @@ -5,10 +5,18 @@ import java.util.Set; import org.junit.Test; +import redis.clients.jedis.Protocol; import redis.clients.jedis.Tuple; import redis.clients.jedis.ZParams; public class SortedSetCommandsTest extends JedisCommandTestBase { + final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; + final byte[] ba = { 0x0A }; + final byte[] bb = { 0x0B }; + final byte[] bc = { 0x0C }; + @Test public void zadd() { int status = jedis.zadd("foo", 1d, "a"); @@ -22,6 +30,20 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { status = jedis.zadd("foo", 2d, "a"); assertEquals(0, status); + + // Binary + int bstatus = jedis.zadd(bfoo, 1d, ba); + assertEquals(1, bstatus); + + bstatus = jedis.zadd(bfoo, 10d, bb); + assertEquals(1, bstatus); + + bstatus = jedis.zadd(bfoo, 0.1d, bc); + assertEquals(1, bstatus); + + bstatus = jedis.zadd(bfoo, 2d, ba); + assertEquals(0, bstatus); + } @Test @@ -41,6 +63,24 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { expected.add("b"); range = jedis.zrange("foo", 0, 100); assertEquals(expected, range); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + Set bexpected = new LinkedHashSet(); + bexpected.add(bc); + bexpected.add(ba); + + Set brange = jedis.zrange(bfoo, 0, 1); + assertEquals(bexpected, brange); + + bexpected.add(bb); + brange = jedis.zrange(bfoo, 0, 100); + assertEquals(bexpected, brange); + } @Test @@ -60,6 +100,24 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { expected.add("c"); range = jedis.zrevrange("foo", 0, 100); assertEquals(expected, range); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + Set bexpected = new LinkedHashSet(); + bexpected.add(bb); + bexpected.add(ba); + + Set brange = jedis.zrevrange(bfoo, 0, 1); + assertEquals(bexpected, brange); + + bexpected.add(bc); + brange = jedis.zrevrange(bfoo, 0, 100); + assertEquals(bexpected, brange); + } @Test @@ -78,6 +136,23 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { status = jedis.zrem("foo", "bar"); assertEquals(0, status); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 2d, bb); + + int bstatus = jedis.zrem(bfoo, ba); + + Set bexpected = new LinkedHashSet(); + bexpected.add(bb); + + assertEquals(1, bstatus); + assertEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + + bstatus = jedis.zrem(bfoo, bbar); + + assertEquals(0, bstatus); + } @Test @@ -91,8 +166,22 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { expected.add("a"); expected.add("b"); - assertEquals(3d, score); + assertEquals(3d, score, 0); assertEquals(expected, jedis.zrange("foo", 0, 100)); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 2d, bb); + + double bscore = jedis.zincrby(bfoo, 2d, ba); + + Set bexpected = new LinkedHashSet(); + bexpected.add(bb); + bexpected.add(ba); + + assertEquals(3d, bscore, 0); + assertEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + } @Test @@ -108,6 +197,20 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { rank = jedis.zrank("car", "b"); assertNull(rank); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 2d, bb); + + Integer brank = jedis.zrank(bfoo, ba); + assertEquals(0, brank.intValue()); + + brank = jedis.zrank(bfoo, bb); + assertEquals(1, brank.intValue()); + + brank = jedis.zrank(bcar, bb); + assertNull(brank); + } @Test @@ -120,6 +223,17 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { rank = jedis.zrevrank("foo", "b"); assertEquals(0, rank); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 2d, bb); + + int brank = jedis.zrevrank(bfoo, ba); + assertEquals(1, brank); + + brank = jedis.zrevrank(bfoo, bb); + assertEquals(0, brank); + } @Test @@ -139,6 +253,24 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { expected.add(new Tuple("b", 10d)); range = jedis.zrangeWithScores("foo", 0, 100); assertEquals(expected, range); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + Set bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(bc, 0.1d)); + bexpected.add(new Tuple(ba, 2d)); + + Set brange = jedis.zrangeWithScores(bfoo, 0, 1); + assertEquals(bexpected, brange); + + bexpected.add(new Tuple(bb, 10d)); + brange = jedis.zrangeWithScores(bfoo, 0, 100); + assertEquals(bexpected, brange); + } @Test @@ -158,6 +290,24 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { expected.add(new Tuple("c", 0.1d)); range = jedis.zrevrangeWithScores("foo", 0, 100); assertEquals(expected, range); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + Set bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(bb, 10d)); + bexpected.add(new Tuple(ba, 2d)); + + Set brange = jedis.zrevrangeWithScores(bfoo, 0, 1); + assertEquals(bexpected, brange); + + bexpected.add(new Tuple(bc, 0.1d)); + brange = jedis.zrevrangeWithScores(bfoo, 0, 100); + assertEquals(bexpected, brange); + } @Test @@ -169,6 +319,16 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { int size = jedis.zcard("foo"); assertEquals(3, size); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + int bsize = jedis.zcard(bfoo); + assertEquals(3, bsize); + } @Test @@ -179,13 +339,29 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { jedis.zadd("foo", 2d, "a"); Double score = jedis.zscore("foo", "b"); - assertEquals(10d, score); + assertEquals((Double) 10d, score); score = jedis.zscore("foo", "c"); - assertEquals(0.1d, score); + assertEquals((Double) 0.1d, score); score = jedis.zscore("foo", "s"); assertNull(score); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + Double bscore = jedis.zscore(bfoo, bb); + assertEquals((Double) 10d, bscore); + + bscore = jedis.zscore(bfoo, bc); + assertEquals((Double) 0.1d, bscore); + + bscore = jedis.zscore(bfoo, "s".getBytes(Protocol.UTF8)); + assertNull(bscore); + } @Test @@ -198,6 +374,17 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { int result = jedis.zcount("foo", 0.01d, 2.1d); assertEquals(2, result); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + int bresult = jedis.zcount(bfoo, 0.01d, 2.1d); + + assertEquals(2, bresult); + } @Test @@ -230,6 +417,38 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { expected.add("a"); assertEquals(expected, range); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + Set brange = jedis.zrangeByScore(bfoo, 0d, 2d); + + Set bexpected = new LinkedHashSet(); + bexpected.add(bc); + bexpected.add(ba); + + assertEquals(bexpected, brange); + + brange = jedis.zrangeByScore(bfoo, 0d, 2d, 0, 1); + + bexpected = new LinkedHashSet(); + bexpected.add(bc); + + assertEquals(bexpected, brange); + + brange = jedis.zrangeByScore(bfoo, 0d, 2d, 1, 1); + Set brange2 = jedis.zrangeByScore(bfoo, "-inf" + .getBytes(Protocol.UTF8), "(2".getBytes(Protocol.UTF8)); + assertEquals(bexpected, brange2); + + bexpected = new LinkedHashSet(); + bexpected.add(ba); + + assertEquals(bexpected, brange); + } @Test @@ -260,6 +479,36 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { expected.add(new Tuple("a", 2d)); assertEquals(expected, range); + + // Binary + + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + Set brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d); + + Set bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(bc, 0.1d)); + bexpected.add(new Tuple(ba, 2d)); + + assertEquals(bexpected, brange); + + brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d, 0, 1); + + bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(bc, 0.1d)); + + assertEquals(bexpected, brange); + + brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d, 1, 1); + + bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(ba, 2d)); + + assertEquals(bexpected, brange); + } @Test @@ -278,6 +527,23 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { expected.add("b"); assertEquals(expected, jedis.zrange("foo", 0, 100)); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + int bresult = jedis.zremrangeByRank(bfoo, 0, 0); + + assertEquals(1, bresult); + + Set bexpected = new LinkedHashSet(); + bexpected.add(ba); + bexpected.add(bb); + + assertEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + } @Test @@ -295,6 +561,21 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { expected.add("b"); assertEquals(expected, jedis.zrange("foo", 0, 100)); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + int bresult = jedis.zremrangeByScore(bfoo, 0, 2); + + assertEquals(2, bresult); + + Set bexpected = new LinkedHashSet(); + bexpected.add(bb); + + assertEquals(bexpected, jedis.zrange(bfoo, 0, 100)); } @Test @@ -313,6 +594,24 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { expected.add(new Tuple("a", new Double(3))); assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); + + // Binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 2, bb); + jedis.zadd(bbar, 2, ba); + jedis.zadd(bbar, 2, bb); + + int bresult = jedis.zunionstore("dst".getBytes(Protocol.UTF8), bfoo, + bbar); + + assertEquals(2, bresult); + + Set bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(bb, new Double(4))); + bexpected.add(new Tuple(ba, new Double(3))); + + assertEquals(bexpected, jedis.zrangeWithScores("dst" + .getBytes(Protocol.UTF8), 0, 100)); } @Test @@ -334,6 +633,27 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { expected.add(new Tuple("a", new Double(6))); assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); + + // Binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 2, bb); + jedis.zadd(bbar, 2, ba); + jedis.zadd(bbar, 2, bb); + + ZParams bparams = new ZParams(); + bparams.weights(2, 2); + bparams.aggregate(ZParams.Aggregate.SUM); + int bresult = jedis.zunionstore("dst".getBytes(Protocol.UTF8), bparams, + bfoo, bbar); + + assertEquals(2, bresult); + + Set bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(bb, new Double(8))); + bexpected.add(new Tuple(ba, new Double(6))); + + assertEquals(bexpected, jedis.zrangeWithScores("dst" + .getBytes(Protocol.UTF8), 0, 100)); } @Test @@ -350,6 +670,22 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { expected.add(new Tuple("a", new Double(3))); assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); + + // Binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 2, bb); + jedis.zadd(bbar, 2, ba); + + int bresult = jedis.zinterstore("dst".getBytes(Protocol.UTF8), bfoo, + bbar); + + assertEquals(1, bresult); + + Set bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(ba, new Double(3))); + + assertEquals(bexpected, jedis.zrangeWithScores("dst" + .getBytes(Protocol.UTF8), 0, 100)); } @Test @@ -369,5 +705,24 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { expected.add(new Tuple("a", new Double(6))); assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); + + // Binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 2, bb); + jedis.zadd(bbar, 2, ba); + + ZParams bparams = new ZParams(); + bparams.weights(2, 2); + bparams.aggregate(ZParams.Aggregate.SUM); + int bresult = jedis.zinterstore("dst".getBytes(Protocol.UTF8), bparams, + bfoo, bbar); + + assertEquals(1, bresult); + + Set bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(ba, new Double(6))); + + assertEquals(bexpected, jedis.zrangeWithScores("dst" + .getBytes(Protocol.UTF8), 0, 100)); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/SortingCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/SortingCommandsTest.java index 6864dae..437069f 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SortingCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SortingCommandsTest.java @@ -8,147 +8,294 @@ import org.junit.Test; import redis.clients.jedis.SortingParams; public class SortingCommandsTest extends JedisCommandTestBase { + final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, '1' }; + final byte[] bbar2 = { 0x05, 0x06, 0x07, 0x08, '2' }; + final byte[] bbar3 = { 0x05, 0x06, 0x07, 0x08, '3' }; + final byte[] bbar10 = { 0x05, 0x06, 0x07, 0x08, '1', '0' }; + final byte[] bbarstar = { 0x05, 0x06, 0x07, 0x08, '*' }; + final byte[] bcar1 = { 0x0A, 0x0B, 0x0C, 0x0D, '1' }; + final byte[] bcar2 = { 0x0A, 0x0B, 0x0C, 0x0D, '2' }; + final byte[] bcar10 = { 0x0A, 0x0B, 0x0C, 0x0D, '1', '0' }; + final byte[] bcarstar = { 0x0A, 0x0B, 0x0C, 0x0D, '*' }; + final byte[] b1 = { '1' }; + final byte[] b2 = { '2' }; + final byte[] b3 = { '3' }; + final byte[] b10 = { '1', '0' }; + @Test public void sort() { - jedis.lpush("foo", "3"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "1"); + jedis.lpush("foo", "3"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "1"); - List result = jedis.sort("foo"); + List result = jedis.sort("foo"); - List expected = new ArrayList(); - expected.add("1"); - expected.add("2"); - expected.add("3"); + List expected = new ArrayList(); + expected.add("1"); + expected.add("2"); + expected.add("3"); - assertEquals(expected, result); + assertEquals(expected, result); + + // Binary + jedis.lpush(bfoo, b3); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b1); + + List bresult = jedis.sort(bfoo); + + List bexpected = new ArrayList(); + bexpected.add(b1); + bexpected.add(b2); + bexpected.add(b3); + + assertEquals(bexpected, bresult); } @Test public void sortBy() { - jedis.lpush("foo", "2"); - jedis.lpush("foo", "3"); - jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "3"); + jedis.lpush("foo", "1"); - jedis.set("bar1", "3"); - jedis.set("bar2", "2"); - jedis.set("bar3", "1"); + jedis.set("bar1", "3"); + jedis.set("bar2", "2"); + jedis.set("bar3", "1"); - SortingParams sp = new SortingParams(); - sp.by("bar*"); + SortingParams sp = new SortingParams(); + sp.by("bar*"); - List result = jedis.sort("foo", sp); + List result = jedis.sort("foo", sp); - List expected = new ArrayList(); - expected.add("3"); - expected.add("2"); - expected.add("1"); + List expected = new ArrayList(); + expected.add("3"); + expected.add("2"); + expected.add("1"); + + assertEquals(expected, result); + + // Binary + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b3); + jedis.lpush(bfoo, b1); + + jedis.set(bbar1, b3); + jedis.set(bbar2, b2); + jedis.set(bbar3, b1); + + SortingParams bsp = new SortingParams(); + bsp.by(bbarstar); + + List bresult = jedis.sort(bfoo, bsp); + + List bexpected = new ArrayList(); + bexpected.add(b3); + bexpected.add(b2); + bexpected.add(b1); + + assertEquals(bexpected, bresult); - assertEquals(expected, result); } @Test public void sortDesc() { - jedis.lpush("foo", "3"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "1"); + jedis.lpush("foo", "3"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "1"); - SortingParams sp = new SortingParams(); - sp.desc(); + SortingParams sp = new SortingParams(); + sp.desc(); - List result = jedis.sort("foo", sp); + List result = jedis.sort("foo", sp); - List expected = new ArrayList(); - expected.add("3"); - expected.add("2"); - expected.add("1"); + List expected = new ArrayList(); + expected.add("3"); + expected.add("2"); + expected.add("1"); - assertEquals(expected, result); + assertEquals(expected, result); + + // Binary + jedis.lpush(bfoo, b3); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b1); + + SortingParams bsp = new SortingParams(); + bsp.desc(); + + List bresult = jedis.sort(bfoo, bsp); + + List bexpected = new ArrayList(); + bexpected.add(b3); + bexpected.add(b2); + bexpected.add(b1); + + assertEquals(bexpected, bresult); } @Test public void sortLimit() { - for (int n = 10; n > 0; n--) { - jedis.lpush("foo", String.valueOf(n)); - } + for (int n = 10; n > 0; n--) { + jedis.lpush("foo", String.valueOf(n)); + } - SortingParams sp = new SortingParams(); - sp.limit(0, 3); + SortingParams sp = new SortingParams(); + sp.limit(0, 3); - List result = jedis.sort("foo", sp); + List result = jedis.sort("foo", sp); - List expected = new ArrayList(); - expected.add("1"); - expected.add("2"); - expected.add("3"); + List expected = new ArrayList(); + expected.add("1"); + expected.add("2"); + expected.add("3"); - assertEquals(expected, result); + assertEquals(expected, result); + + // Binary + jedis.rpush(bfoo, new byte[] { (byte) '4' }); + jedis.rpush(bfoo, new byte[] { (byte) '3' }); + jedis.rpush(bfoo, new byte[] { (byte) '2' }); + jedis.rpush(bfoo, new byte[] { (byte) '1' }); + + SortingParams bsp = new SortingParams(); + bsp.limit(0, 3); + + List bresult = jedis.sort(bfoo, bsp); + + List bexpected = new ArrayList(); + bexpected.add(b1); + bexpected.add(b2); + bexpected.add(b3); + + assertEquals(bexpected, bresult); } @Test public void sortAlpha() { - jedis.lpush("foo", "1"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "10"); + jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "10"); - SortingParams sp = new SortingParams(); - sp.alpha(); + SortingParams sp = new SortingParams(); + sp.alpha(); - List result = jedis.sort("foo", sp); + List result = jedis.sort("foo", sp); - List expected = new ArrayList(); - expected.add("1"); - expected.add("10"); - expected.add("2"); + List expected = new ArrayList(); + expected.add("1"); + expected.add("10"); + expected.add("2"); - assertEquals(expected, result); + assertEquals(expected, result); + + // Binary + jedis.lpush(bfoo, b1); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b10); + + SortingParams bsp = new SortingParams(); + bsp.alpha(); + + List bresult = jedis.sort(bfoo, bsp); + + List bexpected = new ArrayList(); + bexpected.add(b1); + bexpected.add(b10); + bexpected.add(b2); + + assertEquals(bexpected, bresult); } @Test public void sortGet() { - jedis.lpush("foo", "1"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "10"); + jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "10"); - jedis.set("bar1", "bar1"); - jedis.set("bar2", "bar2"); - jedis.set("bar10", "bar10"); + jedis.set("bar1", "bar1"); + jedis.set("bar2", "bar2"); + jedis.set("bar10", "bar10"); - jedis.set("car1", "car1"); - jedis.set("car2", "car2"); - jedis.set("car10", "car10"); + jedis.set("car1", "car1"); + jedis.set("car2", "car2"); + jedis.set("car10", "car10"); - SortingParams sp = new SortingParams(); - sp.get("car*", "bar*"); + SortingParams sp = new SortingParams(); + sp.get("car*", "bar*"); - List result = jedis.sort("foo", sp); + List result = jedis.sort("foo", sp); - List expected = new ArrayList(); - expected.add("car1"); - expected.add("bar1"); - expected.add("car2"); - expected.add("bar2"); - expected.add("car10"); - expected.add("bar10"); + List expected = new ArrayList(); + expected.add("car1"); + expected.add("bar1"); + expected.add("car2"); + expected.add("bar2"); + expected.add("car10"); + expected.add("bar10"); - assertEquals(expected, result); + assertEquals(expected, result); + + // Binary + jedis.lpush(bfoo, b1); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b10); + + jedis.set(bbar1, bbar1); + jedis.set(bbar2, bbar2); + jedis.set(bbar10, bbar10); + + jedis.set(bcar1, bcar1); + jedis.set(bcar2, bcar2); + jedis.set(bcar10, bcar10); + + SortingParams bsp = new SortingParams(); + bsp.get(bcarstar, bbarstar); + + List bresult = jedis.sort(bfoo, bsp); + + List bexpected = new ArrayList(); + bexpected.add(bcar1); + bexpected.add(bbar1); + bexpected.add(bcar2); + bexpected.add(bbar2); + bexpected.add(bcar10); + bexpected.add(bbar10); + + assertEquals(bexpected, bresult); } @Test public void sortStore() { - jedis.lpush("foo", "1"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "10"); + jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "10"); - int result = jedis.sort("foo", "result"); + int result = jedis.sort("foo", "result"); - List expected = new ArrayList(); - expected.add("1"); - expected.add("2"); - expected.add("10"); + List expected = new ArrayList(); + expected.add("1"); + expected.add("2"); + expected.add("10"); - assertEquals(3, result); - assertEquals(expected, jedis.lrange("result", 0, 1000)); + assertEquals(3, result); + assertEquals(expected, jedis.lrange("result", 0, 1000)); + + // Binary + jedis.lpush(bfoo, b1); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b10); + + byte[] bkresult = new byte[] { 0X09, 0x0A, 0x0B, 0x0C }; + int bresult = jedis.sort(bfoo, bkresult); + + List bexpected = new ArrayList(); + bexpected.add(b1); + bexpected.add(b2); + bexpected.add(b10); + + assertEquals(3, bresult); + assertEquals(bexpected, jedis.lrange(bkresult, 0, 1000)); } } \ No newline at end of file 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 ca43163..00a01c3 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java @@ -3,6 +3,7 @@ package redis.clients.jedis.tests.commands; import java.io.IOException; import java.net.UnknownHostException; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import org.junit.Before; @@ -10,105 +11,190 @@ import org.junit.Test; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisException; +import redis.clients.jedis.Protocol; import redis.clients.jedis.Transaction; import redis.clients.jedis.TransactionBlock; +import redis.clients.jedis.Protocol.Keyword; public class TransactionCommandsTest extends JedisCommandTestBase { - Jedis nj; - @Before - public void setUp() throws Exception { - super.setUp(); + final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + final byte[] ba = { 0x0A }; + final byte[] bb = { 0x0B }; - nj = new Jedis(hnp.host, hnp.port, 500); - nj.connect(); - nj.auth("foobared"); - nj.flushAll(); - } + final byte[] bmykey = { 0x42, 0x02, 0x03, 0x04 }; + + Jedis nj; + + @Before + public void setUp() throws Exception { + super.setUp(); + + nj = new Jedis(hnp.host, hnp.port, 500); + nj.connect(); + nj.auth("foobared"); + nj.flushAll(); + } @Test public void multi() { - Transaction trans = jedis.multi(); + Transaction trans = jedis.multi(); - String status = trans.sadd("foo", "a"); - assertEquals("QUEUED", status); + String status = trans.sadd("foo", "a"); + assertEquals(Keyword.QUEUED.name(), status); - status = trans.sadd("foo", "b"); - assertEquals("QUEUED", status); + status = trans.sadd("foo", "b"); + assertEquals(Keyword.QUEUED.name(), status); - status = trans.scard("foo"); - assertEquals("QUEUED", status); + status = trans.scard("foo"); + assertEquals(Keyword.QUEUED.name(), status); - List response = trans.exec(); + List response = trans.exec(); + + List expected = new ArrayList(); + expected.add(1); + expected.add(1); + expected.add(2); + assertEquals(expected, response); + + // Binary + trans = jedis.multi(); + + status = trans.sadd(bfoo, ba); + assertEquals(Keyword.QUEUED.name(), status); + + status = trans.sadd(bfoo, bb); + assertEquals(Keyword.QUEUED.name(), status); + + status = trans.scard(bfoo); + assertEquals(Keyword.QUEUED.name(), status); + + response = trans.exec(); + + expected = new ArrayList(); + expected.add(1); + expected.add(1); + expected.add(2); + assertEquals(expected, response); - List expected = new ArrayList(); - expected.add(1); - expected.add(1); - expected.add(2); - assertEquals(expected, response); } @Test public void multiBlock() { - List response = jedis.multi(new TransactionBlock() { - public void execute() { - String status = sadd("foo", "a"); - assertEquals("QUEUED", status); + List response = jedis.multi(new TransactionBlock() { + public void execute() { + String status = sadd("foo", "a"); + assertEquals(Keyword.QUEUED.name(), status); - status = sadd("foo", "b"); - assertEquals("QUEUED", status); + status = sadd("foo", "b"); + assertEquals(Keyword.QUEUED.name(), status); - status = scard("foo"); - assertEquals("QUEUED", status); - } - }); + status = scard("foo"); + assertEquals(Keyword.QUEUED.name(), status); + } + }); + + List expected = new ArrayList(); + expected.add(1); + expected.add(1); + expected.add(2); + assertEquals(expected, response); + + // Binary + response = jedis.multi(new TransactionBlock() { + public void execute() { + String status = sadd(bfoo, ba); + assertEquals(Keyword.QUEUED.name(), status); + + status = sadd(bfoo, bb); + assertEquals(Keyword.QUEUED.name(), status); + + status = scard(bfoo); + assertEquals(Keyword.QUEUED.name(), status); + } + }); + + expected = new ArrayList(); + expected.add(1); + expected.add(1); + expected.add(2); + assertEquals(expected, response); - List expected = new ArrayList(); - expected.add(1); - expected.add(1); - expected.add(2); - assertEquals(expected, response); } @Test public void watch() throws UnknownHostException, IOException { - jedis.watch("mykey"); - Transaction t = jedis.multi(); + jedis.watch("mykey"); + Transaction t = jedis.multi(); - nj.connect(); - nj.auth("foobared"); - nj.set("mykey", "bar"); - nj.disconnect(); + nj.connect(); + nj.auth("foobared"); + nj.set("mykey", "bar"); + nj.disconnect(); - t.set("mykey", "foo"); - List resp = t.exec(); - assertEquals(null, resp); - assertEquals("bar", jedis.get("mykey")); + t.set("mykey", "foo"); + List resp = t.exec(); + assertEquals(null, resp); + assertEquals("bar", jedis.get("mykey")); + + // Binary + jedis.watch(bmykey); + t = jedis.multi(); + + nj.connect(); + nj.auth("foobared"); + nj.set(bmykey, bbar); + nj.disconnect(); + + t.set(bmykey, bfoo); + resp = t.exec(); + assertEquals(null, resp); + assertTrue(Arrays.equals(bbar, jedis.get(bmykey))); } @Test public void unwatch() throws UnknownHostException, IOException { - jedis.watch("mykey"); - String val = jedis.get("mykey"); - val = "foo"; - String status = jedis.unwatch(); - assertEquals("OK", status); - Transaction t = jedis.multi(); + jedis.watch("mykey"); + String val = jedis.get("mykey"); + val = "foo"; + String status = jedis.unwatch(); + assertEquals("OK", status); + Transaction t = jedis.multi(); - nj.connect(); - nj.auth("foobared"); - nj.set("mykey", "bar"); - nj.disconnect(); + nj.connect(); + nj.auth("foobared"); + nj.set("mykey", "bar"); + nj.disconnect(); - t.set("mykey", val); - List resp = t.exec(); - List expected = new ArrayList(); - expected.add("OK"); - assertEquals(expected, resp); + t.set("mykey", val); + List resp = t.exec(); + assertEquals(1, resp.size()); + assertArrayEquals(Keyword.OK.name().getBytes(Protocol.UTF8), + (byte[]) resp.get(0)); + + // Binary + jedis.watch(bmykey); + byte[] bval = jedis.get(bmykey); + 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()); + assertArrayEquals(Keyword.OK.name().getBytes(Protocol.UTF8), + (byte[]) resp.get(0)); } @Test(expected = JedisException.class) public void validateWhenInMulti() { - jedis.multi(); - jedis.ping(); + jedis.multi(); + jedis.ping(); } } \ No newline at end of file diff --git a/src/test/resources/MySimpson.png b/src/test/resources/MySimpson.png new file mode 100644 index 0000000..025c83d Binary files /dev/null and b/src/test/resources/MySimpson.png differ