DATAREDIS-668 - Polishing.

Align JavaDoc for consistent wording. Remove superfluous final keyword from variables in DefaultSetOperations.

Replace anonymous inner classes with lambdas/method references, where possible. Remove superfluous final keywords used for local variable. Add override JavaDocs and missing Override annoations. Use diamond syntax where possible. Formatting, license headers. Reduce visibility of Default Operations implementations to package-scope.

Original pull request: #259.
This commit is contained in:
Mark Paluch
2017-07-27 15:34:32 +02:00
parent 6ef4a6f8eb
commit 65d320b3c8
180 changed files with 3592 additions and 3327 deletions

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2013 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -38,7 +38,7 @@ import org.w3c.dom.NamedNodeMap;
/**
* Parser for the Redis <code>&lt;listener-container&gt;</code> element.
*
*
* @author Costin Leau
*/
class RedisListenerContainerParser extends AbstractSimpleBeanDefinitionParser {
@@ -73,7 +73,7 @@ class RedisListenerContainerParser extends AbstractSimpleBeanDefinitionParser {
List<Element> listDefs = DomUtils.getChildElementsByTagName(element, "listener");
if (!listDefs.isEmpty()) {
ManagedMap<BeanDefinition, Collection<? extends BeanDefinition>> listeners = new ManagedMap<BeanDefinition, Collection<? extends BeanDefinition>>(
ManagedMap<BeanDefinition, Collection<? extends BeanDefinition>> listeners = new ManagedMap<>(
listDefs.size());
for (Element listElement : listDefs) {
Object[] listenerDefinition = parseListener(listElement);
@@ -92,7 +92,7 @@ class RedisListenerContainerParser extends AbstractSimpleBeanDefinitionParser {
/**
* Parses a listener definition. Returns the listener bean reference definition (as the array first entry) and its
* associated topics (also as bean definitions).
*
*
* @param element
* @return
*/
@@ -113,7 +113,7 @@ class RedisListenerContainerParser extends AbstractSimpleBeanDefinitionParser {
}
// assemble topics
Collection<Topic> topics = new ArrayList<Topic>();
Collection<Topic> topics = new ArrayList<>();
// get topic
String xTopics = element.getAttribute("topic");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014 the original author or authors.
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,12 +25,13 @@ import org.springframework.data.redis.RedisSystemException;
/**
* @author Christoph Strobl
* @author Mark Paluch
* @since 1.4
*/
public abstract class AbstractRedisConnection implements DefaultedRedisConnection {
private RedisSentinelConfiguration sentinelConfiguration;
private ConcurrentHashMap<RedisNode, RedisSentinelConnection> connectionCache = new ConcurrentHashMap<RedisNode, RedisSentinelConnection>();
private ConcurrentHashMap<RedisNode, RedisSentinelConnection> connectionCache = new ConcurrentHashMap<>();
/*
* (non-Javadoc)
@@ -73,7 +74,7 @@ public abstract class AbstractRedisConnection implements DefaultedRedisConnectio
/**
* Check if node is active by sending ping.
*
*
* @param node
* @return
*/
@@ -83,7 +84,7 @@ public abstract class AbstractRedisConnection implements DefaultedRedisConnectio
/**
* Get {@link RedisSentinelCommands} connected to given node.
*
*
* @param sentinel
* @return
*/

View File

@@ -99,7 +99,7 @@ public class ClusterCommandExecutor implements DisposableBean {
public <T> NodeResult<T> executeCommandOnArbitraryNode(ClusterCommandCallback<?, T> cmd) {
Assert.notNull(cmd, "ClusterCommandCallback must not be null!");
List<RedisClusterNode> nodes = new ArrayList<RedisClusterNode>(getClusterTopology().getActiveNodes());
List<RedisClusterNode> nodes = new ArrayList<>(getClusterTopology().getActiveNodes());
return executeCommandOnSingleNode(cmd, nodes.get(new Random().nextInt(nodes.size())));
}
@@ -133,7 +133,7 @@ public class ClusterCommandExecutor implements DisposableBean {
Assert.notNull(client, "Could not acquire resource for node. Is your cluster info up to date?");
try {
return new NodeResult<T>(node, cmd.doInCluster(client));
return new NodeResult<>(node, cmd.doInCluster(client));
} catch (RuntimeException ex) {
RuntimeException translatedException = convertToDataAccessExeption(ex);
@@ -188,7 +188,7 @@ public class ClusterCommandExecutor implements DisposableBean {
Assert.notNull(callback, "Callback must not be null!");
Assert.notNull(nodes, "Nodes must not be null!");
List<RedisClusterNode> resolvedRedisClusterNodes = new ArrayList<RedisClusterNode>();
List<RedisClusterNode> resolvedRedisClusterNodes = new ArrayList<>();
ClusterTopology topology = topologyProvider.getTopology();
for (final RedisClusterNode node : nodes) {
@@ -199,7 +199,7 @@ public class ClusterCommandExecutor implements DisposableBean {
}
}
Map<NodeExecution, Future<NodeResult<T>>> futures = new LinkedHashMap<NodeExecution, Future<NodeResult<T>>>();
Map<NodeExecution, Future<NodeResult<T>>> futures = new LinkedHashMap<>();
for (final RedisClusterNode node : resolvedRedisClusterNodes) {
futures.put(new NodeExecution(node), executor.submit(() -> executeCommandOnSingleNode(callback, node)));
@@ -212,10 +212,10 @@ public class ClusterCommandExecutor implements DisposableBean {
boolean done = false;
MulitNodeResult<T> result = new MulitNodeResult<T>();
Map<RedisClusterNode, Throwable> exceptions = new HashMap<RedisClusterNode, Throwable>();
MulitNodeResult<T> result = new MulitNodeResult<>();
Map<RedisClusterNode, Throwable> exceptions = new HashMap<>();
Set<String> saveGuard = new HashSet<String>();
Set<String> saveGuard = new HashSet<>();
while (!done) {
done = true;
@@ -255,7 +255,7 @@ public class ClusterCommandExecutor implements DisposableBean {
}
if (!exceptions.isEmpty()) {
throw new ClusterCommandExecutionFailureException(new ArrayList<Throwable>(exceptions.values()));
throw new ClusterCommandExecutionFailureException(new ArrayList<>(exceptions.values()));
}
return result;
}
@@ -270,7 +270,7 @@ public class ClusterCommandExecutor implements DisposableBean {
public <S, T> MulitNodeResult<T> executeMuliKeyCommand(final MultiKeyClusterCommandCallback<S, T> cmd,
Iterable<byte[]> keys) {
Map<RedisClusterNode, Set<byte[]>> nodeKeyMap = new HashMap<RedisClusterNode, Set<byte[]>>();
Map<RedisClusterNode, Set<byte[]>> nodeKeyMap = new HashMap<>();
for (byte[] key : keys) {
for (RedisClusterNode node : getClusterTopology().getKeyServingNodes(key)) {
@@ -278,14 +278,14 @@ public class ClusterCommandExecutor implements DisposableBean {
if (nodeKeyMap.containsKey(node)) {
nodeKeyMap.get(node).add(key);
} else {
Set<byte[]> keySet = new LinkedHashSet<byte[]>();
Set<byte[]> keySet = new LinkedHashSet<>();
keySet.add(key);
nodeKeyMap.put(node, keySet);
}
}
}
Map<NodeExecution, Future<NodeResult<T>>> futures = new LinkedHashMap<NodeExecution, Future<NodeResult<T>>>();
Map<NodeExecution, Future<NodeResult<T>>> futures = new LinkedHashMap<>();
for (final Entry<RedisClusterNode, Set<byte[]>> entry : nodeKeyMap.entrySet()) {
@@ -311,7 +311,7 @@ public class ClusterCommandExecutor implements DisposableBean {
Assert.notNull(client, "Could not acquire resource for node. Is your cluster info up to date?");
try {
return new NodeResult<T>(node, cmd.doInCluster(client, key), key);
return new NodeResult<>(node, cmd.doInCluster(client, key), key);
} catch (RuntimeException ex) {
RuntimeException translatedException = convertToDataAccessExeption(ex);
@@ -518,7 +518,7 @@ public class ClusterCommandExecutor implements DisposableBean {
*/
public static class MulitNodeResult<T> {
List<NodeResult<T>> nodeResults = new ArrayList<NodeResult<T>>();
List<NodeResult<T>> nodeResults = new ArrayList<>();
private void add(NodeResult<T> result) {
nodeResults.add(result);
@@ -549,7 +549,7 @@ public class ClusterCommandExecutor implements DisposableBean {
*/
public List<T> resultsAsListSortBy(byte[]... keys) {
ArrayList<NodeResult<T>> clone = new ArrayList<NodeResult<T>>(nodeResults);
ArrayList<NodeResult<T>> clone = new ArrayList<>(nodeResults);
Collections.sort(clone, new ResultByReferenceKeyPositionComperator(keys));
return toList(clone);
@@ -580,7 +580,7 @@ public class ClusterCommandExecutor implements DisposableBean {
private List<T> toList(Collection<NodeResult<T>> source) {
ArrayList<T> result = new ArrayList<T>();
ArrayList<T> result = new ArrayList<>();
for (NodeResult<T> nodeResult : source) {
result.add(nodeResult.getValue());
}
@@ -597,7 +597,7 @@ public class ClusterCommandExecutor implements DisposableBean {
List<ByteArrayWrapper> reference;
public ResultByReferenceKeyPositionComperator(byte[]... keys) {
reference = new ArrayList<ByteArrayWrapper>(new ByteArraySet(Arrays.asList(keys)));
reference = new ArrayList<>(new ByteArraySet(Arrays.asList(keys)));
}
@Override

View File

@@ -25,7 +25,7 @@ import org.springframework.util.StringUtils;
/**
* {@link ClusterTopology} holds snapshot like information about {@link RedisClusterNode}s.
*
*
* @author Christoph Strobl
* @author Mark Paluch
* @since 1.7
@@ -36,7 +36,7 @@ public class ClusterTopology {
/**
* Creates new instance of {@link ClusterTopology}.
*
*
* @param nodes can be {@literal null}.
*/
public ClusterTopology(Set<RedisClusterNode> nodes) {
@@ -45,7 +45,7 @@ public class ClusterTopology {
/**
* Get all {@link RedisClusterNode}s.
*
*
* @return never {@literal null}.
*/
public Set<RedisClusterNode> getNodes() {
@@ -55,12 +55,12 @@ public class ClusterTopology {
/**
* Get all nodes (master and slave) in cluster where {@code link-state} is {@literal connected} and {@code flags} does
* not contain {@literal fail} or {@literal fail?}.
*
*
* @return never {@literal null}.
*/
public Set<RedisClusterNode> getActiveNodes() {
Set<RedisClusterNode> activeNodes = new LinkedHashSet<RedisClusterNode>(nodes.size());
Set<RedisClusterNode> activeNodes = new LinkedHashSet<>(nodes.size());
for (RedisClusterNode node : nodes) {
if (node.isConnected() && !node.isMarkedAsFail()) {
activeNodes.add(node);
@@ -72,12 +72,12 @@ public class ClusterTopology {
/**
* Get all master nodes in cluster where {@code link-state} is {@literal connected} and {@code flags} does not contain
* {@literal fail} or {@literal fail?}.
*
*
* @return never {@literal null}.
*/
public Set<RedisClusterNode> getActiveMasterNodes() {
Set<RedisClusterNode> activeMasterNodes = new LinkedHashSet<RedisClusterNode>(nodes.size());
Set<RedisClusterNode> activeMasterNodes = new LinkedHashSet<>(nodes.size());
for (RedisClusterNode node : nodes) {
if (node.isMaster() && node.isConnected() && !node.isMarkedAsFail()) {
activeMasterNodes.add(node);
@@ -88,12 +88,12 @@ public class ClusterTopology {
/**
* Get all master nodes in cluster.
*
*
* @return never {@literal null}.
*/
public Set<RedisClusterNode> getMasterNodes() {
Set<RedisClusterNode> masterNodes = new LinkedHashSet<RedisClusterNode>(nodes.size());
Set<RedisClusterNode> masterNodes = new LinkedHashSet<>(nodes.size());
for (RedisClusterNode node : nodes) {
if (node.isMaster()) {
masterNodes.add(node);
@@ -104,13 +104,13 @@ public class ClusterTopology {
/**
* Get the {@link RedisClusterNode}s (master and slave) serving s specific slot.
*
*
* @param slot
* @return never {@literal null}.
*/
public Set<RedisClusterNode> getSlotServingNodes(int slot) {
Set<RedisClusterNode> slotServingNodes = new LinkedHashSet<RedisClusterNode>(nodes.size());
Set<RedisClusterNode> slotServingNodes = new LinkedHashSet<>(nodes.size());
for (RedisClusterNode node : nodes) {
if (node.servesSlot(slot)) {
slotServingNodes.add(node);
@@ -121,7 +121,7 @@ public class ClusterTopology {
/**
* Get the {@link RedisClusterNode} that is the current master serving the given key.
*
*
* @param key must not be {@literal null}.
* @return
* @throws ClusterStateFailureException
@@ -142,7 +142,7 @@ public class ClusterTopology {
/**
* Get the {@link RedisClusterNode} matching given {@literal host} and {@literal port}.
*
*
* @param host must not be {@literal null}.
* @param port
* @return

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2013 the original author or authors.
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,14 +22,14 @@ import java.util.concurrent.ConcurrentHashMap;
/**
* Enumeration of the Redis data types.
*
*
* @author Costin Leau
*/
public enum DataType {
NONE("none"), STRING("string"), LIST("list"), SET("set"), ZSET("zset"), HASH("hash");
private static final Map<String, DataType> codeLookup = new ConcurrentHashMap<String, DataType>(6);
private static final Map<String, DataType> codeLookup = new ConcurrentHashMap<>(6);
static {
for (DataType type : EnumSet.allOf(DataType.class))
@@ -45,7 +45,7 @@ public enum DataType {
/**
* Returns the code associated with the current enum.
*
*
* @return code of this enum
*/
public String code() {
@@ -54,7 +54,7 @@ public enum DataType {
/**
* Utility method for converting an enum code to an actual enum.
*
*
* @param code enum code
* @return actual enum corresponding to the given code
*/

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2013 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required byPattern applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,14 +20,14 @@ import java.util.List;
/**
* Default implementation for {@link SortParameters}.
*
*
* @author Costin Leau
*/
public class DefaultSortParameters implements SortParameters {
private byte[] byPattern;
private Range limit;
private final List<byte[]> getPattern = new ArrayList<byte[]>(4);
private final List<byte[]> getPattern = new ArrayList<>(4);
private Order order;
private Boolean alphabetic;
@@ -40,7 +40,7 @@ public class DefaultSortParameters implements SortParameters {
/**
* Constructs a new <code>DefaultSortParameters</code> instance.
*
*
* @param limit
* @param order
* @param alphabetic
@@ -51,7 +51,7 @@ public class DefaultSortParameters implements SortParameters {
/**
* Constructs a new <code>DefaultSortParameters</code> instance.
*
*
* @param byPattern
* @param limit
* @param getPattern

View File

@@ -79,7 +79,7 @@ public class DefaultStringRedisConnection implements StringRedisConnection, Deco
@SuppressWarnings("rawtypes") private Queue<Converter> pipelineConverters = new LinkedList<>();
@SuppressWarnings("rawtypes") private Queue<Converter> txConverters = new LinkedList<>();
private boolean deserializePipelineAndTxResults = false;
private IdentityConverter<Object, ?> identityConverter = new IdentityConverter();
private IdentityConverter<Object, ?> identityConverter = new IdentityConverter<>();
private class DeserializingConverter implements Converter<byte[], String> {
public String convert(byte[] source) {
@@ -284,7 +284,7 @@ public class DefaultStringRedisConnection implements StringRedisConnection, Deco
try {
List<Object> results = delegate.exec();
if (isPipelined()) {
pipelineConverters.add(new TransactionResultConverter(new LinkedList<Converter>(txConverters)));
pipelineConverters.add(new TransactionResultConverter(new LinkedList<>(txConverters)));
return results;
}
return convertResults(results, txConverters);
@@ -3200,54 +3200,6 @@ public class DefaultStringRedisConnection implements StringRedisConnection, Deco
return this.delegate.hScan(key, options);
}
/**
* Specifies if pipelined and tx results should be deserialized to Strings. If false, results of
* {@link #closePipeline()} and {@link #exec()} will be of the type returned by the underlying connection
*
* @param deserializePipelineAndTxResults Whether or not to deserialize pipeline and tx results
*/
public void setDeserializePipelineAndTxResults(boolean deserializePipelineAndTxResults) {
this.deserializePipelineAndTxResults = deserializePipelineAndTxResults;
}
private <T> T convertAndReturn(Object value, Converter converter) {
if (isFutureConversion()) {
addResultConverter(converter);
}
return ObjectUtils.nullSafeEquals(converter, identityConverter) ? (T) value : (T) converter.convert(value);
}
private void addResultConverter(Converter<?, ?> converter) {
if (isQueueing()) {
txConverters.add(converter);
} else {
pipelineConverters.add(converter);
}
}
private boolean isFutureConversion() {
return isPipelined() || isQueueing();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private List<Object> convertResults(List<Object> results, Queue<Converter> converters) {
if (!deserializePipelineAndTxResults || results == null) {
return results;
}
if (results.size() != converters.size()) {
// Some of the commands were done directly on the delegate, don't attempt to convert
log.warn("Delegate returned an unexpected number of results. Abandoning type conversion.");
return results;
}
List<Object> convertedResults = new ArrayList<Object>();
for (Object result : results) {
convertedResults.add(converters.remove().convert(result));
}
return convertedResults;
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.RedisServerCommands#setClientName(java.lang.String)
@@ -3290,29 +3242,23 @@ public class DefaultStringRedisConnection implements StringRedisConnection, Deco
@Override
public Cursor<Entry<String, String>> hScan(String key, ScanOptions options) {
return new ConvertingCursor<Map.Entry<byte[], byte[]>, Map.Entry<String, String>>(
return new ConvertingCursor<>(
this.delegate.hScan(this.serialize(key), options),
new Converter<Map.Entry<byte[], byte[]>, Map.Entry<String, String>>() {
source -> new Entry<String, String>() {
@Override
public Entry<String, String> convert(final Entry<byte[], byte[]> source) {
return new Map.Entry<String, String>() {
public String getKey() {
return bytesToString.convert(source.getKey());
}
@Override
public String getKey() {
return bytesToString.convert(source.getKey());
}
@Override
public String getValue() {
return bytesToString.convert(source.getValue());
}
@Override
public String getValue() {
return bytesToString.convert(source.getValue());
}
@Override
public String setValue(String value) {
throw new UnsupportedOperationException("Cannot set value for entry in cursor");
}
};
@Override
public String setValue(String value) {
throw new UnsupportedOperationException("Cannot set value for entry in cursor");
}
});
}
@@ -3323,7 +3269,7 @@ public class DefaultStringRedisConnection implements StringRedisConnection, Deco
*/
@Override
public Cursor<String> sScan(String key, ScanOptions options) {
return new ConvertingCursor<byte[], String>(this.delegate.sScan(this.serialize(key), options), bytesToString);
return new ConvertingCursor<>(this.delegate.sScan(this.serialize(key), options), bytesToString);
}
/*
@@ -3332,7 +3278,7 @@ public class DefaultStringRedisConnection implements StringRedisConnection, Deco
*/
@Override
public Cursor<StringTuple> zScan(String key, ScanOptions options) {
return new ConvertingCursor<Tuple, StringRedisConnection.StringTuple>(delegate.zScan(this.serialize(key), options),
return new ConvertingCursor<>(delegate.zScan(this.serialize(key), options),
new TupleConverter());
}
@@ -3507,6 +3453,55 @@ public class DefaultStringRedisConnection implements StringRedisConnection, Deco
delegate.migrate(key, target, dbIndex, option, timeout);
}
/**
* Specifies if pipelined and tx results should be deserialized to Strings. If false, results of
* {@link #closePipeline()} and {@link #exec()} will be of the type returned by the underlying connection
*
* @param deserializePipelineAndTxResults Whether or not to deserialize pipeline and tx results
*/
public void setDeserializePipelineAndTxResults(boolean deserializePipelineAndTxResults) {
this.deserializePipelineAndTxResults = deserializePipelineAndTxResults;
}
@SuppressWarnings("unchecked")
private <T> T convertAndReturn(Object value, Converter converter) {
if (isFutureConversion()) {
addResultConverter(converter);
}
return ObjectUtils.nullSafeEquals(converter, identityConverter) ? (T) value : (T) converter.convert(value);
}
private void addResultConverter(Converter<?, ?> converter) {
if (isQueueing()) {
txConverters.add(converter);
} else {
pipelineConverters.add(converter);
}
}
private boolean isFutureConversion() {
return isPipelined() || isQueueing();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private List<Object> convertResults(List<Object> results, Queue<Converter> converters) {
if (!deserializePipelineAndTxResults || results == null) {
return results;
}
if (results.size() != converters.size()) {
// Some of the commands were done directly on the delegate, don't attempt to convert
log.warn("Delegate returned an unexpected number of results. Abandoning type conversion.");
return results;
}
List<Object> convertedResults = new ArrayList<>(results.size());
for (Object result : results) {
convertedResults.add(converters.remove().convert(result));
}
return convertedResults;
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.connection.DecoratedRedisConnection#getDelegate()

View File

@@ -82,7 +82,7 @@ public interface ReactiveNumberCommands {
Assert.notNull(key, "Key must not be null!");
return new IncrByCommand<T>(key, null);
return new IncrByCommand<>(key, null);
}
/**
@@ -96,7 +96,7 @@ public interface ReactiveNumberCommands {
Assert.notNull(value, "Value must not be null!");
return new IncrByCommand<T>(getKey(), value);
return new IncrByCommand<>(getKey(), value);
}
/**
@@ -158,7 +158,7 @@ public interface ReactiveNumberCommands {
Assert.notNull(key, "Key must not be null!");
return new DecrByCommand<T>(key, null);
return new DecrByCommand<>(key, null);
}
/**
@@ -172,7 +172,7 @@ public interface ReactiveNumberCommands {
Assert.notNull(value, "Value must not be null!");
return new DecrByCommand<T>(getKey(), value);
return new DecrByCommand<>(getKey(), value);
}
/**
@@ -259,7 +259,7 @@ public interface ReactiveNumberCommands {
Assert.notNull(field, "Field must not be null!");
return new HIncrByCommand<T>(null, field, null);
return new HIncrByCommand<>(null, field, null);
}
/**
@@ -273,7 +273,7 @@ public interface ReactiveNumberCommands {
Assert.notNull(value, "Value must not be null!");
return new HIncrByCommand<T>(getKey(), field, value);
return new HIncrByCommand<>(getKey(), field, value);
}
/**
@@ -286,7 +286,7 @@ public interface ReactiveNumberCommands {
Assert.notNull(key, "Key must not be null!");
return new HIncrByCommand<T>(key, field, value);
return new HIncrByCommand<>(key, field, value);
}
/**

View File

@@ -267,15 +267,34 @@ public interface ReactiveSetCommands {
this.count = count;
}
/**
* Creates a new {@link SPopCommand} for a single member.
*
* @return a new {@link SPopCommand} for a single member.
*/
public static SPopCommand one() {
return new SPopCommand(null, 1L);
}
/**
* Creates a new {@link SPopCommand} for {@code count} members.
*
* @return a new {@link SPopCommand} for {@code count} members.
*/
public static SPopCommand members(long count) {
return new SPopCommand(null, count);
}
/**
* Applies the {@literal key}. Constructs a new command instance with all previously configured properties.
*
* @param key must not be {@literal null}.
* @return a new {@link SRemCommand} with {@literal key} applied.
*/
public SPopCommand from(ByteBuffer key) {
Assert.notNull(key, "Key must not be null!");
return new SPopCommand(key, count);
}
@@ -299,9 +318,10 @@ public interface ReactiveSetCommands {
}
/**
* Remove and return a random member from set at {@literal key}.
* Remove and return {@code count} random members from set at {@code key}.
*
* @param key must not be {@literal null}.
* @param count number of random members to pop from the set.
* @return
* @see <a href="http://redis.io/commands/spop">Redis Documentation: SPOP</a>
*/
@@ -742,7 +762,7 @@ public interface ReactiveSetCommands {
/**
* {@code SUNIONSTORE} command parameters.
*
*
* @author Christoph Strobl
* @see <a href="http://redis.io/commands/sunionstore">Redis Documentation: SUNIONSTORE</a>
*/

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2015-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,7 +25,7 @@ import org.springframework.util.CollectionUtils;
/**
* Representation of a Redis server within the cluster.
*
*
* @author Christoph Strobl
* @author Mark Paluch
* @since 1.7
@@ -42,7 +42,7 @@ public class RedisClusterNode extends RedisNode {
/**
* Creates new {@link RedisClusterNode} with empty {@link SlotRange}.
*
*
* @param host must not be {@literal null}.
* @param port
*/
@@ -64,7 +64,7 @@ public class RedisClusterNode extends RedisNode {
/**
* Creates new {@link RedisClusterNode} with given {@link SlotRange}.
*
*
* @param host must not be {@literal null}.
* @param port
* @param slotRange can be {@literal null}.
@@ -88,7 +88,7 @@ public class RedisClusterNode extends RedisNode {
/**
* Get the served {@link SlotRange}.
*
*
* @return never {@literal null}.
*/
public SlotRange getSlotRange() {
@@ -146,7 +146,7 @@ public class RedisClusterNode extends RedisNode {
/**
* Get {@link RedisClusterNodeBuilder} for creating new {@link RedisClusterNode}.
*
*
* @return never {@literal null}.
*/
public static RedisClusterNodeBuilder newRedisClusterNode() {
@@ -170,7 +170,7 @@ public class RedisClusterNode extends RedisNode {
Assert.notNull(lowerBound, "LowerBound must not be null!");
Assert.notNull(upperBound, "UpperBound must not be null!");
this.range = new LinkedHashSet<Integer>();
this.range = new LinkedHashSet<>();
for (int i = lowerBound; i <= upperBound; i++) {
this.range.add(i);
}
@@ -178,7 +178,7 @@ public class RedisClusterNode extends RedisNode {
public SlotRange(Collection<Integer> range) {
this.range = CollectionUtils.isEmpty(range) ? Collections.<Integer> emptySet()
: new LinkedHashSet<Integer>(range);
: new LinkedHashSet<>(range);
}
@Override
@@ -245,7 +245,7 @@ public class RedisClusterNode extends RedisNode {
/**
* Builder for creating new {@link RedisClusterNode}.
*
*
* @author Christoph Strobl
* @since 1.7
*/
@@ -310,7 +310,7 @@ public class RedisClusterNode extends RedisNode {
/**
* Set flags for node.
*
*
* @param flags
* @return
*/
@@ -322,7 +322,7 @@ public class RedisClusterNode extends RedisNode {
/**
* Set {@link SlotRange}.
*
*
* @param range
* @return
*/
@@ -334,7 +334,7 @@ public class RedisClusterNode extends RedisNode {
/**
* Set {@link LinkState}.
*
*
* @param linkState
* @return
*/

View File

@@ -43,7 +43,7 @@ public interface RedisGeoCommands {
/**
* Add {@link Point} with given member {@literal name} to {@literal key}.
*
*
* @param key must not be {@literal null}.
* @param point must not be {@literal null}.
* @param member must not be {@literal null}.
@@ -54,7 +54,7 @@ public interface RedisGeoCommands {
/**
* Add {@link GeoLocation} to {@literal key}.
*
*
* @param key must not be {@literal null}.
* @param location must not be {@literal null}.
* @return Number of elements added.
@@ -70,7 +70,7 @@ public interface RedisGeoCommands {
/**
* Add {@link Map} of member / {@link Point} pairs to {@literal key}.
*
*
* @param key must not be {@literal null}.
* @param memberCoordinateMap must not be {@literal null}.
* @return Number of elements added.
@@ -80,7 +80,7 @@ public interface RedisGeoCommands {
/**
* Add {@link GeoLocation}s to {@literal key}
*
*
* @param key must not be {@literal null}.
* @param locations must not be {@literal null}.
* @return Number of elements added.
@@ -90,7 +90,7 @@ public interface RedisGeoCommands {
/**
* Get the {@link Distance} between {@literal member1} and {@literal member2}.
*
*
* @param key must not be {@literal null}.
* @param member1 must not be {@literal null}.
* @param member2 must not be {@literal null}.
@@ -101,7 +101,7 @@ public interface RedisGeoCommands {
/**
* Get the {@link Distance} between {@literal member1} and {@literal member2} in the given {@link Metric}.
*
*
* @param key must not be {@literal null}.
* @param member1 must not be {@literal null}.
* @param member2 must not be {@literal null}.
@@ -113,7 +113,7 @@ public interface RedisGeoCommands {
/**
* Get Geohash representation of the position for one or more {@literal member}s.
*
*
* @param key must not be {@literal null}.
* @param members must not be {@literal null}.
* @return never {@literal null}.
@@ -123,7 +123,7 @@ public interface RedisGeoCommands {
/**
* Get the {@link Point} representation of positions for one or more {@literal member}s.
*
*
* @param key must not be {@literal null}.
* @param members must not be {@literal null}.
* @return never {@literal null}.
@@ -133,7 +133,7 @@ public interface RedisGeoCommands {
/**
* Get the {@literal member}s within the boundaries of a given {@link Circle}.
*
*
* @param key must not be {@literal null}.
* @param within must not be {@literal null}.
* @return never {@literal null}.
@@ -143,7 +143,7 @@ public interface RedisGeoCommands {
/**
* Get the {@literal member}s within the boundaries of a given {@link Circle} applying {@link GeoRadiusCommandArgs}.
*
*
* @param key must not be {@literal null}.
* @param within must not be {@literal null}.
* @param args must not be {@literal null}.
@@ -155,7 +155,7 @@ public interface RedisGeoCommands {
/**
* Get the {@literal member}s within the circle defined by the {@literal members} coordinates and given
* {@literal radius}.
*
*
* @param key must not be {@literal null}.
* @param member must not be {@literal null}.
* @param radius
@@ -169,7 +169,7 @@ public interface RedisGeoCommands {
/**
* Get the {@literal member}s within the circle defined by the {@literal members} coordinates and given
* {@link Distance}.
*
*
* @param key must not be {@literal null}.
* @param member must not be {@literal null}.
* @param radius must not be {@literal null}.
@@ -181,7 +181,7 @@ public interface RedisGeoCommands {
/**
* Get the {@literal member}s within the circle defined by the {@literal members} coordinates, given {@link Distance}
* and {@link GeoRadiusCommandArgs}.
*
*
* @param key must not be {@literal null}.
* @param member must not be {@literal null}.
* @param radius must not be {@literal null}.
@@ -204,14 +204,14 @@ public interface RedisGeoCommands {
/**
* Additional arguments (like count/sort/...) to be used with {@link RedisGeoCommands}.
*
*
* @author Ninad Divadkar
* @author Christoph Strobl
* @since 1.8
*/
class GeoRadiusCommandArgs implements Cloneable {
Set<Flag> flags = new LinkedHashSet<Flag>(2, 1);
Set<Flag> flags = new LinkedHashSet<>(2, 1);
Long limit;
Direction sortDirection;
@@ -219,7 +219,7 @@ public interface RedisGeoCommands {
/**
* Create new {@link GeoRadiusCommandArgs}.
*
*
* @return never {@literal null}.
*/
public static GeoRadiusCommandArgs newGeoRadiusArgs() {
@@ -250,7 +250,7 @@ public interface RedisGeoCommands {
/**
* Sort returned items from the nearest to the furthest, relative to the center.
*
*
* @return never {@literal null}.
*/
public GeoRadiusCommandArgs sortAscending() {
@@ -261,7 +261,7 @@ public interface RedisGeoCommands {
/**
* Sort returned items from the furthest to the nearest, relative to the center.
*
*
* @return never {@literal null}.
*/
public GeoRadiusCommandArgs sortDescending() {
@@ -272,7 +272,7 @@ public interface RedisGeoCommands {
/**
* Limit the results to the first N matching items.
*
*
* @param count
* @return never {@literal null}.
*/
@@ -333,7 +333,7 @@ public interface RedisGeoCommands {
/**
* {@link GeoLocation} representing a {@link Point} associated with a {@literal name}.
*
*
* @author Christoph Strobl
* @param <T>
* @since 1.8
@@ -361,7 +361,7 @@ public interface RedisGeoCommands {
/**
* Creates a new {@link DistanceUnit} using the given muliplier.
*
*
* @param multiplier the earth radius at equator.
*/
private DistanceUnit(double multiplier, String abbreviation) {
@@ -378,7 +378,7 @@ public interface RedisGeoCommands {
return multiplier;
}
/*
/*
* (non-Javadoc)
* @see org.springframework.data.geo.Metric#getAbbreviation()
*/

View File

@@ -23,7 +23,7 @@ import org.springframework.data.redis.core.ScanOptions;
/**
* Set-specific commands supported by Redis.
*
*
* @author Costin Leau
* @author Christoph Strobl
* @author Mark Paluch
@@ -63,7 +63,7 @@ public interface RedisSetCommands {
* Remove and return {@code count} random members from set at {@code key}.
*
* @param key must not be {@literal null}.
* @param count the number of random members to pop from the set.
* @param count number of random members to pop from the set.
* @return empty {@link List} if set does not exist. Never {@literal null}.
* @see <a href="http://redis.io/commands/spop">Redis Documentation: SPOP</a>
* @since 2.0

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2017 the original author or authors.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -37,7 +37,7 @@ import org.springframework.data.redis.serializer.RedisSerializer;
/**
* Convenience extension of {@link RedisConnection} that accepts and returns {@link String}s instead of byte arrays.
* Uses a {@link RedisSerializer} underneath to perform the conversion.
*
*
* @author Costin Leau
* @author Christoph Strobl
* @author Thomas Darimont
@@ -53,7 +53,7 @@ public interface StringRedisConnection extends RedisConnection {
/**
* String-friendly ZSet tuple.
*/
public interface StringTuple extends Tuple {
interface StringTuple extends Tuple {
String getValueAsString();
}

View File

@@ -17,7 +17,16 @@ package org.springframework.data.redis.connection.convert;
import lombok.RequiredArgsConstructor;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.core.convert.converter.Converter;
@@ -66,7 +75,7 @@ abstract public class Converters {
static {
flagLookupMap = new LinkedHashMap<String, RedisClusterNode.Flag>(Flag.values().length, 1);
flagLookupMap = new LinkedHashMap<>(Flag.values().length, 1);
for (Flag flag : Flag.values()) {
flagLookupMap.put(flag.getRaw(), flag);
}
@@ -113,7 +122,7 @@ abstract public class Converters {
String raw = args[FLAGS_INDEX];
Set<Flag> flags = new LinkedHashSet<RedisClusterNode.Flag>(8, 1);
Set<Flag> flags = new LinkedHashSet<>(8, 1);
if (StringUtils.hasText(raw)) {
for (String flag : raw.split(",")) {
flags.add(flagLookupMap.get(flag));
@@ -134,7 +143,7 @@ abstract public class Converters {
private SlotRange parseSlotRange(String[] args) {
Set<Integer> slots = new LinkedHashSet<Integer>();
Set<Integer> slots = new LinkedHashSet<>();
for (int i = SLOTS_INDEX; i < args.length; i++) {
@@ -241,7 +250,7 @@ abstract public class Converters {
return Collections.emptySet();
}
Set<RedisClusterNode> nodes = new LinkedHashSet<RedisClusterNode>(lines.size());
Set<RedisClusterNode> nodes = new LinkedHashSet<>(lines.size());
for (String line : lines) {
nodes.add(toClusterNode(line));
@@ -268,7 +277,7 @@ abstract public class Converters {
}
public static List<Object> toObjects(Set<Tuple> tuples) {
List<Object> tupleArgs = new ArrayList<Object>(tuples.size() * 2);
List<Object> tupleArgs = new ArrayList<>(tuples.size() * 2);
for (Tuple tuple : tuples) {
tupleArgs.add(tuple.getScore());
tupleArgs.add(tuple.getValue());
@@ -316,13 +325,7 @@ abstract public class Converters {
*/
public static Converter<Long, Long> secondsToTimeUnit(final TimeUnit timeUnit) {
return new Converter<Long, Long>() {
@Override
public Long convert(Long seconds) {
return secondsToTimeUnit(seconds, timeUnit);
}
};
return seconds -> secondsToTimeUnit(seconds, timeUnit);
}
/**
@@ -353,13 +356,7 @@ abstract public class Converters {
*/
public static Converter<Long, Long> millisecondsToTimeUnit(final TimeUnit timeUnit) {
return new Converter<Long, Long>() {
@Override
public Long convert(Long seconds) {
return millisecondsToTimeUnit(seconds, timeUnit);
}
};
return seconds -> millisecondsToTimeUnit(seconds, timeUnit);
}
/**
@@ -371,7 +368,7 @@ abstract public class Converters {
*/
public static <V> Converter<GeoResults<GeoLocation<byte[]>>, GeoResults<GeoLocation<V>>> deserializingGeoResultsConverter(
RedisSerializer<V> serializer) {
return new DeserializingGeoResultsConverter<V>(serializer);
return new DeserializingGeoResultsConverter<>(serializer);
}
/**
@@ -414,8 +411,9 @@ abstract public class Converters {
* @return the converter.
* @since 2.0
*/
public static Converter<Map<?, ?>, Properties> mapToPropertiesConverter() {
return MAP_TO_PROPERTIES;
@SuppressWarnings("unchecked")
public static <K, V> Converter<Map<K, V>, Properties> mapToPropertiesConverter() {
return (Converter) MAP_TO_PROPERTIES;
}
/**
@@ -462,18 +460,18 @@ abstract public class Converters {
public GeoResults<GeoLocation<V>> convert(GeoResults<GeoLocation<byte[]>> source) {
if (source == null) {
return new GeoResults<GeoLocation<V>>(Collections.<GeoResult<GeoLocation<V>>> emptyList());
return new GeoResults<>(Collections.<GeoResult<GeoLocation<V>>> emptyList());
}
List<GeoResult<GeoLocation<V>>> values = new ArrayList<GeoResult<GeoLocation<V>>>(source.getContent().size());
List<GeoResult<GeoLocation<V>>> values = new ArrayList<>(source.getContent().size());
for (GeoResult<GeoLocation<byte[]>> value : source.getContent()) {
values.add(new GeoResult<GeoLocation<V>>(
new GeoLocation<V>(serializer.deserialize(value.getContent().getName()), value.getContent().getPoint()),
values.add(new GeoResult<>(
new GeoLocation<>(serializer.deserialize(value.getContent().getName()), value.getContent().getPoint()),
value.getDistance()));
}
return new GeoResults<GeoLocation<V>>(values, source.getAverageDistance().getMetric());
return new GeoResults<>(values, source.getAverageDistance().getMetric());
}
}
}

View File

@@ -1,3 +1,18 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.redis.connection.convert;
import java.util.ArrayList;
@@ -7,8 +22,9 @@ import org.springframework.core.convert.converter.Converter;
/**
* Converts a List of values of one type to a List of values of another type
*
*
* @author Jennifer Hickey
* @author Mark Paluch
* @param <S> The type of elements in the List to convert
* @param <T> The type of elements in the converted List
*/
@@ -24,14 +40,16 @@ public class ListConverter<S, T> implements Converter<List<S>, List<T>> {
}
public List<T> convert(List<S> source) {
if (source == null) {
return null;
}
List<T> results = new ArrayList<T>();
List<T> results = new ArrayList<>();
for (S result : source) {
results.add(itemConverter.convert(result));
}
return results;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013 the original author or authors.
* Copyright 2013-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,7 @@ import org.springframework.core.convert.converter.Converter;
/**
* Converts a Map of values of one key/value type to a Map of values of another type
*
*
* @author Jennifer Hickey
* @param <S> The type of keys and values in the Map to convert
* @param <T> The type of keys and values in the converted Map
@@ -40,18 +40,23 @@ public class MapConverter<S, T> implements Converter<Map<S, S>, Map<T, T>> {
}
public Map<T, T> convert(Map<S, S> source) {
if (source == null) {
return null;
}
Map<T, T> results;
if (source instanceof LinkedHashMap) {
results = new LinkedHashMap<T, T>();
results = new LinkedHashMap<>();
} else {
results = new HashMap<T, T>();
results = new HashMap<>();
}
for (Map.Entry<S, S> result : source.entrySet()) {
results.put(itemConverter.convert(result.getKey()), itemConverter.convert(result.getValue()));
}
return results;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013 the original author or authors.
* Copyright 2013-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,7 @@ import org.springframework.core.convert.converter.Converter;
/**
* Converts a Set of values of one type to a Set of values of another type
*
*
* @author Jennifer Hickey
* @param <S> The type of elements in the Set to convert
* @param <T> The type of elements in the converted Set
@@ -40,18 +40,23 @@ public class SetConverter<S, T> implements Converter<Set<S>, Set<T>> {
}
public Set<T> convert(Set<S> source) {
if (source == null) {
return null;
}
Set<T> results;
if (source instanceof LinkedHashSet) {
results = new LinkedHashSet<T>();
results = new LinkedHashSet<>();
} else {
results = new HashSet<T>();
results = new HashSet<>();
}
for (S result : source) {
results.add(itemConverter.convert(result));
}
return results;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014 the original author or authors.
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,12 +25,12 @@ import org.springframework.data.redis.core.types.RedisClientInfo.RedisClientInfo
/**
* {@link Converter} implementation to create one {@link RedisClientInfo} per line entry in given {@link String} array.
*
*
* <pre>
* ## sample of single line
* addr=127.0.0.1:60311 fd=6 name= age=4059 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=32768 obl=0 oll=0 omem=0 events=r cmd=client
* </pre>
*
*
* @author Christoph Strobl
* @since 1.3
*/
@@ -42,10 +42,12 @@ public class StringToRedisClientInfoConverter implements Converter<String[], Lis
if (lines == null) {
return Collections.emptyList();
}
List<RedisClientInfo> infos = new ArrayList<RedisClientInfo>(lines.length);
List<RedisClientInfo> infos = new ArrayList<>(lines.length);
for (String line : lines) {
infos.add(RedisClientInfoBuilder.fromString(line));
}
return infos;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013 the original author or authors.
* Copyright 2013-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,13 +27,13 @@ import org.springframework.data.redis.connection.FutureResult;
/**
* Converts the results of transaction exec using a supplied Queue of {@link FutureResult}s. Converts any Exception
* objects returned in the list as well, using the supplied Exception {@link Converter}
*
*
* @author Jennifer Hickey
* @param <T> The type of {@link FutureResult} of the individual tx operations
*/
public class TransactionResultConverter<T> implements Converter<List<Object>, List<Object>> {
private Queue<FutureResult<T>> txResults = new LinkedList<FutureResult<T>>();
private Queue<FutureResult<T>> txResults = new LinkedList<>();
private Converter<Exception, DataAccessException> exceptionConverter;
@@ -44,14 +44,18 @@ public class TransactionResultConverter<T> implements Converter<List<Object>, Li
}
public List<Object> convert(List<Object> execResults) {
if (execResults == null) {
return null;
}
if (execResults.size() != txResults.size()) {
throw new IllegalArgumentException("Incorrect number of transaction results. Expected: " + txResults.size()
+ " Actual: " + execResults.size());
}
List<Object> convertedResults = new ArrayList<Object>();
List<Object> convertedResults = new ArrayList<>();
for (Object result : execResults) {
FutureResult<T> futureResult = txResults.remove();
if (result instanceof Exception) {
@@ -61,6 +65,7 @@ public class TransactionResultConverter<T> implements Converter<List<Object>, Li
convertedResults.add(futureResult.convert(result));
}
}
return convertedResults;
}
}

View File

@@ -111,29 +111,14 @@ abstract public class JedisConverters extends Converters {
static {
BYTES_TO_STRING_CONVERTER = new Converter<byte[], String>() {
@Override
public String convert(byte[] source) {
return source == null ? null : SafeEncoder.encode(source);
}
};
BYTES_TO_STRING_CONVERTER = source -> source == null ? null : SafeEncoder.encode(source);
BYTES_LIST_TO_STRING_LIST_CONVERTER = new ListConverter<>(BYTES_TO_STRING_CONVERTER);
STRING_TO_BYTES = new Converter<String, byte[]>() {
public byte[] convert(String source) {
return source == null ? null : SafeEncoder.encode(source);
}
};
STRING_TO_BYTES = source -> source == null ? null : SafeEncoder.encode(source);
STRING_LIST_TO_BYTE_LIST = new ListConverter<>(STRING_TO_BYTES);
STRING_SET_TO_BYTE_SET = new SetConverter<>(STRING_TO_BYTES);
STRING_MAP_TO_BYTE_MAP = new MapConverter<>(STRING_TO_BYTES);
TUPLE_CONVERTER = new Converter<redis.clients.jedis.Tuple, Tuple>() {
public Tuple convert(redis.clients.jedis.Tuple source) {
return source != null ? new DefaultTuple(source.getBinaryElement(), source.getScore()) : null;
}
};
TUPLE_CONVERTER = source -> source != null ? new DefaultTuple(source.getBinaryElement(), source.getScore()) : null;
TUPLE_SET_TO_TUPLE_SET = new SetConverter<>(TUPLE_CONVERTER);
TUPLE_LIST_TO_TUPLE_LIST_CONVERTER = new ListConverter<>(TUPLE_CONVERTER);
PLUS_BYTES = toBytes("+");
@@ -141,18 +126,13 @@ abstract public class JedisConverters extends Converters {
POSITIVE_INFINITY_BYTES = toBytes("+inf");
NEGATIVE_INFINITY_BYTES = toBytes("-inf");
OBJECT_TO_CLUSTER_NODE_CONVERTER = new Converter<Object, RedisClusterNode>() {
OBJECT_TO_CLUSTER_NODE_CONVERTER = infos -> {
@Override
public RedisClusterNode convert(Object infos) {
List<Object> values = (List<Object>) infos;
RedisClusterNode.SlotRange range = new RedisClusterNode.SlotRange(((Number) values.get(0)).intValue(),
((Number) values.get(1)).intValue());
List<Object> nodeInfo = (List<Object>) values.get(2);
return new RedisClusterNode(JedisConverters.toString((byte[]) nodeInfo.get(0)),
((Number) nodeInfo.get(1)).intValue(), range);
}
List<Object> values = (List<Object>) infos;
RedisClusterNode.SlotRange range = new RedisClusterNode.SlotRange(((Number) values.get(0)).intValue(),
((Number) values.get(1)).intValue());
List<Object> nodeInfo = (List<Object>) values.get(2);
return new RedisClusterNode(toString((byte[]) nodeInfo.get(0)), ((Number) nodeInfo.get(1)).intValue(), range);
};
EX = toBytes("EX");
@@ -195,25 +175,18 @@ abstract public class JedisConverters extends Converters {
};
STRING_LIST_TO_TIME_CONVERTER = new Converter<List<String>, Long>() {
STRING_LIST_TO_TIME_CONVERTER = source -> {
@Override
public Long convert(List<String> source) {
Assert.notEmpty(source, "Received invalid result from server. Expected 2 items in collection.");
Assert.isTrue(source.size() == 2,
"Received invalid nr of arguments from redis server. Expected 2 received " + source.size());
Assert.notEmpty(source, "Received invalid result from server. Expected 2 items in collection.");
Assert.isTrue(source.size() == 2,
"Received invalid nr of arguments from redis server. Expected 2 received " + source.size());
return toTimeMillis(source.get(0), source.get(1));
}
return toTimeMillis(source.get(0), source.get(1));
};
GEO_COORDINATE_TO_POINT_CONVERTER = new Converter<redis.clients.jedis.GeoCoordinate, Point>() {
@Override
public Point convert(redis.clients.jedis.GeoCoordinate geoCoordinate) {
return geoCoordinate != null ? new Point(geoCoordinate.getLongitude(), geoCoordinate.getLatitude()) : null;
}
};
GEO_COORDINATE_TO_POINT_CONVERTER = geoCoordinate -> geoCoordinate != null
? new Point(geoCoordinate.getLongitude(), geoCoordinate.getLatitude())
: null;
LIST_GEO_COORDINATE_TO_POINT_CONVERTER = new ListConverter<>(GEO_COORDINATE_TO_POINT_CONVERTER);
}
@@ -620,7 +593,7 @@ abstract public class JedisConverters extends Converters {
* @author Christoph Strobl
* @since 1.8
*/
static enum GeoResultsConverterFactory {
enum GeoResultsConverterFactory {
INSTANCE;
@@ -658,7 +631,7 @@ abstract public class JedisConverters extends Converters {
* @author Christoph Strobl
* @since 1.8
*/
static enum GeoResultConverterFactory {
enum GeoResultConverterFactory {
INSTANCE;

View File

@@ -134,11 +134,11 @@ public class LettuceConnection extends AbstractRedisConnection {
}
}
LettuceResult newLettuceResult(Future resultHolder) {
LettuceResult newLettuceResult(Future<?> resultHolder) {
return new LettuceResult(resultHolder);
}
<T> LettuceResult newLettuceResult(Future resultHolder, Converter<T, ?> converter) {
<T> LettuceResult newLettuceResult(Future<T> resultHolder, Converter<T, ?> converter) {
return new LettuceResult(resultHolder, converter);
}
@@ -150,7 +150,7 @@ public class LettuceConnection extends AbstractRedisConnection {
}
}
LettuceStatusResult newLettuceStatusResult(Future resultHolder) {
LettuceStatusResult newLettuceStatusResult(Future<?> resultHolder) {
return new LettuceStatusResult(resultHolder);
}

View File

@@ -15,7 +15,6 @@
*/
package org.springframework.data.redis.connection.lettuce;
import io.lettuce.core.RedisFuture;
import io.lettuce.core.ScanArgs;
import io.lettuce.core.ValueScanCursor;
import io.lettuce.core.cluster.api.async.RedisClusterAsyncCommands;
@@ -266,7 +265,7 @@ class LettuceSetCommands implements RedisSetCommands {
try {
if (isPipelined()) {
pipeline(connection.newLettuceResult(getAsyncConnection().spop(key, count),
(Converter<Set<byte[]>, List<byte[]>>) ArrayList::new));
ArrayList::new));
return null;
}
if (isQueueing()) {
@@ -309,8 +308,7 @@ class LettuceSetCommands implements RedisSetCommands {
public List<byte[]> sRandMember(byte[] key, long count) {
try {
if (isPipelined()) {
pipeline(connection.newLettuceResult((RedisFuture) getAsyncConnection().srandmember(key, count),
LettuceConverters.bytesCollectionToBytesList()));
pipeline(connection.newLettuceResult(getAsyncConnection().srandmember(key, count)));
return null;
}
if (isQueueing()) {

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2017 the original author or authors.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -28,13 +28,13 @@ import org.springframework.util.ObjectUtils;
/**
* Base implementation for a subscription handling the channel/pattern registration so subclasses only have to deal with
* the actual registration/unregistration.
*
*
* @author Costin Leau
*/
public abstract class AbstractSubscription implements Subscription {
private final Collection<ByteArrayWrapper> channels = new ArrayList<ByteArrayWrapper>(2);
private final Collection<ByteArrayWrapper> patterns = new ArrayList<ByteArrayWrapper>(2);
private final Collection<ByteArrayWrapper> channels = new ArrayList<>(2);
private final Collection<ByteArrayWrapper> patterns = new ArrayList<>(2);
private final AtomicBoolean alive = new AtomicBoolean(true);
private final MessageListener listener;
@@ -46,7 +46,7 @@ public abstract class AbstractSubscription implements Subscription {
* Constructs a new <code>AbstractSubscription</code> instance. Allows channels and patterns to be added to the
* subscription w/o triggering a subscription action (as some clients (Jedis) require an initial call before entering
* into listening mode).
*
*
* @param listener
* @param channels
* @param patterns
@@ -65,14 +65,14 @@ public abstract class AbstractSubscription implements Subscription {
/**
* Subscribe to the given channels.
*
*
* @param channels channels to subscribe to
*/
protected abstract void doSubscribe(byte[]... channels);
/**
* Channel unsubscribe.
*
*
* @param all true if all the channels are unsubscribed (used as a hint for the underlying implementation).
* @param channels channels to be unsubscribed
*/
@@ -80,14 +80,14 @@ public abstract class AbstractSubscription implements Subscription {
/**
* Subscribe to the given patterns
*
*
* @param patterns patterns to subscribe to
*/
protected abstract void doPsubscribe(byte[]... patterns);
/**
* Pattern unsubscribe.
*
*
* @param all true if all the patterns are unsubscribed (used as a hint for the underlying implementation).
* @param patterns patterns to be unsubscribed
*/
@@ -218,7 +218,7 @@ public abstract class AbstractSubscription implements Subscription {
}
private static Collection<byte[]> clone(Collection<ByteArrayWrapper> col) {
Collection<byte[]> list = new ArrayList<byte[]>(col.size());
Collection<byte[]> list = new ArrayList<>(col.size());
for (ByteArrayWrapper wrapper : col) {
list.add(wrapper.getArray().clone());
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2015-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,7 +25,7 @@ public class ByteArraySet implements Set<ByteArrayWrapper> {
LinkedHashSet<ByteArrayWrapper> delegate;
public ByteArraySet() {
this.delegate = new LinkedHashSet<ByteArrayWrapper>();
this.delegate = new LinkedHashSet<>();
}
public ByteArraySet(Collection<byte[]> values) {
@@ -131,7 +131,7 @@ public class ByteArraySet implements Set<ByteArrayWrapper> {
public Set<byte[]> asRawSet() {
Set<byte[]> result = new LinkedHashSet<byte[]>();
Set<byte[]> result = new LinkedHashSet<>();
for (ByteArrayWrapper wrapper : delegate) {
result.add(wrapper.getArray());
}

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2013 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -25,7 +25,7 @@ import java.util.Set;
/**
* Simple class containing various decoding utilities.
*
*
* @author Costin Leau
*/
public abstract class DecodeUtils {
@@ -47,7 +47,7 @@ public abstract class DecodeUtils {
}
public static Map<byte[], byte[]> encodeMap(Map<String, byte[]> map) {
Map<byte[], byte[]> result = new LinkedHashMap<byte[], byte[]>(map.size());
Map<byte[], byte[]> result = new LinkedHashMap<>(map.size());
for (Map.Entry<String, byte[]> entry : map.entrySet()) {
result.put(encode(entry.getKey()), entry.getValue());
}
@@ -55,7 +55,7 @@ public abstract class DecodeUtils {
}
public static Map<String, byte[]> decodeMap(Map<byte[], byte[]> tuple) {
Map<String, byte[]> result = new LinkedHashMap<String, byte[]>(tuple.size());
Map<String, byte[]> result = new LinkedHashMap<>(tuple.size());
for (Map.Entry<byte[], byte[]> entry : tuple.entrySet()) {
result.put(decode(entry.getKey()), entry.getValue());
}
@@ -63,7 +63,7 @@ public abstract class DecodeUtils {
}
public static Set<byte[]> convertToSet(Collection<String> keys) {
Set<byte[]> set = new LinkedHashSet<byte[]>(keys.size());
Set<byte[]> set = new LinkedHashSet<>(keys.size());
for (String string : keys) {
set.add(encode(string));
@@ -72,7 +72,7 @@ public abstract class DecodeUtils {
}
public static List<byte[]> convertToList(Collection<String> keys) {
List<byte[]> set = new ArrayList<byte[]>(keys.size());
List<byte[]> set = new ArrayList<>(keys.size());
for (String string : keys) {
set.add(encode(string));

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2016 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -37,11 +37,12 @@ import org.springframework.util.CollectionUtils;
/**
* Internal base class used by various RedisTemplate XXXOperations implementations.
*
*
* @author Costin Leau
* @author Jennifer Hickey
* @author Christoph Strobl
* @author David Liu
* @author Mark Paluch
*/
abstract class AbstractOperations<K, V> {
@@ -97,10 +98,13 @@ abstract class AbstractOperations<K, V> {
@SuppressWarnings("unchecked")
byte[] rawKey(Object key) {
Assert.notNull(key, "non null key required");
if (keySerializer() == null && key instanceof byte[]) {
return (byte[]) key;
}
return keySerializer().serialize(key);
}
@@ -111,18 +115,22 @@ abstract class AbstractOperations<K, V> {
@SuppressWarnings("unchecked")
byte[] rawValue(Object value) {
if (valueSerializer() == null && value instanceof byte[]) {
return (byte[]) value;
}
return valueSerializer().serialize(value);
}
byte[][] rawValues(Object... values) {
final byte[][] rawValues = new byte[values.length][];
byte[][] rawValues = new byte[values.length][];
int i = 0;
for (Object value : values) {
rawValues[i++] = rawValue(value);
}
return rawValues;
}
@@ -155,7 +163,8 @@ abstract class AbstractOperations<K, V> {
}
<HK> byte[][] rawHashKeys(HK... hashKeys) {
final byte[][] rawHashKeys = new byte[hashKeys.length][];
byte[][] rawHashKeys = new byte[hashKeys.length][];
int i = 0;
for (HK hashKey : hashKeys) {
rawHashKeys[i++] = rawHashKey(hashKey);
@@ -165,6 +174,7 @@ abstract class AbstractOperations<K, V> {
@SuppressWarnings("unchecked")
<HV> byte[] rawHashValue(HV value) {
if (hashValueSerializer() == null & value instanceof byte[]) {
return (byte[]) value;
}
@@ -172,7 +182,8 @@ abstract class AbstractOperations<K, V> {
}
byte[][] rawKeys(K key, K otherKey) {
final byte[][] rawKeys = new byte[2][];
byte[][] rawKeys = new byte[2][];
rawKeys[0] = rawKey(key);
rawKeys[1] = rawKey(key);
@@ -184,7 +195,8 @@ abstract class AbstractOperations<K, V> {
}
byte[][] rawKeys(K key, Collection<K> keys) {
final byte[][] rawKeys = new byte[keys.size() + (key != null ? 1 : 0)][];
byte[][] rawKeys = new byte[keys.size() + (key != null ? 1 : 0)][];
int i = 0;
@@ -211,7 +223,7 @@ abstract class AbstractOperations<K, V> {
if (rawValues == null) {
return null;
}
Set<TypedTuple<V>> set = new LinkedHashSet<TypedTuple<V>>(rawValues.size());
Set<TypedTuple<V>> set = new LinkedHashSet<>(rawValues.size());
for (Tuple rawValue : rawValues) {
set.add(deserializeTuple(rawValue));
}
@@ -232,7 +244,7 @@ abstract class AbstractOperations<K, V> {
if (values == null) {
return null;
}
Set<Tuple> rawTuples = new LinkedHashSet<Tuple>(values.size());
Set<Tuple> rawTuples = new LinkedHashSet<>(values.size());
for (TypedTuple<V> value : values) {
byte[] rawValue;
if (valueSerializer() == null && value.getValue() instanceof byte[]) {
@@ -276,7 +288,7 @@ abstract class AbstractOperations<K, V> {
return null;
}
Map<HK, HV> map = new LinkedHashMap<HK, HV>(entries.size());
Map<HK, HV> map = new LinkedHashMap<>(entries.size());
for (Map.Entry<byte[], byte[]> entry : entries.entrySet()) {
map.put((HK) deserializeHashKey(entry.getKey()), (HV) deserializeHashValue(entry.getValue()));
@@ -303,7 +315,7 @@ abstract class AbstractOperations<K, V> {
if (CollectionUtils.isEmpty(keys)) {
return Collections.emptySet();
}
Set<K> result = new LinkedHashSet<K>(keys.size());
Set<K> result = new LinkedHashSet<>(keys.size());
for (byte[] key : keys) {
result.add(deserializeKey(key));
}
@@ -340,7 +352,7 @@ abstract class AbstractOperations<K, V> {
/**
* Deserialize {@link GeoLocation} of {@link GeoResults}.
*
*
* @param source can be {@literal null}.
* @return converted or {@literal null}.
* @since 1.8

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2016 the original author or authors.
*
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -29,7 +29,7 @@ import org.springframework.data.redis.connection.RedisGeoCommands.GeoRadiusComma
/**
* Default implementation of {@link BoundGeoOperations}.
*
*
* @author Ninad Divadkar
* @author Christoph Strobl
* @since 1.8
@@ -44,7 +44,7 @@ class DefaultBoundGeoOperations<K, M> extends DefaultBoundKeyOperations<K> imple
* @param key must not be {@literal null}.
* @param operations must not be {@literal null}.
*/
public DefaultBoundGeoOperations(K key, RedisOperations<K, M> operations) {
DefaultBoundGeoOperations(K key, RedisOperations<K, M> operations) {
super(key, operations);
this.ops = operations.opsForGeo();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2016 the original author or authors.
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,8 +30,8 @@ import org.springframework.data.redis.connection.DataType;
* @author Christoph Strobl
* @author Ninad Divadkar
*/
class DefaultBoundHashOperations<H, HK, HV> extends DefaultBoundKeyOperations<H> implements
BoundHashOperations<H, HK, HV> {
class DefaultBoundHashOperations<H, HK, HV> extends DefaultBoundKeyOperations<H>
implements BoundHashOperations<H, HK, HV> {
private final HashOperations<H, HK, HV> ops;
@@ -41,74 +41,149 @@ class DefaultBoundHashOperations<H, HK, HV> extends DefaultBoundKeyOperations<H>
* @param key
* @param operations
*/
public DefaultBoundHashOperations(H key, RedisOperations<H, ?> operations) {
DefaultBoundHashOperations(H key, RedisOperations<H, ?> operations) {
super(key, operations);
this.ops = operations.opsForHash();
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundHashOperations#delete(java.lang.Object[])
*/
@Override
public Long delete(Object... keys) {
return ops.delete(getKey(), keys);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundHashOperations#get(java.lang.Object)
*/
@Override
public HV get(Object key) {
return ops.get(getKey(), key);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundHashOperations#multiGet(java.util.Collection)
*/
@Override
public List<HV> multiGet(Collection<HK> hashKeys) {
return ops.multiGet(getKey(), hashKeys);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundHashOperations#getOperations()
*/
@Override
public RedisOperations<H, ?> getOperations() {
return ops.getOperations();
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundHashOperations#hasKey(java.lang.Object)
*/
@Override
public Boolean hasKey(Object key) {
return ops.hasKey(getKey(), key);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundHashOperations#increment(java.lang.Object, long)
*/
@Override
public Long increment(HK key, long delta) {
return ops.increment(getKey(), key, delta);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundHashOperations#increment(java.lang.Object, double)
*/
@Override
public Double increment(HK key, double delta) {
return ops.increment(getKey(), key, delta);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundHashOperations#keys()
*/
@Override
public Set<HK> keys() {
return ops.keys(getKey());
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundHashOperations#size()
*/
@Override
public Long size() {
return ops.size(getKey());
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundHashOperations#putAll(java.util.Map)
*/
@Override
public void putAll(Map<? extends HK, ? extends HV> m) {
ops.putAll(getKey(), m);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundHashOperations#put(java.lang.Object, java.lang.Object)
*/
@Override
public void put(HK key, HV value) {
ops.put(getKey(), key, value);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundHashOperations#putIfAbsent(java.lang.Object, java.lang.Object)
*/
@Override
public Boolean putIfAbsent(HK key, HV value) {
return ops.putIfAbsent(getKey(), key, value);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundHashOperations#values()
*/
@Override
public List<HV> values() {
return ops.values(getKey());
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundHashOperations#entries()
*/
@Override
public Map<HK, HV> entries() {
return ops.entries(getKey());
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundKeyOperations#getType()
*/
@Override
public DataType getType() {
return DataType.HASH;
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundHashOperations#hscan(java.lang.Object)
* @see org.springframework.data.redis.core.BoundHashOperations#scan(org.springframework.data.redis.core.ScanOptions)
*/
@Override
public Cursor<Entry<HK, HV>> scan(ScanOptions options) {

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2013 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,7 +20,7 @@ import java.util.concurrent.TimeUnit;
/**
* Default {@link BoundKeyOperations} implementation. Meant for internal usage.
*
*
* @author Costin Leau
*/
abstract class DefaultBoundKeyOperations<K> implements BoundKeyOperations<K> {
@@ -28,11 +28,17 @@ abstract class DefaultBoundKeyOperations<K> implements BoundKeyOperations<K> {
private K key;
private final RedisOperations<K, ?> ops;
public DefaultBoundKeyOperations(K key, RedisOperations<K, ?> operations) {
DefaultBoundKeyOperations(K key, RedisOperations<K, ?> operations) {
setKey(key);
this.ops = operations;
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundKeyOperations#getKey()
*/
@Override
public K getKey() {
return key;
}
@@ -41,22 +47,47 @@ abstract class DefaultBoundKeyOperations<K> implements BoundKeyOperations<K> {
this.key = key;
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundKeyOperations#expire(long, java.util.concurrent.TimeUnit)
*/
@Override
public Boolean expire(long timeout, TimeUnit unit) {
return ops.expire(key, timeout, unit);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundKeyOperations#expireAt(java.util.Date)
*/
@Override
public Boolean expireAt(Date date) {
return ops.expireAt(key, date);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundKeyOperations#getExpire()
*/
@Override
public Long getExpire() {
return ops.getExpire(key);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundKeyOperations#persist()
*/
@Override
public Boolean persist() {
return ops.persist(key);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundKeyOperations#rename(java.lang.Object)
*/
@Override
public void rename(K newKey) {
if (ops.hasKey(key)) {
ops.rename(key, newKey);

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2013 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,7 +22,7 @@ import org.springframework.data.redis.connection.DataType;
/**
* Default implementation for {@link BoundListOperations}.
*
*
* @author Costin Leau
*/
class DefaultBoundListOperations<K, V> extends DefaultBoundKeyOperations<K> implements BoundListOperations<K, V> {
@@ -31,91 +31,188 @@ class DefaultBoundListOperations<K, V> extends DefaultBoundKeyOperations<K> impl
/**
* Constructs a new <code>DefaultBoundListOperations</code> instance.
*
*
* @param key
* @param operations
*/
public DefaultBoundListOperations(K key, RedisOperations<K, V> operations) {
DefaultBoundListOperations(K key, RedisOperations<K, V> operations) {
super(key, operations);
this.ops = operations.opsForList();
}
@Override
public RedisOperations<K, V> getOperations() {
return ops.getOperations();
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#index(long)
*/
@Override
public V index(long index) {
return ops.index(getKey(), index);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#leftPop()
*/
@Override
public V leftPop() {
return ops.leftPop(getKey());
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#leftPop(long, java.util.concurrent.TimeUnit)
*/
@Override
public V leftPop(long timeout, TimeUnit unit) {
return ops.leftPop(getKey(), timeout, unit);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#leftPush(java.lang.Object)
*/
@Override
public Long leftPush(V value) {
return ops.leftPush(getKey(), value);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#leftPushAll(java.lang.Object[])
*/
@Override
public Long leftPushAll(V... values) {
return ops.leftPushAll(getKey(), values);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#leftPushIfPresent(java.lang.Object)
*/
@Override
public Long leftPushIfPresent(V value) {
return ops.leftPushIfPresent(getKey(), value);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#leftPush(java.lang.Object, java.lang.Object)
*/
@Override
public Long leftPush(V pivot, V value) {
return ops.leftPush(getKey(), pivot, value);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#size()
*/
@Override
public Long size() {
return ops.size(getKey());
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#range(long, long)
*/
@Override
public List<V> range(long start, long end) {
return ops.range(getKey(), start, end);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#remove(long, java.lang.Object)
*/
@Override
public Long remove(long i, Object value) {
return ops.remove(getKey(), i, value);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#rightPop()
*/
@Override
public V rightPop() {
return ops.rightPop(getKey());
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#rightPop(long, java.util.concurrent.TimeUnit)
*/
@Override
public V rightPop(long timeout, TimeUnit unit) {
return ops.rightPop(getKey(), timeout, unit);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#rightPushIfPresent(java.lang.Object)
*/
@Override
public Long rightPushIfPresent(V value) {
return ops.rightPushIfPresent(getKey(), value);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#rightPush(java.lang.Object)
*/
@Override
public Long rightPush(V value) {
return ops.rightPush(getKey(), value);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#rightPushAll(java.lang.Object[])
*/
@Override
public Long rightPushAll(V... values) {
return ops.rightPushAll(getKey(), values);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#rightPush(java.lang.Object, java.lang.Object)
*/
@Override
public Long rightPush(V pivot, V value) {
return ops.rightPush(getKey(), pivot, value);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#trim(long, long)
*/
@Override
public void trim(long start, long end) {
ops.trim(getKey(), start, end);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundListOperations#set(long, java.lang.Object)
*/
@Override
public void set(long index, V value) {
ops.set(getKey(), index, value);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundKeyOperations#getType()
*/
@Override
public DataType getType() {
return DataType.LIST;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2014 the original author or authors.
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,7 +24,7 @@ import org.springframework.data.redis.connection.DataType;
/**
* Default implementation for {@link BoundSetOperations}.
*
*
* @author Costin Leau
* @author Christoph Strobl
*/
@@ -34,114 +34,235 @@ class DefaultBoundSetOperations<K, V> extends DefaultBoundKeyOperations<K> imple
/**
* Constructs a new <code>DefaultBoundSetOperations</code> instance.
*
*
* @param key
* @param operations
*/
DefaultBoundSetOperations(K key, RedisOperations<K, V> operations) {
super(key, operations);
this.ops = operations.opsForSet();
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#add(java.lang.Object[])
*/
@Override
public Long add(V... values) {
return ops.add(getKey(), values);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#diff(java.lang.Object)
*/
@Override
public Set<V> diff(K key) {
return ops.difference(getKey(), key);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#diff(java.util.Collection)
*/
@Override
public Set<V> diff(Collection<K> keys) {
return ops.difference(getKey(), keys);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#diffAndStore(java.lang.Object, java.lang.Object)
*/
@Override
public void diffAndStore(K key, K destKey) {
ops.differenceAndStore(getKey(), key, destKey);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#diffAndStore(java.util.Collection, java.lang.Object)
*/
@Override
public void diffAndStore(Collection<K> keys, K destKey) {
ops.differenceAndStore(getKey(), keys, destKey);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#getOperations()
*/
@Override
public RedisOperations<K, V> getOperations() {
return ops.getOperations();
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#intersect(java.lang.Object)
*/
@Override
public Set<V> intersect(K key) {
return ops.intersect(getKey(), key);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#intersect(java.util.Collection)
*/
@Override
public Set<V> intersect(Collection<K> keys) {
return ops.intersect(getKey(), keys);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#intersectAndStore(java.lang.Object, java.lang.Object)
*/
@Override
public void intersectAndStore(K key, K destKey) {
ops.intersectAndStore(getKey(), key, destKey);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#intersectAndStore(java.util.Collection, java.lang.Object)
*/
@Override
public void intersectAndStore(Collection<K> keys, K destKey) {
ops.intersectAndStore(getKey(), keys, destKey);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#isMember(java.lang.Object)
*/
@Override
public Boolean isMember(Object o) {
return ops.isMember(getKey(), o);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#members()
*/
@Override
public Set<V> members() {
return ops.members(getKey());
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#move(java.lang.Object, java.lang.Object)
*/
@Override
public Boolean move(K destKey, V value) {
return ops.move(getKey(), value, destKey);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#randomMember()
*/
@Override
public V randomMember() {
return ops.randomMember(getKey());
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#distinctRandomMembers(long)
*/
@Override
public Set<V> distinctRandomMembers(long count) {
return ops.distinctRandomMembers(getKey(), count);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#randomMembers(long)
*/
@Override
public List<V> randomMembers(long count) {
return ops.randomMembers(getKey(), count);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#remove(java.lang.Object[])
*/
@Override
public Long remove(Object... values) {
return ops.remove(getKey(), values);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#pop()
*/
@Override
public V pop() {
return ops.pop(getKey());
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#size()
*/
@Override
public Long size() {
return ops.size(getKey());
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#union(java.lang.Object)
*/
@Override
public Set<V> union(K key) {
return ops.union(getKey(), key);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#union(java.util.Collection)
*/
@Override
public Set<V> union(Collection<K> keys) {
return ops.union(getKey(), keys);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#unionAndStore(java.lang.Object, java.lang.Object)
*/
@Override
public void unionAndStore(K key, K destKey) {
ops.unionAndStore(getKey(), key, destKey);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#unionAndStore(java.util.Collection, java.lang.Object)
*/
@Override
public void unionAndStore(Collection<K> keys, K destKey) {
ops.unionAndStore(getKey(), keys, destKey);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundKeyOperations#getType()
*/
@Override
public DataType getType() {
return DataType.SET;
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundSetOperations#sScan(org.springframework.data.redis.core.ScanOptions)
* @see org.springframework.data.redis.core.BoundSetOperations#scan(org.springframework.data.redis.core.ScanOptions)
*/
@Override
public Cursor<V> scan(ScanOptions options) {

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2013 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -28,63 +28,129 @@ class DefaultBoundValueOperations<K, V> extends DefaultBoundKeyOperations<K> imp
/**
* Constructs a new <code>DefaultBoundValueOperations</code> instance.
*
*
* @param key
* @param operations
*/
public DefaultBoundValueOperations(K key, RedisOperations<K, V> operations) {
DefaultBoundValueOperations(K key, RedisOperations<K, V> operations) {
super(key, operations);
this.ops = operations.opsForValue();
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundValueOperations#get()
*/
@Override
public V get() {
return ops.get(getKey());
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundValueOperations#getAndSet(java.lang.Object)
*/
@Override
public V getAndSet(V value) {
return ops.getAndSet(getKey(), value);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundValueOperations#increment(long)
*/
@Override
public Long increment(long delta) {
return ops.increment(getKey(), delta);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundValueOperations#increment(double)
*/
@Override
public Double increment(double delta) {
return ops.increment(getKey(), delta);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundValueOperations#append(java.lang.String)
*/
@Override
public Integer append(String value) {
return ops.append(getKey(), value);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundValueOperations#get(long, long)
*/
@Override
public String get(long start, long end) {
return ops.get(getKey(), start, end);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundValueOperations#set(java.lang.Object, long, java.util.concurrent.TimeUnit)
*/
@Override
public void set(V value, long timeout, TimeUnit unit) {
ops.set(getKey(), value, timeout, unit);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundValueOperations#set(java.lang.Object)
*/
@Override
public void set(V value) {
ops.set(getKey(), value);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundValueOperations#setIfAbsent(java.lang.Object)
*/
@Override
public Boolean setIfAbsent(V value) {
return ops.setIfAbsent(getKey(), value);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundValueOperations#set(java.lang.Object, long)
*/
@Override
public void set(V value, long offset) {
ops.set(getKey(), value, offset);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundValueOperations#size()
*/
@Override
public Long size() {
return ops.size(getKey());
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundValueOperations#getOperations()
*/
@Override
public RedisOperations<K, V> getOperations() {
return ops.getOperations();
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundKeyOperations#getType()
*/
@Override
public DataType getType() {
return DataType.STRING;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2016 the original author or authors.
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,7 +26,7 @@ import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
/**
* Default implementation for {@link BoundZSetOperations}.
*
*
* @author Costin Leau
* @author Christoph Strobl
* @author Mark Paluch
@@ -37,63 +37,129 @@ class DefaultBoundZSetOperations<K, V> extends DefaultBoundKeyOperations<K> impl
/**
* Constructs a new <code>DefaultBoundZSetOperations</code> instance.
*
*
* @param key
* @param operations
*/
public DefaultBoundZSetOperations(K key, RedisOperations<K, V> operations) {
DefaultBoundZSetOperations(K key, RedisOperations<K, V> operations) {
super(key, operations);
this.ops = operations.opsForZSet();
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#add(java.lang.Object, double)
*/
@Override
public Boolean add(V value, double score) {
return ops.add(getKey(), value, score);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#add(java.util.Set)
*/
@Override
public Long add(Set<TypedTuple<V>> tuples) {
return ops.add(getKey(), tuples);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#incrementScore(java.lang.Object, double)
*/
@Override
public Double incrementScore(V value, double delta) {
return ops.incrementScore(getKey(), value, delta);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#getOperations()
*/
@Override
public RedisOperations<K, V> getOperations() {
return ops.getOperations();
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#intersectAndStore(java.lang.Object, java.lang.Object)
*/
@Override
public void intersectAndStore(K otherKey, K destKey) {
ops.intersectAndStore(getKey(), otherKey, destKey);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#intersectAndStore(java.util.Collection, java.lang.Object)
*/
@Override
public void intersectAndStore(Collection<K> otherKeys, K destKey) {
ops.intersectAndStore(getKey(), otherKeys, destKey);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#range(long, long)
*/
@Override
public Set<V> range(long start, long end) {
return ops.range(getKey(), start, end);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#rangeByScore(double, double)
*/
@Override
public Set<V> rangeByScore(double min, double max) {
return ops.rangeByScore(getKey(), min, max);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#rangeByScoreWithScores(double, double)
*/
@Override
public Set<TypedTuple<V>> rangeByScoreWithScores(double min, double max) {
return ops.rangeByScoreWithScores(getKey(), min, max);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#rangeWithScores(long, long)
*/
@Override
public Set<TypedTuple<V>> rangeWithScores(long start, long end) {
return ops.rangeWithScores(getKey(), start, end);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#reverseRangeByScore(double, double)
*/
@Override
public Set<V> reverseRangeByScore(double min, double max) {
return ops.reverseRangeByScore(getKey(), min, max);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#reverseRangeByScoreWithScores(double, double)
*/
@Override
public Set<TypedTuple<V>> reverseRangeByScoreWithScores(double min, double max) {
return ops.reverseRangeByScoreWithScores(getKey(), min, max);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#reverseRangeWithScores(long, long)
*/
@Override
public Set<TypedTuple<V>> reverseRangeWithScores(long start, long end) {
return ops.reverseRangeWithScores(getKey(), start, end);
}
@@ -116,34 +182,74 @@ class DefaultBoundZSetOperations<K, V> extends DefaultBoundKeyOperations<K> impl
return ops.rangeByLex(getKey(), range, limit);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#rank(java.lang.Object)
*/
@Override
public Long rank(Object o) {
return ops.rank(getKey(), o);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#reverseRank(java.lang.Object)
*/
@Override
public Long reverseRank(Object o) {
return ops.reverseRank(getKey(), o);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#score(java.lang.Object)
*/
@Override
public Double score(Object o) {
return ops.score(getKey(), o);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#remove(java.lang.Object[])
*/
@Override
public Long remove(Object... values) {
return ops.remove(getKey(), values);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#removeRange(long, long)
*/
@Override
public void removeRange(long start, long end) {
ops.removeRange(getKey(), start, end);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#removeRangeByScore(double, double)
*/
@Override
public void removeRangeByScore(double min, double max) {
ops.removeRangeByScore(getKey(), min, max);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#reverseRange(long, long)
*/
@Override
public Set<V> reverseRange(long start, long end) {
return ops.reverseRange(getKey(), start, end);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#count(double, double)
*/
@Override
public Long count(double min, double max) {
return ops.count(getKey(), min, max);
}
@@ -166,14 +272,29 @@ class DefaultBoundZSetOperations<K, V> extends DefaultBoundKeyOperations<K> impl
return ops.zCard(getKey());
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#unionAndStore(java.lang.Object, java.lang.Object)
*/
@Override
public void unionAndStore(K otherKey, K destKey) {
ops.unionAndStore(getKey(), otherKey, destKey);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundZSetOperations#unionAndStore(java.util.Collection, java.lang.Object)
*/
@Override
public void unionAndStore(Collection<K> otherKeys, K destKey) {
ops.unionAndStore(getKey(), otherKeys, destKey);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.BoundKeyOperations#getType()
*/
@Override
public DataType getType() {
return DataType.ZSET;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2015-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,6 @@ import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisClusterCommands.AddSlots;
import org.springframework.data.redis.connection.RedisClusterConnection;
import org.springframework.data.redis.connection.RedisClusterNode;
@@ -29,22 +28,22 @@ import org.springframework.util.Assert;
/**
* Default {@link ClusterOperations} implementation.
*
*
* @author Christoph Strobl
* @since 1.7
* @param <K>
* @param <V>
*/
public class DefaultClusterOperations<K, V> extends AbstractOperations<K, V> implements ClusterOperations<K, V> {
class DefaultClusterOperations<K, V> extends AbstractOperations<K, V> implements ClusterOperations<K, V> {
private final RedisTemplate<K, V> template;
/**
* Creates new {@link DefaultClusterOperations} delegating to the given {@link RedisTemplate}.
*
*
* @param template must not be {@literal null}.
*/
public DefaultClusterOperations(RedisTemplate<K, V> template) {
DefaultClusterOperations(RedisTemplate<K, V> template) {
super(template);
this.template = template;
@@ -59,13 +58,7 @@ public class DefaultClusterOperations<K, V> extends AbstractOperations<K, V> imp
Assert.notNull(node, "ClusterNode must not be null.");
return execute(new RedisClusterCallback<Set<K>>() {
@Override
public Set<K> doInRedis(RedisClusterConnection connection) throws DataAccessException {
return deserializeKeys(connection.keys(node, rawKey(pattern)));
}
});
return execute(connection -> deserializeKeys(connection.keys(node, rawKey(pattern))));
}
/*
@@ -77,13 +70,7 @@ public class DefaultClusterOperations<K, V> extends AbstractOperations<K, V> imp
Assert.notNull(node, "ClusterNode must not be null.");
return execute(new RedisClusterCallback<K>() {
@Override
public K doInRedis(RedisClusterConnection connection) throws DataAccessException {
return deserializeKey(connection.randomKey(node));
}
});
return execute(connection -> deserializeKey(connection.randomKey(node)));
}
/*
@@ -95,13 +82,7 @@ public class DefaultClusterOperations<K, V> extends AbstractOperations<K, V> imp
Assert.notNull(node, "ClusterNode must not be null.");
return execute(new RedisClusterCallback<String>() {
@Override
public String doInRedis(RedisClusterConnection connection) throws DataAccessException {
return connection.ping(node);
}
});
return execute(connection -> connection.ping(node));
}
/*
@@ -113,13 +94,9 @@ public class DefaultClusterOperations<K, V> extends AbstractOperations<K, V> imp
Assert.notNull(node, "ClusterNode must not be null.");
execute(new RedisClusterCallback<Void>() {
@Override
public Void doInRedis(RedisClusterConnection connection) throws DataAccessException {
connection.clusterAddSlots(node, slots);
return null;
}
execute((RedisClusterCallback<Void>) connection -> {
connection.clusterAddSlots(node, slots);
return null;
});
}
@@ -145,13 +122,9 @@ public class DefaultClusterOperations<K, V> extends AbstractOperations<K, V> imp
Assert.notNull(node, "ClusterNode must not be null.");
execute(new RedisClusterCallback<Void>() {
@Override
public Void doInRedis(RedisClusterConnection connection) throws DataAccessException {
connection.bgReWriteAof(node);
return null;
}
execute((RedisClusterCallback<Void>) connection -> {
connection.bgReWriteAof(node);
return null;
});
}
@@ -164,13 +137,9 @@ public class DefaultClusterOperations<K, V> extends AbstractOperations<K, V> imp
Assert.notNull(node, "ClusterNode must not be null.");
execute(new RedisClusterCallback<Void>() {
@Override
public Void doInRedis(RedisClusterConnection connection) throws DataAccessException {
connection.bgSave(node);
return null;
}
execute((RedisClusterCallback<Void>) connection -> {
connection.bgSave(node);
return null;
});
}
@@ -183,13 +152,9 @@ public class DefaultClusterOperations<K, V> extends AbstractOperations<K, V> imp
Assert.notNull(node, "ClusterNode must not be null.");
execute(new RedisClusterCallback<Void>() {
@Override
public Void doInRedis(RedisClusterConnection connection) throws DataAccessException {
connection.clusterMeet(node);
return null;
}
execute((RedisClusterCallback<Void>) connection -> {
connection.clusterMeet(node);
return null;
});
}
@@ -202,13 +167,9 @@ public class DefaultClusterOperations<K, V> extends AbstractOperations<K, V> imp
Assert.notNull(node, "ClusterNode must not be null.");
execute(new RedisClusterCallback<Void>() {
@Override
public Void doInRedis(RedisClusterConnection connection) throws DataAccessException {
connection.clusterForget(node);
return null;
}
execute((RedisClusterCallback<Void>) connection -> {
connection.clusterForget(node);
return null;
});
}
@@ -221,13 +182,9 @@ public class DefaultClusterOperations<K, V> extends AbstractOperations<K, V> imp
Assert.notNull(node, "ClusterNode must not be null.");
execute(new RedisClusterCallback<Void>() {
@Override
public Void doInRedis(RedisClusterConnection connection) throws DataAccessException {
connection.flushDb(node);
return null;
}
execute((RedisClusterCallback<Void>) connection -> {
connection.flushDb(node);
return null;
});
}
@@ -240,13 +197,7 @@ public class DefaultClusterOperations<K, V> extends AbstractOperations<K, V> imp
Assert.notNull(node, "ClusterNode must not be null.");
return execute(new RedisClusterCallback<Collection<RedisClusterNode>>() {
@Override
public Collection<RedisClusterNode> doInRedis(RedisClusterConnection connection) throws DataAccessException {
return connection.clusterGetSlaves(node);
}
});
return execute(connection -> connection.clusterGetSlaves(node));
}
/*
@@ -258,13 +209,9 @@ public class DefaultClusterOperations<K, V> extends AbstractOperations<K, V> imp
Assert.notNull(node, "ClusterNode must not be null.");
execute(new RedisClusterCallback<Void>() {
@Override
public Void doInRedis(RedisClusterConnection connection) throws DataAccessException {
connection.save(node);
return null;
}
execute((RedisClusterCallback<Void>) connection -> {
connection.save(node);
return null;
});
}
@@ -277,13 +224,9 @@ public class DefaultClusterOperations<K, V> extends AbstractOperations<K, V> imp
Assert.notNull(node, "ClusterNode must not be null.");
execute(new RedisClusterCallback<Void>() {
@Override
public Void doInRedis(RedisClusterConnection connection) throws DataAccessException {
connection.shutdown(node);
return null;
}
execute((RedisClusterCallback<Void>) connection -> {
connection.shutdown(node);
return null;
});
}
@@ -297,27 +240,23 @@ public class DefaultClusterOperations<K, V> extends AbstractOperations<K, V> imp
Assert.notNull(source, "Source node must not be null.");
Assert.notNull(target, "Target node must not be null.");
execute(new RedisClusterCallback<Void>() {
execute((RedisClusterCallback<Void>) connection -> {
@Override
public Void doInRedis(RedisClusterConnection connection) throws DataAccessException {
connection.clusterSetSlot(target, slot, AddSlots.IMPORTING);
connection.clusterSetSlot(source, slot, AddSlots.MIGRATING);
List<byte[]> keys = connection.clusterGetKeysInSlot(slot, Integer.MAX_VALUE);
connection.clusterSetSlot(target, slot, AddSlots.IMPORTING);
connection.clusterSetSlot(source, slot, AddSlots.MIGRATING);
List<byte[]> keys = connection.clusterGetKeysInSlot(slot, Integer.MAX_VALUE);
for (byte[] key : keys) {
connection.migrate(key, source, 0, MigrateOption.COPY);
}
connection.clusterSetSlot(target, slot, AddSlots.NODE);
return null;
for (byte[] key : keys) {
connection.migrate(key, source, 0, MigrateOption.COPY);
}
connection.clusterSetSlot(target, slot, AddSlots.NODE);
return null;
});
}
/**
* Executed wrapped command upon {@link RedisClusterConnection}.
*
*
* @param callback
* @return
*/

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016 the original author or authors.
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,7 +25,6 @@ import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisGeoCommands.GeoLocation;
import org.springframework.data.redis.connection.RedisGeoCommands.GeoRadiusCommandArgs;
@@ -36,11 +35,11 @@ import org.springframework.data.redis.connection.RedisGeoCommands.GeoRadiusComma
* @author Christoph Strobl
* @since 1.8
*/
public class DefaultGeoOperations<K, M> extends AbstractOperations<K, M> implements GeoOperations<K, M> {
class DefaultGeoOperations<K, M> extends AbstractOperations<K, M> implements GeoOperations<K, M> {
/**
* Creates new {@link DefaultGeoOperations}.
*
*
* @param template must not be {@literal null}.
*/
DefaultGeoOperations(RedisTemplate<K, M> template) {
@@ -52,17 +51,12 @@ public class DefaultGeoOperations<K, M> extends AbstractOperations<K, M> impleme
* @see org.springframework.data.redis.core.GeoOperations#geoAdd(java.lang.Object, org.springframework.data.geo.Point, java.lang.Object)
*/
@Override
public Long geoAdd(K key, final Point point, M member) {
public Long geoAdd(K key, Point point, M member) {
final byte[] rawKey = rawKey(key);
final byte[] rawMember = rawValue(member);
byte[] rawKey = rawKey(key);
byte[] rawMember = rawValue(member);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.geoAdd(rawKey, point, rawMember);
}
}, true);
return execute(connection -> connection.geoAdd(rawKey, point, rawMember), true);
}
/*
@@ -81,20 +75,15 @@ public class DefaultGeoOperations<K, M> extends AbstractOperations<K, M> impleme
@Override
public Long geoAdd(K key, Map<M, Point> memberCoordinateMap) {
final byte[] rawKey = rawKey(key);
final Map<byte[], Point> rawMemberCoordinateMap = new HashMap<byte[], Point>();
byte[] rawKey = rawKey(key);
Map<byte[], Point> rawMemberCoordinateMap = new HashMap<>();
for (M member : memberCoordinateMap.keySet()) {
final byte[] rawMember = rawValue(member);
byte[] rawMember = rawValue(member);
rawMemberCoordinateMap.put(rawMember, memberCoordinateMap.get(member));
}
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.geoAdd(rawKey, rawMemberCoordinateMap);
}
}, true);
return execute(connection -> connection.geoAdd(rawKey, rawMemberCoordinateMap), true);
}
/*
@@ -104,7 +93,7 @@ public class DefaultGeoOperations<K, M> extends AbstractOperations<K, M> impleme
@Override
public Long geoAdd(K key, Iterable<GeoLocation<M>> locations) {
Map<M, Point> memberCoordinateMap = new LinkedHashMap<M, Point>();
Map<M, Point> memberCoordinateMap = new LinkedHashMap<>();
for (GeoLocation<M> location : locations) {
memberCoordinateMap.put(location.getName(), location.getPoint());
}
@@ -117,18 +106,13 @@ public class DefaultGeoOperations<K, M> extends AbstractOperations<K, M> impleme
* @see org.springframework.data.redis.core.GeoOperations#geoDist(java.lang.Object, java.lang.Object, java.lang.Object)
*/
@Override
public Distance geoDist(K key, final M member1, final M member2) {
public Distance geoDist(K key, M member1, M member2) {
final byte[] rawKey = rawKey(key);
final byte[] rawMember1 = rawValue(member1);
final byte[] rawMember2 = rawValue(member2);
byte[] rawKey = rawKey(key);
byte[] rawMember1 = rawValue(member1);
byte[] rawMember2 = rawValue(member2);
return execute(new RedisCallback<Distance>() {
public Distance doInRedis(RedisConnection connection) {
return connection.geoDist(rawKey, rawMember1, rawMember2);
}
}, true);
return execute(connection -> connection.geoDist(rawKey, rawMember1, rawMember2), true);
}
/*
@@ -136,18 +120,13 @@ public class DefaultGeoOperations<K, M> extends AbstractOperations<K, M> impleme
* @see org.springframework.data.redis.core.GeoOperations#geoDist(java.lang.Object, java.lang.Object, java.lang.Object, org.springframework.data.geo.Metric)
*/
@Override
public Distance geoDist(K key, M member1, M member2, final Metric metric) {
public Distance geoDist(K key, M member1, M member2, Metric metric) {
final byte[] rawKey = rawKey(key);
final byte[] rawMember1 = rawValue(member1);
final byte[] rawMember2 = rawValue(member2);
byte[] rawKey = rawKey(key);
byte[] rawMember1 = rawValue(member1);
byte[] rawMember2 = rawValue(member2);
return execute(new RedisCallback<Distance>() {
public Distance doInRedis(RedisConnection connection) {
return connection.geoDist(rawKey, rawMember1, rawMember2, metric);
}
}, true);
return execute(connection -> connection.geoDist(rawKey, rawMember1, rawMember2, metric), true);
}
/*
@@ -155,17 +134,12 @@ public class DefaultGeoOperations<K, M> extends AbstractOperations<K, M> impleme
* @see org.springframework.data.redis.core.GeoOperations#geoHash(java.lang.Object, java.lang.Object[])
*/
@Override
public List<String> geoHash(K key, final M... members) {
public List<String> geoHash(K key, M... members) {
final byte[] rawKey = rawKey(key);
final byte[][] rawMembers = rawValues(members);
byte[] rawKey = rawKey(key);
byte[][] rawMembers = rawValues(members);
return execute(new RedisCallback<List<String>>() {
public List<String> doInRedis(RedisConnection connection) {
return connection.geoHash(rawKey, rawMembers);
}
}, true);
return execute(connection -> connection.geoHash(rawKey, rawMembers), true);
}
/*
@@ -174,15 +148,10 @@ public class DefaultGeoOperations<K, M> extends AbstractOperations<K, M> impleme
*/
@Override
public List<Point> geoPos(K key, M... members) {
final byte[] rawKey = rawKey(key);
final byte[][] rawMembers = rawValues(members);
byte[] rawKey = rawKey(key);
byte[][] rawMembers = rawValues(members);
return execute(new RedisCallback<List<Point>>() {
public List<Point> doInRedis(RedisConnection connection) {
return connection.geoPos(rawKey, rawMembers);
}
}, true);
return execute(connection -> connection.geoPos(rawKey, rawMembers), true);
}
/*
@@ -190,16 +159,11 @@ public class DefaultGeoOperations<K, M> extends AbstractOperations<K, M> impleme
* @see org.springframework.data.redis.core.GeoOperations#geoRadius(java.lang.Object, org.springframework.data.geo.Circle)
*/
@Override
public GeoResults<GeoLocation<M>> geoRadius(K key, final Circle within) {
public GeoResults<GeoLocation<M>> geoRadius(K key, Circle within) {
final byte[] rawKey = rawKey(key);
byte[] rawKey = rawKey(key);
GeoResults<GeoLocation<byte[]>> raw = execute(new RedisCallback<GeoResults<GeoLocation<byte[]>>>() {
public GeoResults<GeoLocation<byte[]>> doInRedis(RedisConnection connection) {
return connection.geoRadius(rawKey, within);
}
}, true);
GeoResults<GeoLocation<byte[]>> raw = execute(connection -> connection.geoRadius(rawKey, within), true);
return deserializeGeoResults(raw);
}
@@ -209,16 +173,11 @@ public class DefaultGeoOperations<K, M> extends AbstractOperations<K, M> impleme
* @see org.springframework.data.redis.core.GeoOperations#geoRadius(java.lang.Object, org.springframework.data.geo.Circle, org.springframework.data.redis.core.GeoRadiusCommandArgs)
*/
@Override
public GeoResults<GeoLocation<M>> geoRadius(K key, final Circle within, final GeoRadiusCommandArgs args) {
public GeoResults<GeoLocation<M>> geoRadius(K key, Circle within, GeoRadiusCommandArgs args) {
final byte[] rawKey = rawKey(key);
byte[] rawKey = rawKey(key);
GeoResults<GeoLocation<byte[]>> raw = execute(new RedisCallback<GeoResults<GeoLocation<byte[]>>>() {
public GeoResults<GeoLocation<byte[]>> doInRedis(RedisConnection connection) {
return connection.geoRadius(rawKey, within, args);
}
}, true);
GeoResults<GeoLocation<byte[]>> raw = execute(connection -> connection.geoRadius(rawKey, within, args), true);
return deserializeGeoResults(raw);
}
@@ -228,16 +187,12 @@ public class DefaultGeoOperations<K, M> extends AbstractOperations<K, M> impleme
* @see org.springframework.data.redis.core.GeoOperations#geoRadiusByMember(java.lang.Object, java.lang.Object, double)
*/
@Override
public GeoResults<GeoLocation<M>> geoRadiusByMember(K key, M member, final double radius) {
public GeoResults<GeoLocation<M>> geoRadiusByMember(K key, M member, double radius) {
final byte[] rawKey = rawKey(key);
final byte[] rawMember = rawValue(member);
GeoResults<GeoLocation<byte[]>> raw = execute(new RedisCallback<GeoResults<GeoLocation<byte[]>>>() {
public GeoResults<GeoLocation<byte[]>> doInRedis(RedisConnection connection) {
return connection.geoRadiusByMember(rawKey, rawMember, radius);
}
}, true);
byte[] rawKey = rawKey(key);
byte[] rawMember = rawValue(member);
GeoResults<GeoLocation<byte[]>> raw = execute(connection -> connection.geoRadiusByMember(rawKey, rawMember, radius),
true);
return deserializeGeoResults(raw);
}
@@ -247,17 +202,13 @@ public class DefaultGeoOperations<K, M> extends AbstractOperations<K, M> impleme
* @see org.springframework.data.redis.core.GeoOperations#geoRadiusByMember(java.lang.Object, java.lang.Object, org.springframework.data.geo.Distance)
*/
@Override
public GeoResults<GeoLocation<M>> geoRadiusByMember(K key, M member, final Distance distance) {
public GeoResults<GeoLocation<M>> geoRadiusByMember(K key, M member, Distance distance) {
final byte[] rawKey = rawKey(key);
final byte[] rawMember = rawValue(member);
byte[] rawKey = rawKey(key);
byte[] rawMember = rawValue(member);
GeoResults<GeoLocation<byte[]>> raw = execute(new RedisCallback<GeoResults<GeoLocation<byte[]>>>() {
public GeoResults<GeoLocation<byte[]>> doInRedis(RedisConnection connection) {
return connection.geoRadiusByMember(rawKey, rawMember, distance);
}
}, true);
GeoResults<GeoLocation<byte[]>> raw = execute(
connection -> connection.geoRadiusByMember(rawKey, rawMember, distance), true);
return deserializeGeoResults(raw);
}
@@ -267,18 +218,13 @@ public class DefaultGeoOperations<K, M> extends AbstractOperations<K, M> impleme
* @see org.springframework.data.redis.core.GeoOperations#geoRadiusByMember(java.lang.Object, java.lang.Object, double, org.springframework.data.geo.Metric, org.springframework.data.redis.core.GeoRadiusCommandArgs)
*/
@Override
public GeoResults<GeoLocation<M>> geoRadiusByMember(K key, M member, final Distance distance,
final GeoRadiusCommandArgs param) {
public GeoResults<GeoLocation<M>> geoRadiusByMember(K key, M member, Distance distance, GeoRadiusCommandArgs param) {
final byte[] rawKey = rawKey(key);
final byte[] rawMember = rawValue(member);
byte[] rawKey = rawKey(key);
byte[] rawMember = rawValue(member);
GeoResults<GeoLocation<byte[]>> raw = execute(new RedisCallback<GeoResults<GeoLocation<byte[]>>>() {
public GeoResults<GeoLocation<byte[]>> doInRedis(RedisConnection connection) {
return connection.geoRadiusByMember(rawKey, rawMember, distance, param);
}
}, true);
GeoResults<GeoLocation<byte[]>> raw = execute(
connection -> connection.geoRadiusByMember(rawKey, rawMember, distance, param), true);
return deserializeGeoResults(raw);
}
@@ -290,14 +236,8 @@ public class DefaultGeoOperations<K, M> extends AbstractOperations<K, M> impleme
@Override
public Long geoRemove(K key, M... members) {
final byte[] rawKey = rawKey(key);
final byte[][] rawMembers = rawValues(members);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.zRem(rawKey, rawMembers);
}
}, true);
byte[] rawKey = rawKey(key);
byte[][] rawMembers = rawValues(members);
return execute(connection -> connection.zRem(rawKey, rawMembers), true);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2016 the original author or authors.
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,8 +24,6 @@ import java.util.Map.Entry;
import java.util.Set;
import org.springframework.core.convert.converter.Converter;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
/**
* Default implementation of {@link HashOperations}.
@@ -41,212 +39,216 @@ class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> imp
super((RedisTemplate<K, Object>) template);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.HashOperations#get(java.lang.Object, java.lang.Object)
*/
@Override
@SuppressWarnings("unchecked")
public HV get(K key, Object hashKey) {
final byte[] rawKey = rawKey(key);
final byte[] rawHashKey = rawHashKey(hashKey);
byte[] rawHashValue = execute(new RedisCallback<byte[]>() {
public byte[] doInRedis(RedisConnection connection) {
return connection.hGet(rawKey, rawHashKey);
}
}, true);
byte[] rawKey = rawKey(key);
byte[] rawHashKey = rawHashKey(hashKey);
byte[] rawHashValue = execute(connection -> connection.hGet(rawKey, rawHashKey), true);
return (HV) deserializeHashValue(rawHashValue);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.HashOperations#hasKey(java.lang.Object, java.lang.Object)
*/
@Override
public Boolean hasKey(K key, Object hashKey) {
final byte[] rawKey = rawKey(key);
final byte[] rawHashKey = rawHashKey(hashKey);
return execute(new RedisCallback<Boolean>() {
public Boolean doInRedis(RedisConnection connection) {
return connection.hExists(rawKey, rawHashKey);
}
}, true);
byte[] rawKey = rawKey(key);
byte[] rawHashKey = rawHashKey(hashKey);
return execute(connection -> connection.hExists(rawKey, rawHashKey), true);
}
public Long increment(K key, HK hashKey, final long delta) {
final byte[] rawKey = rawKey(key);
final byte[] rawHashKey = rawHashKey(hashKey);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.hIncrBy(rawKey, rawHashKey, delta);
}
}, true);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.HashOperations#increment(java.lang.Object, java.lang.Object, long)
*/
@Override
public Long increment(K key, HK hashKey, long delta) {
byte[] rawKey = rawKey(key);
byte[] rawHashKey = rawHashKey(hashKey);
return execute(connection -> connection.hIncrBy(rawKey, rawHashKey, delta), true);
}
public Double increment(K key, HK hashKey, final double delta) {
final byte[] rawKey = rawKey(key);
final byte[] rawHashKey = rawHashKey(hashKey);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.HashOperations#increment(java.lang.Object, java.lang.Object, double)
*/
@Override
public Double increment(K key, HK hashKey, double delta) {
return execute(new RedisCallback<Double>() {
public Double doInRedis(RedisConnection connection) {
return connection.hIncrBy(rawKey, rawHashKey, delta);
}
}, true);
byte[] rawKey = rawKey(key);
byte[] rawHashKey = rawHashKey(hashKey);
return execute(connection -> connection.hIncrBy(rawKey, rawHashKey, delta), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.HashOperations#keys(java.lang.Object)
*/
@Override
public Set<HK> keys(K key) {
final byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
public Set<byte[]> doInRedis(RedisConnection connection) {
return connection.hKeys(rawKey);
}
}, true);
byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(connection -> connection.hKeys(rawKey), true);
return deserializeHashKeys(rawValues);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.HashOperations#size(java.lang.Object)
*/
@Override
public Long size(K key) {
final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.hLen(rawKey);
}
}, true);
byte[] rawKey = rawKey(key);
return execute(connection -> connection.hLen(rawKey), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.HashOperations#putAll(java.lang.Object, java.util.Map)
*/
@Override
public void putAll(K key, Map<? extends HK, ? extends HV> m) {
if (m.isEmpty()) {
return;
}
final byte[] rawKey = rawKey(key);
byte[] rawKey = rawKey(key);
final Map<byte[], byte[]> hashes = new LinkedHashMap<byte[], byte[]>(m.size());
Map<byte[], byte[]> hashes = new LinkedHashMap<>(m.size());
for (Map.Entry<? extends HK, ? extends HV> entry : m.entrySet()) {
hashes.put(rawHashKey(entry.getKey()), rawHashValue(entry.getValue()));
}
execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection) {
connection.hMSet(rawKey, hashes);
return null;
}
execute(connection -> {
connection.hMSet(rawKey, hashes);
return null;
}, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.HashOperations#multiGet(java.lang.Object, java.util.Collection)
*/
@Override
public List<HV> multiGet(K key, Collection<HK> fields) {
if (fields.isEmpty()) {
return Collections.emptyList();
}
final byte[] rawKey = rawKey(key);
final byte[][] rawHashKeys = new byte[fields.size()][];
byte[] rawKey = rawKey(key);
byte[][] rawHashKeys = new byte[fields.size()][];
int counter = 0;
for (HK hashKey : fields) {
rawHashKeys[counter++] = rawHashKey(hashKey);
}
List<byte[]> rawValues = execute(new RedisCallback<List<byte[]>>() {
public List<byte[]> doInRedis(RedisConnection connection) {
return connection.hMGet(rawKey, rawHashKeys);
}
}, true);
List<byte[]> rawValues = execute(connection -> connection.hMGet(rawKey, rawHashKeys), true);
return deserializeHashValues(rawValues);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.HashOperations#put(java.lang.Object, java.lang.Object, java.lang.Object)
*/
@Override
public void put(K key, HK hashKey, HV value) {
final byte[] rawKey = rawKey(key);
final byte[] rawHashKey = rawHashKey(hashKey);
final byte[] rawHashValue = rawHashValue(value);
execute(new RedisCallback<Object>() {
byte[] rawKey = rawKey(key);
byte[] rawHashKey = rawHashKey(hashKey);
byte[] rawHashValue = rawHashValue(value);
public Object doInRedis(RedisConnection connection) {
connection.hSet(rawKey, rawHashKey, rawHashValue);
return null;
}
execute(connection -> {
connection.hSet(rawKey, rawHashKey, rawHashValue);
return null;
}, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.HashOperations#putIfAbsent(java.lang.Object, java.lang.Object, java.lang.Object)
*/
@Override
public Boolean putIfAbsent(K key, HK hashKey, HV value) {
final byte[] rawKey = rawKey(key);
final byte[] rawHashKey = rawHashKey(hashKey);
final byte[] rawHashValue = rawHashValue(value);
return execute(new RedisCallback<Boolean>() {
byte[] rawKey = rawKey(key);
byte[] rawHashKey = rawHashKey(hashKey);
byte[] rawHashValue = rawHashValue(value);
public Boolean doInRedis(RedisConnection connection) {
return connection.hSetNX(rawKey, rawHashKey, rawHashValue);
}
}, true);
return execute(connection -> connection.hSetNX(rawKey, rawHashKey, rawHashValue), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.HashOperations#values(java.lang.Object)
*/
@Override
public List<HV> values(K key) {
final byte[] rawKey = rawKey(key);
List<byte[]> rawValues = execute(new RedisCallback<List<byte[]>>() {
public List<byte[]> doInRedis(RedisConnection connection) {
return connection.hVals(rawKey);
}
}, true);
byte[] rawKey = rawKey(key);
List<byte[]> rawValues = execute(connection -> connection.hVals(rawKey), true);
return deserializeHashValues(rawValues);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.HashOperations#delete(java.lang.Object, java.lang.Object[])
*/
@Override
public Long delete(K key, Object... hashKeys) {
final byte[] rawKey = rawKey(key);
final byte[][] rawHashKeys = rawHashKeys(hashKeys);
return execute(new RedisCallback<Long>() {
byte[] rawKey = rawKey(key);
byte[][] rawHashKeys = rawHashKeys(hashKeys);
public Long doInRedis(RedisConnection connection) {
return connection.hDel(rawKey, rawHashKeys);
}
}, true);
return execute(connection -> connection.hDel(rawKey, rawHashKeys), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.HashOperations#entries(java.lang.Object)
*/
@Override
public Map<HK, HV> entries(K key) {
final byte[] rawKey = rawKey(key);
Map<byte[], byte[]> entries = execute(new RedisCallback<Map<byte[], byte[]>>() {
public Map<byte[], byte[]> doInRedis(RedisConnection connection) {
return connection.hGetAll(rawKey);
}
}, true);
byte[] rawKey = rawKey(key);
Map<byte[], byte[]> entries = execute(connection -> connection.hGetAll(rawKey), true);
return deserializeHashMap(entries);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.HashOperations#hscan(java.lang.Object, org.springframework.data.redis.core.ScanOptions)
* @see org.springframework.data.redis.core.HashOperations#scan(java.lang.Object, org.springframework.data.redis.core.ScanOptions)
*/
@Override
public Cursor<Entry<HK, HV>> scan(K key, final ScanOptions options) {
public Cursor<Entry<HK, HV>> scan(K key, ScanOptions options) {
final byte[] rawKey = rawKey(key);
return template.executeWithStickyConnection(new RedisCallback<Cursor<Map.Entry<HK, HV>>>() {
@Override
public Cursor<Entry<HK, HV>> doInRedis(RedisConnection connection) throws DataAccessException {
return new ConvertingCursor<Map.Entry<byte[], byte[]>, Map.Entry<HK, HV>>(connection.hScan(rawKey, options),
new Converter<Map.Entry<byte[], byte[]>, Map.Entry<HK, HV>>() {
byte[] rawKey = rawKey(key);
return template.executeWithStickyConnection(
(RedisCallback<Cursor<Entry<HK, HV>>>) connection -> new ConvertingCursor<>(connection.hScan(rawKey, options),
new Converter<Entry<byte[], byte[]>, Entry<HK, HV>>() {
@Override
public Entry<HK, HV> convert(final Entry<byte[], byte[]> source) {
return new Map.Entry<HK, HV>() {
return new Entry<HK, HV>() {
@Override
public HK getKey() {
@@ -263,12 +265,8 @@ class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> imp
throw new UnsupportedOperationException("Values cannot be set when scanning through entries.");
}
};
}
});
}
});
}));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014 the original author or authors.
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,18 +17,15 @@ package org.springframework.data.redis.core;
import java.util.Arrays;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
/**
* @author Christoph Strobl
* @since 1.5
* @param <K>
* @param <V>
*/
public class DefaultHyperLogLogOperations<K, V> extends AbstractOperations<K, V> implements HyperLogLogOperations<K, V> {
class DefaultHyperLogLogOperations<K, V> extends AbstractOperations<K, V> implements HyperLogLogOperations<K, V> {
public DefaultHyperLogLogOperations(RedisTemplate<K, V> template) {
DefaultHyperLogLogOperations(RedisTemplate<K, V> template) {
super(template);
}
@@ -39,17 +36,9 @@ public class DefaultHyperLogLogOperations<K, V> extends AbstractOperations<K, V>
@Override
public Long add(K key, V... values) {
final byte[] rawKey = rawKey(key);
final byte[][] rawValues = rawValues(values);
return execute(new RedisCallback<Long>() {
@Override
public Long doInRedis(RedisConnection connection) throws DataAccessException {
return connection.pfAdd(rawKey, rawValues);
}
}, true);
byte[] rawKey = rawKey(key);
byte[][] rawValues = rawValues(values);
return execute(connection -> connection.pfAdd(rawKey, rawValues), true);
}
/*
@@ -59,15 +48,8 @@ public class DefaultHyperLogLogOperations<K, V> extends AbstractOperations<K, V>
@Override
public Long size(K... keys) {
final byte[][] rawKeys = rawKeys(Arrays.asList(keys));
return execute(new RedisCallback<Long>() {
@Override
public Long doInRedis(RedisConnection connection) throws DataAccessException {
return connection.pfCount(rawKeys);
}
}, true);
byte[][] rawKeys = rawKeys(Arrays.asList(keys));
return execute(connection -> connection.pfCount(rawKeys), true);
}
/*
@@ -77,17 +59,12 @@ public class DefaultHyperLogLogOperations<K, V> extends AbstractOperations<K, V>
@Override
public Long union(K destination, K... sourceKeys) {
final byte[] rawDestinationKey = rawKey(destination);
final byte[][] rawSourceKeys = rawKeys(Arrays.asList(sourceKeys));
byte[] rawDestinationKey = rawKey(destination);
byte[][] rawSourceKeys = rawKeys(Arrays.asList(sourceKeys));
return execute(connection -> {
return execute(new RedisCallback<Long>() {
@Override
public Long doInRedis(RedisConnection connection) throws DataAccessException {
connection.pfMerge(rawDestinationKey, rawSourceKeys);
return connection.pfCount(rawDestinationKey);
}
connection.pfMerge(rawDestinationKey, rawSourceKeys);
return connection.pfCount(rawDestinationKey);
}, true);
}

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2014 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -25,7 +25,7 @@ import org.springframework.util.CollectionUtils;
/**
* Default implementation of {@link ListOperations}.
*
*
* @author Costin Leau
* @author David Liu
* @author Thomas Darimont
@@ -37,28 +37,49 @@ class DefaultListOperations<K, V> extends AbstractOperations<K, V> implements Li
super(template);
}
public V index(K key, final long index) {
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#index(java.lang.Object, long)
*/
@Override
public V index(K key, long index) {
return execute(new ValueDeserializingRedisCallback(key) {
@Override
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
return connection.lIndex(rawKey, index);
}
}, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#leftPop(java.lang.Object)
*/
@Override
public V leftPop(K key) {
return execute(new ValueDeserializingRedisCallback(key) {
@Override
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
return connection.lPop(rawKey);
}
}, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#leftPop(java.lang.Object, long, java.util.concurrent.TimeUnit)
*/
@Override
public V leftPop(K key, long timeout, TimeUnit unit) {
final int tm = (int) TimeoutUtils.toSeconds(timeout, unit);
int tm = (int) TimeoutUtils.toSeconds(timeout, unit);
return execute(new ValueDeserializingRedisCallback(key) {
@Override
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
List<byte[]> lPop = connection.bLPop(tm, rawKey);
return (CollectionUtils.isEmpty(lPop) ? null : lPop.get(1));
@@ -66,25 +87,28 @@ class DefaultListOperations<K, V> extends AbstractOperations<K, V> implements Li
}, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#leftPush(java.lang.Object, java.lang.Object)
*/
@Override
public Long leftPush(K key, V value) {
final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.lPush(rawKey, rawValue);
}
}, true);
byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(value);
return execute(connection -> connection.lPush(rawKey, rawValue), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#leftPushAll(java.lang.Object, java.lang.Object[])
*/
@Override
public Long leftPushAll(K key, V... values) {
final byte[] rawKey = rawKey(key);
final byte[][] rawValues = rawValues(values);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.lPush(rawKey, rawValues);
}
}, true);
byte[] rawKey = rawKey(key);
byte[][] rawValues = rawValues(values);
return execute(connection -> connection.lPush(rawKey, rawValues), true);
}
/*
@@ -94,83 +118,99 @@ class DefaultListOperations<K, V> extends AbstractOperations<K, V> implements Li
@Override
public Long leftPushAll(K key, Collection<V> values) {
final byte[] rawKey = rawKey(key);
final byte[][] rawValues = rawValues(values);
byte[] rawKey = rawKey(key);
byte[][] rawValues = rawValues(values);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.lPush(rawKey, rawValues);
}
}, true);
return execute(connection -> connection.lPush(rawKey, rawValues), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#leftPushIfPresent(java.lang.Object, java.lang.Object)
*/
@Override
public Long leftPushIfPresent(K key, V value) {
final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.lPushX(rawKey, rawValue);
}
}, true);
byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(value);
return execute(connection -> connection.lPushX(rawKey, rawValue), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#leftPush(java.lang.Object, java.lang.Object, java.lang.Object)
*/
@Override
public Long leftPush(K key, V pivot, V value) {
final byte[] rawKey = rawKey(key);
final byte[] rawPivot = rawValue(pivot);
final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.lInsert(rawKey, Position.BEFORE, rawPivot, rawValue);
}
}, true);
byte[] rawKey = rawKey(key);
byte[] rawPivot = rawValue(pivot);
byte[] rawValue = rawValue(value);
return execute(connection -> connection.lInsert(rawKey, Position.BEFORE, rawPivot, rawValue), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#size(java.lang.Object)
*/
@Override
public Long size(K key) {
final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.lLen(rawKey);
}
}, true);
byte[] rawKey = rawKey(key);
return execute(connection -> connection.lLen(rawKey), true);
}
public List<V> range(K key, final long start, final long end) {
final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<List<V>>() {
public List<V> doInRedis(RedisConnection connection) {
return deserializeValues(connection.lRange(rawKey, start, end));
}
}, true);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#range(java.lang.Object, long, long)
*/
@Override
public List<V> range(K key, long start, long end) {
byte[] rawKey = rawKey(key);
return execute(connection -> deserializeValues(connection.lRange(rawKey, start, end)), true);
}
public Long remove(K key, final long count, Object value) {
final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Long>() {
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#remove(java.lang.Object, long, java.lang.Object)
*/
@Override
public Long remove(K key, long count, Object value) {
public Long doInRedis(RedisConnection connection) {
return connection.lRem(rawKey, count, rawValue);
}
}, true);
byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(value);
return execute(connection -> connection.lRem(rawKey, count, rawValue), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#rightPop(java.lang.Object)
*/
@Override
public V rightPop(K key) {
return execute(new ValueDeserializingRedisCallback(key) {
@Override
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
return connection.rPop(rawKey);
}
}, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#rightPop(java.lang.Object, long, java.util.concurrent.TimeUnit)
*/
@Override
public V rightPop(K key, long timeout, TimeUnit unit) {
final int tm = (int) TimeoutUtils.toSeconds(timeout, unit);
int tm = (int) TimeoutUtils.toSeconds(timeout, unit);
return execute(new ValueDeserializingRedisCallback(key) {
@Override
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
List<byte[]> bRPop = connection.bRPop(tm, rawKey);
return (CollectionUtils.isEmpty(bRPop) ? null : bRPop.get(1));
@@ -178,25 +218,28 @@ class DefaultListOperations<K, V> extends AbstractOperations<K, V> implements Li
}, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#rightPush(java.lang.Object, java.lang.Object)
*/
@Override
public Long rightPush(K key, V value) {
final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.rPush(rawKey, rawValue);
}
}, true);
byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(value);
return execute(connection -> connection.rPush(rawKey, rawValue), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#rightPushAll(java.lang.Object, java.lang.Object[])
*/
@Override
public Long rightPushAll(K key, V... values) {
final byte[] rawKey = rawKey(key);
final byte[][] rawValues = rawValues(values);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.rPush(rawKey, rawValues);
}
}, true);
byte[] rawKey = rawKey(key);
byte[][] rawValues = rawValues(values);
return execute(connection -> connection.rPush(rawKey, rawValues), true);
}
/*
@@ -206,67 +249,82 @@ class DefaultListOperations<K, V> extends AbstractOperations<K, V> implements Li
@Override
public Long rightPushAll(K key, Collection<V> values) {
final byte[] rawKey = rawKey(key);
final byte[][] rawValues = rawValues(values);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.rPush(rawKey, rawValues);
}
}, true);
byte[] rawKey = rawKey(key);
byte[][] rawValues = rawValues(values);
return execute(connection -> connection.rPush(rawKey, rawValues), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#rightPushIfPresent(java.lang.Object, java.lang.Object)
*/
@Override
public Long rightPushIfPresent(K key, V value) {
final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.rPushX(rawKey, rawValue);
}
}, true);
byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(value);
return execute(connection -> connection.rPushX(rawKey, rawValue), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#rightPush(java.lang.Object, java.lang.Object, java.lang.Object)
*/
@Override
public Long rightPush(K key, V pivot, V value) {
final byte[] rawKey = rawKey(key);
final byte[] rawPivot = rawValue(pivot);
final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.lInsert(rawKey, Position.AFTER, rawPivot, rawValue);
}
}, true);
byte[] rawKey = rawKey(key);
byte[] rawPivot = rawValue(pivot);
byte[] rawValue = rawValue(value);
return execute(connection -> connection.lInsert(rawKey, Position.AFTER, rawPivot, rawValue), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#rightPopAndLeftPush(java.lang.Object, java.lang.Object)
*/
@Override
public V rightPopAndLeftPush(K sourceKey, K destinationKey) {
final byte[] rawDestKey = rawKey(destinationKey);
byte[] rawDestKey = rawKey(destinationKey);
return execute(new ValueDeserializingRedisCallback(sourceKey) {
@Override
protected byte[] inRedis(byte[] rawSourceKey, RedisConnection connection) {
return connection.rPopLPush(rawSourceKey, rawDestKey);
}
}, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#rightPopAndLeftPush(java.lang.Object, java.lang.Object, long, java.util.concurrent.TimeUnit)
*/
@Override
public V rightPopAndLeftPush(K sourceKey, K destinationKey, long timeout, TimeUnit unit) {
final int tm = (int) TimeoutUtils.toSeconds(timeout, unit);
final byte[] rawDestKey = rawKey(destinationKey);
int tm = (int) TimeoutUtils.toSeconds(timeout, unit);
byte[] rawDestKey = rawKey(destinationKey);
return execute(new ValueDeserializingRedisCallback(sourceKey) {
@Override
protected byte[] inRedis(byte[] rawSourceKey, RedisConnection connection) {
return connection.bRPopLPush(tm, rawSourceKey, rawDestKey);
}
}, true);
}
public void set(K key, final long index, V value) {
final byte[] rawValue = rawValue(value);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#set(java.lang.Object, long, java.lang.Object)
*/
@Override
public void set(K key, long index, V value) {
byte[] rawValue = rawValue(value);
execute(new ValueDeserializingRedisCallback(key) {
@Override
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
connection.lSet(rawKey, index, rawValue);
return null;
@@ -274,14 +332,20 @@ class DefaultListOperations<K, V> extends AbstractOperations<K, V> implements Li
}, true);
}
public void trim(K key, final long start, final long end) {
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ListOperations#trim(java.lang.Object, long, long)
*/
@Override
public void trim(K key, long start, long end) {
execute(new ValueDeserializingRedisCallback(key) {
@Override
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
connection.lTrim(rawKey, start, end);
return null;
}
}, true);
}
}

View File

@@ -44,7 +44,7 @@ import org.springframework.util.Assert;
* @author Christoph Strobl
* @since 2.0
*/
public class DefaultReactiveGeoOperations<K, V> implements ReactiveGeoOperations<K, V> {
class DefaultReactiveGeoOperations<K, V> implements ReactiveGeoOperations<K, V> {
private final ReactiveRedisTemplate<?, ?> template;
private final RedisSerializationContext<K, V> serializationContext;
@@ -55,7 +55,7 @@ public class DefaultReactiveGeoOperations<K, V> implements ReactiveGeoOperations
* @param template must not be {@literal null}.
* @param serializationContext must not be {@literal null}.
*/
public DefaultReactiveGeoOperations(ReactiveRedisTemplate<?, ?> template,
DefaultReactiveGeoOperations(ReactiveRedisTemplate<?, ?> template,
RedisSerializationContext<K, V> serializationContext) {
Assert.notNull(template, "ReactiveRedisTemplate must not be null!");

View File

@@ -22,7 +22,6 @@ import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
@@ -39,7 +38,7 @@ import org.springframework.util.Assert;
* @author Christoph Strobl
* @since 2.0
*/
public class DefaultReactiveHashOperations<H, HK, HV> implements ReactiveHashOperations<H, HK, HV> {
class DefaultReactiveHashOperations<H, HK, HV> implements ReactiveHashOperations<H, HK, HV> {
private final ReactiveRedisTemplate<?, ?> template;
private final RedisSerializationContext<H, ?> serializationContext;
@@ -50,7 +49,7 @@ public class DefaultReactiveHashOperations<H, HK, HV> implements ReactiveHashOpe
* @param template must not be {@literal null}.
* @param serializationContext must not be {@literal null}.
*/
public DefaultReactiveHashOperations(ReactiveRedisTemplate<?, ?> template,
DefaultReactiveHashOperations(ReactiveRedisTemplate<?, ?> template,
RedisSerializationContext<H, ?> serializationContext) {
Assert.notNull(template, "ReactiveRedisTemplate must not be null!");
@@ -289,7 +288,7 @@ public class DefaultReactiveHashOperations<H, HK, HV> implements ReactiveHashOpe
private List<HV> deserializeHashValues(List<ByteBuffer> source) {
List<HV> values = new ArrayList<HV>(source.size());
List<HV> values = new ArrayList<>(source.size());
for (ByteBuffer byteBuffer : source) {
values.add(readHashValue(byteBuffer));
}

View File

@@ -15,7 +15,6 @@
*/
package org.springframework.data.redis.core;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -24,16 +23,17 @@ import java.util.function.Function;
import org.reactivestreams.Publisher;
import org.springframework.data.redis.connection.ReactiveHyperLogLogCommands;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.util.Assert;
/**
* Default implementation of {@link ReactiveHyperLogLogOperations}.
*
* @author Mark Paluch
* @auhtor Christoph Strobl
* @author Christoph Strobl
* @since 2.0
*/
public class DefaultReactiveHyperLogLogOperations<K, V> implements ReactiveHyperLogLogOperations<K, V> {
class DefaultReactiveHyperLogLogOperations<K, V> implements ReactiveHyperLogLogOperations<K, V> {
private final ReactiveRedisTemplate<?, ?> template;
private final RedisSerializationContext<K, V> serializationContext;
@@ -44,7 +44,7 @@ public class DefaultReactiveHyperLogLogOperations<K, V> implements ReactiveHyper
* @param template must not be {@literal null}.
* @param serializationContext must not be {@literal null}.
*/
public DefaultReactiveHyperLogLogOperations(ReactiveRedisTemplate<?, ?> template,
DefaultReactiveHyperLogLogOperations(ReactiveRedisTemplate<?, ?> template,
RedisSerializationContext<K, V> serializationContext) {
Assert.notNull(template, "ReactiveRedisTemplate must not be null!");

View File

@@ -39,7 +39,7 @@ import org.springframework.util.Assert;
* @author Christoph Strobl
* @since 2.0
*/
public class DefaultReactiveListOperations<K, V> implements ReactiveListOperations<K, V> {
class DefaultReactiveListOperations<K, V> implements ReactiveListOperations<K, V> {
private final ReactiveRedisTemplate<?, ?> template;
private final RedisSerializationContext<K, V> serializationContext;
@@ -50,7 +50,7 @@ public class DefaultReactiveListOperations<K, V> implements ReactiveListOperatio
* @param template must not be {@literal null}.
* @param serializationContext must not be {@literal null}.
*/
public DefaultReactiveListOperations(ReactiveRedisTemplate<?, ?> template,
DefaultReactiveListOperations(ReactiveRedisTemplate<?, ?> template,
RedisSerializationContext<K, V> serializationContext) {
Assert.notNull(template, "ReactiveRedisTemplate must not be null!");

View File

@@ -37,7 +37,7 @@ import org.springframework.util.Assert;
* @author Christoph Strobl
* @since 2.0
*/
public class DefaultReactiveSetOperations<K, V> implements ReactiveSetOperations<K, V> {
class DefaultReactiveSetOperations<K, V> implements ReactiveSetOperations<K, V> {
private final ReactiveRedisTemplate<?, ?> template;
private final RedisSerializationContext<K, V> serializationContext;
@@ -48,7 +48,7 @@ public class DefaultReactiveSetOperations<K, V> implements ReactiveSetOperations
* @param template must not be {@literal null}.
* @param serializationContext must not be {@literal null}.
*/
public DefaultReactiveSetOperations(ReactiveRedisTemplate<?, ?> template,
DefaultReactiveSetOperations(ReactiveRedisTemplate<?, ?> template,
RedisSerializationContext<K, V> serializationContext) {
Assert.notNull(template, "ReactiveRedisTemplate must not be null!");

View File

@@ -41,7 +41,7 @@ import org.springframework.util.Assert;
* @author Christoph Strobl
* @since 2.0
*/
public class DefaultReactiveValueOperations<K, V> implements ReactiveValueOperations<K, V> {
class DefaultReactiveValueOperations<K, V> implements ReactiveValueOperations<K, V> {
private final ReactiveRedisTemplate<?, ?> template;
private final RedisSerializationContext<K, V> serializationContext;
@@ -52,7 +52,7 @@ public class DefaultReactiveValueOperations<K, V> implements ReactiveValueOperat
* @param template must not be {@literal null}.
* @param serializationContext must not be {@literal null}.
*/
public DefaultReactiveValueOperations(ReactiveRedisTemplate<?, ?> template,
DefaultReactiveValueOperations(ReactiveRedisTemplate<?, ?> template,
RedisSerializationContext<K, V> serializationContext) {
Assert.notNull(template, "ReactiveRedisTemplate must not be null!");

View File

@@ -43,7 +43,7 @@ import org.springframework.util.Assert;
* @author Christoph Strobl
* @since 2.0
*/
public class DefaultReactiveZSetOperations<K, V> implements ReactiveZSetOperations<K, V> {
class DefaultReactiveZSetOperations<K, V> implements ReactiveZSetOperations<K, V> {
private final ReactiveRedisTemplate<?, ?> template;
private final RedisSerializationContext<K, V> serializationContext;
@@ -54,7 +54,7 @@ public class DefaultReactiveZSetOperations<K, V> implements ReactiveZSetOperatio
* @param template must not be {@literal null}.
* @param serializationContext must not be {@literal null}.
*/
public DefaultReactiveZSetOperations(ReactiveRedisTemplate<?, ?> template,
DefaultReactiveZSetOperations(ReactiveRedisTemplate<?, ?> template,
RedisSerializationContext<K, V> serializationContext) {
Assert.notNull(template, "ReactiveRedisTemplate must not be null!");

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2017 the original author or authors.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,16 +22,18 @@ import java.util.List;
import java.util.Set;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.util.Assert;
/**
* Default implementation of {@link SetOperations}.
*
*
* @author Costin Leau
* @author Christoph Strobl
* @author Mark Paluch
*/
class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements SetOperations<K, V> {
public DefaultSetOperations(RedisTemplate<K, V> template) {
DefaultSetOperations(RedisTemplate<K, V> template) {
super(template);
}
@@ -39,9 +41,11 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#add(java.lang.Object, java.lang.Object[])
*/
@Override
public Long add(K key, V... values) {
final byte[] rawKey = rawKey(key);
final byte[][] rawValues = rawValues(values);
byte[] rawKey = rawKey(key);
byte[][] rawValues = rawValues((Object[]) values);
return execute(connection -> connection.sAdd(rawKey, rawValues), true);
}
@@ -49,6 +53,7 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#difference(java.lang.Object, java.lang.Object)
*/
@Override
public Set<V> difference(K key, K otherKey) {
return difference(key, Collections.singleton(otherKey));
}
@@ -57,9 +62,10 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#difference(java.lang.Object, java.util.Collection)
*/
public Set<V> difference(final K key, final Collection<K> otherKeys) {
@Override
public Set<V> difference(K key, Collection<K> otherKeys) {
final byte[][] rawKeys = rawKeys(key, otherKeys);
byte[][] rawKeys = rawKeys(key, otherKeys);
Set<byte[]> rawValues = execute(connection -> connection.sDiff(rawKeys), true);
return deserializeValues(rawValues);
@@ -69,6 +75,7 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#differenceAndStore(java.lang.Object, java.lang.Object, java.lang.Object)
*/
@Override
public Long differenceAndStore(K key, K otherKey, K destKey) {
return differenceAndStore(key, Collections.singleton(otherKey), destKey);
}
@@ -77,10 +84,11 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#differenceAndStore(java.lang.Object, java.util.Collection, java.lang.Object)
*/
public Long differenceAndStore(final K key, final Collection<K> otherKeys, K destKey) {
@Override
public Long differenceAndStore(K key, Collection<K> otherKeys, K destKey) {
final byte[][] rawKeys = rawKeys(key, otherKeys);
final byte[] rawDestKey = rawKey(destKey);
byte[][] rawKeys = rawKeys(key, otherKeys);
byte[] rawDestKey = rawKey(destKey);
return execute(connection -> connection.sDiffStore(rawDestKey, rawKeys), true);
}
@@ -88,6 +96,7 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#intersect(java.lang.Object, java.lang.Object)
*/
@Override
public Set<V> intersect(K key, K otherKey) {
return intersect(key, Collections.singleton(otherKey));
}
@@ -96,9 +105,10 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#intersect(java.lang.Object, java.util.Collection)
*/
@Override
public Set<V> intersect(K key, Collection<K> otherKeys) {
final byte[][] rawKeys = rawKeys(key, otherKeys);
byte[][] rawKeys = rawKeys(key, otherKeys);
Set<byte[]> rawValues = execute(connection -> connection.sInter(rawKeys), true);
return deserializeValues(rawValues);
@@ -108,6 +118,7 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#intersectAndStore(java.lang.Object, java.lang.Object, java.lang.Object)
*/
@Override
public Long intersectAndStore(K key, K otherKey, K destKey) {
return intersectAndStore(key, Collections.singleton(otherKey), destKey);
}
@@ -116,10 +127,11 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#intersectAndStore(java.lang.Object, java.util.Collection, java.lang.Object)
*/
@Override
public Long intersectAndStore(K key, Collection<K> otherKeys, K destKey) {
final byte[][] rawKeys = rawKeys(key, otherKeys);
final byte[] rawDestKey = rawKey(destKey);
byte[][] rawKeys = rawKeys(key, otherKeys);
byte[] rawDestKey = rawKey(destKey);
return execute(connection -> connection.sInterStore(rawDestKey, rawKeys), true);
}
@@ -127,10 +139,11 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#isMember(java.lang.Object, java.lang.Object)
*/
@Override
public Boolean isMember(K key, Object o) {
final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(o);
byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(o);
return execute(connection -> connection.sIsMember(rawKey, rawValue), true);
}
@@ -138,9 +151,10 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#members(java.lang.Object)
*/
@Override
public Set<V> members(K key) {
final byte[] rawKey = rawKey(key);
byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(connection -> connection.sMembers(rawKey), true);
return deserializeValues(rawValues);
@@ -150,11 +164,12 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#move(java.lang.Object, java.lang.Object, java.lang.Object)
*/
@Override
public Boolean move(K key, V value, K destKey) {
final byte[] rawKey = rawKey(key);
final byte[] rawDestKey = rawKey(destKey);
final byte[] rawValue = rawValue(value);
byte[] rawKey = rawKey(key);
byte[] rawDestKey = rawKey(destKey);
byte[] rawValue = rawValue(value);
return execute(connection -> connection.sMove(rawKey, rawDestKey, rawValue), true);
}
@@ -163,10 +178,12 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#randomMember(java.lang.Object)
*/
@Override
public V randomMember(K key) {
return execute(new ValueDeserializingRedisCallback(key) {
@Override
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
return connection.sRandMember(rawKey);
}
@@ -177,14 +194,12 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#distinctRandomMembers(java.lang.Object, long)
*/
public Set<V> distinctRandomMembers(K key, final long count) {
@Override
public Set<V> distinctRandomMembers(K key, long count) {
if (count < 0) {
throw new IllegalArgumentException(
"Negative count not supported. " + "Use randomMembers to allow duplicate elements.");
}
Assert.isTrue(count >= 0, "Negative count not supported. " + "Use randomMembers to allow duplicate elements.");
final byte[] rawKey = rawKey(key);
byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(
(RedisCallback<Set<byte[]>>) connection -> new HashSet<>(connection.sRandMember(rawKey, count)), true);
@@ -195,14 +210,13 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#randomMembers(java.lang.Object, long)
*/
public List<V> randomMembers(K key, final long count) {
@Override
public List<V> randomMembers(K key, long count) {
if (count < 0) {
throw new IllegalArgumentException(
"Use a positive number for count. " + "This method is already allowing duplicate elements.");
}
Assert.isTrue(count >= 0,
"Use a positive number for count. " + "This method is already allowing duplicate elements.");
final byte[] rawKey = rawKey(key);
byte[] rawKey = rawKey(key);
List<byte[]> rawValues = execute(connection -> connection.sRandMember(rawKey, -count), true);
return deserializeValues(rawValues);
@@ -212,10 +226,11 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#remove(java.lang.Object, java.lang.Object[])
*/
@Override
public Long remove(K key, Object... values) {
final byte[] rawKey = rawKey(key);
final byte[][] rawValues = rawValues(values);
byte[] rawKey = rawKey(key);
byte[][] rawValues = rawValues(values);
return execute(connection -> connection.sRem(rawKey, rawValues), true);
}
@@ -223,9 +238,12 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#pop(java.lang.Object)
*/
@Override
public V pop(K key) {
return execute(new ValueDeserializingRedisCallback(key) {
@Override
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
return connection.sPop(rawKey);
}
@@ -239,9 +257,9 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
@Override
public List<V> pop(K key, long count) {
final byte[] rawKey = rawKey(key);
byte[] rawKey = rawKey(key);
List<byte[]> rawValues = execute(connection -> connection.sPop(rawKey, count), true);
return deserializeValues(rawValues);
}
@@ -249,8 +267,10 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#size(java.lang.Object)
*/
@Override
public Long size(K key) {
final byte[] rawKey = rawKey(key);
byte[] rawKey = rawKey(key);
return execute(connection -> connection.sCard(rawKey), true);
}
@@ -258,13 +278,19 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#union(java.lang.Object, java.lang.Object)
*/
@Override
public Set<V> union(K key, K otherKey) {
return union(key, Collections.singleton(otherKey));
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#union(java.lang.Object, java.util.Collection)
*/
@Override
public Set<V> union(K key, Collection<K> otherKeys) {
final byte[][] rawKeys = rawKeys(key, otherKeys);
byte[][] rawKeys = rawKeys(key, otherKeys);
Set<byte[]> rawValues = execute(connection -> connection.sUnion(rawKeys), true);
return deserializeValues(rawValues);
@@ -274,6 +300,7 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#union(java.lang.Object, java.lang.Object, java.lang.Object)
*/
@Override
public Long unionAndStore(K key, K otherKey, K destKey) {
return unionAndStore(key, Collections.singleton(otherKey), destKey);
}
@@ -282,9 +309,11 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* (non-Javadoc)
* @see org.springframework.data.redis.core.SetOperations#unionAndStore(java.lang.Object, java.util.Collection, java.lang.Object)
*/
@Override
public Long unionAndStore(K key, Collection<K> otherKeys, K destKey) {
final byte[][] rawKeys = rawKeys(key, otherKeys);
final byte[] rawDestKey = rawKey(destKey);
byte[][] rawKeys = rawKeys(key, otherKeys);
byte[] rawDestKey = rawKey(destKey);
return execute(connection -> connection.sUnionStore(rawDestKey, rawKeys), true);
}
@@ -293,12 +322,11 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
* @see org.springframework.data.redis.core.SetOperations#sScan(java.lang.Object, org.springframework.data.redis.core.ScanOptions)
*/
@Override
public Cursor<V> scan(K key, final ScanOptions options) {
public Cursor<V> scan(K key, ScanOptions options) {
final byte[] rawKey = rawKey(key);
byte[] rawKey = rawKey(key);
return template.executeWithStickyConnection(
(RedisCallback<Cursor<V>>) connection -> new ConvertingCursor<>(connection.sScan(rawKey, options),
source -> deserializeValue(source)));
this::deserializeValue));
}
}

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2014 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -27,7 +27,7 @@ import org.springframework.data.redis.connection.RedisConnection;
/**
* Default implementation of {@link ValueOperations}.
*
*
* @author Costin Leau
* @author Jennifer Hickey
* @author Christoph Strobl
@@ -38,136 +38,166 @@ class DefaultValueOperations<K, V> extends AbstractOperations<K, V> implements V
super(template);
}
public V get(final Object key) {
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#get(java.lang.Object)
*/
@Override
public V get(Object key) {
return execute(new ValueDeserializingRedisCallback(key) {
@Override
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
return connection.get(rawKey);
}
}, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#getAndSet(java.lang.Object, java.lang.Object)
*/
@Override
public V getAndSet(K key, V newValue) {
final byte[] rawValue = rawValue(newValue);
byte[] rawValue = rawValue(newValue);
return execute(new ValueDeserializingRedisCallback(key) {
@Override
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
return connection.getSet(rawKey, rawValue);
}
}, true);
}
public Long increment(K key, final long delta) {
final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Long>() {
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#increment(java.lang.Object, long)
*/
@Override
public Long increment(K key, long delta) {
public Long doInRedis(RedisConnection connection) {
return connection.incrBy(rawKey, delta);
}
}, true);
byte[] rawKey = rawKey(key);
return execute(connection -> connection.incrBy(rawKey, delta), true);
}
public Double increment(K key, final double delta) {
final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Double>() {
public Double doInRedis(RedisConnection connection) {
return connection.incrBy(rawKey, delta);
}
}, true);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#increment(java.lang.Object, double)
*/
@Override
public Double increment(K key, double delta) {
byte[] rawKey = rawKey(key);
return execute(connection -> connection.incrBy(rawKey, delta), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#append(java.lang.Object, java.lang.String)
*/
@Override
public Integer append(K key, String value) {
final byte[] rawKey = rawKey(key);
final byte[] rawString = rawString(value);
return execute(new RedisCallback<Integer>() {
byte[] rawKey = rawKey(key);
byte[] rawString = rawString(value);
public Integer doInRedis(RedisConnection connection) {
final Long result = connection.append(rawKey, rawString);
return ( result != null ) ? result.intValue() : null;
}
return execute(connection -> {
Long result = connection.append(rawKey, rawString);
return (result != null) ? result.intValue() : null;
}, true);
}
public String get(K key, final long start, final long end) {
final byte[] rawKey = rawKey(key);
byte[] rawReturn = execute(new RedisCallback<byte[]>() {
public byte[] doInRedis(RedisConnection connection) {
return connection.getRange(rawKey, start, end);
}
}, true);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#get(java.lang.Object, long, long)
*/
@Override
public String get(K key, long start, long end) {
byte[] rawKey = rawKey(key);
byte[] rawReturn = execute(connection -> connection.getRange(rawKey, start, end), true);
return deserializeString(rawReturn);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#multiGet(java.util.Collection)
*/
@Override
public List<V> multiGet(Collection<K> keys) {
if (keys.isEmpty()) {
return Collections.emptyList();
}
final byte[][] rawKeys = new byte[keys.size()][];
byte[][] rawKeys = new byte[keys.size()][];
int counter = 0;
for (K hashKey : keys) {
rawKeys[counter++] = rawKey(hashKey);
}
List<byte[]> rawValues = execute(new RedisCallback<List<byte[]>>() {
public List<byte[]> doInRedis(RedisConnection connection) {
return connection.mGet(rawKeys);
}
}, true);
List<byte[]> rawValues = execute(connection -> connection.mGet(rawKeys), true);
return deserializeValues(rawValues);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#multiSet(java.util.Map)
*/
@Override
public void multiSet(Map<? extends K, ? extends V> m) {
if (m.isEmpty()) {
return;
}
final Map<byte[], byte[]> rawKeys = new LinkedHashMap<byte[], byte[]>(m.size());
Map<byte[], byte[]> rawKeys = new LinkedHashMap<>(m.size());
for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
rawKeys.put(rawKey(entry.getKey()), rawValue(entry.getValue()));
}
execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection) {
connection.mSet(rawKeys);
return null;
}
execute(connection -> {
connection.mSet(rawKeys);
return null;
}, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#multiSetIfAbsent(java.util.Map)
*/
@Override
public Boolean multiSetIfAbsent(Map<? extends K, ? extends V> m) {
if (m.isEmpty()) {
return true;
}
final Map<byte[], byte[]> rawKeys = new LinkedHashMap<byte[], byte[]>(m.size());
Map<byte[], byte[]> rawKeys = new LinkedHashMap<>(m.size());
for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
rawKeys.put(rawKey(entry.getKey()), rawValue(entry.getValue()));
}
return execute(new RedisCallback<Boolean>() {
public Boolean doInRedis(RedisConnection connection) {
return connection.mSetNX(rawKeys);
}
}, true);
return execute(connection -> connection.mSetNX(rawKeys), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#set(java.lang.Object, java.lang.Object)
*/
@Override
public void set(K key, V value) {
final byte[] rawValue = rawValue(value);
byte[] rawValue = rawValue(value);
execute(new ValueDeserializingRedisCallback(key) {
@Override
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
connection.set(rawKey, rawValue);
return null;
@@ -175,12 +205,19 @@ class DefaultValueOperations<K, V> extends AbstractOperations<K, V> implements V
}, true);
}
public void set(K key, V value, final long timeout, final TimeUnit unit) {
final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#set(java.lang.Object, java.lang.Object, long, java.util.concurrent.TimeUnit)
*/
@Override
public void set(K key, V value, long timeout, TimeUnit unit) {
byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(value);
execute(new RedisCallback<Object>() {
@Override
public Object doInRedis(RedisConnection connection) throws DataAccessException {
potentiallyUsePsetEx(connection);
@@ -209,64 +246,64 @@ class DefaultValueOperations<K, V> extends AbstractOperations<K, V> implements V
}, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#setIfAbsent(java.lang.Object, java.lang.Object)
*/
@Override
public Boolean setIfAbsent(K key, V value) {
final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Boolean>() {
byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(value);
return execute(connection -> connection.setNX(rawKey, rawValue), true);
}
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
return connection.setNX(rawKey, rawValue);
}
}, true);
}
public void set(K key, final V value, final long offset) {
final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value);
execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection) {
connection.setRange(rawKey, rawValue, offset);
return null;
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#set(java.lang.Object, java.lang.Object, long)
*/
@Override
public void set(K key, V value, long offset) {
byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(value);
execute(connection -> {
connection.setRange(rawKey, rawValue, offset);
return null;
}, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#size(java.lang.Object)
*/
@Override
public Long size(K key) {
final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.strLen(rawKey);
}
}, true);
byte[] rawKey = rawKey(key);
return execute(connection -> connection.strLen(rawKey), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#setBit(java.lang.Object, long, boolean)
*/
@Override
public Boolean setBit(K key, final long offset, final boolean value) {
final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Boolean>() {
public Boolean setBit(K key, long offset, boolean value) {
public Boolean doInRedis(RedisConnection connection) {
return connection.setBit(rawKey, offset, value);
}
}, true);
byte[] rawKey = rawKey(key);
return execute(connection -> connection.setBit(rawKey, offset, value), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ValueOperations#getBit(java.lang.Object, long)
*/
@Override
public Boolean getBit(K key, final long offset) {
final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Boolean>() {
public Boolean getBit(K key, long offset) {
public Boolean doInRedis(RedisConnection connection) {
return connection.getBit(rawKey, offset);
}
}, true);
byte[] rawKey = rawKey(key);
return execute(connection -> connection.getBit(rawKey, offset), true);
}
}

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2016 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,16 +19,13 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import org.springframework.core.convert.converter.Converter;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisZSetCommands.Limit;
import org.springframework.data.redis.connection.RedisZSetCommands.Range;
import org.springframework.data.redis.connection.RedisZSetCommands.Tuple;
/**
* Default implementation of {@link ZSetOperations}.
*
*
* @author Costin Leau
* @author Christoph Strobl
* @author Thomas Darimont
@@ -41,105 +38,111 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
super(template);
}
public Boolean add(final K key, final V value, final double score) {
final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#add(java.lang.Object, java.lang.Object, double)
*/
@Override
public Boolean add(K key, V value, double score) {
return execute(new RedisCallback<Boolean>() {
public Boolean doInRedis(RedisConnection connection) {
return connection.zAdd(rawKey, score, rawValue);
}
}, true);
byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(value);
return execute(connection -> connection.zAdd(rawKey, score, rawValue), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#add(java.lang.Object, java.util.Set)
*/
@Override
public Long add(K key, Set<TypedTuple<V>> tuples) {
final byte[] rawKey = rawKey(key);
final Set<Tuple> rawValues = rawTupleValues(tuples);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.zAdd(rawKey, rawValues);
}
}, true);
byte[] rawKey = rawKey(key);
Set<Tuple> rawValues = rawTupleValues(tuples);
return execute(connection -> connection.zAdd(rawKey, rawValues), true);
}
public Double incrementScore(K key, V value, final double delta) {
final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#incrementScore(java.lang.Object, java.lang.Object, double)
*/
@Override
public Double incrementScore(K key, V value, double delta) {
return execute(new RedisCallback<Double>() {
public Double doInRedis(RedisConnection connection) {
return connection.zIncrBy(rawKey, delta, rawValue);
}
}, true);
byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(value);
return execute(connection -> connection.zIncrBy(rawKey, delta, rawValue), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#intersectAndStore(java.lang.Object, java.lang.Object, java.lang.Object)
*/
@Override
public Long intersectAndStore(K key, K otherKey, K destKey) {
return intersectAndStore(key, Collections.singleton(otherKey), destKey);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#intersectAndStore(java.lang.Object, java.util.Collection, java.lang.Object)
*/
@Override
public Long intersectAndStore(K key, Collection<K> otherKeys, K destKey) {
final byte[][] rawKeys = rawKeys(key, otherKeys);
final byte[] rawDestKey = rawKey(destKey);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.zInterStore(rawDestKey, rawKeys);
}
}, true);
byte[][] rawKeys = rawKeys(key, otherKeys);
byte[] rawDestKey = rawKey(destKey);
return execute(connection -> connection.zInterStore(rawDestKey, rawKeys), true);
}
public Set<V> range(K key, final long start, final long end) {
final byte[] rawKey = rawKey(key);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#range(java.lang.Object, long, long)
*/
@Override
public Set<V> range(K key, long start, long end) {
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
public Set<byte[]> doInRedis(RedisConnection connection) {
return connection.zRange(rawKey, start, end);
}
}, true);
byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(connection -> connection.zRange(rawKey, start, end), true);
return deserializeValues(rawValues);
}
public Set<V> reverseRange(K key, final long start, final long end) {
final byte[] rawKey = rawKey(key);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#reverseRange(java.lang.Object, long, long)
*/
@Override
public Set<V> reverseRange(K key, long start, long end) {
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
public Set<byte[]> doInRedis(RedisConnection connection) {
return connection.zRevRange(rawKey, start, end);
}
}, true);
byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(connection -> connection.zRevRange(rawKey, start, end), true);
return deserializeValues(rawValues);
}
public Set<TypedTuple<V>> rangeWithScores(K key, final long start, final long end) {
final byte[] rawKey = rawKey(key);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#rangeWithScores(java.lang.Object, long, long)
*/
@Override
public Set<TypedTuple<V>> rangeWithScores(K key, long start, long end) {
Set<Tuple> rawValues = execute(new RedisCallback<Set<Tuple>>() {
public Set<Tuple> doInRedis(RedisConnection connection) {
return connection.zRangeWithScores(rawKey, start, end);
}
}, true);
byte[] rawKey = rawKey(key);
Set<Tuple> rawValues = execute(connection -> connection.zRangeWithScores(rawKey, start, end), true);
return deserializeTupleValues(rawValues);
}
public Set<TypedTuple<V>> reverseRangeWithScores(K key, final long start, final long end) {
final byte[] rawKey = rawKey(key);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#reverseRangeWithScores(java.lang.Object, long, long)
*/
@Override
public Set<TypedTuple<V>> reverseRangeWithScores(K key, long start, long end) {
Set<Tuple> rawValues = execute(new RedisCallback<Set<Tuple>>() {
public Set<Tuple> doInRedis(RedisConnection connection) {
return connection.zRevRangeWithScores(rawKey, start, end);
}
}, true);
byte[] rawKey = rawKey(key);
Set<Tuple> rawValues = execute(connection -> connection.zRevRangeWithScores(rawKey, start, end), true);
return deserializeTupleValues(rawValues);
}
@@ -149,7 +152,7 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
* @see org.springframework.data.redis.core.ZSetOperations#rangeByLex(java.lang.Object, org.springframework.data.redis.connection.RedisZSetCommands.Range)
*/
@Override
public Set<V> rangeByLex(K key, final Range range) {
public Set<V> rangeByLex(K key, Range range) {
return rangeByLex(key, range, null);
}
@@ -158,207 +161,208 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
* @see org.springframework.data.redis.core.ZSetOperations#rangeByLex(java.lang.Object, org.springframework.data.redis.connection.RedisZSetCommands.Range, org.springframework.data.redis.connection.RedisZSetCommands.Limit)
*/
@Override
public Set<V> rangeByLex(K key, final Range range, final Limit limit) {
public Set<V> rangeByLex(K key, Range range, Limit limit) {
final byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
public Set<byte[]> doInRedis(RedisConnection connection) {
return connection.zRangeByLex(rawKey, range, limit);
}
}, true);
byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(connection -> connection.zRangeByLex(rawKey, range, limit), true);
return deserializeValues(rawValues);
}
public Set<V> rangeByScore(K key, final double min, final double max) {
final byte[] rawKey = rawKey(key);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#rangeByScore(java.lang.Object, double, double)
*/
@Override
public Set<V> rangeByScore(K key, double min, double max) {
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
public Set<byte[]> doInRedis(RedisConnection connection) {
return connection.zRangeByScore(rawKey, min, max);
}
}, true);
byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(connection -> connection.zRangeByScore(rawKey, min, max), true);
return deserializeValues(rawValues);
}
public Set<V> rangeByScore(K key, final double min, final double max, final long offset, final long count) {
final byte[] rawKey = rawKey(key);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#rangeByScore(java.lang.Object, double, double, long, long)
*/
@Override
public Set<V> rangeByScore(K key, double min, double max, long offset, long count) {
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
public Set<byte[]> doInRedis(RedisConnection connection) {
return connection.zRangeByScore(rawKey, min, max, offset, count);
}
}, true);
byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(connection -> connection.zRangeByScore(rawKey, min, max, offset, count), true);
return deserializeValues(rawValues);
}
public Set<V> reverseRangeByScore(K key, final double min, final double max) {
final byte[] rawKey = rawKey(key);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#reverseRangeByScore(java.lang.Object, double, double)
*/
@Override
public Set<V> reverseRangeByScore(K key, double min, double max) {
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
public Set<byte[]> doInRedis(RedisConnection connection) {
return connection.zRevRangeByScore(rawKey, min, max);
}
}, true);
byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(connection -> connection.zRevRangeByScore(rawKey, min, max), true);
return deserializeValues(rawValues);
}
public Set<V> reverseRangeByScore(K key, final double min, final double max, final long offset, final long count) {
final byte[] rawKey = rawKey(key);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#reverseRangeByScore(java.lang.Object, double, double, long, long)
*/
@Override
public Set<V> reverseRangeByScore(K key, double min, double max, long offset, long count) {
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
public Set<byte[]> doInRedis(RedisConnection connection) {
return connection.zRevRangeByScore(rawKey, min, max, offset, count);
}
}, true);
byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(connection -> connection.zRevRangeByScore(rawKey, min, max, offset, count), true);
return deserializeValues(rawValues);
}
public Set<TypedTuple<V>> rangeByScoreWithScores(K key, final double min, final double max) {
final byte[] rawKey = rawKey(key);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#rangeByScoreWithScores(java.lang.Object, double, double)
*/
@Override
public Set<TypedTuple<V>> rangeByScoreWithScores(K key, double min, double max) {
Set<Tuple> rawValues = execute(new RedisCallback<Set<Tuple>>() {
public Set<Tuple> doInRedis(RedisConnection connection) {
return connection.zRangeByScoreWithScores(rawKey, min, max);
}
}, true);
byte[] rawKey = rawKey(key);
Set<Tuple> rawValues = execute(connection -> connection.zRangeByScoreWithScores(rawKey, min, max), true);
return deserializeTupleValues(rawValues);
}
public Set<TypedTuple<V>> rangeByScoreWithScores(K key, final double min, final double max, final long offset,
final long count) {
final byte[] rawKey = rawKey(key);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#rangeByScoreWithScores(java.lang.Object, double, double, long, long)
*/
@Override
public Set<TypedTuple<V>> rangeByScoreWithScores(K key, double min, double max, long offset, long count) {
Set<Tuple> rawValues = execute(new RedisCallback<Set<Tuple>>() {
public Set<Tuple> doInRedis(RedisConnection connection) {
return connection.zRangeByScoreWithScores(rawKey, min, max, offset, count);
}
}, true);
byte[] rawKey = rawKey(key);
Set<Tuple> rawValues = execute(connection -> connection.zRangeByScoreWithScores(rawKey, min, max, offset, count),
true);
return deserializeTupleValues(rawValues);
}
public Set<TypedTuple<V>> reverseRangeByScoreWithScores(K key, final double min, final double max) {
final byte[] rawKey = rawKey(key);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#reverseRangeByScoreWithScores(java.lang.Object, double, double)
*/
@Override
public Set<TypedTuple<V>> reverseRangeByScoreWithScores(K key, double min, double max) {
Set<Tuple> rawValues = execute(new RedisCallback<Set<Tuple>>() {
public Set<Tuple> doInRedis(RedisConnection connection) {
return connection.zRevRangeByScoreWithScores(rawKey, min, max);
}
}, true);
byte[] rawKey = rawKey(key);
Set<Tuple> rawValues = execute(connection -> connection.zRevRangeByScoreWithScores(rawKey, min, max), true);
return deserializeTupleValues(rawValues);
}
public Set<TypedTuple<V>> reverseRangeByScoreWithScores(K key, final double min, final double max, final long offset,
final long count) {
final byte[] rawKey = rawKey(key);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#reverseRangeByScoreWithScores(java.lang.Object, double, double, long, long)
*/
@Override
public Set<TypedTuple<V>> reverseRangeByScoreWithScores(K key, double min, double max, long offset, long count) {
Set<Tuple> rawValues = execute(new RedisCallback<Set<Tuple>>() {
public Set<Tuple> doInRedis(RedisConnection connection) {
return connection.zRevRangeByScoreWithScores(rawKey, min, max, offset, count);
}
}, true);
byte[] rawKey = rawKey(key);
Set<Tuple> rawValues = execute(connection -> connection.zRevRangeByScoreWithScores(rawKey, min, max, offset, count),
true);
return deserializeTupleValues(rawValues);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#rank(java.lang.Object, java.lang.Object)
*/
@Override
public Long rank(K key, Object o) {
final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(o);
return execute(new RedisCallback<Long>() {
byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(o);
public Long doInRedis(RedisConnection connection) {
Long zRank = connection.zRank(rawKey, rawValue);
return (zRank != null && zRank.longValue() >= 0 ? zRank : null);
}
return execute(connection -> {
Long zRank = connection.zRank(rawKey, rawValue);
return (zRank != null && zRank.longValue() >= 0 ? zRank : null);
}, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#reverseRank(java.lang.Object, java.lang.Object)
*/
@Override
public Long reverseRank(K key, Object o) {
final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(o);
return execute(new RedisCallback<Long>() {
byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(o);
public Long doInRedis(RedisConnection connection) {
Long zRank = connection.zRevRank(rawKey, rawValue);
return (zRank != null && zRank.longValue() >= 0 ? zRank : null);
}
return execute(connection -> {
Long zRank = connection.zRevRank(rawKey, rawValue);
return (zRank != null && zRank.longValue() >= 0 ? zRank : null);
}, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#remove(java.lang.Object, java.lang.Object[])
*/
@Override
public Long remove(K key, Object... values) {
final byte[] rawKey = rawKey(key);
final byte[][] rawValues = rawValues(values);
return execute(new RedisCallback<Long>() {
byte[] rawKey = rawKey(key);
byte[][] rawValues = rawValues(values);
public Long doInRedis(RedisConnection connection) {
return connection.zRem(rawKey, rawValues);
}
}, true);
return execute(connection -> connection.zRem(rawKey, rawValues), true);
}
public Long removeRange(K key, final long start, final long end) {
final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Long>() {
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#removeRange(java.lang.Object, long, long)
*/
@Override
public Long removeRange(K key, long start, long end) {
public Long doInRedis(RedisConnection connection) {
return connection.zRemRange(rawKey, start, end);
}
}, true);
byte[] rawKey = rawKey(key);
return execute(connection -> connection.zRemRange(rawKey, start, end), true);
}
public Long removeRangeByScore(K key, final double min, final double max) {
final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Long>() {
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#removeRangeByScore(java.lang.Object, double, double)
*/
@Override
public Long removeRangeByScore(K key, double min, double max) {
public Long doInRedis(RedisConnection connection) {
return connection.zRemRangeByScore(rawKey, min, max);
}
}, true);
byte[] rawKey = rawKey(key);
return execute(connection -> connection.zRemRangeByScore(rawKey, min, max), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#score(java.lang.Object, java.lang.Object)
*/
@Override
public Double score(K key, Object o) {
final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(o);
return execute(new RedisCallback<Double>() {
public Double doInRedis(RedisConnection connection) {
return connection.zScore(rawKey, rawValue);
}
}, true);
byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(o);
return execute(connection -> connection.zScore(rawKey, rawValue), true);
}
public Long count(K key, final double min, final double max) {
final byte[] rawKey = rawKey(key);
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#count(java.lang.Object, double, double)
*/
@Override
public Long count(K key, double min, double max) {
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.zCount(rawKey, min, max);
}
}, true);
byte[] rawKey = rawKey(key);
return execute(connection -> connection.zCount(rawKey, min, max), true);
}
/*
@@ -377,28 +381,29 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
@Override
public Long zCard(K key) {
final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.zCard(rawKey);
}
}, true);
byte[] rawKey = rawKey(key);
return execute(connection -> connection.zCard(rawKey), true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#unionAndStore(java.lang.Object, java.lang.Object, java.lang.Object)
*/
@Override
public Long unionAndStore(K key, K otherKey, K destKey) {
return unionAndStore(key, Collections.singleton(otherKey), destKey);
}
/*
* (non-Javadoc)
* @see org.springframework.data.redis.core.ZSetOperations#unionAndStore(java.lang.Object, java.util.Collection, java.lang.Object)
*/
@Override
public Long unionAndStore(K key, Collection<K> otherKeys, K destKey) {
final byte[][] rawKeys = rawKeys(key, otherKeys);
final byte[] rawDestKey = rawKey(destKey);
return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) {
return connection.zUnionStore(rawDestKey, rawKeys);
}
}, true);
byte[][] rawKeys = rawKeys(key, otherKeys);
byte[] rawDestKey = rawKey(destKey);
return execute(connection -> connection.zUnionStore(rawDestKey, rawKeys), true);
}
/*
@@ -406,51 +411,24 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
* @see org.springframework.data.redis.core.ZSetOperations#scan(java.lang.Object, org.springframework.data.redis.core.ScanOptions)
*/
@Override
public Cursor<TypedTuple<V>> scan(K key, final ScanOptions options) {
public Cursor<TypedTuple<V>> scan(K key, ScanOptions options) {
final byte[] rawKey = rawKey(key);
Cursor<Tuple> cursor = template.executeWithStickyConnection(new RedisCallback<Cursor<Tuple>>() {
byte[] rawKey = rawKey(key);
Cursor<Tuple> cursor = template.executeWithStickyConnection(connection -> connection.zScan(rawKey, options));
@Override
public Cursor<Tuple> doInRedis(RedisConnection connection) throws DataAccessException {
return connection.zScan(rawKey, options);
}
});
return new ConvertingCursor<Tuple, TypedTuple<V>>(cursor, new Converter<Tuple, TypedTuple<V>>() {
@Override
public TypedTuple<V> convert(Tuple source) {
return deserializeTuple(source);
}
});
return new ConvertingCursor<>(cursor, this::deserializeTuple);
}
public Set<byte[]> rangeByScore(K key, final String min, final String max) {
public Set<byte[]> rangeByScore(K key, String min, String max) {
final byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
public Set<byte[]> doInRedis(RedisConnection connection) {
return connection.zRangeByScore(rawKey, min, max);
}
}, true);
return rawValues;
byte[] rawKey = rawKey(key);
return execute(connection -> connection.zRangeByScore(rawKey, min, max), true);
}
public Set<byte[]> rangeByScore(K key, final String min, final String max, final long offset, final long count) {
public Set<byte[]> rangeByScore(K key, String min, String max, long offset, long count) {
final byte[] rawKey = rawKey(key);
byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
public Set<byte[]> doInRedis(RedisConnection connection) {
return connection.zRangeByScore(rawKey, min, max, offset, count);
}
}, true);
return rawValues;
return execute(connection -> connection.zRangeByScore(rawKey, min, max, offset, count), true);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016 the original author or authors.
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,7 +38,7 @@ public class PartialUpdate<T> {
private final T value;
private boolean refreshTtl = false;
private final List<PropertyUpdate> propertyUpdates = new ArrayList<PropertyUpdate>();
private final List<PropertyUpdate> propertyUpdates = new ArrayList<>();
private PartialUpdate(Object id, Class<T> target, T value, boolean refreshTtl, List<PropertyUpdate> propertyUpdates) {
@@ -90,7 +90,7 @@ public class PartialUpdate<T> {
* @param targetType must not be {@literal null}.
*/
public static <S> PartialUpdate<S> newPartialUpdate(Object id, Class<S> targetType) {
return new PartialUpdate<S>(id, targetType);
return new PartialUpdate<>(id, targetType);
}
/**
@@ -111,7 +111,7 @@ public class PartialUpdate<T> {
Assert.hasText(path, "Path to set must not be null or empty!");
PartialUpdate<T> update = new PartialUpdate<T>(this.id, this.target, this.value, this.refreshTtl,
PartialUpdate<T> update = new PartialUpdate<>(this.id, this.target, this.value, this.refreshTtl,
this.propertyUpdates);
update.propertyUpdates.add(new PropertyUpdate(UpdateCommand.SET, path, value));
@@ -128,7 +128,7 @@ public class PartialUpdate<T> {
Assert.hasText(path, "Path to remove must not be null or empty!");
PartialUpdate<T> update = new PartialUpdate<T>(this.id, this.target, this.value, this.refreshTtl,
PartialUpdate<T> update = new PartialUpdate<>(this.id, this.target, this.value, this.refreshTtl,
this.propertyUpdates);
update.propertyUpdates.add(new PropertyUpdate(UpdateCommand.DEL, path));
@@ -176,7 +176,7 @@ public class PartialUpdate<T> {
* @return a new {@link PartialUpdate}.
*/
public PartialUpdate<T> refreshTtl(boolean refreshTtl) {
return new PartialUpdate<T>(this.id, this.target, this.value, refreshTtl, this.propertyUpdates);
return new PartialUpdate<>(this.id, this.target, this.value, refreshTtl, this.propertyUpdates);
}
/**

View File

@@ -63,7 +63,7 @@ public interface ReactiveSetOperations<K, V> {
* Remove and return {@code count} random members from set at {@code key}.
*
* @param key must not be {@literal null}.
* @param count nr of members to return
* @param count number of random members to pop from the set.
* @return {@link Flux} emitting random members.
* @see <a href="http://redis.io/commands/spop">Redis Documentation: SPOP</a>
*/
@@ -247,7 +247,7 @@ public interface ReactiveSetOperations<K, V> {
* Get {@code count} distinct random elements from set at {@code key}.
*
* @param key must not be {@literal null}.
* @param count
* @param count number of members to return.
* @return
* @see <a href="http://redis.io/commands/srandmember">Redis Documentation: SRANDMEMBER</a>
*/
@@ -257,7 +257,7 @@ public interface ReactiveSetOperations<K, V> {
* Get {@code count} random elements from set at {@code key}.
*
* @param key must not be {@literal null}.
* @param count
* @param count number of members to return.
* @return
* @see <a href="http://redis.io/commands/srandmember">Redis Documentation: SRANDMEMBER</a>
*/

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -211,7 +211,7 @@ public enum RedisCommand {
private boolean read = true;
private boolean write = true;
private Set<String> alias = new HashSet<String>(1);
private Set<String> alias = new HashSet<>(1);
private int minArgs = -1;
private int maxArgs = -1;
@@ -225,7 +225,7 @@ public enum RedisCommand {
private static Map<String, RedisCommand> buildCommandLookupTable() {
RedisCommand[] cmds = RedisCommand.values();
Map<String, RedisCommand> map = new HashMap<String, RedisCommand>(cmds.length, 1.0F);
Map<String, RedisCommand> map = new HashMap<>(cmds.length, 1.0F);
for (RedisCommand cmd : cmds) {
@@ -256,7 +256,7 @@ public enum RedisCommand {
/**
* Creates a new {@link RedisCommand}.
*
*
* @param mode
* @param minArgs
* @param maxArgs
@@ -309,7 +309,7 @@ public enum RedisCommand {
/**
* {@link String#equalsIgnoreCase(String)} compare the given string representation of {@literal command} against the
* {@link #toString()} representation of the command as well as its given {@link #alias}.
*
*
* @param command
* @return true if positive match.
*/
@@ -328,7 +328,7 @@ public enum RedisCommand {
/**
* Validates given argument count against expected ones.
*
*
* @param nrArguments
* @exception IllegalArgumentException in case argument count does not match expected.
*/
@@ -351,7 +351,7 @@ public enum RedisCommand {
/**
* Returns the command represented by the given {@code key}. Returns {@link #UNKNOWN} if no matching command could be
* found.
*
*
* @param key
* @return
*/

View File

@@ -104,7 +104,7 @@ public class RedisKeyValueAdapter extends AbstractKeyValueAdapter
private RedisOperations<?, ?> redisOps;
private RedisConverter converter;
private RedisMessageListenerContainer messageListenerContainer;
private final AtomicReference<KeyExpirationEventMessageListener> expirationListener = new AtomicReference<KeyExpirationEventMessageListener>(
private final AtomicReference<KeyExpirationEventMessageListener> expirationListener = new AtomicReference<>(
null);
private ApplicationEventPublisher eventPublisher;

View File

@@ -95,7 +95,7 @@ public class RedisKeyValueTemplate extends KeyValueTemplate {
? (Iterable<?>) callbackResult
: Collections.singleton(callbackResult);
List<T> result = new ArrayList<T>();
List<T> result = new ArrayList<>();
for (Object id : ids) {
String idToUse = adapter.getConverter().getConversionService().canConvert(id.getClass(), String.class)

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014 the original author or authors.
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,7 @@ import java.util.Iterator;
/**
* {@link ScanIteration} holds the values contained in Redis {@literal Multibulk reply} on exectuting {@literal SCAN}
* command.
*
*
* @author Christoph Strobl
* @since 1.4
*/
@@ -39,12 +39,12 @@ public class ScanIteration<T> implements Iterable<T> {
public ScanIteration(long cursorId, Collection<T> items) {
this.cursorId = cursorId;
this.items = (items != null ? new ArrayList<T>(items) : Collections.<T> emptyList());
this.items = (items != null ? new ArrayList<>(items) : Collections.<T> emptyList());
}
/**
* The cursor id to be used for subsequent requests.
*
*
* @return
*/
public long getCursorId() {
@@ -53,7 +53,7 @@ public class ScanIteration<T> implements Iterable<T> {
/**
* Get the items returned.
*
*
* @return
*/
public Collection<T> getItems() {

View File

@@ -21,7 +21,7 @@ import java.util.Set;
/**
* Redis set specific operations.
*
*
* @author Costin Leau
* @author Christoph Strobl
* @author Mark Paluch
@@ -61,7 +61,7 @@ public interface SetOperations<K, V> {
* Remove and return {@code count} random members from set at {@code key}.
*
* @param key must not be {@literal null}.
* @param count nr of members to return.
* @param count number of random members to pop from the set.
* @return empty {@link List} if key does not exist. Never {@literal null}.
* @see <a href="http://redis.io/commands/spop">Redis Documentation: SPOP</a>
* @since 2.0

View File

@@ -181,7 +181,7 @@ final class BinaryConverters {
@Override
public <T extends Number> Converter<byte[], T> getConverter(Class<T> targetType) {
return new BytesToNumberConverter<T>(targetType);
return new BytesToNumberConverter<>(targetType);
}
private static final class BytesToNumberConverter<T extends Number> extends StringBasedConverter
@@ -212,8 +212,8 @@ final class BinaryConverters {
@WritingConverter
static class BooleanToBytesConverter extends StringBasedConverter implements Converter<Boolean, byte[]> {
final byte[] _true = fromString("1");
final byte[] _false = fromString("0");
byte[] _true = fromString("1");
byte[] _false = fromString("0");
@Override
public byte[] convert(Boolean source) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2015-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,8 +31,9 @@ import org.springframework.util.StringUtils;
/**
* Bucket is the data bag for Redis hash structures to be used with {@link RedisData}.
*
*
* @author Christoph Strobl
* @author Mark Paluch
* @since 1.7
*/
public class Bucket {
@@ -48,19 +49,19 @@ public class Bucket {
* Creates new empty bucket
*/
public Bucket() {
data = new LinkedHashMap<String, byte[]>();
data = new LinkedHashMap<>();
}
Bucket(Map<String, byte[]> data) {
Assert.notNull(data, "Inital data must not be null!");
this.data = new LinkedHashMap<String, byte[]>(data.size());
this.data = new LinkedHashMap<>(data.size());
this.data.putAll(data);
}
/**
* Add {@link String} representation of property dot path with given value.
*
*
* @param path must not be {@literal null} or {@link String#isEmpty()}.
* @param value can be {@literal null}.
*/
@@ -72,7 +73,7 @@ public class Bucket {
/**
* Get value assigned with path.
*
*
* @param path path must not be {@literal null} or {@link String#isEmpty()}.
* @return {@literal null} if not set.
*/
@@ -84,7 +85,7 @@ public class Bucket {
/**
* A set view of the mappings contained in this bucket.
*
*
* @return never {@literal null}.
*/
public Set<Entry<String, byte[]>> entrySet() {
@@ -121,7 +122,7 @@ public class Bucket {
/**
* Key/value pairs contained in the {@link Bucket}.
*
*
* @return never {@literal null}.
*/
public Map<String, byte[]> asMap() {
@@ -130,7 +131,7 @@ public class Bucket {
/**
* Extracts a bucket containing key/value pairs with the {@code prefix}.
*
*
* @param prefix
* @return
*/
@@ -148,7 +149,7 @@ public class Bucket {
/**
* Get all the keys matching a given path.
*
*
* @param path the path to look for. Can be {@literal null}.
* @return all keys if path is {@null} or empty.
*/
@@ -160,7 +161,7 @@ public class Bucket {
Pattern pattern = Pattern.compile("(" + Pattern.quote(path) + ")\\.\\[.*?\\]");
Set<String> keys = new LinkedHashSet<String>();
Set<String> keys = new LinkedHashSet<>();
for (Map.Entry<String, byte[]> entry : data.entrySet()) {
Matcher matcher = pattern.matcher(entry.getKey());
@@ -174,12 +175,12 @@ public class Bucket {
/**
* Get keys and values in binary format.
*
*
* @return never {@literal null}.
*/
public Map<byte[], byte[]> rawMap() {
Map<byte[], byte[]> raw = new LinkedHashMap<byte[], byte[]>(data.size());
Map<byte[], byte[]> raw = new LinkedHashMap<>(data.size());
for (Map.Entry<String, byte[]> entry : data.entrySet()) {
if (entry.getValue() != null) {
raw.put(entry.getKey().getBytes(CHARSET), entry.getValue());
@@ -190,7 +191,7 @@ public class Bucket {
/**
* Creates a new Bucket from a given raw map.
*
*
* @param source can be {@literal null}.
* @return never {@literal null}.
*/
@@ -209,7 +210,7 @@ public class Bucket {
/**
* Creates a new Bucket from a given {@link String} map.
*
*
* @param source can be {@literal null}.
* @return never {@literal null}.
*/
@@ -238,7 +239,7 @@ public class Bucket {
private String safeToString() {
Map<String, String> serialized = new LinkedHashMap<String, String>();
Map<String, String> serialized = new LinkedHashMap<>();
for (Map.Entry<String, byte[]> entry : data.entrySet()) {
if (entry.getValue() != null) {
serialized.put(entry.getKey(), toUtf8String(entry.getValue()));

View File

@@ -32,7 +32,7 @@ import org.springframework.util.CollectionUtils;
* <br />
* <strong>NOTE</strong> {@link IndexedData} created by an {@link IndexResolver} can be overwritten by subsequent
* {@link IndexResolver}.
*
*
* @author Christoph Strobl
* @since 1.7
*/
@@ -42,7 +42,7 @@ public class CompositeIndexResolver implements IndexResolver {
/**
* Create new {@link CompositeIndexResolver}.
*
*
* @param resolvers must not be {@literal null}.
*/
public CompositeIndexResolver(Collection<IndexResolver> resolvers) {
@@ -51,7 +51,7 @@ public class CompositeIndexResolver implements IndexResolver {
if (CollectionUtils.contains(resolvers.iterator(), null)) {
throw new IllegalArgumentException("Resolvers must no contain null values");
}
this.resolvers = new ArrayList<IndexResolver>(resolvers);
this.resolvers = new ArrayList<>(resolvers);
}
/*
@@ -65,7 +65,7 @@ public class CompositeIndexResolver implements IndexResolver {
return Collections.emptySet();
}
Set<IndexedData> data = new LinkedHashSet<IndexedData>();
Set<IndexedData> data = new LinkedHashSet<>();
for (IndexResolver resolver : resolvers) {
data.addAll(resolver.resolveIndexesFor(typeInformation, value));
}
@@ -79,7 +79,7 @@ public class CompositeIndexResolver implements IndexResolver {
public Set<IndexedData> resolveIndexesFor(String keyspace, String path, TypeInformation<?> typeInformation,
Object value) {
Set<IndexedData> data = new LinkedHashSet<IndexedData>();
Set<IndexedData> data = new LinkedHashSet<>();
for (IndexResolver resolver : resolvers) {
data.addAll(resolver.resolveIndexesFor(keyspace, path, typeInformation, value));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016 the original author or authors.
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -57,7 +57,7 @@ public abstract class Jsr310Converters {
return Collections.emptySet();
}
List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
List<Converter<?, ?>> converters = new ArrayList<>();
converters.add(new LocalDateTimeToBytesConverter());
converters.add(new BytesToLocalDateTimeConverter());
converters.add(new LocalDateToBytesConverter());

View File

@@ -39,7 +39,7 @@ public class KeyspaceConfiguration {
public KeyspaceConfiguration() {
this.settingsMap = new ConcurrentHashMap<Class<?>, KeyspaceSettings>();
this.settingsMap = new ConcurrentHashMap<>();
for (KeyspaceSettings initial : initialConfiguration()) {
settingsMap.put(initial.type, initial);
}

View File

@@ -44,7 +44,6 @@ import org.springframework.data.convert.TypeAliasAccessor;
import org.springframework.data.convert.TypeMapper;
import org.springframework.data.keyvalue.core.mapping.KeySpaceResolver;
import org.springframework.data.mapping.Alias;
import org.springframework.data.mapping.Association;
import org.springframework.data.mapping.AssociationHandler;
import org.springframework.data.mapping.MappingException;
import org.springframework.data.mapping.PersistentPropertyAccessor;
@@ -122,8 +121,8 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
private final GenericConversionService conversionService;
private final EntityInstantiators entityInstantiators;
private final TypeMapper<RedisData> typeMapper;
private final Comparator<String> listKeyComparator = new NullSafeComparator<String>(
NaturalOrderingKeyComparator.INSTANCE, true);
private final Comparator<String> listKeyComparator = new NullSafeComparator<>(NaturalOrderingKeyComparator.INSTANCE,
true);
private ReferenceResolver referenceResolver;
private IndexResolver indexResolver;
@@ -155,7 +154,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
this.conversionService = new DefaultConversionService();
this.customConversions = new RedisCustomConversions();
typeMapper = new DefaultTypeMapper<RedisData>(new RedisTypeAliasAccessor(this.conversionService));
typeMapper = new DefaultTypeMapper<>(new RedisTypeAliasAccessor(this.conversionService));
this.referenceResolver = referenceResolver;
@@ -167,12 +166,12 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
* @see org.springframework.data.convert.EntityReader#read(java.lang.Class, java.lang.Object)
*/
@Override
public <R> R read(Class<R> type, final RedisData source) {
public <R> R read(Class<R> type, RedisData source) {
return readInternal("", type, source);
}
@SuppressWarnings("unchecked")
private <R> R readInternal(final String path, Class<R> type, final RedisData source) {
private <R> R readInternal(String path, Class<R> type, RedisData source) {
if (source.getBucket() == null || source.getBucket().isEmpty()) {
return null;
@@ -187,7 +186,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
if (customConversions.hasCustomReadTarget(Map.class, readType.getType())) {
Map<String, byte[]> partial = new HashMap<String, byte[]>();
Map<String, byte[]> partial = new HashMap<>();
if (!path.isEmpty()) {
@@ -217,86 +216,81 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
new PersistentEntityParameterValueProvider<>(entity,
new ConverterAwareParameterValueProvider(path, source, conversionService), this.conversionService));
final PersistentPropertyAccessor accessor = entity.getPropertyAccessor(instance);
PersistentPropertyAccessor accessor = entity.getPropertyAccessor(instance);
entity.doWithProperties(new PropertyHandler<RedisPersistentProperty>() {
entity.doWithProperties((PropertyHandler<RedisPersistentProperty>) persistentProperty -> {
@Override
public void doWithPersistentProperty(RedisPersistentProperty persistentProperty) {
String currentPath = !path.isEmpty() ? path + "." + persistentProperty.getName() : persistentProperty.getName();
String currentPath = !path.isEmpty() ? path + "." + persistentProperty.getName() : persistentProperty.getName();
PreferredConstructor<?, RedisPersistentProperty> constructor = entity.getPersistenceConstructor();
PreferredConstructor<?, RedisPersistentProperty> constructor = entity.getPersistenceConstructor();
if (constructor.isConstructorParameter(persistentProperty)) {
return;
}
if (constructor.isConstructorParameter(persistentProperty)) {
return;
if (persistentProperty.isMap()) {
Map<?, ?> targetValue = null;
Class<?> mapValueType = persistentProperty.getMapValueType();
if (mapValueType == null) {
throw new IllegalArgumentException("Unable to retrieve MapValueType!");
}
if (persistentProperty.isMap()) {
Map<?, ?> targetValue = null;
Class<?> mapValueType = persistentProperty.getMapValueType();
if (mapValueType == null) {
throw new IllegalArgumentException("Unable to retrieve MapValueType!");
}
if (conversionService.canConvert(byte[].class, mapValueType)) {
targetValue = readMapOfSimpleTypes(currentPath, persistentProperty.getType(),
persistentProperty.getComponentType(), mapValueType, source);
} else {
targetValue = readMapOfComplexTypes(currentPath, persistentProperty.getType(),
persistentProperty.getComponentType(), mapValueType, source);
}
if (targetValue != null) {
accessor.setProperty(persistentProperty, targetValue);
}
}
else if (persistentProperty.isCollectionLike()) {
Object targetValue = readCollectionOrArray(currentPath, persistentProperty.getType(),
persistentProperty.getTypeInformation().getRequiredComponentType().getActualType().getType(),
source.getBucket());
if (targetValue != null) {
accessor.setProperty(persistentProperty, targetValue);
}
} else if (persistentProperty.isEntity() && !conversionService.canConvert(byte[].class,
persistentProperty.getTypeInformation().getActualType().getType())) {
Class<R> targetType = (Class<R>) persistentProperty.getTypeInformation().getActualType().getType();
Bucket bucket = source.getBucket().extract(currentPath + ".");
RedisData newBucket = new RedisData(bucket);
byte[] type = bucket.get(currentPath + "." + TYPE_HINT_ALIAS);
if (type != null && type.length > 0) {
newBucket.getBucket().put(TYPE_HINT_ALIAS, type);
}
R val = readInternal(currentPath, targetType, newBucket);
accessor.setProperty(persistentProperty, val);
if (conversionService.canConvert(byte[].class, mapValueType)) {
targetValue = readMapOfSimpleTypes(currentPath, persistentProperty.getType(),
persistentProperty.getComponentType(), mapValueType, source);
} else {
targetValue = readMapOfComplexTypes(currentPath, persistentProperty.getType(),
persistentProperty.getComponentType(), mapValueType, source);
}
if (persistentProperty.isIdProperty() && StringUtils.isEmpty(path.isEmpty())) {
if (source.getBucket().get(currentPath) == null) {
accessor.setProperty(persistentProperty,
fromBytes(source.getBucket().get(currentPath), persistentProperty.getActualType()));
} else {
accessor.setProperty(persistentProperty, source.getId());
}
}
Class<?> typeToUse = getTypeHint(currentPath, source.getBucket(), persistentProperty.getActualType());
accessor.setProperty(persistentProperty, fromBytes(source.getBucket().get(currentPath), typeToUse));
if (targetValue != null) {
accessor.setProperty(persistentProperty, targetValue);
}
}
else if (persistentProperty.isCollectionLike()) {
Object targetValue = readCollectionOrArray(currentPath, persistentProperty.getType(),
persistentProperty.getTypeInformation().getRequiredComponentType().getActualType().getType(),
source.getBucket());
if (targetValue != null) {
accessor.setProperty(persistentProperty, targetValue);
}
} else if (persistentProperty.isEntity() && !conversionService.canConvert(byte[].class,
persistentProperty.getTypeInformation().getActualType().getType())) {
Class<R> targetType = (Class<R>) persistentProperty.getTypeInformation().getActualType().getType();
Bucket bucket = source.getBucket().extract(currentPath + ".");
RedisData newBucket = new RedisData(bucket);
byte[] type1 = bucket.get(currentPath + "." + TYPE_HINT_ALIAS);
if (type1 != null && type1.length > 0) {
newBucket.getBucket().put(TYPE_HINT_ALIAS, type1);
}
R val = readInternal(currentPath, targetType, newBucket);
accessor.setProperty(persistentProperty, val);
} else {
if (persistentProperty.isIdProperty() && StringUtils.isEmpty(path.isEmpty())) {
if (source.getBucket().get(currentPath) == null) {
accessor.setProperty(persistentProperty,
fromBytes(source.getBucket().get(currentPath), persistentProperty.getActualType()));
} else {
accessor.setProperty(persistentProperty, source.getId());
}
}
Class<?> typeToUse = getTypeHint(currentPath, source.getBucket(), persistentProperty.getActualType());
accessor.setProperty(persistentProperty, fromBytes(source.getBucket().get(currentPath), typeToUse));
}
});
readAssociation(path, source, entity, accessor);
@@ -304,56 +298,52 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
return (R) instance;
}
private void readAssociation(final String path, final RedisData source, final RedisPersistentEntity<?> entity,
final PersistentPropertyAccessor accessor) {
private void readAssociation(String path, RedisData source, RedisPersistentEntity<?> entity,
PersistentPropertyAccessor accessor) {
entity.doWithAssociations(new AssociationHandler<RedisPersistentProperty>() {
entity.doWithAssociations((AssociationHandler<RedisPersistentProperty>) association -> {
@Override
public void doWithAssociation(Association<RedisPersistentProperty> association) {
String currentPath = !path.isEmpty() ? path + "." + association.getInverse().getName()
: association.getInverse().getName();
String currentPath = !path.isEmpty() ? path + "." + association.getInverse().getName()
: association.getInverse().getName();
if (association.getInverse().isCollectionLike()) {
if (association.getInverse().isCollectionLike()) {
Bucket bucket = source.getBucket().extract(currentPath + ".[");
Bucket bucket = source.getBucket().extract(currentPath + ".[");
Collection<Object> target = CollectionFactory.createCollection(association.getInverse().getType(),
association.getInverse().getComponentType(), bucket.size());
Collection<Object> target = CollectionFactory.createCollection(association.getInverse().getType(),
association.getInverse().getComponentType(), bucket.size());
for (Entry<String, byte[]> entry : bucket.entrySet()) {
for (Entry<String, byte[]> entry : bucket.entrySet()) {
String referenceKey = fromBytes(entry.getValue(), String.class);
String[] args = referenceKey.split(":");
Map<byte[], byte[]> rawHash = referenceResolver.resolveReference(args[1], args[0]);
if (!CollectionUtils.isEmpty(rawHash)) {
target.add(read(association.getInverse().getActualType(), new RedisData(rawHash)));
}
}
accessor.setProperty(association.getInverse(), target);
} else {
byte[] binKey = source.getBucket().get(currentPath);
if (binKey == null || binKey.length == 0) {
return;
}
String key = fromBytes(binKey, String.class);
String[] args = key.split(":");
String referenceKey = fromBytes(entry.getValue(), String.class);
String[] args = referenceKey.split(":");
Map<byte[], byte[]> rawHash = referenceResolver.resolveReference(args[1], args[0]);
if (!CollectionUtils.isEmpty(rawHash)) {
accessor.setProperty(association.getInverse(),
read(association.getInverse().getActualType(), new RedisData(rawHash)));
target.add(read(association.getInverse().getActualType(), new RedisData(rawHash)));
}
}
accessor.setProperty(association.getInverse(), target);
} else {
byte[] binKey = source.getBucket().get(currentPath);
if (binKey == null || binKey.length == 0) {
return;
}
String key = fromBytes(binKey, String.class);
String[] args = key.split(":");
Map<byte[], byte[]> rawHash = referenceResolver.resolveReference(args[1], args[0]);
if (!CollectionUtils.isEmpty(rawHash)) {
accessor.setProperty(association.getInverse(),
read(association.getInverse().getActualType(), new RedisData(rawHash)));
}
}
});
}
@@ -364,7 +354,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
*/
@Override
@SuppressWarnings({ "rawtypes" })
public void write(Object source, final RedisData sink) {
public void write(Object source, RedisData sink) {
if (source == null) {
return;
@@ -452,10 +442,9 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
targetProperty = getTargetPropertyOrNullForPath(path.replaceAll("\\.\\[.*\\]", ""), update.getTarget());
TypeInformation<?> ti = targetProperty == null ? ClassTypeInformation.OBJECT
: (targetProperty.isMap()
? (targetProperty.getTypeInformation().getMapValueType() != null
? targetProperty.getTypeInformation().getRequiredMapValueType() : ClassTypeInformation.OBJECT)
: targetProperty.getTypeInformation().getActualType());
: (targetProperty.isMap() ? (targetProperty.getTypeInformation().getMapValueType() != null
? targetProperty.getTypeInformation().getRequiredMapValueType()
: ClassTypeInformation.OBJECT) : targetProperty.getTypeInformation().getActualType());
writeInternal(entity.getKeySpace(), pUpdate.getPropertyPath(), pUpdate.getValue(), ti, sink);
return;
@@ -495,7 +484,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
targetProperty.getTypeInformation().getActualType(), sink);
} else if (targetProperty.isMap()) {
Map<Object, Object> map = new HashMap<Object, Object>();
Map<Object, Object> map = new HashMap<>();
if (pUpdate.getValue() instanceof Map) {
map.putAll((Map<?, ?>) pUpdate.getValue());
@@ -547,8 +536,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
* @param typeHint
* @param sink
*/
private void writeInternal(final String keyspace, final String path, final Object value, TypeInformation<?> typeHint,
final RedisData sink) {
private void writeInternal(String keyspace, String path, Object value, TypeInformation<?> typeHint, RedisData sink) {
if (value == null) {
return;
@@ -574,63 +562,58 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
toBytes(value.getClass().getName()));
}
final RedisPersistentEntity<?> entity = mappingContext.getRequiredPersistentEntity(value.getClass());
final PersistentPropertyAccessor accessor = entity.getPropertyAccessor(value);
RedisPersistentEntity<?> entity = mappingContext.getRequiredPersistentEntity(value.getClass());
PersistentPropertyAccessor accessor = entity.getPropertyAccessor(value);
entity.doWithProperties(new PropertyHandler<RedisPersistentProperty>() {
entity.doWithProperties((PropertyHandler<RedisPersistentProperty>) persistentProperty -> {
@Override
public void doWithPersistentProperty(RedisPersistentProperty persistentProperty) {
String propertyStringPath = (!path.isEmpty() ? path + "." : "") + persistentProperty.getName();
String propertyStringPath = (!path.isEmpty() ? path + "." : "") + persistentProperty.getName();
Object propertyValue = accessor.getProperty(persistentProperty);
if (persistentProperty.isIdProperty()) {
Object propertyValue = accessor.getProperty(persistentProperty);
if (persistentProperty.isIdProperty()) {
if (propertyValue != null) {
sink.getBucket().put(propertyStringPath, toBytes(propertyValue));
}
return;
if (propertyValue != null) {
sink.getBucket().put(propertyStringPath, toBytes(propertyValue));
}
return;
}
if (persistentProperty.isMap()) {
if (persistentProperty.isMap()) {
if (propertyValue != null) {
writeMap(keyspace, propertyStringPath, persistentProperty.getMapValueType(), (Map<?, ?>) propertyValue,
sink);
}
} else if (persistentProperty.isCollectionLike()) {
if (propertyValue != null) {
writeMap(keyspace, propertyStringPath, persistentProperty.getMapValueType(), (Map<?, ?>) propertyValue, sink);
}
} else if (persistentProperty.isCollectionLike()) {
if (propertyValue == null) {
writeCollection(keyspace, propertyStringPath, (Iterable<?>) null,
if (propertyValue == null) {
writeCollection(keyspace, propertyStringPath, (Iterable<?>) null,
persistentProperty.getTypeInformation().getRequiredComponentType(), sink);
} else {
if (Iterable.class.isAssignableFrom(propertyValue.getClass())) {
writeCollection(keyspace, propertyStringPath, (Iterable<?>) propertyValue,
persistentProperty.getTypeInformation().getRequiredComponentType(), sink);
} else if (propertyValue.getClass().isArray()) {
writeCollection(keyspace, propertyStringPath, CollectionUtils.arrayToList(propertyValue),
persistentProperty.getTypeInformation().getRequiredComponentType(), sink);
} else {
if (Iterable.class.isAssignableFrom(propertyValue.getClass())) {
writeCollection(keyspace, propertyStringPath, (Iterable<?>) propertyValue,
persistentProperty.getTypeInformation().getRequiredComponentType(), sink);
} else if (propertyValue.getClass().isArray()) {
writeCollection(keyspace, propertyStringPath, CollectionUtils.arrayToList(propertyValue),
persistentProperty.getTypeInformation().getRequiredComponentType(), sink);
} else {
throw new RuntimeException("Don't know how to handle " + propertyValue.getClass() + " type collection");
}
throw new RuntimeException("Don't know how to handle " + propertyValue.getClass() + " type collection");
}
}
} else if (persistentProperty.isEntity()) {
} else if (persistentProperty.isEntity()) {
if (propertyValue != null) {
writeInternal(keyspace, propertyStringPath, propertyValue,
persistentProperty.getTypeInformation().getActualType(), sink);
}
} else {
if (propertyValue != null) {
writeInternal(keyspace, propertyStringPath, propertyValue,
persistentProperty.getTypeInformation().getActualType(), sink);
}
} else {
if (propertyValue != null) {
writeToBucket(propertyStringPath, propertyValue, sink, persistentProperty.getType());
}
if (propertyValue != null) {
writeToBucket(propertyStringPath, propertyValue, sink, persistentProperty.getType());
}
}
});
@@ -638,55 +621,50 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
writeAssociation(path, entity, value, sink);
}
private void writeAssociation(final String path, final RedisPersistentEntity<?> entity, final Object value,
final RedisData sink) {
private void writeAssociation(String path, RedisPersistentEntity<?> entity, Object value, RedisData sink) {
if (value == null) {
return;
}
final PersistentPropertyAccessor accessor = entity.getPropertyAccessor(value);
PersistentPropertyAccessor accessor = entity.getPropertyAccessor(value);
entity.doWithAssociations(new AssociationHandler<RedisPersistentProperty>() {
entity.doWithAssociations((AssociationHandler<RedisPersistentProperty>) association -> {
@Override
public void doWithAssociation(Association<RedisPersistentProperty> association) {
Object refObject = accessor.getProperty(association.getInverse());
if (refObject == null) {
return;
}
Object refObject = accessor.getProperty(association.getInverse());
if (refObject == null) {
return;
if (association.getInverse().isCollectionLike()) {
RedisPersistentEntity<?> ref = mappingContext.getRequiredPersistentEntity(
association.getInverse().getTypeInformation().getRequiredComponentType().getActualType());
String keyspace = ref.getKeySpace();
String propertyStringPath = (!path.isEmpty() ? path + "." : "") + association.getInverse().getName();
int i = 0;
for (Object o : (Collection<?>) refObject) {
Object refId = ref.getPropertyAccessor(o).getProperty(ref.getRequiredIdProperty());
if (refId != null) {
sink.getBucket().put(propertyStringPath + ".[" + i + "]", toBytes(keyspace + ":" + refId));
i++;
}
}
if (association.getInverse().isCollectionLike()) {
} else {
RedisPersistentEntity<?> ref = mappingContext.getRequiredPersistentEntity(
association.getInverse().getTypeInformation().getRequiredComponentType().getActualType());
RedisPersistentEntity<?> ref = mappingContext
.getRequiredPersistentEntity(association.getInverse().getTypeInformation());
String keyspace = ref.getKeySpace();
String keyspace = ref.getKeySpace();
Object refId = ref.getPropertyAccessor(refObject).getProperty(ref.getIdProperty());
if (refId != null) {
String propertyStringPath = (!path.isEmpty() ? path + "." : "") + association.getInverse().getName();
int i = 0;
for (Object o : (Collection<?>) refObject) {
Object refId = ref.getPropertyAccessor(o).getProperty(ref.getRequiredIdProperty());
if (refId != null) {
sink.getBucket().put(propertyStringPath + ".[" + i + "]", toBytes(keyspace + ":" + refId));
i++;
}
}
} else {
RedisPersistentEntity<?> ref = mappingContext
.getRequiredPersistentEntity(association.getInverse().getTypeInformation());
String keyspace = ref.getKeySpace();
Object refId = ref.getPropertyAccessor(refObject).getProperty(ref.getIdProperty());
if (refId != null) {
String propertyStringPath = (!path.isEmpty() ? path + "." : "") + association.getInverse().getName();
sink.getBucket().put(propertyStringPath, toBytes(keyspace + ":" + refId));
}
sink.getBucket().put(propertyStringPath, toBytes(keyspace + ":" + refId));
}
}
});
@@ -764,7 +742,7 @@ public class MappingRedisConverter implements RedisConverter, InitializingBean {
private Object readCollectionOrArray(String path, Class<?> collectionType, Class<?> valueType, Bucket bucket) {
List<String> keys = new ArrayList<String>(bucket.extractAllKeysFor(path));
List<String> keys = new ArrayList<>(bucket.extractAllKeysFor(path));
Collections.sort(keys, listKeyComparator);
boolean isArray = collectionType.isArray();

View File

@@ -55,8 +55,7 @@ import org.springframework.util.CollectionUtils;
*/
public class PathIndexResolver implements IndexResolver {
private final Set<Class<?>> VALUE_TYPES = new HashSet<Class<?>>(
Arrays.<Class<?>> asList(Point.class, GeoLocation.class));
private final Set<Class<?>> VALUE_TYPES = new HashSet<>(Arrays.<Class<?>> asList(Point.class, GeoLocation.class));
private ConfigurableIndexDefinitionProvider indexConfiguration;
private RedisMappingContext mappingContext;
@@ -117,7 +116,7 @@ public class PathIndexResolver implements IndexResolver {
}
final PersistentPropertyAccessor accessor = entity.getPropertyAccessor(value);
final Set<IndexedData> indexes = new LinkedHashSet<IndexedData>();
final Set<IndexedData> indexes = new LinkedHashSet<>();
entity.doWithProperties(new PropertyHandler<RedisPersistentProperty>() {
@@ -202,7 +201,7 @@ public class PathIndexResolver implements IndexResolver {
String path = normalizeIndexPath(propertyPath, property);
Set<IndexedData> data = new LinkedHashSet<IndexedData>();
Set<IndexedData> data = new LinkedHashSet<>();
if (indexConfiguration.hasIndexFor(keyspace, path)) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -66,7 +66,7 @@ public class RedisData {
Assert.notNull(bucket, "Bucket must not be null!");
this.bucket = bucket;
this.indexedData = new HashSet<IndexedData>();
this.indexedData = new HashSet<>();
}
/**

View File

@@ -72,7 +72,7 @@ public class SpelIndexResolver implements IndexResolver {
Assert.notNull(parser, "SpelExpressionParser must not be null!");
this.mappingContext = mappingContext;
this.settings = mappingContext.getMappingConfiguration().getIndexConfiguration();
this.expressionCache = new HashMap<SpelIndexDefinition, Expression>();
this.expressionCache = new HashMap<>();
this.parser = parser;
}
@@ -93,7 +93,7 @@ public class SpelIndexResolver implements IndexResolver {
String keyspace = entity.getKeySpace();
Set<IndexedData> indexes = new HashSet<IndexedData>();
Set<IndexedData> indexes = new HashSet<>();
for (IndexDefinition setting : settings.getIndexDefinitionsFor(keyspace)) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,7 +42,7 @@ public class IndexConfiguration implements ConfigurableIndexDefinitionProvider {
*/
public IndexConfiguration() {
this.definitions = new CopyOnWriteArraySet<IndexDefinition>();
this.definitions = new CopyOnWriteArraySet<>();
for (IndexDefinition initial : initialConfiguration()) {
addIndexDefinition(initial);
}
@@ -79,7 +79,7 @@ public class IndexConfiguration implements ConfigurableIndexDefinitionProvider {
*/
public Set<IndexDefinition> getIndexDefinitionsFor(Serializable keyspace) {
Set<IndexDefinition> indexDefinitions = new LinkedHashSet<IndexDefinition>();
Set<IndexDefinition> indexDefinitions = new LinkedHashSet<>();
for (IndexDefinition indexDef : definitions) {
if (indexDef.getKeyspace().equals(keyspace)) {
@@ -102,7 +102,7 @@ public class IndexConfiguration implements ConfigurableIndexDefinitionProvider {
private Set<IndexDefinition> getIndexDefinitions(Serializable keyspace, String path, Class<?> type) {
Set<IndexDefinition> def = new LinkedHashSet<IndexDefinition>();
Set<IndexDefinition> def = new LinkedHashSet<>();
for (IndexDefinition indexDef : definitions) {
if (ClassUtils.isAssignable(type, indexDef.getClass()) && indexDef.getKeyspace().equals(keyspace)) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016 the original author or authors.
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,7 +26,7 @@ import org.springframework.util.StringUtils;
/**
* Base {@link IndexDefinition} implementation.
*
*
* @author Christoph Strobl
* @since 1.7
*/
@@ -40,7 +40,7 @@ public abstract class RedisIndexDefinition implements IndexDefinition {
/**
* Creates new {@link RedisIndexDefinition}.
*
*
* @param keyspace
* @param path
* @param indexName
@@ -50,7 +50,7 @@ public abstract class RedisIndexDefinition implements IndexDefinition {
this.keyspace = keyspace;
this.indexName = indexName;
this.path = path;
this.conditions = new ArrayList<IndexDefinition.Condition<?>>();
this.conditions = new ArrayList<>();
}
/*
@@ -183,7 +183,7 @@ public abstract class RedisIndexDefinition implements IndexDefinition {
*/
public static class CompositeValueTransformer implements IndexValueTransformer {
private final List<IndexValueTransformer> transformers = new ArrayList<IndexValueTransformer>();
private final List<IndexValueTransformer> transformers = new ArrayList<>();
public CompositeValueTransformer(Collection<IndexValueTransformer> transformers) {
this.transformers.addAll(transformers);
@@ -212,7 +212,7 @@ public abstract class RedisIndexDefinition implements IndexDefinition {
*/
public static class OrCondition<T> implements Condition<T> {
private final List<Condition<T>> conditions = new ArrayList<Condition<T>>();
private final List<Condition<T>> conditions = new ArrayList<>();
public OrCondition(Collection<Condition<T>> conditions) {
this.conditions.addAll(conditions);

View File

@@ -45,8 +45,6 @@ import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.NumberUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.MethodCallback;
import org.springframework.util.ReflectionUtils.MethodFilter;
import org.springframework.util.StringUtils;
/**
@@ -99,7 +97,7 @@ public class RedisMappingContext extends KeyValueMappingContext<RedisPersistentE
@Override
protected <T> RedisPersistentEntity<T> createPersistentEntity(TypeInformation<T> typeInformation) {
return new BasicRedisPersistentEntity<T>(typeInformation, fallbackKeySpaceResolver, timeToLiveAccessor);
return new BasicRedisPersistentEntity<>(typeInformation, fallbackKeySpaceResolver, timeToLiveAccessor);
}
@Override
@@ -199,9 +197,9 @@ public class RedisMappingContext extends KeyValueMappingContext<RedisPersistentE
Assert.notNull(keyspaceConfig, "KeyspaceConfiguration must not be null!");
Assert.notNull(mappingContext, "MappingContext must not be null!");
this.defaultTimeouts = new HashMap<Class<?>, Long>();
this.timeoutProperties = new HashMap<Class<?>, PersistentProperty<?>>();
this.timeoutMethods = new HashMap<Class<?>, Method>();
this.defaultTimeouts = new HashMap<>();
this.timeoutProperties = new HashMap<>();
this.timeoutMethods = new HashMap<>();
this.keyspaceConfig = keyspaceConfig;
this.mappingContext = mappingContext;
}
@@ -340,20 +338,9 @@ public class RedisMappingContext extends KeyValueMappingContext<RedisPersistentE
}
timeoutMethods.put(type, null);
ReflectionUtils.doWithMethods(type, new MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
timeoutMethods.put(type, method);
}
}, new MethodFilter() {
@Override
public boolean matches(Method method) {
return ClassUtils.isAssignable(Number.class, method.getReturnType())
&& AnnotationUtils.findAnnotation(method, TimeToLive.class) != null;
}
});
ReflectionUtils.doWithMethods(type, method -> timeoutMethods.put(type, method),
method -> ClassUtils.isAssignable(Number.class, method.getReturnType())
&& AnnotationUtils.findAnnotation(method, TimeToLive.class) != null);
return timeoutMethods.get(type);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,13 +26,13 @@ import org.springframework.data.mapping.model.SimpleTypeHolder;
/**
* Redis specific {@link PersistentProperty} implementation.
*
*
* @author Christoph Strobl
* @since 1.7
*/
public class RedisPersistentProperty extends KeyValuePersistentProperty<RedisPersistentProperty> {
private static final Set<String> SUPPORTED_ID_PROPERTY_NAMES = new HashSet<String>();
private static final Set<String> SUPPORTED_ID_PROPERTY_NAMES = new HashSet<>();
static {
SUPPORTED_ID_PROPERTY_NAMES.add("id");
@@ -40,7 +40,7 @@ public class RedisPersistentProperty extends KeyValuePersistentProperty<RedisPer
/**
* Creates new {@link RedisPersistentProperty}.
*
*
* @param property
* @param owner
* @param simpleTypeHolder

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2013 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,14 +23,14 @@ import org.springframework.data.redis.connection.SortParameters.Range;
/**
* Default implementation for {@link SortCriterion}.
*
*
* @author Costin Leau
*/
class DefaultSortCriterion<K> implements SortCriterion<K> {
private final K key;
private String by;
private final List<String> getKeys = new ArrayList<String>(4);
private final List<String> getKeys = new ArrayList<>(4);
private Range limit;
private Order order;
@@ -41,12 +41,12 @@ class DefaultSortCriterion<K> implements SortCriterion<K> {
}
public SortCriterion<K> alphabetical(boolean alpha) {
this.alpha = Boolean.valueOf(alpha);
this.alpha = alpha;
return this;
}
public SortQuery<K> build() {
return new DefaultSortQuery<K>(key, by, limit, order, alpha, getKeys);
return new DefaultSortQuery<>(key, by, limit, order, alpha, getKeys);
}
public SortCriterion<K> limit(long offset, long count) {

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2013 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -25,7 +25,7 @@ import org.springframework.data.redis.serializer.RedisSerializer;
/**
* Utilities for {@link SortQuery} implementations.
*
*
* @author Costin Leau
*/
public abstract class QueryUtils {
@@ -42,7 +42,7 @@ public abstract class QueryUtils {
if (strings == null) {
raw = Collections.emptyList();
} else {
raw = new ArrayList<byte[]>(strings.size());
raw = new ArrayList<>(strings.size());
for (String key : strings) {
raw.add(stringSerializer.serialize(key));
}

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2013 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,7 +17,7 @@ package org.springframework.data.redis.core.query;
/**
* Simple builder class for constructing {@link SortQuery}.
*
*
* @author Costin Leau
*/
public class SortQueryBuilder<K> extends DefaultSortCriterion<K> {
@@ -29,7 +29,7 @@ public class SortQueryBuilder<K> extends DefaultSortCriterion<K> {
}
public static <K> SortQueryBuilder<K> sort(K key) {
return new SortQueryBuilder<K>(key);
return new SortQueryBuilder<>(key);
}
public SortCriterion<K> by(String keyPattern) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,6 @@ package org.springframework.data.redis.core.script;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.NonTransientDataAccessException;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.data.redis.connection.RedisConnection;
@@ -31,7 +30,7 @@ import org.springframework.data.redis.serializer.RedisSerializer;
* Default implementation of {@link ScriptExecutor}. Optimizes performance by attempting to execute script first using
* evalsha, then falling back to eval if Redis has not yet cached the script. Evalsha is not attempted if the script is
* executed in a pipeline or transaction.
*
*
* @author Jennifer Hickey
* @author Christoph Strobl
* @author Thomas Darimont
@@ -57,19 +56,17 @@ public class DefaultScriptExecutor<K> implements ScriptExecutor<K> {
public <T> T execute(final RedisScript<T> script, final RedisSerializer<?> argsSerializer,
final RedisSerializer<T> resultSerializer, final List<K> keys, final Object... args) {
return template.execute(new RedisCallback<T>() {
public T doInRedis(RedisConnection connection) throws DataAccessException {
final ReturnType returnType = ReturnType.fromJavaType(script.getResultType());
final byte[][] keysAndArgs = keysAndArgs(argsSerializer, keys, args);
final int keySize = keys != null ? keys.size() : 0;
if (connection.isPipelined() || connection.isQueueing()) {
// We could script load first and then do evalsha to ensure sha is present,
// but this adds a sha1 to exec/closePipeline results. Instead, just eval
connection.eval(scriptBytes(script), returnType, keySize, keysAndArgs);
return null;
}
return eval(connection, script, returnType, keySize, keysAndArgs, resultSerializer);
return template.execute((RedisCallback<T>) connection -> {
final ReturnType returnType = ReturnType.fromJavaType(script.getResultType());
final byte[][] keysAndArgs = keysAndArgs(argsSerializer, keys, args);
final int keySize = keys != null ? keys.size() : 0;
if (connection.isPipelined() || connection.isQueueing()) {
// We could script load first and then do evalsha to ensure sha is present,
// but this adds a sha1 to exec/closePipeline results. Instead, just eval
connection.eval(scriptBytes(script), returnType, keySize, keysAndArgs);
return null;
}
return eval(connection, script, returnType, keySize, keysAndArgs, resultSerializer);
});
}

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2015 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,7 +23,7 @@ import org.apache.commons.beanutils.BeanUtils;
/**
* HashMapper based on Apache Commons BeanUtils project. Does NOT supports nested properties.
*
*
* @author Costin Leau
* @author Christoph Strobl
*/
@@ -56,7 +56,7 @@ public class BeanUtilsHashMapper<T> implements HashMapper<T, String, String> {
Map<String, String> map = BeanUtils.describe(object);
Map<String, String> result = new LinkedHashMap<String, String>();
Map<String, String> result = new LinkedHashMap<>();
for (Entry<String, String> entry : map.entrySet()) {
if (entry.getValue() != null) {
result.put(entry.getKey(), entry.getValue());

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2013 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,7 +21,7 @@ import java.util.Map;
/**
* Delegating hash mapper used for flattening objects into Strings. Suitable when dealing with mappers that support
* Strings and type conversion.
*
*
* @author Costin Leau
*/
public class DecoratingStringHashMapper<T> implements HashMapper<T, String, String> {
@@ -40,7 +40,7 @@ public class DecoratingStringHashMapper<T> implements HashMapper<T, String, Stri
public Map<String, String> toHash(T object) {
Map<?, ?> hash = delegate.toHash(object);
Map<String, String> flatten = new LinkedHashMap<String, String>(hash.size());
Map<String, String> flatten = new LinkedHashMap<>(hash.size());
for (Map.Entry<?, ?> entry : hash.entrySet()) {
flatten.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}

View File

@@ -166,8 +166,8 @@ public class Jackson2HashMapper implements HashMapper<Object, String, Object> {
@SuppressWarnings("unchecked")
private Map<String, Object> doUnflatten(Map<String, Object> source) {
Map<String, Object> result = new LinkedHashMap<String, Object>();
Set<String> treatSeperate = new LinkedHashSet<String>();
Map<String, Object> result = new LinkedHashMap<>();
Set<String> treatSeperate = new LinkedHashSet<>();
for (Entry<String, Object> entry : source.entrySet()) {
String key = entry.getKey();
@@ -193,7 +193,7 @@ public class Jackson2HashMapper implements HashMapper<Object, String, Object> {
for (String partial : treatSeperate) {
Map<String, Object> newSource = new LinkedHashMap<String, Object>();
Map<String, Object> newSource = new LinkedHashMap<>();
for (Entry<String, Object> entry : source.entrySet()) {
if (entry.getKey().startsWith(partial)) {
@@ -220,7 +220,7 @@ public class Jackson2HashMapper implements HashMapper<Object, String, Object> {
private Map<String, Object> flattenMap(Iterator<Entry<String, JsonNode>> source) {
Map<String, Object> resultMap = new HashMap<String, Object>();
Map<String, Object> resultMap = new HashMap<>();
this.doFlatten("", source, resultMap);
return resultMap;
}
@@ -291,9 +291,9 @@ public class Jackson2HashMapper implements HashMapper<Object, String, Object> {
private List<Object> createTypedListWithValue(Object value) {
List<Object> listWithTypeHint = new ArrayList<Object>();
List<Object> listWithTypeHint = new ArrayList<>();
listWithTypeHint.add(ArrayList.class.getName()); // why jackson? why?
List<Object> values = new ArrayList<Object>();
List<Object> values = new ArrayList<>();
values.add(value);
listWithTypeHint.add(values);
return listWithTypeHint;

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2016 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -62,7 +62,7 @@ import org.springframework.util.ErrorHandler;
* <p>
* Adding and removing listeners at the same time has undefined results. It is strongly recommended to synchronize/order
* these methods accordingly.
*
*
* @author Costin Leau
* @author Jennifer Hickey
* @author Way Joke
@@ -118,11 +118,11 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
// contract)
// lookup map between patterns and listeners
private final Map<ByteArrayWrapper, Collection<MessageListener>> patternMapping = new ConcurrentHashMap<ByteArrayWrapper, Collection<MessageListener>>();
private final Map<ByteArrayWrapper, Collection<MessageListener>> patternMapping = new ConcurrentHashMap<>();
// lookup map between channels and listeners
private final Map<ByteArrayWrapper, Collection<MessageListener>> channelMapping = new ConcurrentHashMap<ByteArrayWrapper, Collection<MessageListener>>();
private final Map<ByteArrayWrapper, Collection<MessageListener>> channelMapping = new ConcurrentHashMap<>();
// lookup map between listeners and channels
private final Map<MessageListener, Set<Topic>> listenerTopics = new ConcurrentHashMap<MessageListener, Set<Topic>>();
private final Map<MessageListener, Set<Topic>> listenerTopics = new ConcurrentHashMap<>();
private final SubscriptionTask subscriptionTask = new SubscriptionTask();
@@ -150,7 +150,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
* <p>
* The default implementation builds a {@link org.springframework.core.task.SimpleAsyncTaskExecutor} with the
* specified bean name (or the class name, if no bean name specified) as thread name prefix.
*
*
* @see org.springframework.core.task.SimpleAsyncTaskExecutor#SimpleAsyncTaskExecutor(String)
*/
protected TaskExecutor createDefaultTaskExecutor() {
@@ -231,7 +231,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* Process a message received from the provider.
*
*
* @param message
* @param pattern
*/
@@ -241,7 +241,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* Execute the specified listener.
*
*
* @see #handleListenerException
*/
protected void executeListener(MessageListener listener, Message message, byte[] pattern) {
@@ -263,7 +263,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
* Handle the given exception that arose during listener execution.
* <p>
* The default implementation logs the exception at error level. This can be overridden in subclasses.
*
*
* @param ex the exception to handle
*/
protected void handleListenerException(Throwable ex) {
@@ -280,7 +280,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* Invoke the registered ErrorHandler, if any. Log at error level otherwise.
*
*
* @param ex the uncaught error that arose during message processing.
* @see #setErrorHandler
*/
@@ -294,7 +294,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* Returns the connectionFactory.
*
*
* @return Returns the connectionFactory
*/
public RedisConnectionFactory getConnectionFactory() {
@@ -316,7 +316,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
* Sets the task executor used for running the message listeners when messages are received. If no task executor is
* set, an instance of {@link SimpleAsyncTaskExecutor} will be used by default. The task executor can be adjusted
* depending on the work done by the listeners and the number of messages coming in.
*
*
* @param taskExecutor The taskExecutor to set.
*/
public void setTaskExecutor(Executor taskExecutor) {
@@ -330,7 +330,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
* <p>
* Note: This implementation uses at most one long running thread (depending on whether there are any listeners
* registered or not) and up to two threads during the initial registration.
*
*
* @param subscriptionExecutor The subscriptionExecutor to set.
*/
public void setSubscriptionExecutor(Executor subscriptionExecutor) {
@@ -340,7 +340,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* Sets the serializer for converting the {@link Topic}s into low-level channels and patterns. By default,
* {@link StringRedisSerializer} is used.
*
*
* @param serializer The serializer to set.
*/
public void setTopicSerializer(RedisSerializer<String> serializer) {
@@ -361,7 +361,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
* Note: it's possible to call this method while the container is running forcing a reinitialization of the container.
* Note however that this might cause some messages to be lost (while the container reinitializes) - hence calling
* this method at runtime is considered advanced usage.
*
*
* @param listeners map of message listeners and their associated topics
*/
public void setMessageListeners(Map<? extends MessageListener, Collection<? extends Topic>> listeners) {
@@ -371,7 +371,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* Adds a message listener to the (potentially running) container. If the container is running, the listener starts
* receiving (matching) messages as soon as possible.
*
*
* @param listener message listener
* @param topics message listener topic
*/
@@ -383,7 +383,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* Adds a message listener to the (potentially running) container. If the container is running, the listener starts
* receiving (matching) messages as soon as possible.
*
*
* @param listener message listener
* @param topic message topic
*/
@@ -397,7 +397,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
* <p>
* Note that this method obeys the Redis (p)unsubscribe semantics - meaning an empty/null collection will remove
* listener from all channels. Similarly a null listener will unsubscribe all listeners from the given topic.
*
*
* @param listener message listener
* @param topics message listener topics
*/
@@ -411,7 +411,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
* <p>
* Note that this method obeys the Redis (p)unsubscribe semantics - meaning an empty/null collection will remove
* listener from all channels. Similarly a null listener will unsubscribe all listeners from the given topic.
*
*
* @param listener message listener
* @param topic message topic
*/
@@ -423,7 +423,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
* Removes the given message listener completely (from all topics). If the container is running, the listener stops
* receiving (matching) messages as soon as possible. Similarly a null listener will unsubscribe all listeners from
* the given topic.
*
*
* @param listener message listener
*/
public void removeMessageListener(MessageListener listener) {
@@ -485,15 +485,15 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
Assert.notNull(listener, "a valid listener is required");
Assert.notEmpty(topics, "at least one topic is required");
List<byte[]> channels = new ArrayList<byte[]>(topics.size());
List<byte[]> patterns = new ArrayList<byte[]>(topics.size());
List<byte[]> channels = new ArrayList<>(topics.size());
List<byte[]> patterns = new ArrayList<>(topics.size());
boolean trace = logger.isTraceEnabled();
// add listener mapping
Set<Topic> set = listenerTopics.get(listener);
if (set == null) {
set = new CopyOnWriteArraySet<Topic>();
set = new CopyOnWriteArraySet<>();
listenerTopics.put(listener, set);
}
set.addAll(topics);
@@ -505,7 +505,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
if (topic instanceof ChannelTopic) {
Collection<MessageListener> collection = channelMapping.get(holder);
if (collection == null) {
collection = new CopyOnWriteArraySet<MessageListener>();
collection = new CopyOnWriteArraySet<>();
channelMapping.put(holder, collection);
}
collection.add(listener);
@@ -518,7 +518,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
else if (topic instanceof PatternTopic) {
Collection<MessageListener> collection = patternMapping.get(holder);
if (collection == null) {
collection = new CopyOnWriteArraySet<MessageListener>();
collection = new CopyOnWriteArraySet<>();
patternMapping.put(holder, collection);
}
collection.add(listener);
@@ -549,8 +549,8 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
return;
}
List<byte[]> channelsToRemove = new ArrayList<byte[]>();
List<byte[]> patternsToRemove = new ArrayList<byte[]>();
List<byte[]> channelsToRemove = new ArrayList<>();
List<byte[]> patternsToRemove = new ArrayList<>();
// check unsubscribe all topics case
if (CollectionUtils.isEmpty(topics)) {
@@ -636,7 +636,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* Handle subscription task exception. Will attempt to restart the subscription if the Exception is a connection
* failure (for example, Redis was restarted).
*
*
* @param ex Throwable exception
*/
protected void handleSubscriptionException(Throwable ex) {
@@ -670,7 +670,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* Runnable used for Redis subscription. Implemented as a dedicated class to provide as many hints as possible to the
* underlying thread pool.
*
*
* @author Costin Leau
*/
private class SubscriptionTask implements SchedulingAwareRunnable {
@@ -679,7 +679,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
* Runnable used, on a parallel thread, to do the initial pSubscribe. This is required since, during initialization,
* both subscribe and pSubscribe might be needed but since the first call is blocking, the second call needs to
* executed in parallel.
*
*
* @author Costin Leau
*/
private class PatternSubscriptionTask implements SchedulingAwareRunnable {
@@ -766,7 +766,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* Performs a potentially asynchronous registration of a subscription.
*
*
* @return #SubscriptionPresentCondition that can serve as a handle to check whether the subscription is ready.
*/
private SubscriptionPresentCondition eventuallyPerformSubscription() {
@@ -795,7 +795,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* Checks whether the current connection has an associated subscription.
*
*
* @author Thomas Darimont
*/
private class SubscriptionPresentCondition implements Condition {
@@ -807,7 +807,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* Checks whether the current connection has an associated pattern subscription.
*
*
* @author Thomas Darimont
* @see org.springframework.data.redis.listener.RedisMessageListenerContainer.SubscriptionTask.SubscriptionPresentTestCondition
*/
@@ -935,7 +935,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* Actual message dispatcher/multiplexer.
*
*
* @author Costin Leau
*/
private class DispatchMessageListener implements MessageListener {
@@ -962,17 +962,13 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
final byte[] source = (pattern != null ? pattern.clone() : message.getChannel());
for (final MessageListener messageListener : listeners) {
taskExecutor.execute(new Runnable() {
public void run() {
processMessage(messageListener, message, source);
}
});
taskExecutor.execute(() -> processMessage(messageListener, message, source));
}
}
/**
* Specify the interval between recovery attempts, in <b>milliseconds</b>. The default is 5000 ms, that is, 5 seconds.
*
*
* @see #handleSubscriptionException
*/
public void setRecoveryInterval(long recoveryInterval) {
@@ -986,7 +982,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* Specify the max time to wait for subscription registrations, in <b>milliseconds</b>. The default is 2000ms, that
* is, 2 second.
*
*
* @param maxSubscriptionRegistrationWaitingTime
* @see #DEFAULT_SUBSCRIPTION_REGISTRATION_WAIT_TIME
*/
@@ -1002,7 +998,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* Periodically tests, in 100ms intervals, for a condition until it is met or a timeout occurs.
*
*
* @param condition The condition to periodically test
* @param timeout The timeout
* @return true if condition passes, false if condition does not pass within timeout
@@ -1034,7 +1030,7 @@ public class RedisMessageListenerContainer implements InitializingBean, Disposab
/**
* A condition to test periodically, used in conjunction with
* {@link org.springframework.data.redis.listener.RedisMessageListenerContainer.SpinBarrier}
*
*
* @author Jennifer Hickey
* @author Thomas Darimont Note: Placed here to avoid API exposure.
*/

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2014 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -35,7 +35,6 @@ import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.MethodCallback;
import org.springframework.util.ReflectionUtils.MethodFilter;
import org.springframework.util.StringUtils;
@@ -60,33 +59,33 @@ import org.springframework.util.StringUtils;
* <p>
* Find below some examples of method signatures compliant with this adapter class. This first example handles all
* <code>Message</code> types and gets passed the contents of each <code>Message</code> type as an argument.
*
*
* <pre class="code">
* public interface MessageContentsDelegate {
* void handleMessage(String text);
*
*
* void handleMessage(byte[] bytes);
*
*
* void handleMessage(Person obj);
* }
* </pre>
* <p>
* In addition, the channel or pattern to which a message is sent can be passed in to the method as a second argument of
* type String:
*
*
* <pre class="code">
* public interface MessageContentsDelegate {
* void handleMessage(String text, String channel);
*
*
* void handleMessage(byte[] bytes, String pattern);
* }
* </pre>
*
*
* For further examples and discussion please do refer to the Spring Data reference documentation which describes this
* class (and its attendant configuration) in detail. <b>Important:</b> Due to the nature of messages, the default
* serializer used by the adapter is {@link StringRedisSerializer}. If the messages are of a different type, change them
* accordingly through {@link #setSerializer(RedisSerializer)}.
*
*
* @author Juergen Hoeller
* @author Costin Leau
* @author Greg Turnquist
@@ -109,17 +108,13 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
this.delegate = delegate;
this.methodName = methodName;
this.lenient = delegate instanceof MessageListener;
this.methods = new HashSet<Method>();
this.methods = new HashSet<>();
final Class<?> c = delegate.getClass();
ReflectionUtils.doWithMethods(c, new MethodCallback() {
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
ReflectionUtils.makeAccessible(method);
methods.add(method);
}
ReflectionUtils.doWithMethods(c, method -> {
ReflectionUtils.makeAccessible(method);
methods.add(method);
}, new MostSpecificMethodFilter(methodName, c));
Assert.isTrue(lenient || !methods.isEmpty(), "Cannot find a suitable method named [" + c.getName() + "#"
@@ -150,14 +145,14 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
/**
* Returns the current methodName.
*
*
* @return the methodName
*/
public String getMethodName() {
return methodName;
}
}
/**
* Out-of-the-box value for the default listener method: "handleMessage".
*/
@@ -186,7 +181,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
/**
* Create a new {@link MessageListenerAdapter} for the given delegate.
*
*
* @param delegate the delegate object
*/
public MessageListenerAdapter(Object delegate) {
@@ -196,7 +191,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
/**
* Create a new {@link MessageListenerAdapter} for the given delegate.
*
*
* @param delegate the delegate object
* @param defaultListenerMethod method to call when a message comes
* @see #getListenerMethodName
@@ -212,7 +207,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
* <p>
* If no explicit delegate object has been specified, listener methods are expected to present on this adapter
* instance, that is, on a custom subclass of this adapter, defining listener methods.
*
*
* @param delegate delegate object
*/
public void setDelegate(Object delegate) {
@@ -222,7 +217,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
/**
* Returns the target object to delegate message listening to.
*
*
* @return message listening delegation
*/
public Object getDelegate() {
@@ -232,7 +227,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
/**
* Specify the name of the default listener method to delegate to, for the case where no specific listener method has
* been determined. Out-of-the-box value is {@link #ORIGINAL_DEFAULT_LISTENER_METHOD "handleMessage"}.
*
*
* @see #getListenerMethodName
*/
public void setDefaultListenerMethod(String defaultListenerMethod) {
@@ -250,7 +245,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
* Set the serializer that will convert incoming raw Redis messages to listener method arguments.
* <p>
* The default converter is a {@link StringRedisSerializer}.
*
*
* @param serializer
*/
public void setSerializer(RedisSerializer<?> serializer) {
@@ -261,7 +256,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
* Sets the serializer used for converting the channel/pattern to a String.
* <p>
* The default converter is a {@link StringRedisSerializer}.
*
*
* @param serializer
*/
public void setStringSerializer(RedisSerializer<String> serializer) {
@@ -285,7 +280,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
* <p>
* Delegates the message to the target listener method, with appropriate conversion of the message argument. In case
* of an exception, the {@link #handleListenerException(Throwable)} method will be invoked.
*
*
* @param message the incoming Redis message
* @see #handleListenerException
*/
@@ -315,7 +310,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
/**
* Initialize the default implementations for the adapter's strategies.
*
*
* @see #setSerializer(RedisSerializer)
* @see JdkSerializationRedisSerializer
*/
@@ -328,7 +323,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
/**
* Handle the given exception that arose during listener execution. The default implementation logs the exception at
* error level.
*
*
* @param ex the exception to handle
*/
protected void handleListenerException(Throwable ex) {
@@ -337,7 +332,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
/**
* Extract the message body from the given Redis message.
*
*
* @param message the Redis <code>Message</code>
* @return the content of the message, to be passed into the listener method as argument
*/
@@ -352,7 +347,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
* Determine the name of the listener method that is supposed to handle the given message.
* <p>
* The default implementation simply returns the configured default listener method, if any.
*
*
* @param originalMessage the Redis request message
* @param extractedMessage the converted Redis request message, to be passed into the listener method as argument
* @return the name of the listener method (never <code>null</code>)
@@ -364,7 +359,7 @@ public class MessageListenerAdapter implements InitializingBean, MessageListener
/**
* Invoke the specified listener method.
*
*
* @param methodName the name of the listener method
* @param arguments the message arguments to be passed in
* @see #getListenerMethodName

View File

@@ -98,7 +98,7 @@ public abstract class CdiBean<T> implements Bean<T>, PassivationCapable {
*/
private final String createPassivationId(Set<Annotation> qualifiers, Class<?> repositoryType) {
List<String> qualifierNames = new ArrayList<String>(qualifiers.size());
List<String> qualifierNames = new ArrayList<>(qualifiers.size());
for (Annotation qualifier : qualifiers) {
qualifierNames.add(qualifier.annotationType().getName());
@@ -118,7 +118,7 @@ public abstract class CdiBean<T> implements Bean<T>, PassivationCapable {
*/
public Set<Type> getTypes() {
Set<Type> types = new HashSet<Type>();
Set<Type> types = new HashSet<>();
types.add(beanClass);
types.addAll(Arrays.asList(beanClass.getInterfaces()));
types.addAll(this.types);
@@ -187,7 +187,7 @@ public abstract class CdiBean<T> implements Bean<T>, PassivationCapable {
*/
public Set<Class<? extends Annotation>> getStereotypes() {
Set<Class<? extends Annotation>> stereotypes = new HashSet<Class<? extends Annotation>>();
Set<Class<? extends Annotation>> stereotypes = new HashSet<>();
for (Annotation annotation : beanClass.getAnnotations()) {
Class<? extends Annotation> annotationType = annotation.annotationType();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016 the original author or authors.
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -53,9 +53,9 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport {
private static final Logger LOG = LoggerFactory.getLogger(RedisRepositoryExtension.class);
private final Map<Set<Annotation>, Bean<RedisKeyValueAdapter>> redisKeyValueAdapters = new HashMap<Set<Annotation>, Bean<RedisKeyValueAdapter>>();
private final Map<Set<Annotation>, Bean<KeyValueOperations>> redisKeyValueTemplates = new HashMap<Set<Annotation>, Bean<KeyValueOperations>>();
private final Map<Set<Annotation>, Bean<RedisOperations<?, ?>>> redisOperations = new HashMap<Set<Annotation>, Bean<RedisOperations<?, ?>>>();
private final Map<Set<Annotation>, Bean<RedisKeyValueAdapter>> redisKeyValueAdapters = new HashMap<>();
private final Map<Set<Annotation>, Bean<KeyValueOperations>> redisKeyValueTemplates = new HashMap<>();
private final Map<Set<Annotation>, Bean<RedisOperations<?, ?>>> redisOperations = new HashMap<>();
public RedisRepositoryExtension() {
LOG.info("Activating CDI extension for Spring Data Redis repositories.");
@@ -86,7 +86,7 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport {
}
// Store the Key-Value Templates bean using its qualifiers.
redisKeyValueTemplates.put(new HashSet<Annotation>(bean.getQualifiers()), (Bean<KeyValueOperations>) bean);
redisKeyValueTemplates.put(new HashSet<>(bean.getQualifiers()), (Bean<KeyValueOperations>) bean);
}
if (beanType instanceof Class<?> && RedisKeyValueAdapter.class.isAssignableFrom((Class<?>) beanType)) {
@@ -96,7 +96,7 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport {
}
// Store the RedisKeyValueAdapter bean using its qualifiers.
redisKeyValueAdapters.put(new HashSet<Annotation>(bean.getQualifiers()), (Bean<RedisKeyValueAdapter>) bean);
redisKeyValueAdapters.put(new HashSet<>(bean.getQualifiers()), (Bean<RedisKeyValueAdapter>) bean);
}
if (beanType instanceof Class<?> && RedisOperations.class.isAssignableFrom((Class<?>) beanType)) {
@@ -106,7 +106,7 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport {
}
// Store the RedisOperations bean using its qualifiers.
redisOperations.put(new HashSet<Annotation>(bean.getQualifiers()), (Bean<RedisOperations<?, ?>>) bean);
redisOperations.put(new HashSet<>(bean.getQualifiers()), (Bean<RedisOperations<?, ?>>) bean);
}
}
}
@@ -192,7 +192,7 @@ public class RedisRepositoryExtension extends CdiRepositoryExtensionSupport {
}
// Construct and return the repository bean.
return new RedisRepositoryBean<T>(redisKeyValueTemplate, qualifiers, repositoryType, beanManager,
return new RedisRepositoryBean<>(redisKeyValueTemplate, qualifiers, repositoryType, beanManager,
getCustomImplementationDetector());
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2015-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,14 +28,14 @@ import org.springframework.util.ObjectUtils;
/**
* Simple set of operations required to run queries against Redis.
*
*
* @author Christoph Strobl
* @since 1.7
*/
public class RedisOperationChain {
private Set<PathAndValue> sismember = new LinkedHashSet<PathAndValue>();
private Set<PathAndValue> orSismember = new LinkedHashSet<PathAndValue>();
private Set<PathAndValue> sismember = new LinkedHashSet<>();
private Set<PathAndValue> orSismember = new LinkedHashSet<>();
private NearPath near;
public void sismember(String path, Object value) {

View File

@@ -96,7 +96,7 @@ public class RedisQueryCreator extends AbstractQueryCreator<KeyValueQuery<RedisO
@Override
protected KeyValueQuery<RedisOperationChain> complete(final RedisOperationChain criteria, Sort sort) {
KeyValueQuery<RedisOperationChain> query = new KeyValueQuery<RedisOperationChain>(criteria);
KeyValueQuery<RedisOperationChain> query = new KeyValueQuery<>(criteria);
if (query.getCriteria() != null && !CollectionUtils.isEmpty(query.getCriteria().getSismember())
&& !CollectionUtils.isEmpty(query.getCriteria().getOrSismember()))

View File

@@ -170,7 +170,7 @@ class DefaultRedisSerializationContext<K, V> implements RedisSerializationContex
Assert.notNull(hashKeyTuple, "HashKey SerializationPair must not be null!");
Assert.notNull(hashValueTuple, "ValueKey SerializationPair must not be null!");
return new DefaultRedisSerializationContext<K, V>(keyTuple, valueTuple, hashKeyTuple, hashValueTuple,
return new DefaultRedisSerializationContext<>(keyTuple, valueTuple, hashKeyTuple, hashValueTuple,
stringTuple);
}
}

View File

@@ -161,7 +161,7 @@ public interface RedisSerializationContext<K, V> {
Assert.notNull(serializer, "RedisSerializer must not be null!");
return new RedisSerializerToSerializationPairAdapter<T>(serializer);
return new RedisSerializerToSerializationPairAdapter<>(serializer);
}
/**

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2013 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -25,7 +25,7 @@ import java.util.Set;
/**
* Utility class with various serialization-related methods.
*
*
* @author Costin Leau
*/
public abstract class SerializationUtils {
@@ -44,8 +44,8 @@ public abstract class SerializationUtils {
return null;
}
Collection<Object> values = (List.class.isAssignableFrom(type) ? new ArrayList<Object>(rawValues.size())
: new LinkedHashSet<Object>(rawValues.size()));
Collection<Object> values = (List.class.isAssignableFrom(type) ? new ArrayList<>(rawValues.size())
: new LinkedHashSet<>(rawValues.size()));
for (byte[] bs : rawValues) {
values.add(redisSerializer.deserialize(bs));
}
@@ -72,7 +72,7 @@ public abstract class SerializationUtils {
if (rawValues == null) {
return null;
}
Map<T, T> ret = new LinkedHashMap<T, T>(rawValues.size());
Map<T, T> ret = new LinkedHashMap<>(rawValues.size());
for (Map.Entry<byte[], byte[]> entry : rawValues.entrySet()) {
ret.put(redisSerializer.deserialize(entry.getKey()), redisSerializer.deserialize(entry.getValue()));
}
@@ -85,7 +85,7 @@ public abstract class SerializationUtils {
if (rawValues == null) {
return null;
}
Map<HK, HV> map = new LinkedHashMap<HK, HV>(rawValues.size());
Map<HK, HV> map = new LinkedHashMap<>(rawValues.size());
for (Map.Entry<byte[], byte[]> entry : rawValues.entrySet()) {
// May want to deserialize only key or value
HK key = hashKeySerializer != null ? (HK) hashKeySerializer.deserialize(entry.getKey()) : (HK) entry.getKey();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -75,9 +75,9 @@ public class RedisAtomicDouble extends Number implements Serializable, BoundKeyO
Assert.hasText(redisCounter, "a valid counter name is required");
Assert.notNull(factory, "a valid factory is required");
RedisTemplate<String, Double> redisTemplate = new RedisTemplate<String, Double>();
RedisTemplate<String, Double> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericToStringSerializer<Double>(Double.class));
redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Double.class));
redisTemplate.setExposeConnection(true);
redisTemplate.setConnectionFactory(factory);
redisTemplate.afterPropertiesSet();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2016 the original author or authors.
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -98,9 +98,9 @@ public class RedisAtomicInteger extends Number implements Serializable, BoundKey
}
private RedisAtomicInteger(String redisCounter, RedisConnectionFactory factory, Integer initialValue) {
RedisTemplate<String, Integer> redisTemplate = new RedisTemplate<String, Integer>();
RedisTemplate<String, Integer> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericToStringSerializer<Integer>(Integer.class));
redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Integer.class));
redisTemplate.setExposeConnection(true);
redisTemplate.setConnectionFactory(factory);
redisTemplate.afterPropertiesSet();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2016 the original author or authors.
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -76,9 +76,9 @@ public class RedisAtomicLong extends Number implements Serializable, BoundKeyOpe
Assert.hasText(redisCounter, "a valid counter name is required");
Assert.notNull(factory, "a valid factory is required");
RedisTemplate<String, Long> redisTemplate = new RedisTemplate<String, Long>();
RedisTemplate<String, Long> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericToStringSerializer<Long>(Long.class));
redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Long.class));
redisTemplate.setExposeConnection(true);
redisTemplate.setConnectionFactory(factory);
redisTemplate.afterPropertiesSet();

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2013 the original author or authors.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -26,7 +26,7 @@ import org.springframework.data.redis.core.SessionCallback;
/**
* Utility class used mainly for type conversion by the default collection implementations. Meant for internal use.
*
*
* @author Costin Leau
*/
abstract class CollectionUtils {
@@ -43,7 +43,7 @@ abstract class CollectionUtils {
}
static Collection<String> extractKeys(Collection<? extends RedisStore> stores) {
Collection<String> keys = new ArrayList<String>(stores.size());
Collection<String> keys = new ArrayList<>(stores.size());
for (RedisStore store : stores) {
keys.add(store.getKey());

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2013 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -34,7 +34,7 @@ import org.springframework.data.redis.core.SessionCallback;
/**
* Default implementation for {@link RedisMap}. Note that the current implementation doesn't provide the same locking
* semantics across all methods. In highly concurrent environments, race conditions might appear.
*
*
* @author Costin Leau
*/
public class DefaultRedisMap<K, V> implements RedisMap<K, V> {
@@ -66,7 +66,7 @@ public class DefaultRedisMap<K, V> implements RedisMap<K, V> {
/**
* Constructs a new <code>DefaultRedisMap</code> instance.
*
*
* @param key
* @param operations
*/
@@ -76,7 +76,7 @@ public class DefaultRedisMap<K, V> implements RedisMap<K, V> {
/**
* Constructs a new <code>DefaultRedisMap</code> instance.
*
*
* @param boundOps
*/
public DefaultRedisMap(BoundHashOperations<String, K, V> boundOps) {
@@ -117,7 +117,7 @@ public class DefaultRedisMap<K, V> implements RedisMap<K, V> {
Iterator<K> keys = keySet.iterator();
Iterator<V> values = multiGet.iterator();
Set<Map.Entry<K, V>> entries = new LinkedHashSet<Entry<K, V>>();
Set<Map.Entry<K, V>> entries = new LinkedHashSet<>();
while (keys.hasNext()) {
entries.add(new DefaultRedisMapEntry(keys.next(), values.next()));
}

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2014 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -30,7 +30,7 @@ import org.springframework.data.redis.core.ScanOptions;
/**
* Default implementation for {@link RedisSet}. Note that the collection support works only with normal,
* non-pipeline/multi-exec connections as it requires a reply to be sent right away.
*
*
* @author Costin Leau
* @author Christoph Strobl
*/
@@ -51,7 +51,7 @@ public class DefaultRedisSet<E> extends AbstractRedisCollection<E> implements Re
/**
* Constructs a new <code>DefaultRedisSet</code> instance.
*
*
* @param key
* @param operations
*/
@@ -62,7 +62,7 @@ public class DefaultRedisSet<E> extends AbstractRedisCollection<E> implements Re
/**
* Constructs a new <code>DefaultRedisSet</code> instance.
*
*
* @param boundOps
*/
public DefaultRedisSet(BoundSetOperations<String, E> boundOps) {
@@ -80,12 +80,12 @@ public class DefaultRedisSet<E> extends AbstractRedisCollection<E> implements Re
public RedisSet<E> diffAndStore(RedisSet<?> set, String destKey) {
boundSetOps.diffAndStore(set.getKey(), destKey);
return new DefaultRedisSet<E>(boundSetOps.getOperations().boundSetOps(destKey));
return new DefaultRedisSet<>(boundSetOps.getOperations().boundSetOps(destKey));
}
public RedisSet<E> diffAndStore(Collection<? extends RedisSet<?>> sets, String destKey) {
boundSetOps.diffAndStore(CollectionUtils.extractKeys(sets), destKey);
return new DefaultRedisSet<E>(boundSetOps.getOperations().boundSetOps(destKey));
return new DefaultRedisSet<>(boundSetOps.getOperations().boundSetOps(destKey));
}
public Set<E> intersect(RedisSet<?> set) {
@@ -98,12 +98,12 @@ public class DefaultRedisSet<E> extends AbstractRedisCollection<E> implements Re
public RedisSet<E> intersectAndStore(RedisSet<?> set, String destKey) {
boundSetOps.intersectAndStore(set.getKey(), destKey);
return new DefaultRedisSet<E>(boundSetOps.getOperations().boundSetOps(destKey));
return new DefaultRedisSet<>(boundSetOps.getOperations().boundSetOps(destKey));
}
public RedisSet<E> intersectAndStore(Collection<? extends RedisSet<?>> sets, String destKey) {
boundSetOps.intersectAndStore(CollectionUtils.extractKeys(sets), destKey);
return new DefaultRedisSet<E>(boundSetOps.getOperations().boundSetOps(destKey));
return new DefaultRedisSet<>(boundSetOps.getOperations().boundSetOps(destKey));
}
public Set<E> union(RedisSet<?> set) {
@@ -116,12 +116,12 @@ public class DefaultRedisSet<E> extends AbstractRedisCollection<E> implements Re
public RedisSet<E> unionAndStore(RedisSet<?> set, String destKey) {
boundSetOps.unionAndStore(set.getKey(), destKey);
return new DefaultRedisSet<E>(boundSetOps.getOperations().boundSetOps(destKey));
return new DefaultRedisSet<>(boundSetOps.getOperations().boundSetOps(destKey));
}
public RedisSet<E> unionAndStore(Collection<? extends RedisSet<?>> sets, String destKey) {
boundSetOps.unionAndStore(CollectionUtils.extractKeys(sets), destKey);
return new DefaultRedisSet<E>(boundSetOps.getOperations().boundSetOps(destKey));
return new DefaultRedisSet<>(boundSetOps.getOperations().boundSetOps(destKey));
}
@SuppressWarnings("unchecked")

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2016 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,7 +20,6 @@ import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.connection.RedisZSetCommands.Limit;
import org.springframework.data.redis.connection.RedisZSetCommands.Range;
@@ -34,7 +33,7 @@ import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
/**
* Default implementation for {@link RedisZSet}. Note that the collection support works only with normal,
* non-pipeline/multi-exec connections as it requires a reply to be sent right away.
*
*
* @author Costin Leau
* @author Christoph Strobl
* @author Mark Paluch
@@ -57,7 +56,7 @@ public class DefaultRedisZSet<E> extends AbstractRedisCollection<E> implements R
/**
* Constructs a new <code>DefaultRedisZSet</code> instance with a default score of '1'.
*
*
* @param key
* @param operations
*/
@@ -67,7 +66,7 @@ public class DefaultRedisZSet<E> extends AbstractRedisCollection<E> implements R
/**
* Constructs a new <code>DefaultRedisSortedSet</code> instance.
*
*
* @param key
* @param operations
* @param defaultScore
@@ -80,7 +79,7 @@ public class DefaultRedisZSet<E> extends AbstractRedisCollection<E> implements R
/**
* Constructs a new <code>DefaultRedisZSet</code> instance with a default score of '1'.
*
*
* @param boundOps
*/
public DefaultRedisZSet(BoundZSetOperations<String, E> boundOps) {
@@ -89,7 +88,7 @@ public class DefaultRedisZSet<E> extends AbstractRedisCollection<E> implements R
/**
* Constructs a new <code>DefaultRedisZSet</code> instance.
*
*
* @param boundOps
* @param defaultScore
*/
@@ -101,12 +100,12 @@ public class DefaultRedisZSet<E> extends AbstractRedisCollection<E> implements R
public RedisZSet<E> intersectAndStore(RedisZSet<?> set, String destKey) {
boundZSetOps.intersectAndStore(set.getKey(), destKey);
return new DefaultRedisZSet<E>(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore());
return new DefaultRedisZSet<>(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore());
}
public RedisZSet<E> intersectAndStore(Collection<? extends RedisZSet<?>> sets, String destKey) {
boundZSetOps.intersectAndStore(CollectionUtils.extractKeys(sets), destKey);
return new DefaultRedisZSet<E>(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore());
return new DefaultRedisZSet<>(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore());
}
public Set<E> range(long start, long end) {
@@ -171,12 +170,12 @@ public class DefaultRedisZSet<E> extends AbstractRedisCollection<E> implements R
public RedisZSet<E> unionAndStore(RedisZSet<?> set, String destKey) {
boundZSetOps.unionAndStore(set.getKey(), destKey);
return new DefaultRedisZSet<E>(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore());
return new DefaultRedisZSet<>(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore());
}
public RedisZSet<E> unionAndStore(Collection<? extends RedisZSet<?>> sets, String destKey) {
boundZSetOps.unionAndStore(CollectionUtils.extractKeys(sets), destKey);
return new DefaultRedisZSet<E>(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore());
return new DefaultRedisZSet<>(boundZSetOps.getOperations().boundZSetOps(destKey), getDefaultScore());
}
public boolean add(E e) {
@@ -262,13 +261,7 @@ public class DefaultRedisZSet<E> extends AbstractRedisCollection<E> implements R
*/
@Override
public Cursor<E> scan() {
return new ConvertingCursor<TypedTuple<E>, E>(scan(ScanOptions.NONE), new Converter<TypedTuple<E>, E>() {
@Override
public E convert(TypedTuple<E> source) {
return source.getValue();
}
});
return new ConvertingCursor<>(scan(ScanOptions.NONE), TypedTuple::getValue);
}
/**

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2013 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -39,7 +39,7 @@ import org.springframework.data.redis.core.RedisOperations;
* {@link org.springframework.beans.factory.config.PropertiesFactoryBean}.
* <p/>
* Note that this implementation only accepts Strings - objects of other type are not supported.
*
*
* @see Properties
* @see org.springframework.core.io.support.PropertiesLoaderSupport
* @author Costin Leau
@@ -58,7 +58,7 @@ public class RedisProperties extends Properties implements RedisMap<Object, Obje
/**
* Constructs a new <code>RedisProperties</code> instance.
*
*
* @param key
* @param operations
*/
@@ -68,19 +68,19 @@ public class RedisProperties extends Properties implements RedisMap<Object, Obje
/**
* Constructs a new <code>RedisProperties</code> instance.
*
*
* @param defaults
* @param boundOps
*/
public RedisProperties(Properties defaults, BoundHashOperations<String, String, String> boundOps) {
super(defaults);
this.hashOps = boundOps;
this.delegate = new DefaultRedisMap<String, String>(boundOps);
this.delegate = new DefaultRedisMap<>(boundOps);
}
/**
* Constructs a new <code>RedisProperties</code> instance.
*
*
* @param defaults
* @param key
* @param operations
@@ -103,7 +103,7 @@ public class RedisProperties extends Properties implements RedisMap<Object, Obje
}
public Enumeration<?> propertyNames() {
Set<String> keys = new LinkedHashSet<String>(delegate.keySet());
Set<String> keys = new LinkedHashSet<>(delegate.keySet());
if (defaults != null) {
keys.addAll(defaults.stringPropertyNames());
}

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2011-2016 the original author or authors.
*
* Copyright 2011-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -32,10 +32,10 @@ import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
* associated with each item.
* <p/>
* Since using a {@link Comparator} does not apply, a ZSet implements the {@link SortedSet} methods where applicable.
*
*
* @author Costin Leau
* @author Mark Paluch
* @auhtor Christoph Strobl
* @author Christoph Strobl
*/
public interface RedisZSet<E> extends RedisCollection<E>, Set<E> {
@@ -54,7 +54,7 @@ public interface RedisZSet<E> extends RedisCollection<E>, Set<E> {
/**
* Get all elements with lexicographical ordering with a value between {@link Range#getMin()} and
* {@link Range#getMax()}.
*
*
* @param range must not be {@literal null}.
* @return
* @see BoundZSetOperations#rangeByLex(Range)
@@ -66,7 +66,7 @@ public interface RedisZSet<E> extends RedisCollection<E>, Set<E> {
* Get all elements {@literal n} elements, where {@literal n = } {@link Limit#getCount()}, starting at
* {@link Limit#getOffset()} with lexicographical ordering having a value between {@link Range#getMin()} and
* {@link Range#getMax()}.
*
*
* @param range must not be {@literal null}.
* @param limit can be {@literal null}.
* @return
@@ -93,7 +93,7 @@ public interface RedisZSet<E> extends RedisCollection<E>, Set<E> {
/**
* Adds an element to the set with the given score, or updates the score if the element exists.
*
*
* @param e element to add
* @param score element score
* @return true if a new element was added, false otherwise (only the score has been updated)
@@ -108,7 +108,7 @@ public interface RedisZSet<E> extends RedisCollection<E>, Set<E> {
/**
* Returns the score of the given element. Returns null if the element is not contained by the set.
*
*
* @param o object
* @return the score associated with the given object
*/
@@ -117,7 +117,7 @@ public interface RedisZSet<E> extends RedisCollection<E>, Set<E> {
/**
* Returns the rank (position) of the given element in the set, in ascending order. Returns null if the element is not
* contained by the set.
*
*
* @param o object
* @return rank of the given object
*/
@@ -126,7 +126,7 @@ public interface RedisZSet<E> extends RedisCollection<E>, Set<E> {
/**
* Returns the rank (position) of the given element in the set, in descending order. Returns null if the element is
* not contained by the set.
*
*
* @param o object
* @return reverse rank of the given object
*/
@@ -134,14 +134,14 @@ public interface RedisZSet<E> extends RedisCollection<E>, Set<E> {
/**
* Returns the default score used by this set.
*
*
* @return the default score used by the implementation.
*/
Double getDefaultScore();
/**
* Returns the first (lowest) element currently in this sorted set.
*
*
* @return the first (lowest) element currently in this sorted set.
* @throws NoSuchElementException sorted set is empty.
*/
@@ -149,7 +149,7 @@ public interface RedisZSet<E> extends RedisCollection<E>, Set<E> {
/**
* Returns the last (highest) element currently in this sorted set.
*
*
* @return the last (highest) element currently in this sorted set.
* @throws NoSuchElementException sorted set is empty.
*/

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -63,7 +63,7 @@ public final class ByteUtils {
return new byte[][] {};
}
List<byte[]> bytes = new ArrayList<byte[]>();
List<byte[]> bytes = new ArrayList<>();
int offset = 0;
for (int i = 0; i <= source.length; i++) {