proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/MultiNodeExecution.java
MultiNodeExecution
firstOfAsync
class MultiNodeExecution { public static <T> T execute(Callable<T> function) { try { return function.call(); } catch (Exception e) { throw Exceptions.bubble(e); } } /** * Aggregate (sum) results of the {@link RedisFuture}s. * * @param executions mapping of a key to the future * @return future producing an aggregation result */ public static RedisFuture<Long> aggregateAsync(Map<?, ? extends CompletionStage<Long>> executions) { return new PipelinedRedisFuture<>(executions, objectPipelinedRedisFuture -> { AtomicLong result = new AtomicLong(); for (CompletionStage<Long> future : executions.values()) { Long value = execute(() -> future.toCompletableFuture().get()); if (value != null) { result.getAndAdd(value); } } return result.get(); }); } /** * Returns the result of the first {@link RedisFuture} and guarantee that all futures are finished. * * @param executions mapping of a key to the future * @param <T> result type * @return future returning the first result. */ public static <T> RedisFuture<T> firstOfAsync(Map<?, ? extends CompletionStage<T>> executions) {<FILL_FUNCTION_BODY>} /** * Returns the result of the last {@link RedisFuture} and guarantee that all futures are finished. * * @param executions mapping of a key to the future * @param <T> result type * @return future returning the first result. */ public static <T> RedisFuture<T> lastOfAsync(Map<?, ? extends CompletionStage<T>> executions) { return new PipelinedRedisFuture<>(executions, objectPipelinedRedisFuture -> { // make sure, that all futures are executed before returning the result. T result = null; for (CompletionStage<T> future : executions.values()) { result = execute(() -> future.toCompletableFuture().get()); } return result; }); } /** * Returns always {@literal OK} and guarantee that all futures are finished. * * @param executions mapping of a key to the future * @return future returning the first result. */ public static RedisFuture<String> alwaysOkOfAsync(Map<?, ? extends CompletionStage<String>> executions) { return new PipelinedRedisFuture<>(executions, objectPipelinedRedisFuture -> { synchronize(executions); return "OK"; }); } private static void synchronize(Map<?, ? extends CompletionStage<String>> executions) { // make sure, that all futures are executed before returning the result. for (CompletionStage<String> future : executions.values()) { try { future.toCompletableFuture().get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RedisCommandInterruptedException(e); } catch (ExecutionException e) { // swallow exceptions } } } }
return new PipelinedRedisFuture<>(executions, objectPipelinedRedisFuture -> { // make sure, that all futures are executed before returning the result. for (CompletionStage<T> future : executions.values()) { execute(() -> future.toCompletableFuture().get()); } for (CompletionStage<T> future : executions.values()) { return execute(() -> future.toCompletableFuture().get()); } return null; });
855
131
986
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/PartitionAccessor.java
PartitionAccessor
get
class PartitionAccessor { private final Collection<RedisClusterNode> partitions; PartitionAccessor(Collection<RedisClusterNode> partitions) { this.partitions = partitions; } List<RedisClusterNode> getUpstream() { return get(redisClusterNode -> redisClusterNode.is(RedisClusterNode.NodeFlag.UPSTREAM)); } List<RedisClusterNode> getReadCandidates(RedisClusterNode upstream) { return get(redisClusterNode -> redisClusterNode.getNodeId().equals(upstream.getNodeId()) || (redisClusterNode.is(RedisClusterNode.NodeFlag.REPLICA) && upstream.getNodeId().equals(redisClusterNode.getSlaveOf()))); } List<RedisClusterNode> get(Predicate<RedisClusterNode> test) {<FILL_FUNCTION_BODY>} }
List<RedisClusterNode> result = new ArrayList<>(partitions.size()); for (RedisClusterNode partition : partitions) { if (test.test(partition)) { result.add(partition); } } return result;
241
67
308
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/PartitionsConsensusImpl.java
KnownMajority
getPartitions
class KnownMajority extends PartitionsConsensus { @Override Partitions getPartitions(Partitions current, Map<RedisURI, Partitions> topologyViews) {<FILL_FUNCTION_BODY>} }
if (topologyViews.isEmpty()) { return current; } List<VotedPartitions> votedList = new ArrayList<>(); for (Partitions partitions : topologyViews.values()) { int knownNodes = 0; for (RedisClusterNode knownNode : current) { if (partitions.getPartitionByNodeId(knownNode.getNodeId()) != null) { knownNodes++; } } votedList.add(new VotedPartitions(knownNodes, partitions)); } Collections.shuffle(votedList); Collections.sort(votedList, (o1, o2) -> Integer.compare(o2.votes, o1.votes)); return votedList.get(0).partitions;
60
203
263
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/PubSubClusterEndpoint.java
NotifyingMessageListener
ssubscribed
class NotifyingMessageListener extends RedisClusterPubSubAdapter<K, V> { @Override public void message(RedisClusterNode node, K channel, V message) { getListeners().forEach(listener -> listener.message(channel, message)); clusterListeners.forEach(listener -> listener.message(node, channel, message)); } @Override public void message(RedisClusterNode node, K pattern, K channel, V message) { getListeners().forEach(listener -> listener.message(pattern, channel, message)); clusterListeners.forEach(listener -> listener.message(node, pattern, channel, message)); } @Override public void subscribed(RedisClusterNode node, K channel, long count) { getListeners().forEach(listener -> listener.subscribed(channel, count)); clusterListeners.forEach(listener -> listener.subscribed(node, channel, count)); } @Override public void psubscribed(RedisClusterNode node, K pattern, long count) { getListeners().forEach(listener -> listener.psubscribed(pattern, count)); clusterListeners.forEach(listener -> listener.psubscribed(node, pattern, count)); } @Override public void unsubscribed(RedisClusterNode node, K channel, long count) { getListeners().forEach(listener -> listener.unsubscribed(channel, count)); clusterListeners.forEach(listener -> listener.unsubscribed(node, channel, count)); } @Override public void punsubscribed(RedisClusterNode node, K pattern, long count) { getListeners().forEach(listener -> listener.punsubscribed(pattern, count)); clusterListeners.forEach(listener -> listener.punsubscribed(node, pattern, count)); } @Override public void ssubscribed(RedisClusterNode node, K channel, long count) {<FILL_FUNCTION_BODY>} }
getListeners().forEach(listener -> listener.ssubscribed(channel, count)); clusterListeners.forEach(listener -> listener.ssubscribed(node, channel, count));
523
51
574
<methods>public void <init>(io.lettuce.core.ClientOptions, io.lettuce.core.resource.ClientResources) ,public void addListener(RedisPubSubListener<K,V>) ,public Set<K> getChannels() ,public Set<K> getPatterns() ,public boolean hasChannelSubscriptions() ,public boolean hasPatternSubscriptions() ,public boolean isSubscribed() ,public void notifyChannelActive(Channel) ,public void removeListener(RedisPubSubListener<K,V>) ,public RedisCommand<K1,V1,T> write(RedisCommand<K1,V1,T>) ,public Collection<RedisCommand<K1,V1,?>> write(Collection<? extends RedisCommand<K1,V1,?>>) <variables>private static final non-sealed Set<java.lang.String> ALLOWED_COMMANDS_SUBSCRIBED,private static final non-sealed Set<java.lang.String> SUBSCRIBE_COMMANDS,private final non-sealed Set<Wrapper<K>> channels,private io.lettuce.core.ConnectionState connectionState,private final List<RedisPubSubListener<K,V>> listeners,private static final InternalLogger logger,private final non-sealed Set<Wrapper<K>> patterns,private final non-sealed Set<Wrapper<K>> shardChannels,private volatile boolean subscribeWritten
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/RedisClusterPubSubAsyncCommandsImpl.java
RedisClusterPubSubAsyncCommandsImpl
nodes
class RedisClusterPubSubAsyncCommandsImpl<K, V> extends RedisPubSubAsyncCommandsImpl<K, V> implements RedisClusterPubSubAsyncCommands<K, V> { /** * Initialize a new connection. * * @param connection the connection . * @param codec Codec used to encode/decode keys and values. */ public RedisClusterPubSubAsyncCommandsImpl(StatefulRedisPubSubConnection<K, V> connection, RedisCodec<K, V> codec) { super(connection, codec); } @Override public RedisFuture<Set<V>> georadius(K key, double longitude, double latitude, double distance, GeoArgs.Unit unit) { return super.georadius_ro(key, longitude, latitude, distance, unit); } @Override public RedisFuture<List<GeoWithin<V>>> georadius(K key, double longitude, double latitude, double distance, GeoArgs.Unit unit, GeoArgs geoArgs) { return super.georadius_ro(key, longitude, latitude, distance, unit, geoArgs); } @Override public RedisFuture<Set<V>> georadiusbymember(K key, V member, double distance, GeoArgs.Unit unit) { return super.georadiusbymember_ro(key, member, distance, unit); } @Override public RedisFuture<List<GeoWithin<V>>> georadiusbymember(K key, V member, double distance, GeoArgs.Unit unit, GeoArgs geoArgs) { return super.georadiusbymember_ro(key, member, distance, unit, geoArgs); } @Override public StatefulRedisClusterPubSubConnectionImpl<K, V> getStatefulConnection() { return (StatefulRedisClusterPubSubConnectionImpl<K, V>) super.getStatefulConnection(); } @SuppressWarnings("unchecked") @Override public PubSubAsyncNodeSelection<K, V> nodes(Predicate<RedisClusterNode> predicate) {<FILL_FUNCTION_BODY>} private static class StaticPubSubAsyncNodeSelection<K, V> extends AbstractNodeSelection<RedisPubSubAsyncCommands<K, V>, NodeSelectionPubSubAsyncCommands<K, V>, K, V> implements PubSubAsyncNodeSelection<K, V> { private final List<RedisClusterNode> redisClusterNodes; private final ClusterDistributionChannelWriter writer; @SuppressWarnings("unchecked") public StaticPubSubAsyncNodeSelection(StatefulRedisClusterPubSubConnection<K, V> globalConnection, Predicate<RedisClusterNode> selector) { this.redisClusterNodes = globalConnection.getPartitions().stream().filter(selector).collect(Collectors.toList()); writer = ((StatefulRedisClusterPubSubConnectionImpl) globalConnection).getClusterDistributionChannelWriter(); } @Override protected CompletableFuture<RedisPubSubAsyncCommands<K, V>> getApi(RedisClusterNode redisClusterNode) { return getConnection(redisClusterNode).thenApply(StatefulRedisPubSubConnection::async); } protected List<RedisClusterNode> nodes() { return redisClusterNodes; } @SuppressWarnings("unchecked") protected CompletableFuture<StatefulRedisPubSubConnection<K, V>> getConnection(RedisClusterNode redisClusterNode) { RedisURI uri = redisClusterNode.getUri(); AsyncClusterConnectionProvider async = (AsyncClusterConnectionProvider) writer.getClusterConnectionProvider(); return async.getConnectionAsync(ConnectionIntent.WRITE, uri.getHost(), uri.getPort()) .thenApply(it -> (StatefulRedisPubSubConnection<K, V>) it); } } }
PubSubAsyncNodeSelection<K, V> selection = new StaticPubSubAsyncNodeSelection<>(getStatefulConnection(), predicate); NodeSelectionInvocationHandler h = new NodeSelectionInvocationHandler((AbstractNodeSelection<?, ?, ?, ?>) selection, RedisPubSubAsyncCommands.class, ASYNC); return (PubSubAsyncNodeSelection<K, V>) Proxy.newProxyInstance(NodeSelectionSupport.class.getClassLoader(), new Class<?>[] { NodeSelectionPubSubAsyncCommands.class, PubSubAsyncNodeSelection.class }, h);
1,005
143
1,148
<methods>public void <init>(StatefulRedisPubSubConnection<K,V>, RedisCodec<K,V>) ,public StatefulRedisPubSubConnection<K,V> getStatefulConnection() ,public transient RedisFuture<java.lang.Void> psubscribe(K[]) ,public RedisFuture<java.lang.Long> publish(K, V) ,public RedisFuture<List<K>> pubsubChannels(K) ,public transient RedisFuture<Map<K,java.lang.Long>> pubsubNumsub(K[]) ,public RedisFuture<List<K>> pubsubShardChannels(K) ,public transient RedisFuture<Map<K,java.lang.Long>> pubsubShardNumsub(K[]) ,public transient RedisFuture<java.lang.Void> punsubscribe(K[]) ,public transient RedisFuture<java.lang.Void> ssubscribe(K[]) ,public transient RedisFuture<java.lang.Void> subscribe(K[]) ,public transient RedisFuture<java.lang.Void> unsubscribe(K[]) <variables>private final non-sealed PubSubCommandBuilder<K,V> commandBuilder
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/RedisClusterPubSubReactiveCommandsImpl.java
StaticPubSubReactiveNodeSelection
getConnection
class StaticPubSubReactiveNodeSelection<K, V> extends AbstractNodeSelection<RedisPubSubReactiveCommands<K, V>, NodeSelectionPubSubReactiveCommands<K, V>, K, V> implements PubSubReactiveNodeSelection<K, V> { private final List<RedisClusterNode> redisClusterNodes; private final ClusterDistributionChannelWriter writer; @SuppressWarnings("unchecked") public StaticPubSubReactiveNodeSelection(StatefulRedisClusterPubSubConnection<K, V> globalConnection, Predicate<RedisClusterNode> selector) { this.redisClusterNodes = globalConnection.getPartitions().stream().filter(selector).collect(Collectors.toList()); writer = ((StatefulRedisClusterPubSubConnectionImpl) globalConnection).getClusterDistributionChannelWriter(); } @Override protected CompletableFuture<RedisPubSubReactiveCommands<K, V>> getApi(RedisClusterNode redisClusterNode) { return getConnection(redisClusterNode).thenApply(StatefulRedisPubSubConnection::reactive); } protected List<RedisClusterNode> nodes() { return redisClusterNodes; } @SuppressWarnings("unchecked") protected CompletableFuture<StatefulRedisPubSubConnection<K, V>> getConnection(RedisClusterNode redisClusterNode) {<FILL_FUNCTION_BODY>} }
RedisURI uri = redisClusterNode.getUri(); AsyncClusterConnectionProvider async = (AsyncClusterConnectionProvider) writer.getClusterConnectionProvider(); return async.getConnectionAsync(ConnectionIntent.WRITE, uri.getHost(), uri.getPort()) .thenApply(it -> (StatefulRedisPubSubConnection<K, V>) it);
364
92
456
<methods>public void <init>(StatefulRedisPubSubConnection<K,V>, RedisCodec<K,V>) ,public StatefulRedisPubSubConnection<K,V> getStatefulConnection() ,public Flux<ChannelMessage<K,V>> observeChannels() ,public Flux<ChannelMessage<K,V>> observeChannels(FluxSink.OverflowStrategy) ,public Flux<PatternMessage<K,V>> observePatterns() ,public Flux<PatternMessage<K,V>> observePatterns(FluxSink.OverflowStrategy) ,public transient Mono<java.lang.Void> psubscribe(K[]) ,public Mono<java.lang.Long> publish(K, V) ,public Flux<K> pubsubChannels(K) ,public transient Mono<Map<K,java.lang.Long>> pubsubNumsub(K[]) ,public Flux<K> pubsubShardChannels(K) ,public transient Mono<Map<K,java.lang.Long>> pubsubShardNumsub(K[]) ,public transient Mono<java.lang.Void> punsubscribe(K[]) ,public transient Mono<java.lang.Void> ssubscribe(K[]) ,public transient Mono<java.lang.Void> subscribe(K[]) ,public transient Mono<java.lang.Void> unsubscribe(K[]) <variables>private final non-sealed PubSubCommandBuilder<K,V> commandBuilder
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/RedisClusterURIUtil.java
RedisClusterURIUtil
toRedisURIs
class RedisClusterURIUtil { private RedisClusterURIUtil() { } /** * Parse a Redis Cluster URI with potentially multiple hosts into a {@link List} of {@link RedisURI}. * * An URI follows the syntax: {@code redis://[password@]host[:port][,host2[:port2]]} * * @param uri must not be empty or {@code null}. * @return {@link List} of {@link RedisURI}. */ public static List<RedisURI> toRedisURIs(URI uri) {<FILL_FUNCTION_BODY>} /** * Apply {@link RedisURI} settings such as SSL/Timeout/password. * * @param from from {@link RedisURI}. * @param to from {@link RedisURI}. */ static void applyUriConnectionSettings(RedisURI from, RedisURI to) { to.applyAuthentication(from); to.applySsl(from); to.setTimeout(from.getTimeout()); } }
RedisURI redisURI = RedisURI.create(uri); String[] parts = redisURI.getHost().split("\\,"); List<RedisURI> redisURIs = new ArrayList<>(parts.length); for (String part : parts) { HostAndPort hostAndPort = HostAndPort.parse(part); RedisURI nodeUri = RedisURI.create(hostAndPort.getHostText(), hostAndPort.hasPort() ? hostAndPort.getPort() : redisURI.getPort()); applyUriConnectionSettings(redisURI, nodeUri); redisURIs.add(nodeUri); } return redisURIs;
269
178
447
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/RoundRobin.java
RoundRobin
isConsistent
class RoundRobin<V> { protected volatile Collection<? extends V> collection = Collections.emptyList(); protected volatile V offset; private final BiPredicate<V, V> isEqual; public RoundRobin() { this((a, b) -> true); } public RoundRobin(BiPredicate<V, V> hasElementChanged) { this.isEqual = hasElementChanged; } /** * Return whether this {@link RoundRobin} is still consistent and contains all items from the leader {@link Collection} and * vice versa. * * @param leader the leader collection containing source elements for this {@link RoundRobin}. * @return {@code true} if this {@link RoundRobin} is consistent with the leader {@link Collection}. */ public boolean isConsistent(Collection<? extends V> leader) {<FILL_FUNCTION_BODY>} private boolean find(Collection<? extends V> hayStack, V needle) { for (V searchedElement : hayStack) { if (searchedElement.equals(needle)) { return isEqual.test(needle, searchedElement); } } return false; } /** * Rebuild the {@link RoundRobin} from the leader {@link Collection}. * * @param leader the leader collection containing source elements for this {@link RoundRobin}. */ public void rebuild(Collection<? extends V> leader) { this.collection = new ArrayList<>(leader); this.offset = null; } /** * Returns the next item. * * @return the next item */ public V next() { Collection<? extends V> collection = this.collection; V offset = this.offset; if (offset != null) { boolean accept = false; for (V element : collection) { if (element == offset) { accept = true; continue; } if (accept) { return this.offset = element; } } } return this.offset = collection.iterator().next(); } }
Collection<? extends V> collection = this.collection; if (collection.size() != leader.size()) { return false; } for (V currentElement : collection) { boolean found = find(leader, currentElement); if (!found) { return false; } } return true;
548
93
641
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/RoundRobinSocketAddressSupplier.java
RoundRobinSocketAddressSupplier
get
class RoundRobinSocketAddressSupplier implements Supplier<SocketAddress> { private static final InternalLogger logger = InternalLoggerFactory.getInstance(RoundRobinSocketAddressSupplier.class); private final Supplier<Partitions> partitions; private final Function<Collection<RedisClusterNode>, Collection<RedisClusterNode>> sortFunction; private final ClientResources clientResources; private final RoundRobin<RedisClusterNode> roundRobin; @SuppressWarnings({ "unchecked", "rawtypes" }) public RoundRobinSocketAddressSupplier(Supplier<Partitions> partitions, Function<? extends Collection<RedisClusterNode>, Collection<RedisClusterNode>> sortFunction, ClientResources clientResources) { LettuceAssert.notNull(partitions, "Partitions must not be null"); LettuceAssert.notNull(sortFunction, "Sort-Function must not be null"); this.partitions = partitions; this.roundRobin = new RoundRobin<>( (l, r) -> l.getUri() == r.getUri() || (l.getUri() != null && l.getUri().equals(r.getUri()))); this.sortFunction = (Function) sortFunction; this.clientResources = clientResources; resetRoundRobin(partitions.get()); } @Override public SocketAddress get() {<FILL_FUNCTION_BODY>} protected void resetRoundRobin(Partitions partitions) { roundRobin.rebuild(sortFunction.apply(partitions)); } protected SocketAddress getSocketAddress(RedisClusterNode redisClusterNode) { SocketAddress resolvedAddress = clientResources.socketAddressResolver().resolve(redisClusterNode.getUri()); logger.debug("Resolved SocketAddress {} using for Cluster node {}", resolvedAddress, redisClusterNode.getNodeId()); return resolvedAddress; } }
Partitions partitions = this.partitions.get(); if (!roundRobin.isConsistent(partitions)) { resetRoundRobin(partitions); } RedisClusterNode redisClusterNode = roundRobin.next(); return getSocketAddress(redisClusterNode);
483
77
560
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/SlotHash.java
SlotHash
getSlots
class SlotHash { /** * Constant for a subkey start. */ public static final byte SUBKEY_START = (byte) '{'; /** * Constant for a subkey end. */ public static final byte SUBKEY_END = (byte) '}'; /** * Number of redis cluster slot hashes. */ public static final int SLOT_COUNT = 16384; private SlotHash() { } /** * Calculate the slot from the given key. * * @param key the key * @return slot */ public static int getSlot(String key) { return getSlot(key.getBytes()); } /** * Calculate the slot from the given key. * * @param key the key * @return slot */ public static int getSlot(byte[] key) { return getSlot(ByteBuffer.wrap(key)); } /** * Calculate the slot from the given key. * * @param key the key * @return slot */ public static int getSlot(ByteBuffer key) { int limit = key.limit(); int position = key.position(); int start = indexOf(key, SUBKEY_START); if (start != -1) { int end = indexOf(key, start + 1, SUBKEY_END); if (end != -1 && end != start + 1) { key.position(start + 1).limit(end); } } try { if (key.hasArray()) { return CRC16.crc16(key.array(), key.position(), key.limit() - key.position()) % SLOT_COUNT; } return CRC16.crc16(key) % SLOT_COUNT; } finally { key.position(position).limit(limit); } } private static int indexOf(ByteBuffer haystack, byte needle) { return indexOf(haystack, haystack.position(), needle); } private static int indexOf(ByteBuffer haystack, int start, byte needle) { for (int i = start; i < haystack.remaining(); i++) { if (haystack.get(i) == needle) { return i; } } return -1; } /** * Partition keys by slot-hash. The resulting map honors order of the keys. * * @param codec codec to encode the key. * @param keys iterable of keys. * @param <K> Key type. * @param <V> Value type. * @return map between slot-hash and an ordered list of keys. */ public static <K, V> Map<Integer, List<K>> partition(RedisCodec<K, V> codec, Iterable<K> keys) { Map<Integer, List<K>> partitioned = new HashMap<>(); for (K key : keys) { int slot = getSlot(codec.encodeKey(key)); if (!partitioned.containsKey(slot)) { partitioned.put(slot, new ArrayList<>()); } Collection<K> list = partitioned.get(slot); list.add(key); } return partitioned; } /** * Create mapping between the Key and hash slot. * * @param partitioned map partitioned by slot-hash and keys. * @return map of keys to their slot-hash. * @param <K> key type * @param <S> slot-hash number type. */ public static <S extends Number, K> Map<K, S> getSlots(Map<S, ? extends Iterable<K>> partitioned) {<FILL_FUNCTION_BODY>} }
Map<K, S> result = new HashMap<>(); for (Map.Entry<S, ? extends Iterable<K>> entry : partitioned.entrySet()) { for (K key : entry.getValue()) { result.put(key, entry.getKey()); } } return result;
1,004
83
1,087
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/StatefulRedisClusterPubSubConnectionImpl.java
StatefulRedisClusterPubSubConnectionImpl
getConnectionAsync
class StatefulRedisClusterPubSubConnectionImpl<K, V> extends StatefulRedisPubSubConnectionImpl<K, V> implements StatefulRedisClusterPubSubConnection<K, V> { private final PubSubClusterEndpoint<K, V> endpoint; private final ClusterPushHandler clusterPushHandler; private volatile Partitions partitions; private volatile String nodeId; /** * Initialize a new connection. * * @param endpoint the channel writer. * @param clusterPushHandler the cluster push message handler. * @param codec Codec used to encode/decode keys and values. * @param timeout Maximum time to wait for a response. */ public StatefulRedisClusterPubSubConnectionImpl(PubSubClusterEndpoint<K, V> endpoint, ClusterPushHandler clusterPushHandler, RedisChannelWriter writer, RedisCodec<K, V> codec, Duration timeout) { super(endpoint, writer, codec, timeout); this.endpoint = endpoint; this.clusterPushHandler = clusterPushHandler; } @Override public RedisClusterPubSubAsyncCommands<K, V> async() { return (RedisClusterPubSubAsyncCommands<K, V>) super.async(); } @Override protected RedisPubSubAsyncCommandsImpl<K, V> newRedisAsyncCommandsImpl() { return new RedisClusterPubSubAsyncCommandsImpl<>(this, codec); } @Override public RedisClusterPubSubCommands<K, V> sync() { return (RedisClusterPubSubCommands<K, V>) super.sync(); } @SuppressWarnings("unchecked") @Override protected RedisPubSubCommands<K, V> newRedisSyncCommandsImpl() { return (RedisPubSubCommands) Proxy.newProxyInstance(AbstractRedisClient.class.getClassLoader(), new Class<?>[] { RedisClusterPubSubCommands.class, RedisPubSubCommands.class }, syncInvocationHandler()); } private InvocationHandler syncInvocationHandler() { return new ClusterFutureSyncInvocationHandler<K, V>(this, RedisPubSubAsyncCommands.class, PubSubNodeSelection.class, NodeSelectionPubSubCommands.class, async()); } @Override public RedisClusterPubSubReactiveCommands<K, V> reactive() { return (RedisClusterPubSubReactiveCommands<K, V>) super.reactive(); } @Override protected RedisPubSubReactiveCommandsImpl<K, V> newRedisReactiveCommandsImpl() { return new RedisClusterPubSubReactiveCommandsImpl<K, V>(this, codec); } @Override protected List<RedisFuture<Void>> resubscribe() { async().clusterMyId().thenAccept(nodeId -> endpoint.setClusterNode(partitions.getPartitionByNodeId(nodeId))); return super.resubscribe(); } @Override public StatefulRedisPubSubConnection<K, V> getConnection(String nodeId) { RedisURI redisURI = lookup(nodeId); if (redisURI == null) { throw new RedisException("NodeId " + nodeId + " does not belong to the cluster"); } return (StatefulRedisPubSubConnection<K, V>) getClusterDistributionChannelWriter().getClusterConnectionProvider() .getConnection(ConnectionIntent.WRITE, nodeId); } @Override @SuppressWarnings("unchecked") public CompletableFuture<StatefulRedisPubSubConnection<K, V>> getConnectionAsync(String nodeId) {<FILL_FUNCTION_BODY>} @Override public StatefulRedisPubSubConnection<K, V> getConnection(String host, int port) { return (StatefulRedisPubSubConnection<K, V>) getClusterDistributionChannelWriter().getClusterConnectionProvider() .getConnection(ConnectionIntent.WRITE, host, port); } @Override public CompletableFuture<StatefulRedisPubSubConnection<K, V>> getConnectionAsync(String host, int port) { AsyncClusterConnectionProvider provider = (AsyncClusterConnectionProvider) getClusterDistributionChannelWriter() .getClusterConnectionProvider(); return (CompletableFuture) provider.getConnectionAsync(ConnectionIntent.WRITE, host, port); } @Override public void activated() { if (!endpoint.isSubscribed()) { async.clusterMyId().thenAccept(this::setNodeId); } super.activated(); } public void setPartitions(Partitions partitions) { LettuceAssert.notNull(partitions, "Partitions must not be null"); this.partitions = partitions; String nodeId = getNodeId(); if (nodeId != null && expireStaleConnections()) { if (partitions.getPartitionByNodeId(nodeId) == null) { endpoint.disconnect(); } } getClusterDistributionChannelWriter().setPartitions(partitions); } private String getNodeId() { return this.nodeId; } private void setNodeId(String nodeId) { this.nodeId = nodeId; } public Partitions getPartitions() { return partitions; } @Override public void setNodeMessagePropagation(boolean enabled) { this.endpoint.setNodeMessagePropagation(enabled); } /** * Add a new {@link RedisClusterPubSubListener listener}. * * @param listener the listener, must not be {@code null}. */ @Override public void addListener(RedisClusterPubSubListener<K, V> listener) { endpoint.addListener(listener); } /** * Remove an existing {@link RedisClusterPubSubListener listener}. * * @param listener the listener, must not be {@code null}. */ @Override public void removeListener(RedisClusterPubSubListener<K, V> listener) { endpoint.removeListener(listener); } @Override public void addListener(RedisClusterPushListener listener) { clusterPushHandler.addListener(listener); } @Override public void removeListener(RedisClusterPushListener listener) { clusterPushHandler.removeListener(listener); } protected ClusterDistributionChannelWriter getClusterDistributionChannelWriter() { return (ClusterDistributionChannelWriter) super.getChannelWriter(); } private RedisURI lookup(String nodeId) { for (RedisClusterNode partition : partitions) { if (partition.getNodeId().equals(nodeId)) { return partition.getUri(); } } return null; } private boolean expireStaleConnections() { ClusterClientOptions options = getClusterClientOptions(); return options == null || options.isCloseStaleConnections(); } private ClusterClientOptions getClusterClientOptions() { ClientOptions options = getOptions(); return options instanceof ClusterClientOptions ? (ClusterClientOptions) options : null; } }
RedisURI redisURI = lookup(nodeId); if (redisURI == null) { throw new RedisException("NodeId " + nodeId + " does not belong to the cluster"); } AsyncClusterConnectionProvider provider = (AsyncClusterConnectionProvider) getClusterDistributionChannelWriter() .getClusterConnectionProvider(); return (CompletableFuture) provider.getConnectionAsync(ConnectionIntent.WRITE, nodeId);
1,859
111
1,970
<methods>public void <init>(PubSubEndpoint<K,V>, io.lettuce.core.RedisChannelWriter, RedisCodec<K,V>, java.time.Duration) ,public void activated() ,public void addListener(RedisPubSubListener<K,V>) ,public RedisPubSubAsyncCommands<K,V> async() ,public RedisPubSubReactiveCommands<K,V> reactive() ,public void removeListener(RedisPubSubListener<K,V>) ,public RedisPubSubCommands<K,V> sync() <variables>private final non-sealed PubSubEndpoint<K,V> endpoint
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/StaticNodeSelection.java
StaticNodeSelection
getConnection
class StaticNodeSelection<API, CMD, K, V> extends AbstractNodeSelection<API, CMD, K, V> { private final ClusterDistributionChannelWriter writer; private final ConnectionIntent connectionIntent; private final List<RedisClusterNode> redisClusterNodes; private final Function<StatefulRedisConnection<K, V>, API> apiExtractor; public StaticNodeSelection(ClusterDistributionChannelWriter writer, Predicate<RedisClusterNode> selector, ConnectionIntent connectionIntent, Function<StatefulRedisConnection<K, V>, API> apiExtractor) { this.writer = writer; this.connectionIntent = connectionIntent; this.apiExtractor = apiExtractor; this.redisClusterNodes = writer.getPartitions().stream().filter(selector).collect(Collectors.toList()); } @Override protected CompletableFuture<StatefulRedisConnection<K, V>> getConnection(RedisClusterNode redisClusterNode) {<FILL_FUNCTION_BODY>} @Override protected CompletableFuture<API> getApi(RedisClusterNode redisClusterNode) { return getConnection(redisClusterNode).thenApply(apiExtractor); } @Override protected List<RedisClusterNode> nodes() { return redisClusterNodes; } }
RedisURI uri = redisClusterNode.getUri(); AsyncClusterConnectionProvider async = (AsyncClusterConnectionProvider) writer.getClusterConnectionProvider(); return async.getConnectionAsync(connectionIntent, uri.getHost(), uri.getPort());
339
64
403
<methods>public Map<io.lettuce.core.cluster.models.partitions.RedisClusterNode,API> asMap() ,public CMD commands() ,public API commands(int) ,public io.lettuce.core.cluster.models.partitions.RedisClusterNode node(int) ,public int size() <variables>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/event/ClusterTopologyChangedEvent.java
ClusterTopologyChangedEvent
toString
class ClusterTopologyChangedEvent implements Event { private final List<RedisClusterNode> before; private final List<RedisClusterNode> after; /** * Creates a new {@link ClusterTopologyChangedEvent}. * * @param before the cluster topology view before the topology changed, must not be {@code null} * @param after the cluster topology view after the topology changed, must not be {@code null} */ public ClusterTopologyChangedEvent(List<RedisClusterNode> before, List<RedisClusterNode> after) { this.before = Collections.unmodifiableList(before); this.after = Collections.unmodifiableList(after); } /** * Returns the cluster topology view before the topology changed. * * @return the cluster topology view before the topology changed. */ public List<RedisClusterNode> before() { return before; } /** * Returns the cluster topology view after the topology changed. * * @return the cluster topology view after the topology changed. */ public List<RedisClusterNode> after() { return after; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" [before=").append(before.size()); sb.append(", after=").append(after.size()); sb.append(']'); return sb.toString();
317
73
390
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/models/slots/ClusterSlotRange.java
ClusterSlotRange
toRedisClusterNodes
class ClusterSlotRange implements Serializable { private int from; private int to; private RedisClusterNode upstream; private List<RedisClusterNode> replicaNodes = Collections.emptyList(); public ClusterSlotRange() { } /** * Constructs a {@link ClusterSlotRange} * * @param from from slot * @param to to slot * @param upstream master for the slots, may be {@code null} * @param replicaNodes list of replicas must not be {@code null} but may be empty */ public ClusterSlotRange(int from, int to, RedisClusterNode upstream, List<RedisClusterNode> replicaNodes) { LettuceAssert.notNull(upstream, "Upstream must not be null"); LettuceAssert.notNull(replicaNodes, "ReplicaNodes must not be null"); this.from = from; this.to = to; this.upstream = upstream; this.replicaNodes = replicaNodes; } private RedisClusterNode toRedisClusterNode(HostAndPort hostAndPort, String slaveOf, Set<RedisClusterNode.NodeFlag> flags) { int port = hostAndPort.hasPort() ? hostAndPort.getPort() : RedisURI.DEFAULT_REDIS_PORT; RedisClusterNode redisClusterNode = new RedisClusterNode(); redisClusterNode.setUri(RedisURI.create(hostAndPort.getHostText(), port)); redisClusterNode.setSlaveOf(slaveOf); redisClusterNode.setFlags(flags); return redisClusterNode; } private List<RedisClusterNode> toRedisClusterNodes(List<HostAndPort> hostAndPorts, String slaveOf, Set<RedisClusterNode.NodeFlag> flags) {<FILL_FUNCTION_BODY>} public int getFrom() { return from; } public int getTo() { return to; } public RedisClusterNode getUpstream() { return upstream; } public void setUpstream(RedisClusterNode upstream) { this.upstream = upstream; } @Deprecated public List<RedisClusterNode> getSlaveNodes() { return replicaNodes; } @Deprecated public void setSlaveNodes(List<RedisClusterNode> slaveNodes) { this.replicaNodes = slaveNodes; } public List<RedisClusterNode> getReplicaNodes() { return replicaNodes; } public void setReplicaNodes(List<RedisClusterNode> replicaNodes) { this.replicaNodes = replicaNodes; } public void setFrom(int from) { this.from = from; } public void setTo(int to) { this.to = to; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" [from=").append(from); sb.append(", to=").append(to); sb.append(", masterNode=").append(upstream); sb.append(", replicaNodes=").append(replicaNodes); sb.append(']'); return sb.toString(); } }
List<RedisClusterNode> result = new ArrayList<>(); for (HostAndPort hostAndPort : hostAndPorts) { result.add(toRedisClusterNode(hostAndPort, slaveOf, flags)); } return result;
863
64
927
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/models/slots/ClusterSlotsParser.java
ClusterSlotsParser
createSlots
class ClusterSlotsParser { /** * Utility constructor. */ private ClusterSlotsParser() { } /** * Parse the output of the Redis CLUSTER SLOTS command and convert it to a list of * {@link io.lettuce.core.cluster.models.slots.ClusterSlotRange} * * @param clusterSlotsOutput output of CLUSTER SLOTS command * @return List&gt;ClusterSlotRange&gt; */ public static List<ClusterSlotRange> parse(List<?> clusterSlotsOutput) { List<ClusterSlotRange> result = new ArrayList<>(); Map<String, RedisClusterNode> nodeCache = new HashMap<>(); for (Object o : clusterSlotsOutput) { if (!(o instanceof List)) { continue; } List<?> range = (List<?>) o; if (range.size() < 2) { continue; } ClusterSlotRange clusterSlotRange = parseRange(range, nodeCache); result.add(clusterSlotRange); } Collections.sort(result, new Comparator<ClusterSlotRange>() { @Override public int compare(ClusterSlotRange o1, ClusterSlotRange o2) { return o1.getFrom() - o2.getFrom(); } }); return Collections.unmodifiableList(result); } private static ClusterSlotRange parseRange(List<?> range, Map<String, RedisClusterNode> nodeCache) { Iterator<?> iterator = range.iterator(); int from = Math.toIntExact(getLongFromIterator(iterator, 0)); int to = Math.toIntExact(getLongFromIterator(iterator, 0)); RedisClusterNode upstream = null; List<RedisClusterNode> replicas = new ArrayList<>(); if (iterator.hasNext()) { upstream = getRedisClusterNode(iterator, nodeCache); if (upstream != null) { upstream.setFlags(Collections.singleton(RedisClusterNode.NodeFlag.UPSTREAM)); Set<Integer> slots = new TreeSet<>(upstream.getSlots()); slots.addAll(createSlots(from, to)); upstream.setSlots(new ArrayList<>(slots)); } } while (iterator.hasNext()) { RedisClusterNode replica = getRedisClusterNode(iterator, nodeCache); if (replica != null && upstream != null) { replica.setSlaveOf(upstream.getNodeId()); replica.setFlags(Collections.singleton(RedisClusterNode.NodeFlag.REPLICA)); replicas.add(replica); } } return new ClusterSlotRange(from, to, upstream, Collections.unmodifiableList(replicas)); } private static List<Integer> createSlots(int from, int to) {<FILL_FUNCTION_BODY>} private static RedisClusterNode getRedisClusterNode(Iterator<?> iterator, Map<String, RedisClusterNode> nodeCache) { Object element = iterator.next(); RedisClusterNode redisClusterNode = null; if (element instanceof List) { List<?> hostAndPortList = (List<?>) element; if (hostAndPortList.size() < 2) { return null; } Iterator<?> hostAndPortIterator = hostAndPortList.iterator(); String host = (String) hostAndPortIterator.next(); int port = Math.toIntExact(getLongFromIterator(hostAndPortIterator, 0)); String nodeId; if (hostAndPortIterator.hasNext()) { nodeId = (String) hostAndPortIterator.next(); redisClusterNode = nodeCache.get(nodeId); if (redisClusterNode == null) { redisClusterNode = createNode(host, port); nodeCache.put(nodeId, redisClusterNode); redisClusterNode.setNodeId(nodeId); } } else { String key = host + ":" + port; redisClusterNode = nodeCache.get(key); if (redisClusterNode == null) { redisClusterNode = createNode(host, port); nodeCache.put(key, redisClusterNode); } } } return redisClusterNode; } private static RedisClusterNode createNode(String host, int port) { RedisClusterNode redisClusterNode = new RedisClusterNode(); redisClusterNode.setUri(RedisURI.create(host, port)); redisClusterNode.setSlots(new ArrayList<>()); return redisClusterNode; } private static long getLongFromIterator(Iterator<?> iterator, long defaultValue) { if (iterator.hasNext()) { Object object = iterator.next(); if (object instanceof String) { return Long.parseLong((String) object); } if (object instanceof Number) { return ((Number) object).longValue(); } } return defaultValue; } }
List<Integer> slots = new ArrayList<>(); for (int i = from; i < to + 1; i++) { slots.add(i); } return slots;
1,342
50
1,392
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/topology/Connections.java
Connections
addConnection
class Connections { private final static InternalLogger LOG = InternalLoggerFactory.getInstance(Connections.class); private final Lock lock = new ReentrantLock(); private final ClientResources clientResources; private final Map<RedisURI, StatefulRedisConnection<String, String>> connections; private volatile boolean closed = false; public Connections(ClientResources clientResources, Map<RedisURI, StatefulRedisConnection<String, String>> connections) { this.clientResources = clientResources; this.connections = connections; } /** * Add a connection for a {@link RedisURI} * * @param redisURI * @param connection */ public void addConnection(RedisURI redisURI, StatefulRedisConnection<String, String> connection) {<FILL_FUNCTION_BODY>} /** * @return {@code true} if no connections present. */ public boolean isEmpty() { try { lock.lock(); return this.connections.isEmpty(); } finally { lock.unlock(); } } /* * Initiate {@code CLUSTER NODES} on all connections and return the {@link Requests}. * @return the {@link Requests}. */ public Requests requestTopology(long timeout, TimeUnit timeUnit) { return doRequest(() -> { CommandArgs<String, String> args = new CommandArgs<>(StringCodec.UTF8).add(CommandKeyword.NODES); Command<String, String, String> command = new Command<>(CommandType.CLUSTER, new StatusOutput<>(StringCodec.UTF8), args); return new TimedAsyncCommand<>(command); }, timeout, timeUnit); } /* * Initiate {@code INFO} on all connections and return the {@link Requests}. * @return the {@link Requests}. */ public Requests requestInfo(long timeout, TimeUnit timeUnit) { return doRequest(() -> { Command<String, String, String> command = new Command<>(CommandType.INFO, new StatusOutput<>(StringCodec.UTF8), new CommandArgs<>(StringCodec.UTF8)); return new TimedAsyncCommand<>(command); }, timeout, timeUnit); } /* * Initiate {@code CLUSTER NODES} on all connections and return the {@link Requests}. * @return the {@link Requests}. */ private Requests doRequest(Supplier<TimedAsyncCommand<String, String, String>> commandFactory, long timeout, TimeUnit timeUnit) { Requests requests = new Requests(); Duration timeoutDuration = Duration.ofNanos(timeUnit.toNanos(timeout)); try { lock.lock(); for (Map.Entry<RedisURI, StatefulRedisConnection<String, String>> entry : this.connections.entrySet()) { TimedAsyncCommand<String, String, String> timedCommand = commandFactory.get(); clientResources.timer().newTimeout(it -> { timedCommand.completeExceptionally(ExceptionFactory.createTimeoutException(timeoutDuration)); }, timeout, timeUnit); entry.getValue().dispatch(timedCommand); requests.addRequest(entry.getKey(), timedCommand); } } finally { lock.unlock(); } return requests; } public Connections retainAll(Set<RedisURI> connectionsToRetain) { Set<RedisURI> keys = new LinkedHashSet<>(connections.keySet()); for (RedisURI key : keys) { if (!connectionsToRetain.contains(key)) { this.connections.remove(key); } } return this; } }
if (this.closed) { // fastpath connection.closeAsync(); return; } try { lock.lock(); if (this.closed) { connection.closeAsync(); return; } this.connections.put(redisURI, connection); } finally { lock.unlock(); }
965
94
1,059
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/topology/DefaultClusterTopologyRefresh.java
ConnectionTracker
collectConnections
class ConnectionTracker { private final Map<RedisURI, CompletableFuture<StatefulRedisConnection<String, String>>> connections = new LinkedHashMap<>(); public void addConnection(RedisURI uri, CompletableFuture<StatefulRedisConnection<String, String>> future) { CompletableFuture<StatefulRedisConnection<String, String>> existing = connections.put(uri, future); } @SuppressWarnings("rawtypes") public CompletableFuture<Void> close() { CompletableFuture[] futures = connections.values().stream() .map(it -> it.thenCompose(StatefulConnection::closeAsync).exceptionally(ignore -> null)) .toArray(CompletableFuture[]::new); return CompletableFuture.allOf(futures); } public boolean contains(RedisURI uri) { return connections.containsKey(uri); } public <T> CompletableFuture<T> whenComplete( Function<? super Map<RedisURI, StatefulRedisConnection<String, String>>, ? extends T> mappingFunction) { int expectedCount = connections.size(); AtomicInteger latch = new AtomicInteger(); CompletableFuture<T> continuation = new CompletableFuture<>(); for (Map.Entry<RedisURI, CompletableFuture<StatefulRedisConnection<String, String>>> entry : connections .entrySet()) { CompletableFuture<StatefulRedisConnection<String, String>> future = entry.getValue(); future.whenComplete((it, ex) -> { if (latch.incrementAndGet() == expectedCount) { try { continuation.complete(mappingFunction.apply(collectConnections())); } catch (RuntimeException e) { continuation.completeExceptionally(e); } } }); } return continuation; } protected Map<RedisURI, StatefulRedisConnection<String, String>> collectConnections() {<FILL_FUNCTION_BODY>} }
Map<RedisURI, StatefulRedisConnection<String, String>> activeConnections = new LinkedHashMap<>(); for (Map.Entry<RedisURI, CompletableFuture<StatefulRedisConnection<String, String>>> entry : connections .entrySet()) { CompletableFuture<StatefulRedisConnection<String, String>> future = entry.getValue(); if (future.isDone() && !future.isCompletedExceptionally()) { activeConnections.put(entry.getKey(), future.join()); } } return activeConnections;
512
142
654
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/topology/NodeTopologyView.java
NodeTopologyView
getOwnPartition
class NodeTopologyView { private final boolean available; private final RedisURI redisURI; private Partitions partitions; private final int connectedClients; private final long replicationOffset; private final long latency; private final String clusterNodes; private final String info; private static final Pattern CONNECTED_CLIENTS_PATTERN = patternFor("connected_clients"); private static final Pattern MASTER_REPL_OFFSET_PATTERN = patternFor("master_repl_offset"); private NodeTopologyView(RedisURI redisURI) { this.available = false; this.redisURI = redisURI; this.partitions = new Partitions(); this.connectedClients = 0; this.replicationOffset = -1; this.clusterNodes = null; this.info = null; this.latency = 0; } NodeTopologyView(RedisURI redisURI, String clusterNodes, String info, long latency) { this.available = true; this.redisURI = redisURI; this.partitions = ClusterPartitionParser.parse(clusterNodes); this.connectedClients = getClientCount(info); this.replicationOffset = getReplicationOffset(info); this.clusterNodes = clusterNodes; this.info = info; this.latency = latency; } private static Pattern patternFor(String propertyName) { return Pattern.compile(String.format("^%s:(.*)$", Pattern.quote(propertyName)), Pattern.MULTILINE); } private int getClientCount(String info) { return getMatchOrDefault(info, CONNECTED_CLIENTS_PATTERN, Integer::parseInt, 0); } private long getReplicationOffset(String info) { return getMatchOrDefault(info, MASTER_REPL_OFFSET_PATTERN, Long::parseLong, -1L); } private static <T> T getMatchOrDefault(String haystack, Pattern pattern, Function<String, T> converter, T defaultValue) { if (haystack == null) { return defaultValue; } Matcher matcher = pattern.matcher(haystack); if (matcher.find() && LettuceStrings.isNotEmpty(matcher.group(1))) { return converter.apply(matcher.group(1)); } return defaultValue; } static NodeTopologyView from(RedisURI redisURI, Requests clusterNodesRequests, Requests infoRequests) { TimedAsyncCommand<String, String, String> nodes = clusterNodesRequests.getRequest(redisURI); TimedAsyncCommand<String, String, String> info = infoRequests.getRequest(redisURI); if (resultAvailable(nodes) && !nodes.isCompletedExceptionally() && resultAvailable(info)) { return new NodeTopologyView(redisURI, nodes.join(), optionallyGet(info), nodes.duration()); } return new NodeTopologyView(redisURI); } private static <T> T optionallyGet(TimedAsyncCommand<?, ?, T> command) { if (command.isCompletedExceptionally()) { return null; } return command.join(); } private static boolean resultAvailable(RedisFuture<?> redisFuture) { if (redisFuture != null && redisFuture.isDone() && !redisFuture.isCancelled()) { return true; } return false; } String getNodeId() { return getOwnPartition().getNodeId(); } RedisURI getRedisURI() { if (partitions.isEmpty()) { return redisURI; } return getOwnPartition().getUri(); } RedisClusterNode getOwnPartition() {<FILL_FUNCTION_BODY>} private RedisClusterNode findOwnPartition() { for (RedisClusterNode partition : partitions) { if (partition.is(RedisClusterNode.NodeFlag.MYSELF)) { return partition; } } return null; } void postProcessPartitions() { TopologyComparators.SortAction sortAction = TopologyComparators.SortAction.getSortAction(); sortAction.sort(getPartitions()); getPartitions().updateCache(); } public boolean canContribute() { RedisClusterNode ownPartition = findOwnPartition(); if (ownPartition == null) { return false; } return true; } long getLatency() { return latency; } boolean isAvailable() { return available; } Partitions getPartitions() { return partitions; } int getConnectedClients() { return connectedClients; } long getReplicationOffset() { return replicationOffset; } String getInfo() { return info; } String getClusterNodes() { return clusterNodes; } void setPartitions(Partitions partitions) { this.partitions = partitions; } }
RedisClusterNode own = findOwnPartition(); if (own != null) { return own; } throw new IllegalStateException("Cannot determine own partition");
1,357
48
1,405
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/topology/NodeTopologyViews.java
NodeTopologyViews
getClusterNodes
class NodeTopologyViews { private List<NodeTopologyView> views; public NodeTopologyViews(List<NodeTopologyView> views) { this.views = views; } /** * Return cluster node URI's using the topology query sources and partitions. * * @return */ public Set<RedisURI> getClusterNodes() {<FILL_FUNCTION_BODY>} /** * @return {@code true} if no views are present. */ public boolean isEmpty() { return views.isEmpty(); } public Map<RedisURI, Partitions> toMap() { Map<RedisURI, Partitions> nodeSpecificViews = new TreeMap<>(TopologyComparators.RedisURIComparator.INSTANCE); for (NodeTopologyView view : views) { nodeSpecificViews.put(view.getRedisURI(), view.getPartitions()); } return nodeSpecificViews; } }
Set<RedisURI> result = new HashSet<>(); Map<String, RedisURI> knownUris = new HashMap<>(); for (NodeTopologyView view : views) { knownUris.put(view.getNodeId(), view.getRedisURI()); } for (NodeTopologyView view : views) { for (RedisClusterNode redisClusterNode : view.getPartitions()) { if (knownUris.containsKey(redisClusterNode.getNodeId())) { result.add(knownUris.get(redisClusterNode.getNodeId())); } else { result.add(redisClusterNode.getUri()); } } } return result;
262
186
448
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/topology/Requests.java
Requests
mergeWith
class Requests { private final Map<RedisURI, TimedAsyncCommand<String, String, String>> rawViews; protected Requests() { rawViews = new TreeMap<>(TopologyComparators.RedisURIComparator.INSTANCE); } private Requests(Map<RedisURI, TimedAsyncCommand<String, String, String>> rawViews) { this.rawViews = rawViews; } protected void addRequest(RedisURI redisURI, TimedAsyncCommand<String, String, String> command) { rawViews.put(redisURI, command); } /** * Returns a marker future that completes when all of the futures in this {@link Requests} complete. The marker never fails * exceptionally but signals completion only. * * @return */ public CompletableFuture<Void> allCompleted() { return CompletableFuture.allOf(rawViews.values().stream().map(it -> it.exceptionally(throwable -> "ignore")) .toArray(CompletableFuture[]::new)); } protected Set<RedisURI> nodes() { return rawViews.keySet(); } protected TimedAsyncCommand<String, String, String> getRequest(RedisURI redisURI) { return rawViews.get(redisURI); } protected Requests mergeWith(Requests requests) {<FILL_FUNCTION_BODY>} }
Map<RedisURI, TimedAsyncCommand<String, String, String>> result = new TreeMap<>( TopologyComparators.RedisURIComparator.INSTANCE); result.putAll(this.rawViews); result.putAll(requests.rawViews); return new Requests(result);
375
85
460
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/topology/TimedAsyncCommand.java
TimedAsyncCommand
duration
class TimedAsyncCommand<K, V, T> extends AsyncCommand<K, V, T> { long encodedAtNs = -1; long completedAtNs = -1; public TimedAsyncCommand(RedisCommand<K, V, T> command) { super(command); } @Override public void encode(ByteBuf buf) { completedAtNs = -1; encodedAtNs = -1; super.encode(buf); encodedAtNs = System.nanoTime(); } @Override public void complete() { completedAtNs = System.nanoTime(); super.complete(); } public long duration() {<FILL_FUNCTION_BODY>} }
if (completedAtNs == -1 || encodedAtNs == -1) { return -1; } return completedAtNs - encodedAtNs;
198
47
245
<methods>public void <init>(RedisCommand<K,V,T>) ,public boolean await(long, java.util.concurrent.TimeUnit) ,public boolean cancel(boolean) ,public void cancel() ,public void complete() ,public boolean completeExceptionally(java.lang.Throwable) ,public void encode(ByteBuf) ,public boolean equals(java.lang.Object) ,public CommandArgs<K,V> getArgs() ,public RedisCommand<K,V,T> getDelegate() ,public java.lang.String getError() ,public CommandOutput<K,V,T> getOutput() ,public io.lettuce.core.protocol.ProtocolKeyword getType() ,public int hashCode() ,public void onComplete(Consumer<? super T>) ,public void onComplete(BiConsumer<? super T,java.lang.Throwable>) ,public void setOutput(CommandOutput<K,V,T>) ,public java.lang.String toString() <variables>private static final AtomicIntegerFieldUpdater<AsyncCommand#RAW> COUNT_UPDATER,private final non-sealed RedisCommand<K,V,T> command,private volatile int count
redis_lettuce
lettuce/src/main/java/io/lettuce/core/cluster/topology/TopologyComparators.java
PredefinedRedisClusterNodeComparator
compare
class PredefinedRedisClusterNodeComparator implements Comparator<RedisClusterNode> { private final List<RedisURI> fixedOrder; public PredefinedRedisClusterNodeComparator(List<RedisURI> fixedOrder) { this.fixedOrder = fixedOrder; } @Override public int compare(RedisClusterNode o1, RedisClusterNode o2) { int index1 = fixedOrder.indexOf(o1.getUri()); int index2 = fixedOrder.indexOf(o2.getUri()); return Integer.compare(index1, index2); } } /** * Compare {@link RedisClusterNodeSnapshot} based on their latency. Lowest comes first. Objects of type * {@link RedisClusterNode} cannot be compared and yield to a result of {@literal 0}. */ enum LatencyComparator implements Comparator<RedisClusterNode> { INSTANCE; @Override public int compare(RedisClusterNode o1, RedisClusterNode o2) { if (o1 instanceof RedisClusterNodeSnapshot && o2 instanceof RedisClusterNodeSnapshot) { RedisClusterNodeSnapshot w1 = (RedisClusterNodeSnapshot) o1; RedisClusterNodeSnapshot w2 = (RedisClusterNodeSnapshot) o2; if (w1.getLatencyNs() != null && w2.getLatencyNs() != null) { return w1.getLatencyNs().compareTo(w2.getLatencyNs()); } if (w1.getLatencyNs() != null && w2.getLatencyNs() == null) { return -1; } if (w1.getLatencyNs() == null && w2.getLatencyNs() != null) { return 1; } } return 0; } } /** * Compare {@link RedisClusterNodeSnapshot} based on their client count. Lowest comes first. Objects of type * {@link RedisClusterNode} cannot be compared and yield to a result of {@literal 0}. */ enum ClientCountComparator implements Comparator<RedisClusterNode> { INSTANCE; @Override public int compare(RedisClusterNode o1, RedisClusterNode o2) {<FILL_FUNCTION_BODY>
if (o1 instanceof RedisClusterNodeSnapshot && o2 instanceof RedisClusterNodeSnapshot) { RedisClusterNodeSnapshot w1 = (RedisClusterNodeSnapshot) o1; RedisClusterNodeSnapshot w2 = (RedisClusterNodeSnapshot) o2; if (w1.getConnectedClients() != null && w2.getConnectedClients() != null) { return w1.getConnectedClients().compareTo(w2.getConnectedClients()); } if (w1.getConnectedClients() == null && w2.getConnectedClients() != null) { return 1; } if (w1.getConnectedClients() != null && w2.getConnectedClients() == null) { return -1; } } return 0;
609
224
833
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/codec/Base16.java
Base16
digest
class Base16 { private static final char[] upper = "0123456789ABCDEF".toCharArray(); private static final char[] lower = "0123456789abcdef".toCharArray(); private static final byte[] decode = new byte[128]; static { for (int i = 0; i < 10; i++) { decode['0' + i] = (byte) i; decode['A' + i] = (byte) (10 + i); decode['a' + i] = (byte) (10 + i); } } /** * Utility constructor. */ private Base16() { } /** * Encode bytes to base16 chars. * * @param src Bytes to encode. * @param upper Use upper or lowercase chars. * * @return Encoded chars. */ public static char[] encode(byte[] src, boolean upper) { char[] table = upper ? Base16.upper : Base16.lower; char[] dst = new char[src.length * 2]; for (int si = 0, di = 0; si < src.length; si++) { byte b = src[si]; dst[di++] = table[(b & 0xf0) >>> 4]; dst[di++] = table[(b & 0x0f)]; } return dst; } /** * Create SHA1 digest from Lua script. * * @param script the script * @return the Base16 encoded SHA1 value */ public static String digest(byte[] script) { return digest(ByteBuffer.wrap(script)); } /** * Create SHA1 digest from Lua script. * * @param script the script * @return the Base16 encoded SHA1 value */ public static String digest(ByteBuffer script) {<FILL_FUNCTION_BODY>} }
try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(script); return new String(Base16.encode(md.digest(), false)); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("JVM does not support SHA1"); }
538
84
622
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/codec/ByteArrayCodec.java
ByteArrayCodec
estimateSize
class ByteArrayCodec implements RedisCodec<byte[], byte[]>, ToByteBufEncoder<byte[], byte[]> { public static final ByteArrayCodec INSTANCE = new ByteArrayCodec(); private static final byte[] EMPTY = new byte[0]; @Override public void encodeKey(byte[] key, ByteBuf target) { if (key != null) { target.writeBytes(key); } } @Override public void encodeValue(byte[] value, ByteBuf target) { encodeKey(value, target); } @Override public int estimateSize(Object keyOrValue) {<FILL_FUNCTION_BODY>} @Override public boolean isEstimateExact() { return true; } @Override public byte[] decodeKey(ByteBuffer bytes) { return getBytes(bytes); } @Override public byte[] decodeValue(ByteBuffer bytes) { return getBytes(bytes); } @Override public ByteBuffer encodeKey(byte[] key) { if (key == null) { return ByteBuffer.wrap(EMPTY); } return ByteBuffer.wrap(key); } @Override public ByteBuffer encodeValue(byte[] value) { return encodeKey(value); } private static byte[] getBytes(ByteBuffer buffer) { int remaining = buffer.remaining(); if (remaining == 0) { return EMPTY; } byte[] b = new byte[remaining]; buffer.get(b); return b; } }
if (keyOrValue == null) { return 0; } return ((byte[]) keyOrValue).length;
428
38
466
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/codec/ByteBufferInputStream.java
ByteBufferInputStream
read
class ByteBufferInputStream extends InputStream { private final ByteBuffer buffer; public ByteBufferInputStream(ByteBuffer b) { this.buffer = b; } @Override public int available() throws IOException { return buffer.remaining(); } @Override public int read() throws IOException {<FILL_FUNCTION_BODY>} }
if (buffer.remaining() > 0) { return (buffer.get() & 0xFF); } return -1;
96
39
135
<methods>public void <init>() ,public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public static java.io.InputStream nullInputStream() ,public abstract int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public byte[] readAllBytes() throws java.io.IOException,public byte[] readNBytes(int) throws java.io.IOException,public int readNBytes(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException,public void skipNBytes(long) throws java.io.IOException,public long transferTo(java.io.OutputStream) throws java.io.IOException<variables>private static final int DEFAULT_BUFFER_SIZE,private static final int MAX_BUFFER_SIZE,private static final int MAX_SKIP_BUFFER_SIZE
redis_lettuce
lettuce/src/main/java/io/lettuce/core/codec/CipherCodec.java
KeyDescriptor
getName
class KeyDescriptor { private static final KeyDescriptor UNNAMED = new KeyDescriptor("".getBytes(StandardCharsets.US_ASCII), 0); private final byte[] name; private final int version; private KeyDescriptor(byte[] name, int version) { for (byte b : name) { if (b == '+' || b == '$') { throw new IllegalArgumentException( String.format("Key name %s must not contain plus (+) or dollar ($) characters", new String(name))); } } this.name = name; this.version = version; } /** * Returns the default {@link KeyDescriptor} that has no specified name. * * @return the default {@link KeyDescriptor}. */ public static KeyDescriptor unnamed() { return UNNAMED; } /** * Create a named {@link KeyDescriptor} without version. Version defaults to zero. * * @param name the key name. Must not contain plus or dollar character. * @return the {@link KeyDescriptor} for {@code name}. */ public static KeyDescriptor create(String name) { return create(name, 0); } /** * Create a named and versioned {@link KeyDescriptor}. * * @param name the key name. Must not contain plus or dollar character. * @param version the key version. * @return the {@link KeyDescriptor} for {@code name}. */ public static KeyDescriptor create(String name, int version) { return create(name, version, Charset.defaultCharset()); } /** * Create a named and versioned {@link KeyDescriptor} using {@link Charset} to encode {@code name} to its binary * representation. * * @param name the key name. Must not contain plus or dollar character. * @param version the key version. * @param charset must not be {@code null}. * @return the {@link KeyDescriptor} for {@code name}. */ public static KeyDescriptor create(String name, int version, Charset charset) { LettuceAssert.notNull(name, "Name must not be null"); LettuceAssert.notNull(charset, "Charset must not be null"); return new KeyDescriptor(name.getBytes(charset), version); } static KeyDescriptor from(ByteBuffer bytes) { int end = -1; int version = -1; if (bytes.get() != '$') { throw new IllegalArgumentException("Cannot extract KeyDescriptor. Malformed message header."); } int startPosition = bytes.position(); for (int i = 0; i < bytes.remaining(); i++) { if (bytes.get(bytes.position() + i) == '$') { end = (bytes.position() - startPosition) + i; break; } if (bytes.get(bytes.position() + i) == '+') { version = (bytes.position() - startPosition) + i; } } if (end == -1 || version == -1) { throw new IllegalArgumentException("Cannot extract KeyDescriptor"); } byte[] name = new byte[version]; bytes.get(name); bytes.get(); byte[] versionBytes = new byte[end - version - 1]; bytes.get(versionBytes); bytes.get(); // skip last char return new KeyDescriptor(name, Integer.parseInt(new String(versionBytes))); } public int getVersion() { return version; } /** * Returns the key {@code name} by decoding name bytes using the {@link Charset#defaultCharset() default charset}. * * @return the key name. */ public String getName() { return getName(Charset.defaultCharset()); } /** * Returns the key {@code name} by decoding name bytes using the given {@link Charset}. * * @param charset the {@link Charset} to use to decode the key name, must not be {@code null}. * @return the key name. */ public String getName(Charset charset) {<FILL_FUNCTION_BODY>} void writeTo(ByteBuf target) { target.writeByte('$').writeBytes(this.name).writeByte('+').writeBytes(Integer.toString(this.version).getBytes()) .writeByte('$'); } void writeTo(ByteBuffer target) { target.put((byte) '$').put(this.name).put((byte) '+').put(Integer.toString(this.version).getBytes()) .put((byte) '$'); } }
LettuceAssert.notNull(charset, "Charset must not be null"); return new String(name, charset);
1,199
35
1,234
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/codec/CompressionCodec.java
CompressionCodec
valueCompressor
class CompressionCodec { private CompressionCodec() { } /** * A {@link RedisCodec} that compresses values from a delegating {@link RedisCodec}. * * @param delegate codec used for key-value encoding/decoding, must not be {@code null}. * @param compressionType the compression type, must not be {@code null}. * @param <K> Key type. * @param <V> Value type. * @return Value-compressing codec. */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static <K, V> RedisCodec<K, V> valueCompressor(RedisCodec<K, V> delegate, CompressionType compressionType) {<FILL_FUNCTION_BODY>} private static class CompressingValueCodecWrapper implements RedisCodec<Object, Object> { private RedisCodec<Object, Object> delegate; private CompressionType compressionType; public CompressingValueCodecWrapper(RedisCodec<Object, Object> delegate, CompressionType compressionType) { this.delegate = delegate; this.compressionType = compressionType; } @Override public Object decodeKey(ByteBuffer bytes) { return delegate.decodeKey(bytes); } @Override public Object decodeValue(ByteBuffer bytes) { try { return delegate.decodeValue(decompress(bytes)); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public ByteBuffer encodeKey(Object key) { return delegate.encodeKey(key); } @Override public ByteBuffer encodeValue(Object value) { try { return compress(delegate.encodeValue(value)); } catch (IOException e) { throw new IllegalStateException(e); } } private ByteBuffer compress(ByteBuffer source) throws IOException { if (source.remaining() == 0) { return source; } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(source.remaining() / 2); OutputStream compressor = null; try { try (ByteBufferInputStream sourceStream = new ByteBufferInputStream(source)) { if (compressionType == CompressionType.GZIP) { compressor = new GZIPOutputStream(outputStream); } if (compressionType == CompressionType.DEFLATE) { compressor = new DeflaterOutputStream(outputStream); } copy(sourceStream, compressor); } finally { if (compressor != null) { compressor.close(); } } return ByteBuffer.wrap(outputStream.toByteArray()); } finally { outputStream.close(); } } private ByteBuffer decompress(ByteBuffer source) throws IOException { if (source.remaining() == 0) { return source; } InputStream decompressor = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(source.remaining() * 2); try { try (ByteBufferInputStream sourceStream = new ByteBufferInputStream(source);) { if (compressionType == CompressionType.GZIP) { decompressor = new GZIPInputStream(sourceStream); } if (compressionType == CompressionType.DEFLATE) { decompressor = new InflaterInputStream(sourceStream); } copy(decompressor, outputStream); } finally { if (decompressor != null) { decompressor.close(); } } return ByteBuffer.wrap(outputStream.toByteArray()); } finally { outputStream.close(); } } } /** * Copies all bytes from the input stream to the output stream. Does not close or flush either stream. * * @param from the input stream to read from * @param to the output stream to write to * @return the number of bytes copied * @throws IOException if an I/O error occurs */ private static long copy(InputStream from, OutputStream to) throws IOException { LettuceAssert.notNull(from, "From must not be null"); LettuceAssert.notNull(to, "From must not be null"); byte[] buf = new byte[4096]; long total = 0; while (true) { int r = from.read(buf); if (r == -1) { break; } to.write(buf, 0, r); total += r; } return total; } public enum CompressionType { GZIP, DEFLATE; } }
LettuceAssert.notNull(delegate, "RedisCodec must not be null"); LettuceAssert.notNull(compressionType, "CompressionType must not be null"); return (RedisCodec) new CompressingValueCodecWrapper((RedisCodec) delegate, compressionType);
1,220
78
1,298
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/codec/StringCodec.java
StringCodec
encode
class StringCodec implements RedisCodec<String, String>, ToByteBufEncoder<String, String> { public static final StringCodec UTF8 = new StringCodec(StandardCharsets.UTF_8); public static final StringCodec ASCII = new StringCodec(StandardCharsets.US_ASCII); private static final byte[] EMPTY = new byte[0]; private final Charset charset; private final float averageBytesPerChar; private final float maxBytesPerChar; private final boolean ascii; private final boolean utf8; /** * Creates a new {@link StringCodec} with the default {@link Charset#defaultCharset() charset}. The default is determined * from the {@code file.encoding} system property. */ public StringCodec() { this(Charset.defaultCharset()); } /** * Creates a new {@link StringCodec} for the given {@link Charset} that encodes and decodes keys and values. * * @param charset must not be {@code null}. */ public StringCodec(Charset charset) { LettuceAssert.notNull(charset, "Charset must not be null"); this.charset = charset; CharsetEncoder encoder = CharsetUtil.encoder(charset); this.averageBytesPerChar = encoder.averageBytesPerChar(); this.maxBytesPerChar = encoder.maxBytesPerChar(); if (charset.name().equals("UTF-8")) { utf8 = true; ascii = false; } else if (charset.name().contains("ASCII")) { utf8 = false; ascii = true; } else { ascii = false; utf8 = false; } } @Override public void encodeKey(String key, ByteBuf target) { encode(key, target); } @Override public int estimateSize(Object keyOrValue) { if (keyOrValue instanceof String) { return sizeOf((String) keyOrValue, true); } return 0; } @Override public boolean isEstimateExact() { if (ascii) { return true; } return ToByteBufEncoder.super.isEstimateExact(); } @Override public void encodeValue(String value, ByteBuf target) { encode(value, target); } @Override public String decodeKey(ByteBuffer bytes) { return Unpooled.wrappedBuffer(bytes).toString(charset); } @Override public String decodeValue(ByteBuffer bytes) { return Unpooled.wrappedBuffer(bytes).toString(charset); } @Override public ByteBuffer encodeKey(String key) { return encodeAndAllocateBuffer(key); } @Override public ByteBuffer encodeValue(String value) { return encodeAndAllocateBuffer(value); } /** * Compatibility implementation. * * @param key * @return */ private ByteBuffer encodeAndAllocateBuffer(String key) { if (key == null) { return ByteBuffer.wrap(EMPTY); } ByteBuffer buffer = ByteBuffer.allocate(sizeOf(key, false)); ByteBuf byteBuf = Unpooled.wrappedBuffer(buffer); byteBuf.clear(); encode(key, byteBuf); buffer.limit(byteBuf.writerIndex()); return buffer; } public void encode(String str, ByteBuf target) {<FILL_FUNCTION_BODY>} /** * Calculate either the maximum number of bytes a string may occupy in a given character set or the average number of bytes * it may hold. */ int sizeOf(String value, boolean estimate) { if (utf8) { return ByteBufUtil.utf8MaxBytes(value); } if (ascii) { return value.length(); } if (estimate) { return (int) averageBytesPerChar * value.length(); } return (int) maxBytesPerChar * value.length(); } }
if (str == null) { return; } if (utf8) { ByteBufUtil.writeUtf8(target, str); return; } if (ascii) { ByteBufUtil.writeAscii(target, str); return; } CharsetEncoder encoder = CharsetUtil.encoder(charset); int length = sizeOf(str, false); target.ensureWritable(length); try { ByteBuffer dstBuf = target.nioBuffer(0, length); int pos = dstBuf.position(); CoderResult cr = encoder.encode(CharBuffer.wrap(str), dstBuf, true); if (!cr.isUnderflow()) { cr.throwException(); } cr = encoder.flush(dstBuf); if (!cr.isUnderflow()) { cr.throwException(); } target.writerIndex(target.writerIndex() + dstBuf.position() - pos); } catch (CharacterCodingException x) { throw new IllegalStateException(x); }
1,096
285
1,381
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/AsyncExecutableCommand.java
AsyncExecutableCommand
dispatchCommand
class AsyncExecutableCommand implements ExecutableCommand { private final CommandMethod commandMethod; private final CommandFactory commandFactory; private final StatefulConnection<Object, Object> connection; AsyncExecutableCommand(CommandMethod commandMethod, CommandFactory commandFactory, StatefulConnection<Object, Object> connection) { this.commandMethod = commandMethod; this.commandFactory = commandFactory; this.connection = connection; } @Override public Object execute(Object[] parameters) throws ExecutionException, InterruptedException { RedisCommand<Object, Object, Object> command = commandFactory.createCommand(parameters); return dispatchCommand(parameters, command); } protected Object dispatchCommand(Object[] arguments, RedisCommand<Object, Object, Object> command) throws InterruptedException, java.util.concurrent.ExecutionException {<FILL_FUNCTION_BODY>} @Override public CommandMethod getCommandMethod() { return commandMethod; } }
AsyncCommand<Object, Object, Object> asyncCommand = new AsyncCommand<>(command); if (commandMethod.isFutureExecution()) { RedisCommand<Object, Object, Object> dispatched = connection.dispatch(asyncCommand); if (dispatched instanceof AsyncCommand) { return dispatched; } return asyncCommand; } connection.dispatch(asyncCommand); Duration timeout = connection.getTimeout(); if (commandMethod.getParameters() instanceof ExecutionSpecificParameters) { ExecutionSpecificParameters executionSpecificParameters = (ExecutionSpecificParameters) commandMethod .getParameters(); if (executionSpecificParameters.hasTimeoutIndex()) { Timeout timeoutArg = (Timeout) arguments[executionSpecificParameters.getTimeoutIndex()]; if (timeoutArg != null) { timeout = timeoutArg.getTimeout(); } } } Futures.await(timeout, asyncCommand); return asyncCommand.get();
252
255
507
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/AsyncExecutableCommandLookupStrategy.java
AsyncExecutableCommandLookupStrategy
resolveCommandMethod
class AsyncExecutableCommandLookupStrategy extends ExecutableCommandLookupStrategySupport { private final StatefulConnection<Object, Object> connection; public AsyncExecutableCommandLookupStrategy(List<RedisCodec<?, ?>> redisCodecs, CommandOutputFactoryResolver commandOutputFactoryResolver, CommandMethodVerifier commandMethodVerifier, StatefulConnection<Object, Object> connection) { super(redisCodecs, commandOutputFactoryResolver, commandMethodVerifier); this.connection = connection; } @Override public ExecutableCommand resolveCommandMethod(CommandMethod method, RedisCommandsMetadata metadata) {<FILL_FUNCTION_BODY>} }
LettuceAssert.isTrue(!method.isReactiveExecution(), () -> String.format("Command method %s not supported by this command lookup strategy", method)); CommandFactory commandFactory = super.resolveCommandFactory(method, metadata); return new AsyncExecutableCommand(method, commandFactory, connection);
168
80
248
<methods>public void <init>(List<RedisCodec<?,?>>, io.lettuce.core.dynamic.output.CommandOutputFactoryResolver, io.lettuce.core.dynamic.CommandMethodVerifier) <variables>private final non-sealed io.lettuce.core.dynamic.CommandFactoryResolver commandFactoryResolver,private final non-sealed io.lettuce.core.dynamic.CommandMethodVerifier commandMethodVerifier,private final non-sealed io.lettuce.core.dynamic.output.CommandOutputFactoryResolver commandOutputFactoryResolver,private final non-sealed List<RedisCodec<?,?>> redisCodecs
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/BatchExecutableCommand.java
BatchExecutableCommand
synchronize
class BatchExecutableCommand implements ExecutableCommand { private final CommandMethod commandMethod; private final CommandFactory commandFactory; private final Batcher batcher; private final StatefulConnection<Object, Object> connection; private final ExecutionSpecificParameters parameters; private final boolean async; BatchExecutableCommand(CommandMethod commandMethod, CommandFactory commandFactory, Batcher batcher, StatefulConnection<Object, Object> connection) { this.commandMethod = commandMethod; this.commandFactory = commandFactory; this.batcher = batcher; this.parameters = (ExecutionSpecificParameters) commandMethod.getParameters(); this.async = commandMethod.isFutureExecution(); this.connection = connection; } @Override public Object execute(Object[] parameters) throws ExecutionException, InterruptedException { RedisCommand<Object, Object, Object> command = commandFactory.createCommand(parameters); CommandBatching batching = null; if (this.parameters.hasCommandBatchingIndex()) { batching = (CommandBatching) parameters[this.parameters.getCommandBatchingIndex()]; } AsyncCommand<Object, Object, Object> asyncCommand = new AsyncCommand<>(command); if (async) { batcher.batch(asyncCommand, batching); return asyncCommand; } BatchTasks batchTasks = batcher.batch(asyncCommand, batching); return synchronize(batchTasks, connection); } protected static Object synchronize(BatchTasks batchTasks, StatefulConnection<Object, Object> connection) {<FILL_FUNCTION_BODY>} @Override public CommandMethod getCommandMethod() { return commandMethod; } }
if (batchTasks == BatchTasks.EMPTY) { return null; } Duration timeout = connection.getTimeout(); BatchException exception = null; List<RedisCommand<?, ?, ?>> failures = null; for (RedisCommand<?, ?, ?> batchTask : batchTasks) { try { Futures.await(timeout, (RedisFuture) batchTask); } catch (Exception e) { if (exception == null) { failures = new ArrayList<>(); exception = new BatchException(failures); } failures.add(batchTask); exception.addSuppressed(e); } } if (exception != null) { throw exception; } return null;
439
202
641
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/BatchExecutableCommandLookupStrategy.java
BatchExecutableCommandLookupStrategy
resolveCommandMethod
class BatchExecutableCommandLookupStrategy extends ExecutableCommandLookupStrategySupport { private final Set<Class<?>> SYNCHRONOUS_RETURN_TYPES = new HashSet<Class<?>>(Arrays.asList(Void.class, Void.TYPE)); private final Batcher batcher; private final StatefulConnection<Object, Object> connection; public BatchExecutableCommandLookupStrategy(List<RedisCodec<?, ?>> redisCodecs, CommandOutputFactoryResolver commandOutputFactoryResolver, CommandMethodVerifier commandMethodVerifier, Batcher batcher, StatefulConnection<Object, Object> connection) { super(redisCodecs, commandOutputFactoryResolver, commandMethodVerifier); this.batcher = batcher; this.connection = connection; } public static boolean supports(CommandMethod method) { return method.isBatchExecution() || isForceFlush(method); } private static boolean isForceFlush(CommandMethod method) { return method.getName().equals("flush") && method.getMethod().getDeclaringClass().equals(BatchExecutor.class); } @Override public ExecutableCommand resolveCommandMethod(CommandMethod method, RedisCommandsMetadata metadata) {<FILL_FUNCTION_BODY>} }
LettuceAssert.isTrue(!method.isReactiveExecution(), () -> String.format("Command method %s not supported by this command lookup strategy", method)); ExecutionSpecificParameters parameters = (ExecutionSpecificParameters) method.getParameters(); if (parameters.hasTimeoutIndex()) { throw new IllegalArgumentException( String.format("Timeout and batching is not supported, offending command method %s ", method)); } if (isForceFlush(method)) { return new ExecutableCommand() { @Override public Object execute(Object[] parameters) throws ExecutionException, InterruptedException { BatchExecutableCommand.synchronize(batcher.flush(), connection); return null; } @Override public CommandMethod getCommandMethod() { return method; } }; } if (method.isFutureExecution() || SYNCHRONOUS_RETURN_TYPES.contains(method.getReturnType().getRawClass())) { CommandFactory commandFactory = super.resolveCommandFactory(method, metadata); return new BatchExecutableCommand(method, commandFactory, batcher, connection); } throw new IllegalArgumentException( String.format("Batching command method %s must declare either a Future or void return type", method));
325
327
652
<methods>public void <init>(List<RedisCodec<?,?>>, io.lettuce.core.dynamic.output.CommandOutputFactoryResolver, io.lettuce.core.dynamic.CommandMethodVerifier) <variables>private final non-sealed io.lettuce.core.dynamic.CommandFactoryResolver commandFactoryResolver,private final non-sealed io.lettuce.core.dynamic.CommandMethodVerifier commandMethodVerifier,private final non-sealed io.lettuce.core.dynamic.output.CommandOutputFactoryResolver commandOutputFactoryResolver,private final non-sealed List<RedisCodec<?,?>> redisCodecs
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/CodecAwareMethodParametersAccessor.java
CodecAwareMethodParametersAccessor
isKey
class CodecAwareMethodParametersAccessor implements MethodParametersAccessor { private final MethodParametersAccessor delegate; private final TypeContext typeContext; public CodecAwareMethodParametersAccessor(MethodParametersAccessor delegate, RedisCodec<?, ?> redisCodec) { LettuceAssert.notNull(delegate, "MethodParametersAccessor must not be null"); LettuceAssert.notNull(redisCodec, "RedisCodec must not be null"); this.delegate = delegate; this.typeContext = new TypeContext(redisCodec); } public CodecAwareMethodParametersAccessor(MethodParametersAccessor delegate, TypeContext typeContext) { LettuceAssert.notNull(delegate, "MethodParametersAccessor must not be null"); LettuceAssert.notNull(typeContext, "TypeContext must not be null"); this.delegate = delegate; this.typeContext = typeContext; } @Override public int getParameterCount() { return delegate.getParameterCount(); } @Override public Object getBindableValue(int index) { return delegate.getBindableValue(index); } @Override public boolean isKey(int index) {<FILL_FUNCTION_BODY>} @Override public boolean isValue(int index) { if (delegate.isKey(index)) { return false; } if (delegate.isValue(index)) { return true; } Object bindableValue = getBindableValue(index); if (bindableValue != null && typeContext.valueType.getType().isAssignableFrom(bindableValue.getClass())) { return true; } return false; } @Override public Iterator<Object> iterator() { return delegate.iterator(); } @Override public int resolveParameterIndex(String name) { return delegate.resolveParameterIndex(name); } @Override public boolean isBindableNullValue(int index) { return delegate.isBindableNullValue(index); } /** * Cacheable type context for a {@link RedisCodec}. */ public static class TypeContext { final TypeInformation<?> keyType; final TypeInformation<?> valueType; @SuppressWarnings("rawtypes") public TypeContext(RedisCodec<?, ?> redisCodec) { LettuceAssert.notNull(redisCodec, "RedisCodec must not be null"); ClassTypeInformation<? extends RedisCodec> typeInformation = ClassTypeInformation.from(redisCodec.getClass()); this.keyType = typeInformation.getTypeArgument(RedisCodec.class, 0); this.valueType = typeInformation.getTypeArgument(RedisCodec.class, 1); } } }
if (delegate.isValue(index)) { return false; } if (delegate.isKey(index)) { return true; } Object bindableValue = getBindableValue(index); if (bindableValue != null && typeContext.keyType.getType().isAssignableFrom(bindableValue.getClass())) { return true; } return false;
758
113
871
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/CommandSegmentCommandFactory.java
CommandSegmentCommandFactory
createCommand
class CommandSegmentCommandFactory implements CommandFactory { private final CommandMethod commandMethod; private final CommandSegments segments; private final CommandOutputFactoryResolver outputResolver; private final RedisCodec<Object, Object> redisCodec; private final ParameterBinder parameterBinder = new ParameterBinder(); private final CommandOutputFactory outputFactory; private final TypeContext typeContext; public CommandSegmentCommandFactory(CommandSegments commandSegments, CommandMethod commandMethod, RedisCodec<?, ?> redisCodec, CommandOutputFactoryResolver outputResolver) { this.segments = commandSegments; this.commandMethod = commandMethod; this.redisCodec = (RedisCodec) redisCodec; this.outputResolver = outputResolver; this.typeContext = new TypeContext(redisCodec); OutputSelector outputSelector = new OutputSelector(commandMethod.getActualReturnType(), redisCodec); CommandOutputFactory factory = resolveCommandOutputFactory(outputSelector); if (factory == null) { throw new IllegalArgumentException(String.format("Cannot resolve CommandOutput for result type %s on method %s", commandMethod.getActualReturnType(), commandMethod.getMethod())); } if (commandMethod.getParameters() instanceof ExecutionSpecificParameters) { ExecutionSpecificParameters executionAwareParameters = (ExecutionSpecificParameters) commandMethod.getParameters(); if (commandMethod.isFutureExecution() && executionAwareParameters.hasTimeoutIndex()) { throw new CommandCreationException(commandMethod, "Asynchronous command methods do not support Timeout parameters"); } } this.outputFactory = factory; } protected CommandOutputFactoryResolver getOutputResolver() { return outputResolver; } protected CommandOutputFactory resolveCommandOutputFactory(OutputSelector outputSelector) { return outputResolver.resolveCommandOutput(outputSelector); } @Override public RedisCommand<Object, Object, Object> createCommand(Object[] parameters) {<FILL_FUNCTION_BODY>} }
MethodParametersAccessor parametersAccessor = new CodecAwareMethodParametersAccessor( new DefaultMethodParametersAccessor(commandMethod.getParameters(), parameters), typeContext); CommandArgs<Object, Object> args = new CommandArgs<>(redisCodec); CommandOutput<Object, Object, ?> output = outputFactory.create(redisCodec); Command<Object, Object, ?> command = new Command<>(this.segments.getCommandType(), output, args); parameterBinder.bind(args, redisCodec, segments, parametersAccessor); return (Command) command;
516
150
666
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/ConversionService.java
ConversionService
findConverter
class ConversionService { private Map<ConvertiblePair, Function<?, ?>> converterMap = new HashMap<>(10); /** * Register a converter {@link Function}. * * @param converter the converter. */ @SuppressWarnings("rawtypes") public void addConverter(Function<?, ?> converter) { LettuceAssert.notNull(converter, "Converter must not be null"); ClassTypeInformation<? extends Function> classTypeInformation = ClassTypeInformation.from(converter.getClass()); TypeInformation<?> typeInformation = classTypeInformation.getSuperTypeInformation(Function.class); List<TypeInformation<?>> typeArguments = typeInformation.getTypeArguments(); ConvertiblePair pair = new ConvertiblePair(typeArguments.get(0).getType(), typeArguments.get(1).getType()); converterMap.put(pair, converter); } @SuppressWarnings("unchecked") public <S, T> T convert(S source, Class<T> targetType) { LettuceAssert.notNull(source, "Source must not be null"); return (T) getConverter(source.getClass(), targetType).apply(source); } public <S, T> boolean canConvert(Class<S> sourceType, Class<T> targetType) { return findConverter(sourceType, targetType).isPresent(); } @SuppressWarnings("unchecked") Function<Object, Object> getConverter(Class<?> source, Class<?> target) { return findConverter(source, target).orElseThrow(() -> new IllegalArgumentException( String.format("No converter found for %s to %s conversion", source.getName(), target.getName()))); } private Optional<Function<Object, Object>> findConverter(Class<?> source, Class<?> target) {<FILL_FUNCTION_BODY>} /** * Holder for a source-to-target class pair. */ final class ConvertiblePair { private final Class<?> sourceType; private final Class<?> targetType; /** * Create a new source-to-target pair. * * @param sourceType the source type * @param targetType the target type */ public ConvertiblePair(Class<?> sourceType, Class<?> targetType) { LettuceAssert.notNull(sourceType, "Source type must not be null"); LettuceAssert.notNull(targetType, "Target type must not be null"); this.sourceType = sourceType; this.targetType = targetType; } public Class<?> getSourceType() { return this.sourceType; } public Class<?> getTargetType() { return this.targetType; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || other.getClass() != ConvertiblePair.class) { return false; } ConvertiblePair otherPair = (ConvertiblePair) other; return (this.sourceType == otherPair.sourceType && this.targetType == otherPair.targetType); } @Override public int hashCode() { return (this.sourceType.hashCode() * 31 + this.targetType.hashCode()); } @Override public String toString() { return (this.sourceType.getName() + " -> " + this.targetType.getName()); } } }
LettuceAssert.notNull(source, "Source type must not be null"); LettuceAssert.notNull(target, "Target type must not be null"); for (ConvertiblePair pair : converterMap.keySet()) { if (pair.getSourceType().isAssignableFrom(source) && target.isAssignableFrom(pair.getTargetType())) { return Optional.of((Function) converterMap.get(pair)); } } return Optional.empty();
905
124
1,029
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/ConvertingCommand.java
ConvertingCommand
execute
class ConvertingCommand implements ExecutableCommand { private final ConversionService conversionService; private final ExecutableCommand delegate; public ConvertingCommand(ConversionService conversionService, ExecutableCommand delegate) { this.conversionService = conversionService; this.delegate = delegate; } @Override public Object execute(Object[] parameters) throws ExecutionException, InterruptedException {<FILL_FUNCTION_BODY>} @Override public CommandMethod getCommandMethod() { return delegate.getCommandMethod(); } }
Object result = delegate.execute(parameters); if (delegate.getCommandMethod().getReturnType().isAssignableFrom(result.getClass())) { return result; } return conversionService.convert(result, delegate.getCommandMethod().getReturnType().getRawClass());
141
77
218
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/DeclaredCommandMethod.java
DeclaredCommandMethod
equals
class DeclaredCommandMethod implements CommandMethod { private final Method method; private final ResolvableType returnType; private final List<Class<?>> arguments = new ArrayList<>(); private final ExecutionSpecificParameters parameters; private final ResolvableType actualReturnType; private final boolean futureExecution; private final boolean reactiveExecution; /** * Create a new {@link DeclaredCommandMethod} given a {@link Method}. * * @param method must not be null. */ private DeclaredCommandMethod(Method method) { this(method, new ExecutionSpecificParameters(method)); } /** * Create a new {@link DeclaredCommandMethod} given a {@link Method} and {@link Parameters}. * * @param method must not be null. * @param parameters must not be null. */ private DeclaredCommandMethod(Method method, ExecutionSpecificParameters parameters) { LettuceAssert.notNull(method, "Method must not be null"); LettuceAssert.notNull(parameters, "Parameters must not be null"); this.method = method; this.returnType = ResolvableType.forMethodReturnType(method); this.parameters = parameters; this.futureExecution = Future.class.isAssignableFrom(getReturnType().getRawClass()); this.reactiveExecution = ReactiveTypes.supports(getReturnType().getRawClass()); Collections.addAll(arguments, method.getParameterTypes()); ResolvableType actualReturnType = this.returnType; while (Future.class.isAssignableFrom(actualReturnType.getRawClass())) { ResolvableType[] generics = actualReturnType.getGenerics(); if (generics.length != 1) { break; } actualReturnType = generics[0]; } this.actualReturnType = actualReturnType; } /** * Create a new {@link DeclaredCommandMethod} given a {@link Method}. * * @param method must not be null. */ public static CommandMethod create(Method method) { return new DeclaredCommandMethod(method); } /** * @return the method {@link Parameters}. */ @Override public Parameters<? extends Parameter> getParameters() { return parameters; } /** * @return the {@link Method}. */ @Override public Method getMethod() { return method; } /** * @return declared {@link Method} return {@link TypeInformation}. */ @Override public ResolvableType getReturnType() { return returnType; } /** * @return the actual {@link Method} return {@link TypeInformation} after unwrapping. */ @Override public ResolvableType getActualReturnType() { return actualReturnType; } /** * Lookup a method annotation. * * @param annotationClass the annotation class. * @return the annotation object or {@code null} if not found. */ @Override public <A extends Annotation> A getAnnotation(Class<A> annotationClass) { return method.getAnnotation(annotationClass); } /** * @param annotationClass the annotation class. * @return {@code true} if the method is annotated with {@code annotationClass}. */ @Override public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { return method.getAnnotation(annotationClass) != null; } /** * @return the method name. */ @Override public String getName() { return method.getName(); } /** * @return {@code true} if the method uses asynchronous execution declaring {@link Future} as result type. */ @Override public boolean isFutureExecution() { return futureExecution; } /** * @return {@code true} if the method uses reactive execution declaring {@link Publisher} as result type. */ @Override public boolean isReactiveExecution() { return reactiveExecution; } /** * @return {@code true} if the method defines a {@link io.lettuce.core.dynamic.batch.CommandBatching} argument. */ @Override public boolean isBatchExecution() { return parameters.hasCommandBatchingIndex() || (method.getName().equals("flush") && method.getDeclaringClass().equals(BatchExecutor.class)); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = method != null ? method.hashCode() : 0; result = 31 * result + (returnType != null ? returnType.hashCode() : 0); result = 31 * result + (arguments != null ? arguments.hashCode() : 0); return result; } @Override public String toString() { return method.toGenericString(); } }
if (this == o) return true; if (!(o instanceof DeclaredCommandMethod)) return false; DeclaredCommandMethod that = (DeclaredCommandMethod) o; if (method != null ? !method.equals(that.method) : that.method != null) return false; if (returnType != null ? !returnType.equals(that.returnType) : that.returnType != null) return false; return arguments != null ? arguments.equals(that.arguments) : that.arguments == null;
1,295
141
1,436
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/DefaultCommandMethodVerifier.java
DefaultCommandMethodVerifier
validate
class DefaultCommandMethodVerifier implements CommandMethodVerifier { /** * Default maximum property distance: 2 */ public static final int DEFAULT_MAX_DISTANCE = 2; private List<CommandDetail> commandDetails; /** * Create a new {@link DefaultCommandMethodVerifier} given a {@link List} of {@link CommandDetail} * * @param commandDetails must not be {@code null}. */ public DefaultCommandMethodVerifier(List<CommandDetail> commandDetails) { LettuceAssert.notNull(commandDetails, "Command details must not be null"); this.commandDetails = LettuceLists.newList(commandDetails); } /** * Verify a {@link CommandMethod} with its {@link CommandSegments}. This method verifies that the command exists and that * the required number of arguments is declared. * * @param commandSegments * @param commandMethod */ @Override public void validate(CommandSegments commandSegments, CommandMethod commandMethod) throws CommandMethodSyntaxException {<FILL_FUNCTION_BODY>} private void validateParameters(CommandDetail commandDetail, CommandSegments commandSegments, CommandMethod commandMethod) { List<? extends Parameter> bindableParameters = commandMethod.getParameters().getBindableParameters(); int availableParameterCount = calculateAvailableParameterCount(commandSegments, bindableParameters); // exact parameter count if (commandDetail.getArity() - 1 == availableParameterCount) { return; } // more or same parameter cound for dynamic arg count commands if (0 > commandDetail.getArity() && availableParameterCount >= -(commandDetail.getArity() + 1)) { return; } for (Parameter bindableParameter : bindableParameters) { // Can't verify collection-like arguments as they may contain multiple elements. if (bindableParameter.getTypeInformation().isCollectionLike()) { return; } } String message; if (commandDetail.getArity() == 1) { message = String.format("Command %s accepts no parameters.", commandDetail.getName().toUpperCase()); } else if (commandDetail.getArity() < -1) { message = String.format("Command %s requires at least %d parameters but method declares %d parameter(s).", commandDetail.getName().toUpperCase(), Math.abs(commandDetail.getArity()) - 1, availableParameterCount); } else { message = String.format("Command %s accepts %d parameters but method declares %d parameter(s).", commandDetail.getName().toUpperCase(), commandDetail.getArity() - 1, availableParameterCount); } throw new CommandMethodSyntaxException(commandMethod, message); } private int calculateAvailableParameterCount(CommandSegments commandSegments, List<? extends Parameter> bindableParameters) { int count = commandSegments.size(); for (int i = 0; i < bindableParameters.size(); i++) { Parameter bindableParameter = bindableParameters.get(i); boolean consumed = isConsumed(commandSegments, bindableParameter); if (consumed) { continue; } if (bindableParameter.isAssignableTo(KeyValue.class) || bindableParameter.isAssignableTo(ScoredValue.class)) { count++; } if (bindableParameter.isAssignableTo(GeoCoordinates.class) || bindableParameter.isAssignableTo(Range.class)) { count++; } if (bindableParameter.isAssignableTo(Limit.class)) { count += 2; } count++; } return count; } private boolean isConsumed(CommandSegments commandSegments, Parameter bindableParameter) { for (CommandSegment commandSegment : commandSegments) { if (commandSegment.canConsume(bindableParameter)) { return true; } } return false; } private CommandMethodSyntaxException syntaxException(String commandName, CommandMethod commandMethod) { CommandMatches commandMatches = CommandMatches.forCommand(commandName, commandDetails); if (commandMatches.hasMatches()) { return new CommandMethodSyntaxException(commandMethod, String.format("Command %s does not exist. Did you mean: %s?", commandName, commandMatches)); } return new CommandMethodSyntaxException(commandMethod, String.format("Command %s does not exist", commandName)); } private Optional<CommandDetail> findCommandDetail(String commandName) { return commandDetails.stream().filter(commandDetail -> commandDetail.getName().equalsIgnoreCase(commandName)) .findFirst(); } static class CommandMatches { private final List<String> matches = new ArrayList<>(); private CommandMatches(List<String> matches) { this.matches.addAll(matches); } public static CommandMatches forCommand(String command, List<CommandDetail> commandDetails) { return new CommandMatches(calculateMatches(command, commandDetails)); } private static List<String> calculateMatches(String command, List<CommandDetail> commandDetails) { return commandDetails.stream() // .filter(commandDetail -> calculateStringDistance(commandDetail.getName().toLowerCase(), command.toLowerCase()) <= DEFAULT_MAX_DISTANCE) .map(CommandDetail::getName) // .map(String::toUpperCase) // .sorted(CommandMatches::calculateStringDistance).collect(Collectors.toList()); } public boolean hasMatches() { return !matches.isEmpty(); } @Override public String toString() { return LettuceStrings.collectionToDelimitedString(matches, ", ", "", ""); } /** * Calculate the distance between the given two Strings according to the Levenshtein algorithm. * * @param s1 the first String * @param s2 the second String * @return the distance value */ private static int calculateStringDistance(String s1, String s2) { if (s1.length() == 0) { return s2.length(); } if (s2.length() == 0) { return s1.length(); } int d[][] = new int[s1.length() + 1][s2.length() + 1]; for (int i = 0; i <= s1.length(); i++) { d[i][0] = i; } for (int j = 0; j <= s2.length(); j++) { d[0][j] = j; } for (int i = 1; i <= s1.length(); i++) { char s_i = s1.charAt(i - 1); for (int j = 1; j <= s2.length(); j++) { int cost; char t_j = s2.charAt(j - 1); if (s_i == t_j) { cost = 0; } else { cost = 1; } d[i][j] = Math.min(Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1), d[i - 1][j - 1] + cost); } } return d[s1.length()][s2.length()]; } } }
LettuceAssert.notEmpty(commandSegments.getCommandType().name(), "Command name must not be empty"); CommandDetail commandDetail = findCommandDetail(commandSegments.getCommandType().name()) .orElseThrow(() -> syntaxException(commandSegments.getCommandType().name(), commandMethod)); validateParameters(commandDetail, commandSegments, commandMethod);
1,931
96
2,027
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/DefaultMethodParametersAccessor.java
DefaultMethodParametersAccessor
isBindableNullValue
class DefaultMethodParametersAccessor implements MethodParametersAccessor { private final Parameters<? extends Parameter> parameters; private final List<Object> values; DefaultMethodParametersAccessor(Parameters<? extends Parameter> parameters, Object... values) { LettuceAssert.notNull(parameters, "Parameters must not be null"); LettuceAssert.notNull(values, "Values must not be null"); this.parameters = parameters; this.values = Arrays.asList(values); } public int getParameterCount() { return parameters.getBindableParameters().size(); } @Override public Object getBindableValue(int index) { return values.get(parameters.getBindableParameter(index).getParameterIndex()); } @Override public boolean isKey(int index) { return parameters.getBindableParameter(index).findAnnotation(Key.class) != null; } @Override public boolean isValue(int index) { return parameters.getBindableParameter(index).findAnnotation(Value.class) != null; } @Override public Iterator<Object> iterator() { return new BindableParameterIterator(this); } @Override public int resolveParameterIndex(String name) { List<? extends Parameter> bindableParameters = parameters.getBindableParameters(); for (int i = 0; i < bindableParameters.size(); i++) { if (name.equals(bindableParameters.get(i).getName())) { return i; } } throw new IllegalArgumentException(String.format("Cannot resolve named parameter %s", name)); } public Parameters<? extends Parameter> getParameters() { return parameters; } @Override public boolean isBindableNullValue(int index) {<FILL_FUNCTION_BODY>} /** * Iterator class to allow traversing all bindable parameters inside the accessor. */ static class BindableParameterIterator implements Iterator<Object> { private final int bindableParameterCount; private final DefaultMethodParametersAccessor accessor; private int currentIndex = 0; /** * Creates a new {@link BindableParameterIterator}. * * @param accessor must not be {@code null}. */ BindableParameterIterator(DefaultMethodParametersAccessor accessor) { LettuceAssert.notNull(accessor, "ParametersParameterAccessor must not be null!"); this.accessor = accessor; this.bindableParameterCount = accessor.getParameters().getBindableParameters().size(); } /** * Return the next bindable parameter. * * @return */ public Object next() { return accessor.getBindableValue(currentIndex++); } public boolean hasNext() { return bindableParameterCount > currentIndex; } public void remove() { throw new UnsupportedOperationException(); } } }
Parameter bindableParameter = parameters.getBindableParameter(index); if (bindableParameter.isAssignableTo(Limit.class) || bindableParameter.isAssignableTo(io.lettuce.core.Value.class) || bindableParameter.isAssignableTo(KeyValue.class) || bindableParameter.isAssignableTo(ScoredValue.class) || bindableParameter.isAssignableTo(GeoCoordinates.class) || bindableParameter.isAssignableTo(Range.class)) { return false; } return true;
773
147
920
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/DefaultRedisCommandsMetadata.java
DefaultRedisCommandsMetadata
getMostSpecificMethod
class DefaultRedisCommandsMetadata implements RedisCommandsMetadata { /** The package separator character: '.' */ private static final char PACKAGE_SEPARATOR = '.'; private final Class<?> apiInterface; /** * Create {@link DefaultRedisCommandsMetadata} given a {@link Class command interface}. * * @param apiInterface must not be {@code null}. */ DefaultRedisCommandsMetadata(Class<?> apiInterface) { this.apiInterface = apiInterface; } @Override public Class<?> getCommandsInterface() { return apiInterface; } @Override public Collection<Method> getMethods() { Set<Method> result = new HashSet<Method>(); for (Method method : getCommandsInterface().getMethods()) { method = getMostSpecificMethod(method, getCommandsInterface()); if (isQueryMethodCandidate(method)) { result.add(method); } } return Collections.unmodifiableSet(result); } /** * Checks whether the given method is a query method candidate. * * @param method * @return */ private boolean isQueryMethodCandidate(Method method) { return !method.isBridge() && !method.isDefault() && !Modifier.isStatic(method.getModifiers()); } @Override public <A extends Annotation> A getAnnotation(Class<A> annotationClass) { return getCommandsInterface().getAnnotation(annotationClass); } @Override public boolean hasAnnotation(Class<? extends Annotation> annotationClass) { return getCommandsInterface().getAnnotation(annotationClass) != null; } /** * Given a method, which may come from an interface, and a target class used in the current reflective invocation, find the * corresponding target method if there is one. E.g. the method may be {@code IFoo.bar()} and the target class may be * {@code DefaultFoo}. In this case, the method may be {@code DefaultFoo.bar()}. This enables attributes on that method to * be found. * * @param method the method to be invoked, which may come from an interface * @param targetClass the target class for the current invocation. May be {@code null} or may not even implement the method. * @return the specific target method, or the original method if the {@code targetClass} doesn't implement it or is * {@code null} */ public static Method getMostSpecificMethod(Method method, Class<?> targetClass) {<FILL_FUNCTION_BODY>} /** * Determine whether the given method is overridable in the given target class. * * @param method the method to check * @param targetClass the target class to check against */ private static boolean isOverridable(Method method, Class<?> targetClass) { if (Modifier.isPrivate(method.getModifiers())) { return false; } if (Modifier.isPublic(method.getModifiers()) || Modifier.isProtected(method.getModifiers())) { return true; } return getPackageName(method.getDeclaringClass()).equals(getPackageName(targetClass)); } /** * Determine the name of the package of the given class, e.g. "java.lang" for the {@code java.lang.String} class. * * @param clazz the class * @return the package name, or the empty String if the class is defined in the default package */ private static String getPackageName(Class<?> clazz) { LettuceAssert.notNull(clazz, "Class must not be null"); return getPackageName(clazz.getName()); } /** * Determine the name of the package of the given fully-qualified class name, e.g. "java.lang" for the * {@code java.lang.String} class name. * * @param fqClassName the fully-qualified class name * @return the package name, or the empty String if the class is defined in the default package */ private static String getPackageName(String fqClassName) { LettuceAssert.notNull(fqClassName, "Class name must not be null"); int lastDotIndex = fqClassName.lastIndexOf(PACKAGE_SEPARATOR); return (lastDotIndex != -1 ? fqClassName.substring(0, lastDotIndex) : ""); } }
if (method != null && isOverridable(method, targetClass) && targetClass != null && targetClass != method.getDeclaringClass()) { try { try { return targetClass.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException ex) { return method; } } catch (SecurityException ex) { } } return method;
1,159
112
1,271
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/ExecutableCommandLookupStrategySupport.java
DefaultCommandFactoryResolver
resolveRedisCommandFactory
class DefaultCommandFactoryResolver implements CommandFactoryResolver { final AnnotationCommandSegmentFactory commandSegmentFactory = new AnnotationCommandSegmentFactory(); final AnnotationRedisCodecResolver codecResolver; DefaultCommandFactoryResolver() { codecResolver = new AnnotationRedisCodecResolver(redisCodecs); } @Override public CommandFactory resolveRedisCommandFactory(CommandMethod commandMethod, RedisCommandsMetadata commandsMetadata) {<FILL_FUNCTION_BODY>} }
RedisCodec<?, ?> codec = codecResolver.resolve(commandMethod); if (codec == null) { throw new CommandCreationException(commandMethod, "Cannot resolve RedisCodec"); } CodecAwareOutputFactoryResolver outputFactoryResolver = new CodecAwareOutputFactoryResolver( commandOutputFactoryResolver, codec); CommandSegments commandSegments = commandSegmentFactory.createCommandSegments(commandMethod); commandMethodVerifier.validate(commandSegments, commandMethod); return new CommandSegmentCommandFactory(commandSegments, commandMethod, codec, outputFactoryResolver);
124
154
278
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/ReactiveCommandSegmentCommandFactory.java
ReactiveCommandSegmentCommandFactory
resolveCommandOutputFactory
class ReactiveCommandSegmentCommandFactory extends CommandSegmentCommandFactory { private boolean streamingExecution; ReactiveCommandSegmentCommandFactory(CommandSegments commandSegments, CommandMethod commandMethod, RedisCodec<?, ?> redisCodec, CommandOutputFactoryResolver outputResolver) { super(commandSegments, commandMethod, redisCodec, outputResolver); if (commandMethod.getParameters() instanceof ExecutionSpecificParameters) { ExecutionSpecificParameters executionAwareParameters = (ExecutionSpecificParameters) commandMethod.getParameters(); if (executionAwareParameters.hasTimeoutIndex()) { throw new CommandCreationException(commandMethod, "Reactive command methods do not support Timeout parameters"); } } } @Override protected CommandOutputFactory resolveCommandOutputFactory(OutputSelector outputSelector) {<FILL_FUNCTION_BODY>} /** * @return {@code true} if the resolved {@link io.lettuce.core.output.CommandOutput} should use streaming. */ boolean isStreamingExecution() { return streamingExecution; } }
streamingExecution = ReactiveTypes.isMultiValueType(outputSelector.getOutputType().getRawClass()); OutputSelector componentType = new OutputSelector(outputSelector.getOutputType().getGeneric(0), outputSelector.getRedisCodec()); if (streamingExecution) { CommandOutputFactory streamingFactory = getOutputResolver().resolveStreamingCommandOutput(componentType); if (streamingExecution && streamingFactory != null) { return streamingFactory; } } return super.resolveCommandOutputFactory(componentType);
271
138
409
<methods>public void <init>(io.lettuce.core.dynamic.segment.CommandSegments, io.lettuce.core.dynamic.CommandMethod, RedisCodec<?,?>, io.lettuce.core.dynamic.output.CommandOutputFactoryResolver) ,public RedisCommand<java.lang.Object,java.lang.Object,java.lang.Object> createCommand(java.lang.Object[]) <variables>private final non-sealed io.lettuce.core.dynamic.CommandMethod commandMethod,private final non-sealed io.lettuce.core.dynamic.output.CommandOutputFactory outputFactory,private final non-sealed io.lettuce.core.dynamic.output.CommandOutputFactoryResolver outputResolver,private final io.lettuce.core.dynamic.ParameterBinder parameterBinder,private final non-sealed RedisCodec<java.lang.Object,java.lang.Object> redisCodec,private final non-sealed io.lettuce.core.dynamic.segment.CommandSegments segments,private final non-sealed io.lettuce.core.dynamic.CodecAwareMethodParametersAccessor.TypeContext typeContext
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/ReactiveExecutableCommand.java
ReactiveExecutableCommand
dispatch
class ReactiveExecutableCommand implements ExecutableCommand { private final CommandMethod commandMethod; private final ReactiveCommandSegmentCommandFactory commandFactory; private final AbstractRedisReactiveCommands<Object, Object> redisReactiveCommands; ReactiveExecutableCommand(CommandMethod commandMethod, ReactiveCommandSegmentCommandFactory commandFactory, AbstractRedisReactiveCommands<Object, Object> redisReactiveCommands) { this.commandMethod = commandMethod; this.commandFactory = commandFactory; this.redisReactiveCommands = redisReactiveCommands; } @Override public Object execute(Object[] parameters) { return dispatch(parameters); } protected Object dispatch(Object[] arguments) {<FILL_FUNCTION_BODY>} @Override public CommandMethod getCommandMethod() { return commandMethod; } }
if (ReactiveTypes.isSingleValueType(commandMethod.getReturnType().getRawClass())) { return redisReactiveCommands.createMono(() -> commandFactory.createCommand(arguments)); } if (commandFactory.isStreamingExecution()) { return redisReactiveCommands.createDissolvingFlux(() -> commandFactory.createCommand(arguments)); } return redisReactiveCommands.createFlux(() -> commandFactory.createCommand(arguments));
224
126
350
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/ReactiveExecutableCommandLookupStrategy.java
ReactiveExecutableCommandLookupStrategy
resolveCommandMethod
class ReactiveExecutableCommandLookupStrategy implements ExecutableCommandLookupStrategy { private final AbstractRedisReactiveCommands<Object, Object> redisReactiveCommands; private final ConversionService conversionService = new ConversionService(); private final List<RedisCodec<?, ?>> redisCodecs; private final CommandOutputFactoryResolver outputFactoryResolver; private final ReactiveCommandFactoryResolver commandFactoryResolver; private final CommandMethodVerifier commandMethodVerifier; ReactiveExecutableCommandLookupStrategy(List<RedisCodec<?, ?>> redisCodecs, CommandOutputFactoryResolver outputFactoryResolver, CommandMethodVerifier commandMethodVerifier, AbstractRedisReactiveCommands<Object, Object> redisReactiveCommands) { this.redisReactiveCommands = redisReactiveCommands; this.redisCodecs = redisCodecs; this.outputFactoryResolver = outputFactoryResolver; this.commandMethodVerifier = commandMethodVerifier; ReactiveTypeAdapters.registerIn(this.conversionService); this.commandFactoryResolver = new ReactiveCommandFactoryResolver(); } @Override public ExecutableCommand resolveCommandMethod(CommandMethod method, RedisCommandsMetadata commandsMetadata) {<FILL_FUNCTION_BODY>} class ReactiveCommandFactoryResolver implements CommandFactoryResolver { final AnnotationCommandSegmentFactory commandSegmentFactory = new AnnotationCommandSegmentFactory(); final AnnotationRedisCodecResolver codecResolver; ReactiveCommandFactoryResolver() { codecResolver = new AnnotationRedisCodecResolver(redisCodecs); } public ReactiveCommandSegmentCommandFactory resolveRedisCommandFactory(CommandMethod commandMethod, RedisCommandsMetadata redisCommandsMetadata) { RedisCodec<?, ?> codec = codecResolver.resolve(commandMethod); if (codec == null) { throw new CommandCreationException(commandMethod, "Cannot resolve RedisCodec"); } CommandSegments commandSegments = commandSegmentFactory.createCommandSegments(commandMethod); commandMethodVerifier.validate(commandSegments, commandMethod); CodecAwareOutputFactoryResolver outputFactoryResolver = new CodecAwareOutputFactoryResolver( ReactiveExecutableCommandLookupStrategy.this.outputFactoryResolver, codec); return new ReactiveCommandSegmentCommandFactory(commandSegments, commandMethod, codec, outputFactoryResolver); } } }
LettuceAssert.isTrue(!method.isBatchExecution(), () -> String.format("Command batching %s not supported with ReactiveExecutableCommandLookupStrategy", method)); LettuceAssert.isTrue(method.isReactiveExecution(), () -> String.format("Command method %s not supported by ReactiveExecutableCommandLookupStrategy", method)); ReactiveCommandSegmentCommandFactory commandFactory = commandFactoryResolver.resolveRedisCommandFactory(method, commandsMetadata); return new ConvertingCommand(conversionService, new ReactiveExecutableCommand(method, commandFactory, redisReactiveCommands));
614
156
770
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/RedisCommandFactory.java
CompositeCommandLookupStrategy
getReactiveCommands
class CompositeCommandLookupStrategy implements ExecutableCommandLookupStrategy { private final AsyncExecutableCommandLookupStrategy async; private final ReactiveExecutableCommandLookupStrategy reactive; CompositeCommandLookupStrategy() { CommandMethodVerifier verifier = verifyCommandMethods ? commandMethodVerifier : CommandMethodVerifier.NONE; AbstractRedisReactiveCommands reactive = getReactiveCommands(); LettuceAssert.isTrue(reactive != null, "Reactive commands is null"); this.async = new AsyncExecutableCommandLookupStrategy(redisCodecs, commandOutputFactoryResolver, verifier, (StatefulConnection) connection); this.reactive = new ReactiveExecutableCommandLookupStrategy(redisCodecs, commandOutputFactoryResolver, verifier, reactive); } private AbstractRedisReactiveCommands getReactiveCommands() {<FILL_FUNCTION_BODY>} @Override public ExecutableCommand resolveCommandMethod(CommandMethod method, RedisCommandsMetadata metadata) { if (method.isReactiveExecution()) { return reactive.resolveCommandMethod(method, metadata); } return async.resolveCommandMethod(method, metadata); } }
Object reactive = null; if (connection instanceof StatefulRedisConnection) { reactive = ((StatefulRedisConnection) connection).reactive(); } if (connection instanceof StatefulRedisClusterConnection) { reactive = ((StatefulRedisClusterConnection) connection).reactive(); } if (reactive != null && Proxy.isProxyClass(reactive.getClass())) { InvocationHandler invocationHandler = Proxy.getInvocationHandler(reactive); reactive = ConnectionWrapping.unwrap(invocationHandler); } return (AbstractRedisReactiveCommands) reactive;
314
163
477
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/SimpleBatcher.java
SimpleBatcher
doFlush
class SimpleBatcher implements Batcher { private final StatefulConnection<Object, Object> connection; private final int batchSize; private final BlockingQueue<RedisCommand<Object, Object, Object>> queue = new LinkedBlockingQueue<>(); private final AtomicBoolean flushing = new AtomicBoolean(); public SimpleBatcher(StatefulConnection<Object, Object> connection, int batchSize) { LettuceAssert.isTrue(batchSize == -1 || batchSize > 1, "Batch size must be greater zero or -1"); this.connection = connection; this.batchSize = batchSize; } @Override public BatchTasks batch(RedisCommand<Object, Object, Object> command, CommandBatching batching) { queue.add(command); if (batching == CommandBatching.queue()) { return BatchTasks.EMPTY; } boolean forcedFlush = batching == CommandBatching.flush(); boolean defaultFlush = false; if (!forcedFlush) { if (queue.size() >= batchSize) { defaultFlush = true; } } if (defaultFlush || forcedFlush) { return flush(forcedFlush); } return BatchTasks.EMPTY; } @Override public BatchTasks flush() { return flush(true); } protected BatchTasks flush(boolean forcedFlush) { boolean defaultFlush = false; List<RedisCommand<?, ?, ?>> commands = newDrainTarget(); while (flushing.compareAndSet(false, true)) { try { int consume = -1; if (!forcedFlush) { long queuedItems = queue.size(); if (queuedItems >= batchSize) { consume = batchSize; defaultFlush = true; } } List<? extends RedisCommand<?, ?, ?>> batch = doFlush(forcedFlush, defaultFlush, consume); if (batch != null) { commands.addAll(batch); } if (defaultFlush && !queue.isEmpty() && queue.size() > batchSize) { continue; } return new BatchTasks(commands); } finally { flushing.set(false); } } return BatchTasks.EMPTY; } private List<? extends RedisCommand<?, ?, ?>> doFlush(boolean forcedFlush, boolean defaultFlush, int consume) {<FILL_FUNCTION_BODY>} private List<RedisCommand<Object, Object, Object>> prepareForceFlush() { List<RedisCommand<Object, Object, Object>> batch = newDrainTarget(); while (!queue.isEmpty()) { RedisCommand<Object, Object, Object> poll = queue.poll(); if (poll != null) { batch.add(poll); } } return batch; } private List<RedisCommand<Object, Object, Object>> prepareDefaultFlush(int consume) { List<RedisCommand<Object, Object, Object>> batch = newDrainTarget(); while ((batch.size() < consume || consume == -1) && !queue.isEmpty()) { RedisCommand<Object, Object, Object> poll = queue.poll(); if (poll != null) { batch.add(poll); } } return batch; } private <T> ArrayList<T> newDrainTarget() { return new ArrayList<>(Math.max(0, Math.min(batchSize, queue.size()))); } }
List<RedisCommand<Object, Object, Object>> commands = null; if (forcedFlush) { commands = prepareForceFlush(); } else if (defaultFlush) { commands = prepareDefaultFlush(consume); } if (commands != null && !commands.isEmpty()) { if (commands.size() == 1) { connection.dispatch(commands.get(0)); } else { connection.dispatch(commands); } return commands; } return Collections.emptyList();
950
145
1,095
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/domain/Timeout.java
Timeout
create
class Timeout { private final Duration timeout; private Timeout(Duration timeout) { LettuceAssert.notNull(timeout, "Timeout must not be null"); LettuceAssert.isTrue(!timeout.isNegative(), "Timeout must be greater or equal to zero"); this.timeout = timeout; } /** * Create a {@link Timeout}. * * @param timeout the timeout value, must be non-negative. * @return the {@link Timeout}. */ public static Timeout create(Duration timeout) { return new Timeout(timeout); } /** * Create a {@link Timeout}. * * @param timeout the timeout value, must be non-negative. * @param timeUnit the associated {@link TimeUnit}, must not be {@code null}. * @return the {@link Timeout}. */ public static Timeout create(long timeout, TimeUnit timeUnit) {<FILL_FUNCTION_BODY>} /** * @return the timeout value. */ public Duration getTimeout() { return timeout; } }
LettuceAssert.notNull(timeUnit, "TimeUnit must not be null"); return new Timeout(Duration.ofNanos(timeUnit.toNanos(timeout)));
287
50
337
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/intercept/DefaultMethodInvokingInterceptor.java
DefaultMethodInvokingInterceptor
lookupMethodHandle
class DefaultMethodInvokingInterceptor implements MethodInterceptor { private final Map<Method, MethodHandle> methodHandleCache = new ConcurrentHashMap<>(); @Override public Object invoke(MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); if (!method.isDefault()) { return invocation.proceed(); } LettuceAssert.isTrue(invocation instanceof InvocationTargetProvider, "Invocation must provide a target object via InvocationTargetProvider"); InvocationTargetProvider targetProvider = (InvocationTargetProvider) invocation; return methodHandleCache.computeIfAbsent(method, DefaultMethodInvokingInterceptor::lookupMethodHandle) .bindTo(targetProvider.getInvocationTarget()).invokeWithArguments(invocation.getArguments()); } private static MethodHandle lookupMethodHandle(Method method) {<FILL_FUNCTION_BODY>} }
try { return DefaultMethods.lookupMethodHandle(method); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException(e); }
234
45
279
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/intercept/InvocationProxyFactory.java
InvocationProxyFactory
createProxy
class InvocationProxyFactory { private final List<MethodInterceptor> interceptors = new ArrayList<>(); private final List<Class<?>> interfaces = new ArrayList<>(); /** * Create a proxy instance give a {@link ClassLoader}. * * @param classLoader must not be {@code null}. * @param <T> inferred result type. * @return the invocation proxy instance. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T createProxy(ClassLoader classLoader) {<FILL_FUNCTION_BODY>} /** * Add a interface type that should be implemented by the resulting invocation proxy. * * @param ifc must not be {@code null} and must be an interface type. */ public void addInterface(Class<?> ifc) { LettuceAssert.notNull(ifc, "Interface type must not be null"); LettuceAssert.isTrue(ifc.isInterface(), "Type must be an interface"); this.interfaces.add(ifc); } /** * Add a {@link MethodInterceptor} to the interceptor chain. * * @param interceptor notNull */ public void addInterceptor(MethodInterceptor interceptor) { LettuceAssert.notNull(interceptor, "MethodInterceptor must not be null"); this.interceptors.add(interceptor); } /** * {@link MethodInterceptor}-based {@link InterceptorChainInvocationHandler}. */ static class InterceptorChainInvocationHandler extends AbstractInvocationHandler { private final MethodInterceptorChain.Head context; InterceptorChainInvocationHandler(List<MethodInterceptor> interceptors) { this.context = MethodInterceptorChain.from(interceptors); } @Override protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { return context.invoke(proxy, method, args); } } }
LettuceAssert.notNull(classLoader, "ClassLoader must not be null"); Class<?>[] interfaces = this.interfaces.toArray(new Class[0]); return (T) Proxy.newProxyInstance(classLoader, interfaces, new InterceptorChainInvocationHandler(interceptors));
531
80
611
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/intercept/MethodInterceptorChain.java
MethodInterceptorChain
invoke
class MethodInterceptorChain { private final ThreadLocal<PooledMethodInvocation> pool = ThreadLocal.withInitial(PooledMethodInvocation::new); final MethodInterceptorChain next; MethodInterceptorChain(MethodInterceptorChain next) { this.next = next; } /** * Create a {@link MethodInterceptorChain} from {@link MethodInterceptor}s. Chain elements are created eagerly by * stack-walking {@code interceptors}. Make sure the {@link Iterable} does not exhaust the stack size. * * @param interceptors must not be {@code null}. * @return the {@link MethodInterceptorChain} that is an entry point for method invocations. */ public static Head from(Iterable<? extends MethodInterceptor> interceptors) { return new Head(next(interceptors.iterator())); } private static MethodInterceptorChain next(Iterator<? extends MethodInterceptor> iterator) { return iterator.hasNext() ? createContext(iterator, iterator.next()) : Tail.INSTANCE; } private static MethodInterceptorChain createContext(Iterator<? extends MethodInterceptor> iterator, MethodInterceptor interceptor) { return new MethodInterceptorContext(next(iterator), interceptor); } /** * Invoke a {@link Method} with its {@code args}. * * @param target must not be {@code null}. * @param method must not be {@code null}. * @param args must not be {@code null}. * @return * @throws Throwable */ public Object invoke(Object target, Method method, Object[] args) throws Throwable {<FILL_FUNCTION_BODY>} private PooledMethodInvocation getInvocation(Object target, Method method, Object[] args, MethodInterceptorChain next) { PooledMethodInvocation pooledMethodInvocation = pool.get(); pooledMethodInvocation.initialize(target, method, args, next); return pooledMethodInvocation; } /** * Proceed to the next {@link MethodInterceptorChain}. * * @param invocation must not be {@code null}. * @return * @throws Throwable */ abstract Object proceed(MethodInvocation invocation) throws Throwable; /** * {@link MethodInterceptorChain} using {@link MethodInterceptor} to handle invocations. */ static class MethodInterceptorContext extends MethodInterceptorChain { private final MethodInterceptor interceptor; MethodInterceptorContext(MethodInterceptorChain next, MethodInterceptor interceptor) { super(next); this.interceptor = interceptor; } @Override Object proceed(MethodInvocation invocation) throws Throwable { return interceptor.invoke(invocation); } } /** * Head {@link MethodInterceptorChain} to delegate to the next {@link MethodInterceptorChain}. */ static class Head extends MethodInterceptorChain { protected Head(MethodInterceptorChain next) { super(next); } @Override Object proceed(MethodInvocation invocation) throws Throwable { return next.proceed(invocation); } } /** * Tail {@link MethodInterceptorChain}, no-op. */ static class Tail extends MethodInterceptorChain { public static Tail INSTANCE = new Tail(); private Tail() { super(null); } @Override Object proceed(MethodInvocation invocation) throws Throwable { return null; } } /** * Stateful {@link MethodInvocation} using {@link MethodInterceptorChain}. The state is only valid throughout a call. */ static class PooledMethodInvocation implements MethodInvocation, InvocationTargetProvider { private Object target; private Method method; private Object args[]; private MethodInterceptorChain current; PooledMethodInvocation() { } /** * Initialize state from the method call. * * @param target * @param method * @param args * @param head */ public void initialize(Object target, Method method, Object[] args, MethodInterceptorChain head) { this.target = target; this.method = method; this.args = args; this.current = head; } /** * Clear invocation state. */ public void clear() { this.target = null; this.method = null; this.args = null; this.current = null; } @Override public Object proceed() throws Throwable { current = current.next; return current.proceed(this); } @Override public Object getInvocationTarget() { return target; } @Override public Method getMethod() { return method; } @Override public Object[] getArguments() { return args; } } }
PooledMethodInvocation invocation = getInvocation(target, method, args, next); try { // JIT hint if (next instanceof MethodInterceptorContext) { return next.proceed(invocation); } return next.proceed(invocation); } finally { invocation.clear(); }
1,324
90
1,414
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/output/CommandOutputResolverSupport.java
CommandOutputResolverSupport
isAssignableFrom
class CommandOutputResolverSupport { /** * Overridable hook to check whether {@code selector} can be assigned from the provider type {@code provider}. * <p> * This method descends the component type hierarchy and considers primitive/wrapper type conversion. * * @param selector must not be {@code null}. * @param provider must not be {@code null}. * @return {@code true} if selector can be assigned from its provider type. */ protected boolean isAssignableFrom(OutputSelector selector, OutputType provider) {<FILL_FUNCTION_BODY>} }
ResolvableType selectorType = selector.getOutputType(); ResolvableType resolvableType = provider.withCodec(selector.getRedisCodec()); return selectorType.isAssignableFrom(resolvableType);
146
60
206
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/output/OutputRegistryCommandOutputFactoryResolver.java
OutputRegistryCommandOutputFactoryResolver
resolveStreamingCommandOutput
class OutputRegistryCommandOutputFactoryResolver extends CommandOutputResolverSupport implements CommandOutputFactoryResolver { @SuppressWarnings("rawtypes") private static final ClassTypeInformation<CommandOutput> COMMAND_OUTPUT = ClassTypeInformation.from(CommandOutput.class); private final OutputRegistry outputRegistry; /** * Create a new {@link OutputRegistryCommandOutputFactoryResolver} given {@link OutputRegistry}. * * @param outputRegistry must not be {@code null}. */ public OutputRegistryCommandOutputFactoryResolver(OutputRegistry outputRegistry) { LettuceAssert.notNull(outputRegistry, "OutputRegistry must not be null"); this.outputRegistry = outputRegistry; } @Override public CommandOutputFactory resolveCommandOutput(OutputSelector outputSelector) { Map<OutputType, CommandOutputFactory> registry = outputRegistry.getRegistry(); List<OutputType> outputTypes = registry.keySet().stream().filter((outputType) -> !outputType.isStreaming()) .collect(Collectors.toList()); List<OutputType> candidates = getCandidates(outputTypes, outputSelector); if (candidates.isEmpty()) { return null; } return registry.get(candidates.get(0)); } @Override public CommandOutputFactory resolveStreamingCommandOutput(OutputSelector outputSelector) {<FILL_FUNCTION_BODY>} private List<OutputType> getCandidates(Collection<OutputType> outputTypes, OutputSelector outputSelector) { return outputTypes.stream().filter(outputType -> { if (COMMAND_OUTPUT.getType().isAssignableFrom(outputSelector.getOutputType().getRawClass())) { if (outputSelector.getOutputType().getRawClass().isAssignableFrom(outputType.getCommandOutputClass())) { return true; } } return isAssignableFrom(outputSelector, outputType); }).collect(Collectors.toList()); } }
Map<OutputType, CommandOutputFactory> registry = outputRegistry.getRegistry(); List<OutputType> outputTypes = registry.keySet().stream().filter(OutputType::isStreaming).collect(Collectors.toList()); List<OutputType> candidates = getCandidates(outputTypes, outputSelector); if (candidates.isEmpty()) { return null; } return registry.get(candidates.get(0));
503
115
618
<methods>public non-sealed void <init>() <variables>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/output/OutputType.java
OutputType
toString
class OutputType { private final Class<? extends CommandOutput> commandOutputClass; private final TypeInformation<?> typeInformation; private final boolean streaming; /** * Create a new {@link OutputType} given {@code primaryType}, the {@code commandOutputClass}, {@link TypeInformation} and * whether the {@link OutputType} is for a {@link io.lettuce.core.output.StreamingOutput}. * * @param commandOutputClass must not be {@code null}. * @param typeInformation must not be {@code null}. * @param streaming {@code true} if the type descriptor concerns the {@link io.lettuce.core.output.StreamingOutput} */ OutputType(Class<? extends CommandOutput> commandOutputClass, TypeInformation<?> typeInformation, boolean streaming) { LettuceAssert.notNull(commandOutputClass, "CommandOutput class must not be null"); LettuceAssert.notNull(typeInformation, "TypeInformation must not be null"); this.commandOutputClass = commandOutputClass; this.typeInformation = typeInformation; this.streaming = streaming; } /** * @return */ public TypeInformation<?> getTypeInformation() { return typeInformation; } /** * @return */ public boolean isStreaming() { return streaming; } public ResolvableType withCodec(RedisCodec<?, ?> codec) { return ResolvableType.forClass(typeInformation.getType()); } /** * @return */ public Class<?> getCommandOutputClass() { return commandOutputClass; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" [commandOutputClass=").append(commandOutputClass); sb.append(", typeInformation=").append(typeInformation); sb.append(", streaming=").append(streaming); sb.append(']'); return sb.toString();
448
91
539
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/parameter/Parameter.java
Parameter
isAssignableTo
class Parameter { private final ParameterNameDiscoverer discoverer = new CompositeParameterNameDiscoverer( new StandardReflectionParameterNameDiscoverer(), new AnnotationParameterNameDiscoverer()); private final Method method; private final String name; private final int parameterIndex; private final TypeInformation<?> typeInformation; private final MethodParameter methodParameter; private final Map<Class<? extends Annotation>, Annotation> annotationCache = new ConcurrentHashMap<>(); private final Set<Class<? extends Annotation>> absentCache = ConcurrentHashMap.newKeySet(); private final List<Annotation> annotations; public Parameter(Method method, int parameterIndex) { this.method = method; this.parameterIndex = parameterIndex; this.methodParameter = new MethodParameter(method, parameterIndex); this.methodParameter.initParameterNameDiscovery(discoverer); this.name = methodParameter.getParameterName(); this.typeInformation = ClassTypeInformation.fromMethodParameter(method, parameterIndex); Annotation[] annotations = method.getParameterAnnotations()[parameterIndex]; List<Annotation> allAnnotations = new ArrayList<>(annotations.length); for (Annotation annotation : annotations) { this.annotationCache.put(annotation.getClass(), annotation); allAnnotations.add(annotation); } this.annotations = Collections.unmodifiableList(allAnnotations); } /** * Return the parameter annotation of the given type, if available. * * @param annotationType the annotation type to look for * @return the annotation object, or {@code null} if not found */ @SuppressWarnings("unchecked") public <A extends Annotation> A findAnnotation(Class<A> annotationType) { if (absentCache.contains(annotationType)) { return null; } A result = (A) annotationCache.computeIfAbsent(annotationType, key -> methodParameter.getParameterAnnotation(annotationType)); if (result == null) { absentCache.add(annotationType); } return result; } /** * Return all parameter annotations. * * @return the {@link List} of annotation objects. */ public List<? extends Annotation> getAnnotations() { return annotations; } /** * * @return the parameter index. */ public int getParameterIndex() { return parameterIndex; } /** * * @return the parameter type. */ public Class<?> getParameterType() { return method.getParameterTypes()[parameterIndex]; } /** * * @return the parameter {@link TypeInformation}. */ public TypeInformation<?> getTypeInformation() { return typeInformation; } /** * Check whether the parameter is assignable to {@code target}. * * @param target must not be {@code null}. * @return */ public boolean isAssignableTo(Class<?> target) {<FILL_FUNCTION_BODY>} /** * * @return {@code true} if the parameter is a special parameter. */ public boolean isSpecialParameter() { return false; } /** * @return {@code true} if the {@link Parameter} can be bound to a command. */ boolean isBindable() { return !isSpecialParameter(); } /** * @return the parameter name or {@code null} if not available. */ public String getName() { return name; } }
LettuceAssert.notNull(target, "Target type must not be null"); return LettuceClassUtils.isAssignable(target, getParameterType());
937
45
982
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/parameter/Parameters.java
Parameters
createBindableParameters
class Parameters<P extends Parameter> implements Iterable<P> { private final List<P> parameters; private final List<P> bindableParameters; /** * Create new {@link Parameters} given a {@link Method}. * * @param method must not be {@code null}. */ public Parameters(Method method) { LettuceAssert.notNull(method, "Method must not be null"); this.parameters = new ArrayList<>(method.getParameterCount()); for (int i = 0; i < method.getParameterCount(); i++) { P parameter = createParameter(method, i); parameters.add(parameter); } this.bindableParameters = createBindableParameters(); } /** * Create a new {@link Parameters} for given a {@link Method} at {@code parameterIndex}. * * @param method must not be {@code null}. * @param parameterIndex the parameter index. * @return the {@link Parameter}. */ protected abstract P createParameter(Method method, int parameterIndex); /** * Returns {@link Parameter} instances with effectively all special parameters removed. * * @return */ private List<P> createBindableParameters() {<FILL_FUNCTION_BODY>} /** * @return */ public List<P> getParameters() { return parameters; } /** * Get the bindable parameter according it's logical position in the command. Declarative position may differ because of * special parameters interleaved. * * @param index * @return the {@link Parameter}. */ public Parameter getBindableParameter(int index) { return getBindableParameters().get(index); } /** * Returns {@link Parameter} instances with effectively all special parameters removed. * * @return */ public List<P> getBindableParameters() { return bindableParameters; } @Override public Iterator<P> iterator() { return getBindableParameters().iterator(); } }
List<P> bindables = new ArrayList<>(parameters.size()); for (P parameter : parameters) { if (parameter.isBindable()) { bindables.add(parameter); } } return bindables;
542
65
607
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/segment/AnnotationCommandSegmentFactory.java
AnnotationCommandSegmentFactory
getNamingStrategy
class AnnotationCommandSegmentFactory implements CommandSegmentFactory { private static final Pattern SPACE = Pattern.compile("\\s"); private static final String INDEX_BASED_PARAM_START = "?"; private static final String NAME_BASED_PARAM_START = ":"; @Override public CommandSegments createCommandSegments(CommandMethod commandMethod) { if (CommandSegmentParser.INSTANCE.hasCommandString(commandMethod)) { return CommandSegmentParser.INSTANCE.createCommandSegments(commandMethod); } LetterCase letterCase = getLetterCase(commandMethod); Strategy strategy = getNamingStrategy(commandMethod); List<String> parts = parseMethodName(commandMethod.getName(), strategy); return createCommandSegments(parts, letterCase); } private CommandSegments createCommandSegments(List<String> parts, LetterCase letterCase) { List<CommandSegment> segments = new ArrayList<>(parts.size()); for (String part : parts) { if (letterCase == LetterCase.AS_IS) { segments.add(CommandSegment.constant(part)); } else { segments.add(CommandSegment.constant(part.toUpperCase())); } } return new CommandSegments(segments); } private List<String> parseMethodName(String name, Strategy strategy) { if (strategy == Strategy.METHOD_NAME) { return Collections.singletonList(name); } List<String> parts = new ArrayList<>(); char[] chars = name.toCharArray(); boolean previousUpperCase = false; StringBuffer buffer = new StringBuffer(chars.length); for (char theChar : chars) { if (!Character.isUpperCase(theChar)) { buffer.append(theChar); previousUpperCase = false; continue; } // Camel hump if (!previousUpperCase) { if (!LettuceStrings.isEmpty(buffer)) { if (strategy == Strategy.DOT) { buffer.append('.'); } if (strategy == Strategy.SPLIT) { parts.add(buffer.toString()); buffer = new StringBuffer(chars.length); } } } previousUpperCase = true; buffer.append(theChar); } if (LettuceStrings.isNotEmpty(buffer)) { parts.add(buffer.toString()); } return parts; } private LetterCase getLetterCase(CommandMethod commandMethod) { if (commandMethod.hasAnnotation(CommandNaming.class)) { LetterCase letterCase = commandMethod.getMethod().getAnnotation(CommandNaming.class).letterCase(); if (letterCase != LetterCase.DEFAULT) { return letterCase; } } Class<?> declaringClass = commandMethod.getMethod().getDeclaringClass(); CommandNaming annotation = declaringClass.getAnnotation(CommandNaming.class); if (annotation != null && annotation.letterCase() != LetterCase.DEFAULT) { return annotation.letterCase(); } return LetterCase.UPPERCASE; } private Strategy getNamingStrategy(CommandMethod commandMethod) {<FILL_FUNCTION_BODY>} private enum CommandSegmentParser implements CommandSegmentFactory { INSTANCE; @Override public CommandSegments createCommandSegments(CommandMethod commandMethod) { return parse(getCommandString(commandMethod)); } private CommandSegments parse(String command) { String[] split = SPACE.split(command); LettuceAssert.notEmpty(split, "Command must not be empty"); return getCommandSegments(split); } private CommandSegments getCommandSegments(String[] split) { List<CommandSegment> segments = new ArrayList<>(); for (String segment : split) { if (segment.startsWith(INDEX_BASED_PARAM_START)) { segments.add(parseIndexBasedArgument(segment)); continue; } if (segment.startsWith(NAME_BASED_PARAM_START)) { segments.add(parseNameBasedArgument(segment)); continue; } segments.add(CommandSegment.constant(segment)); } return new CommandSegments(segments); } private CommandSegment parseIndexBasedArgument(String segment) { String index = segment.substring(INDEX_BASED_PARAM_START.length()); return getIndexBasedArgument(index); } private CommandSegment parseNameBasedArgument(String segment) { return CommandSegment.namedParameter(segment.substring(NAME_BASED_PARAM_START.length())); } private CommandSegment getIndexBasedArgument(String index) { return CommandSegment.indexedParameter(Integer.parseInt(index)); } private String getCommandString(CommandMethod commandMethod) { Command annotation = commandMethod.getAnnotation(Command.class); return annotation.value(); } private boolean hasCommandString(CommandMethod commandMethod) { if (commandMethod.hasAnnotation(Command.class)) { Command annotation = commandMethod.getAnnotation(Command.class); return LettuceStrings.isNotEmpty(annotation.value()); } return false; } } }
if (commandMethod.hasAnnotation(CommandNaming.class)) { Strategy strategy = commandMethod.getMethod().getAnnotation(CommandNaming.class).strategy(); if (strategy != Strategy.DEFAULT) { return strategy; } } Class<?> declaringClass = commandMethod.getMethod().getDeclaringClass(); CommandNaming annotation = declaringClass.getAnnotation(CommandNaming.class); if (annotation != null && annotation.strategy() != Strategy.DEFAULT) { return annotation.strategy(); } return Strategy.SPLIT;
1,388
156
1,544
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/segment/CommandSegment.java
CommandSegment
toString
class CommandSegment { /** * Create a constant {@link CommandSegment}. * * @param content must not be empty or {@code null}. * @return the {@link CommandSegment}. */ public static CommandSegment constant(String content) { return new Constant(content); } /** * Create a named parameter reference {@link CommandSegment}. * * @param name must not be empty or {@code null}. * @return */ public static CommandSegment namedParameter(String name) { return new NamedParameter(name); } public static CommandSegment indexedParameter(int index) { return new IndexedParameter(index); } /** * * @return the command segment in its {@link String representation} */ public abstract String asString(); /** * Check whether this segment can consume the {@link Parameter} by applying parameter substitution. * * @param parameter * @return * @since 5.1.3 */ public abstract boolean canConsume(Parameter parameter); /** * @param parametersAccessor * @return */ public abstract ArgumentContribution contribute(MethodParametersAccessor parametersAccessor); @Override public String toString() {<FILL_FUNCTION_BODY>} private static class Constant extends CommandSegment { private final String content; public Constant(String content) { LettuceAssert.notEmpty(content, "Constant must not be empty"); this.content = content; } @Override public String asString() { return content; } @Override public boolean canConsume(Parameter parameter) { return false; } @Override public ArgumentContribution contribute(MethodParametersAccessor parametersAccessor) { return new ArgumentContribution(-1, asString()); } } private static class NamedParameter extends CommandSegment { private final String name; public NamedParameter(String name) { LettuceAssert.notEmpty(name, "Parameter name must not be empty"); this.name = name; } @Override public String asString() { return name; } @Override public boolean canConsume(Parameter parameter) { return parameter.getName() != null && parameter.getName().equals(name); } @Override public ArgumentContribution contribute(MethodParametersAccessor parametersAccessor) { int index = parametersAccessor.resolveParameterIndex(name); return new ArgumentContribution(index, parametersAccessor.getBindableValue(index)); } } private static class IndexedParameter extends CommandSegment { private final int index; public IndexedParameter(int index) { LettuceAssert.isTrue(index >= 0, "Parameter index must be non-negative starting at 0"); this.index = index; } @Override public String asString() { return Integer.toString(index); } @Override public boolean canConsume(Parameter parameter) { return parameter.getParameterIndex() == index; } @Override public ArgumentContribution contribute(MethodParametersAccessor parametersAccessor) { return new ArgumentContribution(index, parametersAccessor.getBindableValue(index)); } } public static class ArgumentContribution { private final int parameterIndex; private final Object value; ArgumentContribution(int parameterIndex, Object value) { this.parameterIndex = parameterIndex; this.value = value; } public int getParameterIndex() { return parameterIndex; } public Object getValue() { return value; } } }
StringBuffer sb = new StringBuffer(); sb.append(getClass().getSimpleName()); sb.append(" ").append(asString()); return sb.toString();
967
47
1,014
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/segment/CommandSegments.java
StringCommandType
toString
class StringCommandType implements ProtocolKeyword { private final byte[] commandTypeBytes; private final String commandType; StringCommandType(String commandType) { this.commandType = commandType; this.commandTypeBytes = commandType.getBytes(); } @Override public byte[] getBytes() { return commandTypeBytes; } @Override public String name() { return commandType; } @Override public String toString() { return name(); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof StringCommandType)) return false; StringCommandType that = (StringCommandType) o; return commandType.equals(that.commandType); } @Override public int hashCode() { return commandType.hashCode(); } } @Override public String toString() {<FILL_FUNCTION_BODY>
StringBuilder sb = new StringBuilder(); sb.append(getCommandType().name()); for (CommandSegment segment : segments) { sb.append(' ').append(segment); } return sb.toString();
265
61
326
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/support/AnnotationParameterNameDiscoverer.java
AnnotationParameterNameDiscoverer
getParameterNames
class AnnotationParameterNameDiscoverer implements ParameterNameDiscoverer { @Override public String[] getParameterNames(Method method) { if (method.getParameterCount() == 0) { return new String[0]; } return doGetParameterNames(method.getParameterAnnotations()); } @Override public String[] getParameterNames(Constructor<?> ctor) {<FILL_FUNCTION_BODY>} protected String[] doGetParameterNames(Annotation[][] parameterAnnotations) { List<String> names = new ArrayList<>(); for (int i = 0; i < parameterAnnotations.length; i++) { boolean foundParam = false; for (int j = 0; j < parameterAnnotations[i].length; j++) { if (parameterAnnotations[i][j].annotationType().equals(Param.class)) { foundParam = true; Param param = (Param) parameterAnnotations[i][j]; names.add(param.value()); break; } } if (!foundParam) { return null; } } return names.toArray(new String[names.size()]); } }
if (ctor.getParameterCount() == 0) { return new String[0]; } return doGetParameterNames(ctor.getParameterAnnotations());
310
45
355
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/support/ClassTypeInformation.java
ClassTypeInformation
getUserClass
class ClassTypeInformation<S> extends TypeDiscoverer<S> { public static final ClassTypeInformation<Collection> COLLECTION = new ClassTypeInformation(Collection.class); public static final ClassTypeInformation<List> LIST = new ClassTypeInformation(List.class); public static final ClassTypeInformation<Set> SET = new ClassTypeInformation(Set.class); public static final ClassTypeInformation<Map> MAP = new ClassTypeInformation(Map.class); public static final ClassTypeInformation<Object> OBJECT = new ClassTypeInformation(Object.class); private static final Map<Class<?>, Reference<ClassTypeInformation<?>>> CACHE = Collections .synchronizedMap(new WeakHashMap<Class<?>, Reference<ClassTypeInformation<?>>>()); static { for (ClassTypeInformation<?> info : Arrays.asList(COLLECTION, LIST, SET, MAP, OBJECT)) { CACHE.put(info.getType(), new WeakReference<>(info)); } } private final Class<S> type; /** * Simple factory method to easily create new instances of {@link ClassTypeInformation}. * * @param <S> * @param type must not be {@code null}. * @return */ public static <S> ClassTypeInformation<S> from(Class<S> type) { LettuceAssert.notNull(type, "Type must not be null!"); Reference<ClassTypeInformation<?>> cachedReference = CACHE.get(type); TypeInformation<?> cachedTypeInfo = cachedReference == null ? null : cachedReference.get(); if (cachedTypeInfo != null) { return (ClassTypeInformation<S>) cachedTypeInfo; } ClassTypeInformation<S> result = new ClassTypeInformation<S>(type); CACHE.put(type, new WeakReference<ClassTypeInformation<?>>(result)); return result; } /** * Creates a {@link TypeInformation} from the given method's return type. * * @param method must not be {@code null}. * @return */ public static <S> TypeInformation<S> fromReturnTypeOf(Method method) { LettuceAssert.notNull(method, "Method must not be null!"); return new ClassTypeInformation(method.getDeclaringClass()).createInfo(method.getGenericReturnType()); } /** * Creates a {@link TypeInformation} from the given method's parameter type. * * @param method must not be {@code null}. * @return */ public static <S> TypeInformation<S> fromMethodParameter(Method method, int index) { LettuceAssert.notNull(method, "Method must not be null!"); return new ClassTypeInformation(method.getDeclaringClass()).createInfo(method.getGenericParameterTypes()[index]); } /** * Creates {@link ClassTypeInformation} for the given type. * * @param type */ ClassTypeInformation(Class<S> type) { super(getUserClass(type), getTypeVariableMap(type)); this.type = type; } /** * Return the user-defined class for the given class: usually simply the given class, but the original class in case of a * CGLIB-generated subclass. * * @param clazz the class to check * @return the user-defined class */ private static Class<?> getUserClass(Class<?> clazz) {<FILL_FUNCTION_BODY>} /** * Little helper to allow us to create a generified map, actually just to satisfy the compiler. * * @param type must not be {@code null}. * @return */ private static Map<TypeVariable<?>, Type> getTypeVariableMap(Class<?> type) { return getTypeVariableMap(type, new HashSet<Type>()); } @SuppressWarnings("deprecation") private static Map<TypeVariable<?>, Type> getTypeVariableMap(Class<?> type, Collection<Type> visited) { if (visited.contains(type)) { return Collections.emptyMap(); } else { visited.add(type); } Map<TypeVariable, Type> source = GenericTypeResolver.getTypeVariableMap(type); Map<TypeVariable<?>, Type> map = new HashMap<>(source.size()); for (Entry<TypeVariable, Type> entry : source.entrySet()) { Type value = entry.getValue(); map.put(entry.getKey(), entry.getValue()); if (value instanceof Class) { map.putAll(getTypeVariableMap((Class<?>) value, visited)); } } return map; } @Override public Class<S> getType() { return type; } @Override public ClassTypeInformation<?> getRawTypeInformation() { return this; } @Override public boolean isAssignableFrom(TypeInformation<?> target) { return getType().isAssignableFrom(target.getType()); } @Override public String toString() { return type.getName(); } }
if (clazz != null && clazz.getName().contains(LettuceClassUtils.CGLIB_CLASS_SEPARATOR)) { Class<?> superclass = clazz.getSuperclass(); if (superclass != null && Object.class != superclass) { return superclass; } } return clazz;
1,353
90
1,443
<methods>public boolean equals(java.lang.Object) ,public TypeInformation<?> getActualType() ,public final TypeInformation<?> getComponentType() ,public java.lang.reflect.Type getGenericType() ,public TypeInformation<?> getMapValueType() ,public List<TypeInformation<?>> getParameterTypes(Constructor<?>) ,public List<TypeInformation<?>> getParameterTypes(java.lang.reflect.Method) ,public ClassTypeInformation<?> getRawTypeInformation() ,public TypeInformation<?> getReturnType(java.lang.reflect.Method) ,public TypeInformation<?> getSuperTypeInformation(Class<?>) ,public Class<S> getType() ,public TypeInformation<?> getTypeArgument(Class<?>, int) ,public List<TypeInformation<?>> getTypeArguments() ,public Map<TypeVariable<?>,java.lang.reflect.Type> getTypeVariableMap() ,public int hashCode() ,public boolean isAssignableFrom(TypeInformation<?>) ,public boolean isCollectionLike() ,public boolean isMap() <variables>private TypeInformation<?> componentType,private boolean componentTypeResolved,private final non-sealed int hashCode,private Class<S> resolvedType,private final non-sealed java.lang.reflect.Type type,private final non-sealed Map<TypeVariable<?>,java.lang.reflect.Type> typeVariableMap,private TypeInformation<?> valueType,private boolean valueTypeResolved
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/support/CompositeParameterNameDiscoverer.java
CompositeParameterNameDiscoverer
getParameterNames
class CompositeParameterNameDiscoverer implements ParameterNameDiscoverer { private Collection<ParameterNameDiscoverer> parameterNameDiscoverers; public CompositeParameterNameDiscoverer(ParameterNameDiscoverer... parameterNameDiscoverers) { this(Arrays.asList(parameterNameDiscoverers)); } public CompositeParameterNameDiscoverer(Collection<ParameterNameDiscoverer> parameterNameDiscoverers) { this.parameterNameDiscoverers = parameterNameDiscoverers; } @Override public String[] getParameterNames(Method method) {<FILL_FUNCTION_BODY>} @Override public String[] getParameterNames(Constructor<?> ctor) { for (ParameterNameDiscoverer parameterNameDiscoverer : parameterNameDiscoverers) { String[] parameterNames = parameterNameDiscoverer.getParameterNames(ctor); if (parameterNames != null) { return parameterNames; } } return null; } }
for (ParameterNameDiscoverer parameterNameDiscoverer : parameterNameDiscoverers) { String[] parameterNames = parameterNameDiscoverer.getParameterNames(method); if (parameterNames != null) { return parameterNames; } } return null;
254
74
328
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/support/GenericTypeResolver.java
GenericTypeResolver
resolveTypeArguments
class GenericTypeResolver { /** * Build a mapping of {@link TypeVariable#getName TypeVariable names} to {@link Class concrete classes} for the specified * {@link Class}. Searches all super types, enclosing types and interfaces. */ @SuppressWarnings("rawtypes") public static Map<TypeVariable, Type> getTypeVariableMap(Class<?> clazz) { Map<TypeVariable, Type> typeVariableMap = new HashMap<TypeVariable, Type>(); buildTypeVariableMap(ResolvableType.forClass(clazz), typeVariableMap); return typeVariableMap; } /** * Resolve the type arguments of the given generic interface against the given target class which is assumed to implement * the generic interface and possibly declare concrete types for its type variables. * * @param clazz the target class to check against * @param genericIfc the generic interface or superclass to resolve the type argument from * @return the resolved type of each argument, with the array size matching the number of actual type arguments, or * {@code null} if not resolvable */ public static Class<?>[] resolveTypeArguments(Class<?> clazz, Class<?> genericIfc) {<FILL_FUNCTION_BODY>} @SuppressWarnings("rawtypes") private static void buildTypeVariableMap(ResolvableType type, Map<TypeVariable, Type> typeVariableMap) { if (type != ResolvableType.NONE) { if (type.getType() instanceof ParameterizedType) { TypeVariable<?>[] variables = type.resolve().getTypeParameters(); for (int i = 0; i < variables.length; i++) { ResolvableType generic = type.getGeneric(i); while (generic.getType() instanceof TypeVariable<?>) { generic = generic.resolveType(); } if (generic != ResolvableType.NONE) { typeVariableMap.put(variables[i], generic.getType()); } } } buildTypeVariableMap(type.getSuperType(), typeVariableMap); for (ResolvableType interfaceType : type.getInterfaces()) { buildTypeVariableMap(interfaceType, typeVariableMap); } if (type.resolve().isMemberClass()) { buildTypeVariableMap(ResolvableType.forClass(type.resolve().getEnclosingClass()), typeVariableMap); } } } }
ResolvableType type = ResolvableType.forClass(clazz).as(genericIfc); if (!type.hasGenerics() || type.isEntirelyUnresolvable()) { return null; } return type.resolveGenerics(Object.class);
614
71
685
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/support/ParametrizedTypeInformation.java
ParametrizedTypeInformation
isAssignableFrom
class ParametrizedTypeInformation<T> extends ParentTypeAwareTypeInformation<T> { private final ParameterizedType type; private Boolean resolved; /** * Creates a new {@link ParametrizedTypeInformation} for the given {@link Type} and parent {@link TypeDiscoverer}. * * @param type must not be {@code null} * @param parent must not be {@code null} */ public ParametrizedTypeInformation(ParameterizedType type, TypeDiscoverer<?> parent, Map<TypeVariable<?>, Type> typeVariableMap) { super(type, parent, typeVariableMap); this.type = type; } @Override protected TypeInformation<?> doGetMapValueType() { if (Map.class.isAssignableFrom(getType())) { Type[] arguments = type.getActualTypeArguments(); if (arguments.length > 1) { return createInfo(arguments[1]); } } Class<?> rawType = getType(); Set<Type> supertypes = new HashSet<Type>(); supertypes.add(rawType.getGenericSuperclass()); supertypes.addAll(Arrays.asList(rawType.getGenericInterfaces())); for (Type supertype : supertypes) { Class<?> rawSuperType = resolveClass(supertype); if (Map.class.isAssignableFrom(rawSuperType)) { ParameterizedType parameterizedSupertype = (ParameterizedType) supertype; Type[] arguments = parameterizedSupertype.getActualTypeArguments(); return createInfo(arguments[1]); } } return super.doGetMapValueType(); } @Override public List<TypeInformation<?>> getTypeArguments() { List<TypeInformation<?>> result = new ArrayList<>(); for (Type argument : type.getActualTypeArguments()) { result.add(createInfo(argument)); } return result; } @Override public boolean isAssignableFrom(TypeInformation<?> target) {<FILL_FUNCTION_BODY>} @Override protected TypeInformation<?> doGetComponentType() { return createInfo(type.getActualTypeArguments()[0]); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ParametrizedTypeInformation)) { return false; } ParametrizedTypeInformation<?> that = (ParametrizedTypeInformation<?>) obj; if (this.isResolvedCompletely() && that.isResolvedCompletely()) { return this.type.equals(that.type); } return super.equals(obj); } @Override public int hashCode() { return isResolvedCompletely() ? this.type.hashCode() : super.hashCode(); } @Override public String toString() { return String.format("%s<%s>", getType().getName(), LettuceStrings.collectionToDelimitedString(getTypeArguments(), ",", "", "")); } private boolean isResolvedCompletely() { if (resolved != null) { return resolved; } Type[] typeArguments = type.getActualTypeArguments(); if (typeArguments.length == 0) { return cacheAndReturn(false); } for (Type typeArgument : typeArguments) { TypeInformation<?> info = createInfo(typeArgument); if (info instanceof ParametrizedTypeInformation) { if (!((ParametrizedTypeInformation<?>) info).isResolvedCompletely()) { return cacheAndReturn(false); } } if (!(info instanceof ClassTypeInformation)) { return cacheAndReturn(false); } } return cacheAndReturn(true); } private boolean cacheAndReturn(boolean resolved) { this.resolved = resolved; return resolved; } }
if (this.equals(target)) { return true; } Class<T> rawType = getType(); Class<?> rawTargetType = target.getType(); if (!rawType.isAssignableFrom(rawTargetType)) { return false; } TypeInformation<?> otherTypeInformation = rawType.equals(rawTargetType) ? target : target.getSuperTypeInformation(rawType); List<TypeInformation<?>> myParameters = getTypeArguments(); List<TypeInformation<?>> typeParameters = otherTypeInformation.getTypeArguments(); if (myParameters.size() != typeParameters.size()) { return false; } for (int i = 0; i < myParameters.size(); i++) { if (myParameters.get(i) instanceof WildcardTypeInformation) { if (!myParameters.get(i).isAssignableFrom(typeParameters.get(i))) { return false; } } else { if (!myParameters.get(i).getType().equals(typeParameters.get(i).getType())) { return false; } if (!myParameters.get(i).isAssignableFrom(typeParameters.get(i))) { return false; } } } return true;
1,062
337
1,399
<methods>public boolean equals(java.lang.Object) ,public int hashCode() <variables>private int hashCode,private final non-sealed TypeDiscoverer<?> parent
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/support/ParentTypeAwareTypeInformation.java
ParentTypeAwareTypeInformation
equals
class ParentTypeAwareTypeInformation<S> extends TypeDiscoverer<S> { private final TypeDiscoverer<?> parent; private int hashCode; /** * Creates a new {@link ParentTypeAwareTypeInformation}. * * @param type must not be {@code null}. * @param parent must not be {@code null}. * @param map must not be {@code null}. */ protected ParentTypeAwareTypeInformation(Type type, TypeDiscoverer<?> parent, Map<TypeVariable<?>, Type> map) { super(type, mergeMaps(parent, map)); this.parent = parent; } /** * Merges the type variable maps of the given parent with the new map. * * @param parent must not be {@code null}. * @param map must not be {@code null}. * @return */ private static Map<TypeVariable<?>, Type> mergeMaps(TypeDiscoverer<?> parent, Map<TypeVariable<?>, Type> map) { Map<TypeVariable<?>, Type> typeVariableMap = new HashMap<TypeVariable<?>, Type>(); typeVariableMap.putAll(map); typeVariableMap.putAll(parent.getTypeVariableMap()); return typeVariableMap; } @Override protected TypeInformation<?> createInfo(Type fieldType) { if (parent.getType().equals(fieldType)) { return parent; } return super.createInfo(fieldType); } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { if (this.hashCode == 0) { this.hashCode = super.hashCode() + 31 * parent.hashCode(); } return this.hashCode; } }
if (!super.equals(obj)) { return false; } if (!this.getClass().equals(obj.getClass())) { return false; } ParentTypeAwareTypeInformation<?> that = (ParentTypeAwareTypeInformation<?>) obj; return this.parent == null ? that.parent == null : this.parent.equals(that.parent);
488
101
589
<methods>public boolean equals(java.lang.Object) ,public TypeInformation<?> getActualType() ,public final TypeInformation<?> getComponentType() ,public java.lang.reflect.Type getGenericType() ,public TypeInformation<?> getMapValueType() ,public List<TypeInformation<?>> getParameterTypes(Constructor<?>) ,public List<TypeInformation<?>> getParameterTypes(java.lang.reflect.Method) ,public ClassTypeInformation<?> getRawTypeInformation() ,public TypeInformation<?> getReturnType(java.lang.reflect.Method) ,public TypeInformation<?> getSuperTypeInformation(Class<?>) ,public Class<S> getType() ,public TypeInformation<?> getTypeArgument(Class<?>, int) ,public List<TypeInformation<?>> getTypeArguments() ,public Map<TypeVariable<?>,java.lang.reflect.Type> getTypeVariableMap() ,public int hashCode() ,public boolean isAssignableFrom(TypeInformation<?>) ,public boolean isCollectionLike() ,public boolean isMap() <variables>private TypeInformation<?> componentType,private boolean componentTypeResolved,private final non-sealed int hashCode,private Class<S> resolvedType,private final non-sealed java.lang.reflect.Type type,private final non-sealed Map<TypeVariable<?>,java.lang.reflect.Type> typeVariableMap,private TypeInformation<?> valueType,private boolean valueTypeResolved
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/support/StandardReflectionParameterNameDiscoverer.java
StandardReflectionParameterNameDiscoverer
getParameterNames
class StandardReflectionParameterNameDiscoverer implements ParameterNameDiscoverer { @Override public String[] getParameterNames(Method method) { Parameter[] parameters = method.getParameters(); String[] parameterNames = new String[parameters.length]; for (int i = 0; i < parameters.length; i++) { Parameter param = parameters[i]; if (!param.isNamePresent()) { return null; } parameterNames[i] = param.getName(); } return parameterNames; } @Override public String[] getParameterNames(Constructor<?> ctor) {<FILL_FUNCTION_BODY>} }
Parameter[] parameters = ctor.getParameters(); String[] parameterNames = new String[parameters.length]; for (int i = 0; i < parameters.length; i++) { Parameter param = parameters[i]; if (!param.isNamePresent()) { return null; } parameterNames[i] = param.getName(); } return parameterNames;
171
99
270
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/support/TypeVariableTypeInformation.java
TypeVariableTypeInformation
equals
class TypeVariableTypeInformation<T> extends ParentTypeAwareTypeInformation<T> { private final TypeVariable<?> variable; private final Type owningType; /** * Creates a bew {@link TypeVariableTypeInformation} for the given {@link TypeVariable} owning {@link Type} and parent * {@link TypeDiscoverer}. * * @param variable must not be {@code null} * @param owningType must not be {@code null} * @param parent can be be {@code null} * @param typeVariableMap must not be {@code null} */ public TypeVariableTypeInformation(TypeVariable<?> variable, Type owningType, TypeDiscoverer<?> parent, Map<TypeVariable<?>, Type> typeVariableMap) { super(variable, parent, typeVariableMap); LettuceAssert.notNull(variable, "TypeVariable must not be null"); this.variable = variable; this.owningType = owningType; } @Override public Class<T> getType() { int index = getIndex(variable); if (owningType instanceof ParameterizedType && index != -1) { Type fieldType = ((ParameterizedType) owningType).getActualTypeArguments()[index]; return resolveClass(fieldType); } return resolveClass(variable); } /** * Returns the index of the type parameter binding the given {@link TypeVariable}. * * @param variable * @return */ private int getIndex(TypeVariable<?> variable) { Class<?> rawType = resolveClass(owningType); TypeVariable<?>[] typeParameters = rawType.getTypeParameters(); for (int i = 0; i < typeParameters.length; i++) { if (variable.equals(typeParameters[i])) { return i; } } return -1; } @Override public List<TypeInformation<?>> getTypeArguments() { List<TypeInformation<?>> result = new ArrayList<>(); Type type = resolveType(variable); if (type instanceof ParameterizedType) { for (Type typeArgument : ((ParameterizedType) type).getActualTypeArguments()) { result.add(createInfo(typeArgument)); } } return result; } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(super.hashCode(), variable, owningType); } @Override public String toString() { return variable.getName(); } public String getVariableName() { return variable.getName(); } }
if (obj == this) { return true; } if (!(obj instanceof TypeVariableTypeInformation)) { return false; } TypeVariableTypeInformation<?> that = (TypeVariableTypeInformation<?>) obj; return getType().equals(that.getType());
708
80
788
<methods>public boolean equals(java.lang.Object) ,public int hashCode() <variables>private int hashCode,private final non-sealed TypeDiscoverer<?> parent
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/support/TypeWrapper.java
MethodInvokeTypeProvider
getType
class MethodInvokeTypeProvider implements TypeProvider { private final TypeProvider provider; private final String methodName; private final int index; private transient Method method; private transient volatile Object result; public MethodInvokeTypeProvider(TypeProvider provider, Method method, int index) { this.provider = provider; this.methodName = method.getName(); this.index = index; this.method = method; } @Override public Type getType() {<FILL_FUNCTION_BODY>} @Override public Object getSource() { return null; } }
Object result = this.result; if (result == null) { // Lazy invocation of the target method on the provided type result = ReflectionUtils.invokeMethod(this.method, this.provider.getType()); // Cache the result for further calls to getType() this.result = result; } return (result instanceof Type[] ? ((Type[]) result)[this.index] : (Type) result);
163
107
270
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/dynamic/support/WildcardTypeInformation.java
WildcardTypeInformation
isAssignableFrom
class WildcardTypeInformation<S> extends TypeDiscoverer<S> { private final WildcardType type; /** * Creates a new {@link WildcardTypeInformation} for the given type, type variable map. * * @param type must not be {@code null}. * @param typeVariableMap must not be {@code null}. */ protected WildcardTypeInformation(WildcardType type, Map<TypeVariable<?>, Type> typeVariableMap) { super(type, typeVariableMap); this.type = type; } @Override public boolean isAssignableFrom(TypeInformation<?> target) {<FILL_FUNCTION_BODY>} public List<TypeInformation<?>> getUpperBounds() { return getBounds(type.getUpperBounds()); } public List<TypeInformation<?>> getLowerBounds() { return getBounds(type.getLowerBounds()); } private List<TypeInformation<?>> getBounds(Type[] bounds) { List<TypeInformation<?>> typeInformations = new ArrayList<>(bounds.length); Arrays.stream(bounds).map(this::createInfo).forEach(typeInformations::add); return typeInformations; } }
for (TypeInformation<?> lowerBound : getLowerBounds()) { if (!target.isAssignableFrom(lowerBound)) { return false; } } for (TypeInformation<?> upperBound : getUpperBounds()) { if (!upperBound.isAssignableFrom(target)) { return false; } } return true;
324
100
424
<methods>public boolean equals(java.lang.Object) ,public TypeInformation<?> getActualType() ,public final TypeInformation<?> getComponentType() ,public java.lang.reflect.Type getGenericType() ,public TypeInformation<?> getMapValueType() ,public List<TypeInformation<?>> getParameterTypes(Constructor<?>) ,public List<TypeInformation<?>> getParameterTypes(java.lang.reflect.Method) ,public ClassTypeInformation<?> getRawTypeInformation() ,public TypeInformation<?> getReturnType(java.lang.reflect.Method) ,public TypeInformation<?> getSuperTypeInformation(Class<?>) ,public Class<S> getType() ,public TypeInformation<?> getTypeArgument(Class<?>, int) ,public List<TypeInformation<?>> getTypeArguments() ,public Map<TypeVariable<?>,java.lang.reflect.Type> getTypeVariableMap() ,public int hashCode() ,public boolean isAssignableFrom(TypeInformation<?>) ,public boolean isCollectionLike() ,public boolean isMap() <variables>private TypeInformation<?> componentType,private boolean componentTypeResolved,private final non-sealed int hashCode,private Class<S> resolvedType,private final non-sealed java.lang.reflect.Type type,private final non-sealed Map<TypeVariable<?>,java.lang.reflect.Type> typeVariableMap,private TypeInformation<?> valueType,private boolean valueTypeResolved
redis_lettuce
lettuce/src/main/java/io/lettuce/core/event/DefaultEventBus.java
DefaultEventBus
publish
class DefaultEventBus implements EventBus { private final Sinks.Many<Event> bus; private final Scheduler scheduler; private final EventRecorder recorder = EventRecorder.getInstance(); public DefaultEventBus(Scheduler scheduler) { this.bus = Sinks.many().multicast().directBestEffort(); this.scheduler = scheduler; } @Override public Flux<Event> get() { return bus.asFlux().onBackpressureDrop().publishOn(scheduler); } @Override public void publish(Event event) {<FILL_FUNCTION_BODY>} }
recorder.record(event); Sinks.EmitResult emitResult; while ((emitResult = bus.tryEmitNext(event)) == Sinks.EmitResult.FAIL_NON_SERIALIZED) { // busy-loop } if (emitResult != Sinks.EmitResult.FAIL_ZERO_SUBSCRIBER) { emitResult.orThrow(); }
170
111
281
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/event/DefaultEventPublisherOptions.java
Builder
eventEmitInterval
class Builder { private Duration eventEmitInterval = DEFAULT_EMIT_INTERVAL_DURATION; private Builder() { } /** * Sets the emit interval and the interval unit. Event emission will be disabled if the {@code eventEmitInterval} is set * to 0}. Defaults to 10} {@link TimeUnit#MINUTES}. See {@link DefaultEventPublisherOptions#DEFAULT_EMIT_INTERVAL} * {@link DefaultEventPublisherOptions#DEFAULT_EMIT_INTERVAL_UNIT}. * * @param eventEmitInterval the event interval, must be greater or equal to 0} * @return this * @since 5.0 */ public Builder eventEmitInterval(Duration eventEmitInterval) {<FILL_FUNCTION_BODY>} /** * Sets the emit interval and the interval unit. Event emission will be disabled if the {@code eventEmitInterval} is set * to 0}. Defaults to 10} {@link TimeUnit#MINUTES}. See {@link DefaultEventPublisherOptions#DEFAULT_EMIT_INTERVAL} * {@link DefaultEventPublisherOptions#DEFAULT_EMIT_INTERVAL_UNIT}. * * @param eventEmitInterval the event interval, must be greater or equal to 0} * @param eventEmitIntervalUnit the {@link TimeUnit} for the interval, must not be null * @return this * @deprecated since 5.0, use {@link #eventEmitInterval(Duration)} */ @Deprecated public Builder eventEmitInterval(long eventEmitInterval, TimeUnit eventEmitIntervalUnit) { LettuceAssert.isTrue(eventEmitInterval >= 0, "EventEmitInterval must be greater or equal to 0"); LettuceAssert.notNull(eventEmitIntervalUnit, "EventEmitIntervalUnit must not be null"); return eventEmitInterval(Duration.ofNanos(eventEmitIntervalUnit.toNanos(eventEmitInterval))); } /** * * @return a new instance of {@link DefaultEventPublisherOptions}. */ public DefaultEventPublisherOptions build() { return new DefaultEventPublisherOptions(this); } }
LettuceAssert.notNull(eventEmitInterval, "EventEmitInterval must not be null"); LettuceAssert.isTrue(!eventEmitInterval.isNegative(), "EventEmitInterval must be greater or equal to 0"); this.eventEmitInterval = eventEmitInterval; return this;
556
82
638
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/event/command/CommandBaseEvent.java
CommandBaseEvent
toString
class CommandBaseEvent { private final RedisCommand<Object, Object, Object> command; private final Map<String, Object> context; protected CommandBaseEvent(RedisCommand<Object, Object, Object> command, Map<String, Object> context) { this.command = command; this.context = context; } /** * @return the actual command. */ public RedisCommand<Object, Object, Object> getCommand() { return command; } /** * @return shared context. */ public Map<String, Object> getContext() { synchronized (this) { return context; } } @Override public String toString() {<FILL_FUNCTION_BODY>} }
StringBuffer sb = new StringBuffer(); sb.append(getClass().getSimpleName()); sb.append(" [command=").append(command); sb.append(", context=").append(context); sb.append(']'); return sb.toString();
200
69
269
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/event/connection/ConnectionEventSupport.java
ConnectionEventSupport
toString
class ConnectionEventSupport implements ConnectionEvent { private final String redisUri; private final String epId; private final String channelId; private final SocketAddress local; private final SocketAddress remote; ConnectionEventSupport(SocketAddress local, SocketAddress remote) { this(null, null, null, local, remote); } ConnectionEventSupport(String redisUri, String epId, String channelId, SocketAddress local, SocketAddress remote) { LettuceAssert.notNull(local, "Local must not be null"); LettuceAssert.notNull(remote, "Remote must not be null"); this.redisUri = redisUri; this.epId = epId; this.channelId = channelId; this.local = local; this.remote = remote; } /** * Returns the local address. * * @return the local address */ public SocketAddress localAddress() { return local; } /** * Returns the remote address. * * @return the remote address */ public SocketAddress remoteAddress() { return remote; } /** * @return the underlying Redis URI. */ String getRedisUri() { return redisUri; } /** * @return endpoint identifier. */ String getEpId() { return epId; } /** * @return channel identifier. */ String getChannelId() { return channelId; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append(local); sb.append(" -> ").append(remote); sb.append(']'); return sb.toString();
428
71
499
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/event/jfr/JfrEventRecorder.java
JfrEventRecorder
createEvent
class JfrEventRecorder implements EventRecorder { private final Map<Class<?>, Constructor<?>> constructorMap = new HashMap<>(); @Override public void record(Event event) { LettuceAssert.notNull(event, "Event must not be null"); jdk.jfr.Event jfrEvent = createEvent(event); if (jfrEvent != null) { jfrEvent.commit(); } } @Override public RecordableEvent start(Event event) { LettuceAssert.notNull(event, "Event must not be null"); jdk.jfr.Event jfrEvent = createEvent(event); if (jfrEvent != null) { jfrEvent.begin(); return new JfrRecordableEvent(jfrEvent); } return NoOpEventRecorder.INSTANCE; } private Constructor<?> getEventConstructor(Event event) throws NoSuchMethodException { Constructor<?> constructor; synchronized (constructorMap) { constructor = constructorMap.get(event.getClass()); } if (constructor == null) { String jfrClassName = event.getClass().getPackage().getName() + ".Jfr" + event.getClass().getSimpleName(); Class<?> eventClass = LettuceClassUtils.findClass(jfrClassName); if (eventClass == null) { constructor = Object.class.getConstructor(); } else { constructor = eventClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); } synchronized (constructorMap) { constructorMap.put(event.getClass(), constructor); } } return constructor; } private jdk.jfr.Event createEvent(Event event) {<FILL_FUNCTION_BODY>} static class JfrRecordableEvent implements RecordableEvent { private final jdk.jfr.Event jfrEvent; public JfrRecordableEvent(jdk.jfr.Event jfrEvent) { this.jfrEvent = jfrEvent; } @Override public void record() { jfrEvent.end(); jfrEvent.commit(); } } }
try { Constructor<?> constructor = getEventConstructor(event); if (constructor.getDeclaringClass() == Object.class) { return null; } return (jdk.jfr.Event) constructor.newInstance(event); } catch (ReflectiveOperationException e) { throw new IllegalStateException(e); }
585
95
680
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/event/metrics/DefaultCommandLatencyEventPublisher.java
DefaultCommandLatencyEventPublisher
shutdown
class DefaultCommandLatencyEventPublisher implements MetricEventPublisher { private final EventExecutorGroup eventExecutorGroup; private final EventPublisherOptions options; private final EventBus eventBus; private final CommandLatencyCollector commandLatencyCollector; private final Runnable EMITTER = this::emitMetricsEvent; private volatile ScheduledFuture<?> scheduledFuture; public DefaultCommandLatencyEventPublisher(EventExecutorGroup eventExecutorGroup, EventPublisherOptions options, EventBus eventBus, CommandLatencyCollector commandLatencyCollector) { this.eventExecutorGroup = eventExecutorGroup; this.options = options; this.eventBus = eventBus; this.commandLatencyCollector = commandLatencyCollector; if (!options.eventEmitInterval().isZero()) { scheduledFuture = this.eventExecutorGroup.scheduleAtFixedRate(EMITTER, options.eventEmitInterval().toMillis(), options.eventEmitInterval().toMillis(), TimeUnit.MILLISECONDS); } } @Override public boolean isEnabled() { return !options.eventEmitInterval().isZero() && scheduledFuture != null; } @Override public void shutdown() {<FILL_FUNCTION_BODY>} @Override public void emitMetricsEvent() { if (!isEnabled() || !commandLatencyCollector.isEnabled()) { return; } eventBus.publish(new CommandLatencyEvent(commandLatencyCollector.retrieveMetrics())); } }
if (scheduledFuture != null) { scheduledFuture.cancel(true); scheduledFuture = null; }
398
35
433
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/internal/AbstractInvocationHandler.java
MethodTranslator
createMethodMap
class MethodTranslator { private static final WeakHashMap<Class<?>, MethodTranslator> TRANSLATOR_MAP = new WeakHashMap<>(32); private final Map<Method, Method> map; private MethodTranslator(Class<?> delegate, Class<?>... methodSources) { map = createMethodMap(delegate, methodSources); } public static MethodTranslator of(Class<?> delegate, Class<?>... methodSources) { synchronized (TRANSLATOR_MAP) { return TRANSLATOR_MAP.computeIfAbsent(delegate, key -> new MethodTranslator(key, methodSources)); } } private Map<Method, Method> createMethodMap(Class<?> delegate, Class<?>[] methodSources) {<FILL_FUNCTION_BODY>} private Collection<? extends Method> getMethods(Class<?> sourceClass) { Set<Method> result = new HashSet<>(); Class<?> searchType = sourceClass; while (searchType != null && searchType != Object.class) { result.addAll(filterPublicMethods(Arrays.asList(sourceClass.getDeclaredMethods()))); if (sourceClass.isInterface()) { Class<?>[] interfaces = sourceClass.getInterfaces(); for (Class<?> interfaceClass : interfaces) { result.addAll(getMethods(interfaceClass)); } searchType = null; } else { searchType = searchType.getSuperclass(); } } return result; } private Collection<? extends Method> filterPublicMethods(List<Method> methods) { List<Method> result = new ArrayList<>(methods.size()); for (Method method : methods) { if (Modifier.isPublic(method.getModifiers())) { result.add(method); } } return result; } public Method get(Method key) { Method result = map.get(key); if (result != null) { return result; } throw new IllegalStateException("Cannot find source method " + key); } }
Map<Method, Method> map; List<Method> methods = new ArrayList<>(); for (Class<?> sourceClass : methodSources) { methods.addAll(getMethods(sourceClass)); } map = new HashMap<>(methods.size(), 1.0f); for (Method method : methods) { try { map.put(method, delegate.getMethod(method.getName(), method.getParameterTypes())); } catch (NoSuchMethodException ignore) { } } return map;
571
140
711
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/internal/AsyncConnectionProvider.java
AsyncConnectionProvider
getSynchronizer
class AsyncConnectionProvider<K, T extends AsyncCloseable, F extends CompletionStage<T>> { private final Function<K, F> connectionFactory; private final Map<K, Sync<K, T, F>> connections = new ConcurrentHashMap<>(); private volatile boolean closed; /** * Create a new {@link AsyncConnectionProvider}. * * @param connectionFactory must not be {@code null}. */ @SuppressWarnings("unchecked") public AsyncConnectionProvider(Function<? extends K, ? extends F> connectionFactory) { LettuceAssert.notNull(connectionFactory, "AsyncConnectionProvider must not be null"); this.connectionFactory = (Function<K, F>) connectionFactory; } /** * Request a connection for the given the connection {@code key} and return a {@link CompletionStage} that is notified about * the connection outcome. * * @param key the connection {@code key}, must not be {@code null}. * @return */ public F getConnection(K key) { return getSynchronizer(key).getConnection(); } /** * Obtain a connection to a target given the connection {@code key}. * * @param key the connection {@code key}. * @return */ private Sync<K, T, F> getSynchronizer(K key) {<FILL_FUNCTION_BODY>} /** * Register a connection identified by {@code key}. Overwrites existing entries. * * @param key the connection {@code key}. * @param connection the connection object. */ public void register(K key, T connection) { connections.put(key, new Sync<>(key, connection)); } /** * @return number of established connections. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public int getConnectionCount() { Sync[] syncs = connections.values().toArray(new Sync[0]); int count = 0; for (Sync sync : syncs) { if (sync.isComplete()) { count++; } } return count; } /** * Close all connections. Pending connections are closed using future chaining. */ @SuppressWarnings("unchecked") public CompletableFuture<Void> close() { this.closed = true; List<CompletableFuture<Void>> futures = new ArrayList<>(); forEach((connectionKey, closeable) -> { futures.add(closeable.closeAsync()); connections.remove(connectionKey); }); return Futures.allOf(futures); } /** * Close a connection by its connection {@code key}. Pending connections are closed using future chaining. * * @param key the connection {@code key}, must not be {@code null}. */ public void close(K key) { LettuceAssert.notNull(key, "ConnectionKey must not be null!"); Sync<K, T, F> sync = connections.get(key); if (sync != null) { connections.remove(key); sync.doWithConnection(AsyncCloseable::closeAsync); } } /** * Execute an action for all established and pending connections. * * @param action the action. */ public void forEach(Consumer<? super T> action) { LettuceAssert.notNull(action, "Action must not be null!"); connections.values().forEach(sync -> { if (sync != null) { sync.doWithConnection(action); } }); } /** * Execute an action for all established and pending {@link AsyncCloseable}s. * * @param action the action. */ public void forEach(BiConsumer<? super K, ? super T> action) { connections.forEach((key, sync) -> sync.doWithConnection(action)); } static class Sync<K, T extends AsyncCloseable, F extends CompletionStage<T>> { private static final int PHASE_IN_PROGRESS = 0; private static final int PHASE_COMPLETE = 1; private static final int PHASE_FAILED = 2; private static final int PHASE_CANCELED = 3; @SuppressWarnings({ "rawtypes", "unchecked" }) private static final AtomicIntegerFieldUpdater<Sync> PHASE = AtomicIntegerFieldUpdater.newUpdater(Sync.class, "phase"); // Updated with AtomicIntegerFieldUpdater @SuppressWarnings("unused") private volatile int phase = PHASE_IN_PROGRESS; private volatile T connection; private final K key; private final F future; @SuppressWarnings("unchecked") public Sync(K key, F future) { this.key = key; this.future = (F) future.whenComplete((connection, throwable) -> { if (throwable != null) { if (throwable instanceof CancellationException) { PHASE.compareAndSet(this, PHASE_IN_PROGRESS, PHASE_CANCELED); } PHASE.compareAndSet(this, PHASE_IN_PROGRESS, PHASE_FAILED); } if (PHASE.compareAndSet(this, PHASE_IN_PROGRESS, PHASE_COMPLETE)) { if (connection != null) { Sync.this.connection = connection; } } }); } @SuppressWarnings("unchecked") public Sync(K key, T value) { this.key = key; this.connection = value; this.future = (F) CompletableFuture.completedFuture(value); PHASE.set(this, PHASE_COMPLETE); } public void cancel() { future.toCompletableFuture().cancel(false); doWithConnection(AsyncCloseable::closeAsync); } public F getConnection() { return future; } void doWithConnection(Consumer<? super T> action) { if (isComplete()) { action.accept(connection); } else { future.thenAccept(action); } } void doWithConnection(BiConsumer<? super K, ? super T> action) { if (isComplete()) { action.accept(key, connection); } else { future.thenAccept(c -> action.accept(key, c)); } } private boolean isComplete() { return PHASE.get(this) == PHASE_COMPLETE; } } }
if (closed) { throw new IllegalStateException("ConnectionProvider is already closed"); } Sync<K, T, F> sync = connections.get(key); if (sync != null) { return sync; } AtomicBoolean atomicBoolean = new AtomicBoolean(); sync = connections.computeIfAbsent(key, connectionKey -> { Sync<K, T, F> createdSync = new Sync<>(key, connectionFactory.apply(key)); if (closed) { createdSync.cancel(); } return createdSync; }); if (atomicBoolean.compareAndSet(false, true)) { sync.getConnection().whenComplete((c, t) -> { if (t != null) { connections.remove(key); } }); } return sync;
1,754
226
1,980
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/internal/DefaultMethods.java
DefaultMethods
getLookup
class DefaultMethods { private static final MethodHandleLookup methodHandleLookup = MethodHandleLookup.getMethodHandleLookup(); /** * Lookup a {@link MethodHandle} for a default {@link Method}. * * @param method must be a {@link Method#isDefault() default} {@link Method}. * @return the {@link MethodHandle}. */ public static MethodHandle lookupMethodHandle(Method method) throws ReflectiveOperationException { LettuceAssert.notNull(method, "Method must not be null"); LettuceAssert.isTrue(method.isDefault(), "Method is not a default method"); return methodHandleLookup.lookup(method); } /** * Strategies for {@link MethodHandle} lookup. */ enum MethodHandleLookup { /** * Open (via reflection construction of {@link Lookup}) method handle lookup. Works with Java 8 and with Java 9 * permitting illegal access. */ OPEN { private final Optional<Constructor<Lookup>> constructor = getLookupConstructor(); @Override MethodHandle lookup(Method method) throws ReflectiveOperationException { Constructor<Lookup> constructor = this.constructor .orElseThrow(() -> new IllegalStateException("Could not obtain MethodHandles.lookup constructor")); return constructor.newInstance(method.getDeclaringClass()).unreflectSpecial(method, method.getDeclaringClass()); } @Override boolean isAvailable() { return constructor.isPresent(); } }, /** * Encapsulated {@link MethodHandle} lookup working on Java 9. */ ENCAPSULATED { Method privateLookupIn = findBridgeMethod(); @Override MethodHandle lookup(Method method) throws ReflectiveOperationException { MethodType methodType = MethodType.methodType(method.getReturnType(), method.getParameterTypes()); return getLookup(method.getDeclaringClass()).findSpecial(method.getDeclaringClass(), method.getName(), methodType, method.getDeclaringClass()); } private Method findBridgeMethod() { try { return MethodHandles.class.getDeclaredMethod("privateLookupIn", Class.class, Lookup.class); } catch (ReflectiveOperationException e) { return null; } } private Lookup getLookup(Class<?> declaringClass) {<FILL_FUNCTION_BODY>} @Override boolean isAvailable() { return true; } }; /** * Lookup a {@link MethodHandle} given {@link Method} to look up. * * @param method must not be {@code null}. * @return the method handle. * @throws ReflectiveOperationException */ abstract MethodHandle lookup(Method method) throws ReflectiveOperationException; /** * @return {@code true} if the lookup is available. */ abstract boolean isAvailable(); /** * Obtain the first available {@link MethodHandleLookup}. * * @return the {@link MethodHandleLookup} * @throws IllegalStateException if no {@link MethodHandleLookup} is available. */ public static MethodHandleLookup getMethodHandleLookup() { return Arrays.stream(MethodHandleLookup.values()).filter(MethodHandleLookup::isAvailable).findFirst() .orElseThrow(() -> new IllegalStateException("No MethodHandleLookup available!")); } private static Optional<Constructor<Lookup>> getLookupConstructor() { try { Constructor<Lookup> constructor = Lookup.class.getDeclaredConstructor(Class.class); if (!constructor.isAccessible()) { constructor.setAccessible(true); } return Optional.of(constructor); } catch (Exception ex) { // this is the signal that we are on Java 9 (encapsulated) and can't use the accessible constructor approach. if (ex.getClass().getName().equals("java.lang.reflect.InaccessibleObjectException")) { return Optional.empty(); } throw new IllegalStateException(ex); } } } }
Lookup lookup = MethodHandles.lookup(); if (privateLookupIn != null) { try { return (Lookup) privateLookupIn.invoke(null, declaringClass, lookup); } catch (ReflectiveOperationException e) { return lookup; } } return lookup;
1,068
87
1,155
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/internal/ExceptionFactory.java
ExceptionFactory
isExactSeconds
class ExceptionFactory { private static final DateTimeFormatter MINUTES = new DateTimeFormatterBuilder().appendText(ChronoField.MINUTE_OF_DAY) .appendLiteral(" minute(s)").toFormatter(); private static final DateTimeFormatter SECONDS = new DateTimeFormatterBuilder().appendText(ChronoField.SECOND_OF_DAY) .appendLiteral(" second(s)").toFormatter(); private static final DateTimeFormatter MILLISECONDS = new DateTimeFormatterBuilder().appendText(ChronoField.MILLI_OF_DAY) .appendLiteral(" millisecond(s)").toFormatter(); private ExceptionFactory() { } /** * Create a {@link RedisCommandTimeoutException} with a detail message given the timeout. * * @param timeout the timeout value. * @return the {@link RedisCommandTimeoutException}. */ public static RedisCommandTimeoutException createTimeoutException(Duration timeout) { return new RedisCommandTimeoutException(String.format("Command timed out after %s", formatTimeout(timeout))); } /** * Create a {@link RedisCommandTimeoutException} with a detail message given the message and timeout. * * @param message the detail message. * @param timeout the timeout value. * @return the {@link RedisCommandTimeoutException}. */ public static RedisCommandTimeoutException createTimeoutException(String message, Duration timeout) { return new RedisCommandTimeoutException( String.format("%s. Command timed out after %s", message, formatTimeout(timeout))); } public static String formatTimeout(Duration duration) { if (duration.isZero()) { return "no timeout"; } LocalTime time = LocalTime.MIDNIGHT.plus(duration); if (isExactMinutes(duration)) { return MINUTES.format(time); } if (isExactSeconds(duration)) { return SECONDS.format(time); } if (isExactMillis(duration)) { return MILLISECONDS.format(time); } return String.format("%d ns", duration.toNanos()); } private static boolean isExactMinutes(Duration duration) { return duration.toMillis() % (1000 * 60) == 0 && duration.getNano() == 0; } private static boolean isExactSeconds(Duration duration) {<FILL_FUNCTION_BODY>} private static boolean isExactMillis(Duration duration) { return duration.toNanos() % (1000 * 1000) == 0; } /** * Create a {@link RedisCommandExecutionException} with a detail message. Specific Redis error messages may create subtypes * of {@link RedisCommandExecutionException}. * * @param message the detail message. * @return the {@link RedisCommandExecutionException}. */ public static RedisCommandExecutionException createExecutionException(String message) { return createExecutionException(message, null); } /** * Create a {@link RedisCommandExecutionException} with a detail message and optionally a {@link Throwable cause}. Specific * Redis error messages may create subtypes of {@link RedisCommandExecutionException}. * * @param message the detail message. * @param cause the nested exception, may be {@code null}. * @return the {@link RedisCommandExecutionException}. */ public static RedisCommandExecutionException createExecutionException(String message, Throwable cause) { if (message != null) { if (message.startsWith("BUSY")) { return cause != null ? new RedisBusyException(message, cause) : new RedisBusyException(message); } if (message.startsWith("NOSCRIPT")) { return cause != null ? new RedisNoScriptException(message, cause) : new RedisNoScriptException(message); } if (message.startsWith("LOADING")) { return cause != null ? new RedisLoadingException(message, cause) : new RedisLoadingException(message); } if (message.startsWith("READONLY")) { return cause != null ? new RedisReadOnlyException(message, cause) : new RedisReadOnlyException(message); } return cause != null ? new RedisCommandExecutionException(message, cause) : new RedisCommandExecutionException(message); } return new RedisCommandExecutionException(cause); } }
return duration.toMillis() % (1000) == 0 && duration.getNano() == 0;
1,162
31
1,193
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/internal/Exceptions.java
Exceptions
fromSynchronization
class Exceptions { /** * Unwrap the exception if the given {@link Throwable} is a {@link ExecutionException} or {@link CompletionException}. * * @param t the root cause * @return the unwrapped {@link Throwable#getCause() cause} or the actual {@link Throwable}. */ public static Throwable unwrap(Throwable t) { if (t instanceof ExecutionException || t instanceof CompletionException) { return t.getCause(); } return t; } /** * Prepare an unchecked {@link RuntimeException} that will bubble upstream if thrown by an operator. * * @param t the root cause * @return an unchecked exception that should choose bubbling up over error callback path. */ public static RuntimeException bubble(Throwable t) { Throwable throwableToUse = unwrap(t); if (throwableToUse instanceof TimeoutException) { return new RedisCommandTimeoutException(throwableToUse); } if (throwableToUse instanceof InterruptedException) { Thread.currentThread().interrupt(); return new RedisCommandInterruptedException(throwableToUse); } if (throwableToUse instanceof RedisCommandExecutionException) { return ExceptionFactory.createExecutionException(throwableToUse.getMessage(), throwableToUse); } if (throwableToUse instanceof RedisException) { return (RedisException) throwableToUse; } if (throwableToUse instanceof RuntimeException) { return (RuntimeException) throwableToUse; } return new RedisException(throwableToUse); } /** * Prepare an unchecked {@link RuntimeException} that will bubble upstream for synchronization usage (i.e. on calling * {@link Future#get()}). * * @param t the root cause * @return an unchecked exception that should choose bubbling up over error callback path. */ public static RuntimeException fromSynchronization(Throwable t) {<FILL_FUNCTION_BODY>} }
Throwable throwableToUse = unwrap(t); if (throwableToUse instanceof RedisCommandTimeoutException) { return new RedisCommandTimeoutException(throwableToUse); } if (throwableToUse instanceof RedisCommandExecutionException) { return bubble(throwableToUse); } if (throwableToUse instanceof RuntimeException) { return new RedisException(throwableToUse); } return bubble(throwableToUse);
537
125
662
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/internal/Futures.java
Futures
failed
class Futures { private Futures() { // no instances allowed } /** * Create a composite {@link CompletableFuture} is composed from the given {@code stages}. * * @param stages must not be {@code null}. * @return the composed {@link CompletableFuture}. * @since 5.1.1 */ @SuppressWarnings({ "rawtypes" }) public static CompletableFuture<Void> allOf(Collection<? extends CompletionStage<?>> stages) { LettuceAssert.notNull(stages, "Futures must not be null"); CompletableFuture[] futures = new CompletableFuture[stages.size()]; int index = 0; for (CompletionStage<?> stage : stages) { futures[index++] = stage.toCompletableFuture(); } return CompletableFuture.allOf(futures); } /** * Create a {@link CompletableFuture} that is completed exceptionally with {@code throwable}. * * @param throwable must not be {@code null}. * @return the exceptionally completed {@link CompletableFuture}. */ public static <T> CompletableFuture<T> failed(Throwable throwable) {<FILL_FUNCTION_BODY>} /** * Adapt Netty's {@link ChannelFuture} emitting a {@link Void} result. * * @param future the {@link ChannelFuture} to adapt. * @return the {@link CompletableFuture}. * @since 6.0 */ public static <V> CompletionStage<V> toCompletionStage(io.netty.util.concurrent.Future<V> future) { LettuceAssert.notNull(future, "Future must not be null"); CompletableFuture<V> promise = new CompletableFuture<>(); if (future.isDone() || future.isCancelled()) { if (future.isSuccess()) { promise.complete(null); } else { promise.completeExceptionally(future.cause()); } return promise; } future.addListener(f -> { if (f.isSuccess()) { promise.complete(null); } else { promise.completeExceptionally(f.cause()); } }); return promise; } /** * Adapt Netty's {@link io.netty.util.concurrent.Future} emitting a value result into a {@link CompletableFuture}. * * @param source source {@link io.netty.util.concurrent.Future} emitting signals. * @param target target {@link CompletableFuture}. * @since 6.0 */ public static <V> void adapt(io.netty.util.concurrent.Future<V> source, CompletableFuture<V> target) { source.addListener(f -> { if (f.isSuccess()) { target.complete(null); } else { target.completeExceptionally(f.cause()); } }); if (source.isSuccess()) { target.complete(null); } else if (source.isCancelled()) { target.cancel(false); } else if (source.isDone() && !source.isSuccess()) { target.completeExceptionally(source.cause()); } } /** * Wait until future is complete or the supplied timeout is reached. * * @param timeout Maximum time to wait for futures to complete. * @param future Future to wait for. * @return {@code true} if future completes in time, otherwise {@code false} * @since 6.0 */ public static boolean await(Duration timeout, Future<?> future) { return await(timeout.toNanos(), TimeUnit.NANOSECONDS, future); } /** * Wait until future is complete or the supplied timeout is reached. * * @param timeout Maximum time to wait for futures to complete. * @param unit Unit of time for the timeout. * @param future Future to wait for. * @return {@code true} if future completes in time, otherwise {@code false} * @since 6.0 */ public static boolean await(long timeout, TimeUnit unit, Future<?> future) { try { long nanos = unit.toNanos(timeout); if (nanos < 0) { return false; } if (nanos == 0) { future.get(); } else { future.get(nanos, TimeUnit.NANOSECONDS); } return true; } catch (TimeoutException e) { return false; } catch (Exception e) { throw Exceptions.fromSynchronization(e); } } /** * Wait until futures are complete or the supplied timeout is reached. * * @param timeout Maximum time to wait for futures to complete. * @param futures Futures to wait for. * @return {@code true} if all futures complete in time, otherwise {@code false} * @since 6.0 */ public static boolean awaitAll(Duration timeout, Future<?>... futures) { return awaitAll(timeout.toNanos(), TimeUnit.NANOSECONDS, futures); } /** * Wait until futures are complete or the supplied timeout is reached. * * @param timeout Maximum time to wait for futures to complete. * @param unit Unit of time for the timeout. * @param futures Futures to wait for. * @return {@code true} if all futures complete in time, otherwise {@code false} */ public static boolean awaitAll(long timeout, TimeUnit unit, Future<?>... futures) { try { long nanos = unit.toNanos(timeout); long time = System.nanoTime(); for (Future<?> f : futures) { if (timeout <= 0) { f.get(); } else { if (nanos < 0) { return false; } f.get(nanos, TimeUnit.NANOSECONDS); long now = System.nanoTime(); nanos -= now - time; time = now; } } return true; } catch (TimeoutException e) { return false; } catch (Exception e) { throw Exceptions.fromSynchronization(e); } } /** * Wait until futures are complete or the supplied timeout is reached. Commands are canceled if the timeout is reached but * the command is not finished. * * @param cmd Command to wait for * @param timeout Maximum time to wait for futures to complete * @param unit Unit of time for the timeout * @param <T> Result type * @return Result of the command. * @since 6.0 */ public static <T> T awaitOrCancel(RedisFuture<T> cmd, long timeout, TimeUnit unit) { try { if (timeout > 0 && !cmd.await(timeout, unit)) { cmd.cancel(true); throw ExceptionFactory.createTimeoutException(Duration.ofNanos(unit.toNanos(timeout))); } return cmd.get(); } catch (Exception e) { throw Exceptions.bubble(e); } } }
LettuceAssert.notNull(throwable, "Throwable must not be null"); CompletableFuture<T> future = new CompletableFuture<>(); future.completeExceptionally(throwable); return future;
1,911
59
1,970
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/internal/HostAndPort.java
HostAndPort
parse
class HostAndPort { private static final int NO_PORT = -1; public final String hostText; public final int port; /** * * @param hostText must not be empty or {@code null}. * @param port */ private HostAndPort(String hostText, int port) { LettuceAssert.notNull(hostText, "HostText must not be null"); this.hostText = hostText; this.port = port; } /** * Create a {@link HostAndPort} of {@code host} and {@code port} * * @param host the hostname * @param port a valid port * @return the {@link HostAndPort} of {@code host} and {@code port} */ public static HostAndPort of(String host, int port) { LettuceAssert.isTrue(isValidPort(port), () -> String.format("Port out of range: %s", port)); HostAndPort parsedHost = parse(host); LettuceAssert.isTrue(!parsedHost.hasPort(), () -> String.format("Host has a port: %s", host)); return new HostAndPort(host, port); } /** * Parse a host and port string into a {@link HostAndPort}. The port is optional. Examples: {@code host:port} or * {@code host} * * @param hostPortString * @return */ public static HostAndPort parse(String hostPortString) {<FILL_FUNCTION_BODY>} /** * Temporary workaround until Redis provides IPv6 addresses in bracket notation. Allows parsing of {@code 1.2.3.4:6479} and * {@code dead:beef:dead:beef:affe::1:6379} into host and port. We assume the last item after the colon is a port. * * @param hostAndPortPart the string containing the host and port * @return the parsed {@link HostAndPort}. */ public static HostAndPort parseCompat(String hostAndPortPart) { int firstColonIndex = hostAndPortPart.indexOf(':'); int lastColonIndex = hostAndPortPart.lastIndexOf(':'); int bracketIndex = hostAndPortPart.lastIndexOf(']'); if (firstColonIndex != lastColonIndex && lastColonIndex != -1 && bracketIndex == -1) { String hostPart = hostAndPortPart.substring(0, lastColonIndex); String portPart = hostAndPortPart.substring(lastColonIndex + 1); return HostAndPort.of(hostPart, Integer.parseInt(portPart)); } return HostAndPort.parse(hostAndPortPart); } /** * * @return {@code true} if has a port. */ public boolean hasPort() { return port != NO_PORT; } /** * * @return the host text. */ public String getHostText() { return hostText; } /** * * @return the port. */ public int getPort() { if (!hasPort()) { throw new IllegalStateException("No port present."); } return port; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof HostAndPort)) return false; HostAndPort that = (HostAndPort) o; if (port != that.port) return false; return hostText != null ? hostText.equals(that.hostText) : that.hostText == null; } @Override public int hashCode() { int result = hostText != null ? hostText.hashCode() : 0; result = 31 * result + port; return result; } /** * Parses a bracketed host-port string, throwing IllegalArgumentException if parsing fails. * * @param hostPortString the full bracketed host-port specification. Post might not be specified. * @return an array with 2 strings: host and port, in that order. * @throws IllegalArgumentException if parsing the bracketed host-port string fails. */ private static String[] getHostAndPortFromBracketedHost(String hostPortString) { LettuceAssert.isTrue(hostPortString.charAt(0) == '[', () -> String.format("Bracketed host-port string must start with a bracket: %s", hostPortString)); int colonIndex = hostPortString.indexOf(':'); int closeBracketIndex = hostPortString.lastIndexOf(']'); LettuceAssert.isTrue(colonIndex > -1 && closeBracketIndex > colonIndex, () -> String.format("Invalid bracketed host/port: %s", hostPortString)); String host = hostPortString.substring(1, closeBracketIndex); if (closeBracketIndex + 1 == hostPortString.length()) { return new String[] { host, "" }; } else { LettuceAssert.isTrue(hostPortString.charAt(closeBracketIndex + 1) == ':', "Only a colon may follow a close bracket: " + hostPortString); for (int i = closeBracketIndex + 2; i < hostPortString.length(); ++i) { LettuceAssert.isTrue(Character.isDigit(hostPortString.charAt(i)), () -> String.format("Port must be numeric: %s", hostPortString)); } return new String[] { host, hostPortString.substring(closeBracketIndex + 2) }; } } /** * * @param port the port number * @return {@code true} for valid port numbers. */ private static boolean isValidPort(int port) { return port >= 0 && port <= 65535; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(hostText); if (hasPort()) { sb.append(':').append(port); } return sb.toString(); } }
LettuceAssert.notNull(hostPortString, "HostPortString must not be null"); String host; String portString = null; if (hostPortString.startsWith("[")) { String[] hostAndPort = getHostAndPortFromBracketedHost(hostPortString); host = hostAndPort[0]; portString = hostAndPort[1]; } else { int colonPos = hostPortString.indexOf(':'); if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) { // Exactly 1 colon. Split into host:port. host = hostPortString.substring(0, colonPos); portString = hostPortString.substring(colonPos + 1); } else { // 0 or 2+ colons. Bare hostname or IPv6 literal. host = hostPortString; } } int port = NO_PORT; if (!LettuceStrings.isEmpty(portString)) { // Try to parse the whole port string as a number. // JDK7 accepts leading plus signs. We don't want to. LettuceAssert.isTrue(!portString.startsWith("+"), () -> String.format("Cannot port number: %s", hostPortString)); try { port = Integer.parseInt(portString); } catch (NumberFormatException e) { throw new IllegalArgumentException(String.format("Cannot parse port number: %s", hostPortString)); } LettuceAssert.isTrue(isValidPort(port), () -> String.format("Port number out of range: %s", hostPortString)); } return new HostAndPort(host, port);
1,603
435
2,038
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/internal/LettuceClassUtils.java
LettuceClassUtils
getDefaultClassLoader
class LettuceClassUtils { /** The CGLIB class separator character "$$" */ public static final String CGLIB_CLASS_SEPARATOR = "$$"; /** * Map with primitive wrapper type as key and corresponding primitive type as value, for example: Integer.class -> * int.class. */ private static final Map<Class<?>, Class<?>> primitiveWrapperTypeMap = new IdentityHashMap<Class<?>, Class<?>>(9); /** * Map with primitive type as key and corresponding wrapper type as value, for example: int.class -> Integer.class. */ private static final Map<Class<?>, Class<?>> primitiveTypeToWrapperMap = new IdentityHashMap<Class<?>, Class<?>>(9); static { primitiveWrapperTypeMap.put(Boolean.class, boolean.class); primitiveWrapperTypeMap.put(Byte.class, byte.class); primitiveWrapperTypeMap.put(Character.class, char.class); primitiveWrapperTypeMap.put(Double.class, double.class); primitiveWrapperTypeMap.put(Float.class, float.class); primitiveWrapperTypeMap.put(Integer.class, int.class); primitiveWrapperTypeMap.put(Long.class, long.class); primitiveWrapperTypeMap.put(Short.class, short.class); primitiveWrapperTypeMap.put(Void.class, void.class); } /** * Determine whether the {@link Class} identified by the supplied name is present and can be loaded. Will return * {@code false} if either the class or one of its dependencies is not present or cannot be loaded. * * @param className the name of the class to check * @return whether the specified class is present */ public static boolean isPresent(String className) { try { forName(className); return true; } catch (Throwable ex) { // Class or one of its dependencies is not present... return false; } } /** * Loads a class using the {@link #getDefaultClassLoader()}. * * @param className * @return */ public static Class<?> findClass(String className) { try { return forName(className, getDefaultClassLoader()); } catch (ClassNotFoundException e) { return null; } } /** * Loads a class using the {@link #getDefaultClassLoader()}. * * @param className * @return * @throws ClassNotFoundException */ public static Class<?> forName(String className) throws ClassNotFoundException { return forName(className, getDefaultClassLoader()); } private static Class<?> forName(String className, ClassLoader classLoader) throws ClassNotFoundException { try { return classLoader.loadClass(className); } catch (ClassNotFoundException ex) { int lastDotIndex = className.lastIndexOf('.'); if (lastDotIndex != -1) { String innerClassName = className.substring(0, lastDotIndex) + '$' + className.substring(lastDotIndex + 1); try { return classLoader.loadClass(innerClassName); } catch (ClassNotFoundException ex2) { // swallow - let original exception get through } } throw ex; } } /** * Return the default ClassLoader to use: typically the thread context ClassLoader, if available; the ClassLoader that * loaded the ClassUtils class will be used as fallback. * * @return the default ClassLoader (never <code>null</code>) * @see java.lang.Thread#getContextClassLoader() */ private static ClassLoader getDefaultClassLoader() {<FILL_FUNCTION_BODY>} /** * Check if the right-hand side type may be assigned to the left-hand side type, assuming setting by reflection. Considers * primitive wrapper classes as assignable to the corresponding primitive types. * * @param lhsType the target type * @param rhsType the value type that should be assigned to the target type * @return if the target type is assignable from the value type */ public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) { LettuceAssert.notNull(lhsType, "Left-hand side type must not be null"); LettuceAssert.notNull(rhsType, "Right-hand side type must not be null"); if (lhsType.isAssignableFrom(rhsType)) { return true; } if (lhsType.isPrimitive()) { Class<?> resolvedPrimitive = primitiveWrapperTypeMap.get(rhsType); if (lhsType == resolvedPrimitive) { return true; } } else { Class<?> resolvedWrapper = primitiveTypeToWrapperMap.get(rhsType); if (resolvedWrapper != null && lhsType.isAssignableFrom(resolvedWrapper)) { return true; } } return false; } }
ClassLoader cl = null; try { cl = Thread.currentThread().getContextClassLoader(); } catch (Throwable ex) { // Cannot access thread context ClassLoader - falling back to system class loader... } if (cl == null) { // No thread context class loader -> use class loader of this class. cl = LettuceClassUtils.class.getClassLoader(); } return cl;
1,295
109
1,404
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/internal/LettuceFactories.java
LettuceFactories
newConcurrentQueue
class LettuceFactories { /** * Threshold used to determine queue implementation. A queue size above the size indicates usage of * {@link LinkedBlockingQueue} otherwise {@link ArrayBlockingQueue}. */ private static final int ARRAY_QUEUE_THRESHOLD = Integer .getInteger("io.lettuce.core.LettuceFactories.array-queue-threshold", 200000); /** * Creates a new, optionally bounded, {@link Queue} that does not require external synchronization. * * @param maxSize queue size. If {@link Integer#MAX_VALUE}, then creates an {@link ConcurrentLinkedQueue unbounded queue}. * @return a new, empty {@link Queue}. */ public static <T> Queue<T> newConcurrentQueue(int maxSize) {<FILL_FUNCTION_BODY>} /** * Creates a new {@link Queue} for single producer/single consumer. * * @return a new, empty {@link ArrayDeque}. */ public static <T> Deque<T> newSpScQueue() { return new ArrayDeque<>(); } /** * Creates a new {@link BlockingQueue}. * * @return a new, empty {@link BlockingQueue}. */ public static <T> LinkedBlockingQueue<T> newBlockingQueue() { return new LinkedBlockingQueue<>(); } }
if (maxSize == Integer.MAX_VALUE) { return new ConcurrentLinkedQueue<>(); } return maxSize > ARRAY_QUEUE_THRESHOLD ? new LinkedBlockingQueue<>(maxSize) : new ArrayBlockingQueue<>(maxSize);
372
71
443
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/internal/LettuceLists.java
LettuceLists
newList
class LettuceLists { /** * prevent instances. */ private LettuceLists() { } /** * Creates a new {@link ArrayList} containing all elements from {@code elements}. * * @param elements the elements that the list should contain, must not be {@code null}. * @param <T> the element type * @return a new {@link ArrayList} containing all elements from {@code elements}. */ @SafeVarargs public static <T> List<T> newList(T... elements) { LettuceAssert.notNull(elements, "Elements must not be null"); List<T> list = new ArrayList<>(elements.length); Collections.addAll(list, elements); return list; } /** * Creates a new {@link ArrayList} containing all elements from {@code elements}. * * @param elements the elements that the list should contain, must not be {@code null}. * @param <T> the element type * @return a new {@link ArrayList} containing all elements from {@code elements}. */ @SuppressWarnings("unchecked") public static <T> List<T> newList(Iterable<? extends T> elements) {<FILL_FUNCTION_BODY>} /** * Creates a new {@link ArrayList} containing all elements from {@code elements}. * * @param elements the elements that the list should contain, must not be {@code null}. * @param <T> the element type * @return a new {@link ArrayList} containing all elements from {@code elements}. */ public static <T> List<T> newList(Iterator<? extends T> elements) { LettuceAssert.notNull(elements, "Iterator must not be null"); List<T> objects = new ArrayList<>(); while (elements.hasNext()) { objects.add(elements.next()); } return objects; } /** * Creates a new unmodifiable {@link ArrayList} containing all elements from {@code elements}. * * @param elements the elements that the list should contain, must not be {@code null}. * @param <T> the element type * @return a new {@link ArrayList} containing all elements from {@code elements}. */ @SafeVarargs public static <T> List<T> unmodifiableList(T... elements) { return Collections.unmodifiableList(newList(elements)); } /** * Creates a new unmodifiable {@link ArrayList} containing all elements from {@code elements}. * * @param elements the elements that the list should contain, must not be {@code null}. * @param <T> the element type * @return a new {@link ArrayList} containing all elements from {@code elements}. */ public static <T> List<T> unmodifiableList(Collection<? extends T> elements) { return Collections.unmodifiableList(new ArrayList<>(elements)); } }
LettuceAssert.notNull(elements, "Iterable must not be null"); if (elements instanceof Collection<?>) { return new ArrayList<>((Collection<? extends T>) elements); } return newList(elements.iterator());
751
66
817
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/internal/LettuceSets.java
LettuceSets
newHashSet
class LettuceSets { /** * prevent instances. */ private LettuceSets() { } /** * Creates a new {@code HashSet} containing all elements from {@code elements}. * * @param elements the elements that the set should contain, must not be {@code null}. * @param <T> the element type * @return a new {@code HashSet} containing all elements from {@code elements}. */ public static <T> Set<T> newHashSet(Collection<? extends T> elements) { LettuceAssert.notNull(elements, "Collection must not be null"); HashSet<T> set = new HashSet<>(elements.size()); set.addAll(elements); return set; } /** * Creates a new {@code HashSet} containing all elements from {@code elements}. * * @param elements the elements that the set should contain, must not be {@code null}. * @param <T> the element type * @return a new {@code HashSet} containing all elements from {@code elements}. */ @SuppressWarnings("unchecked") public static <T> Set<T> newHashSet(Iterable<? extends T> elements) {<FILL_FUNCTION_BODY>} /** * Creates a new {@code HashSet} containing all elements from {@code elements}. * * @param elements the elements that the set should contain, must not be {@code null}. * @param <T> the element type * @return a new {@code HashSet} containing all elements from {@code elements}. */ @SafeVarargs public static <T> Set<T> newHashSet(T... elements) { LettuceAssert.notNull(elements, "Elements must not be null"); HashSet<T> set = new HashSet<>(elements.length); Collections.addAll(set, elements); return set; } /** * Creates a new unmodifiable {@code HashSet} containing all elements from {@code elements}. * * @param elements the elements that the set should contain, must not be {@code null}. * @param <T> the element type * @return a new {@code HashSet} containing all elements from {@code elements}. */ @SafeVarargs public static <T> Set<T> unmodifiableSet(T... elements) { return Collections.unmodifiableSet(newHashSet(elements)); } }
LettuceAssert.notNull(elements, "Iterable must not be null"); if (elements instanceof Collection<?>) { return newHashSet((Collection<T>) elements); } Set<T> set = new HashSet<>(); for (T e : elements) { set.add(e); } return set;
629
93
722
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/internal/LettuceStrings.java
LettuceStrings
isEmpty
class LettuceStrings { /** * Utility constructor. */ private LettuceStrings() { } /** * Checks if a String is empty or null. * * @param cs the char sequence * @return true if empty * @since 6.0.3 * @see String#isEmpty() */ public static boolean isEmpty(String cs) { return cs == null || cs.isEmpty(); } /** * Checks if a CharSequence has a length of 0 or null. * * @param cs the char sequence * @return true if empty * @see CharSequence#length() */ public static boolean isEmpty(CharSequence cs) {<FILL_FUNCTION_BODY>} /** * Checks if a String is not empty and not null. * * @param cs the char sequence * @return true if not empty * @since 6.0.3 * @see String#isEmpty() */ public static boolean isNotEmpty(String cs) { return !isEmpty(cs); } /** * Checks if a CharSequence has a non-zero length and is not null. * * @param cs the char sequence * @return true if not empty * @see CharSequence#length() */ public static boolean isNotEmpty(CharSequence cs) { return !isEmpty(cs); } /** * Convert {@code double} to {@link String}. If {@code n} is infinite, returns positive/negative infinity {@code +inf} and * {@code -inf}. * * @param n the double. * @return string representation of {@code n} */ public static String string(double n) { if (Double.isInfinite(n)) { return (n > 0) ? "+inf" : "-inf"; } return Double.toString(n); } /** * Convert {@link String} to {@code double}. If {@code s} is {@literal +inf}/{@literal -inf}, returns positive/negative * infinity. If {@code s} is {@literal +nan}/{@literal -nan}, returns NaN. * * @param s string representation of the number * @return the {@code double} value. * @since 4.3.3 */ public static double toDouble(String s) { if ("+inf".equals(s) || "inf".equals(s)) { return Double.POSITIVE_INFINITY; } if ("-inf".equals(s)) { return Double.NEGATIVE_INFINITY; } if ("-nan".equals(s) || "nan".equals(s) || "+nan".equals(s)) { return Double.NaN; } return Double.parseDouble(s); } /** * Convert a {@code String} array into a delimited {@code String} (e.g. CSV). * <p> * Useful for {@code toString()} implementations. * * @param arr the array to display * @param delim the delimiter to use (typically a ",") * @return the delimited {@code String} */ public static String arrayToDelimitedString(Object[] arr, String delim) { if ((arr == null || arr.length == 0)) { return ""; } if (arr.length == 1) { return "" + arr[0]; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { if (i > 0) { sb.append(delim); } sb.append(arr[i]); } return sb.toString(); } /** * Convert a {@link Collection} to a delimited {@code String} (e.g. CSV). * <p> * Useful for {@code toString()} implementations. * * @param coll the {@code Collection} to convert * @param delim the delimiter to use (typically a ",") * @param prefix the {@code String} to start each element with * @param suffix the {@code String} to end each element with * @return the delimited {@code String} */ public static String collectionToDelimitedString(Collection<?> coll, String delim, String prefix, String suffix) { if (coll == null || coll.isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(); Iterator<?> it = coll.iterator(); while (it.hasNext()) { sb.append(prefix).append(it.next()).append(suffix); if (it.hasNext()) { sb.append(delim); } } return sb.toString(); } /** * Return a {@code char[]} from the give {@link CharSequence}. * * @param seq the sequence to read * @return the character array * @since 6.2 */ public static char[] toCharArray(CharSequence seq) { LettuceAssert.notNull(seq, "CharSequence must not be null"); if (seq instanceof String) { return ((String) seq).toCharArray(); } char[] chars = new char[seq.length()]; for (int i = 0; i < chars.length; i++) { chars[i] = seq.charAt(i); } return chars; } }
if (cs instanceof String) { return isEmpty((String) cs); } return cs == null || cs.length() == 0;
1,456
42
1,498
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/internal/TimeoutProvider.java
TimeoutProvider
getTimeoutNs
class TimeoutProvider { private final Supplier<TimeoutOptions> timeoutOptionsSupplier; private final LongSupplier defaultTimeoutSupplier; private State state; /** * Creates a new {@link TimeoutProvider} given {@link TimeoutOptions supplier} and {@link LongSupplier default timeout * supplier in nano seconds}. * * @param timeoutOptionsSupplier must not be {@code null}. * @param defaultTimeoutNsSupplier must not be {@code null}. */ public TimeoutProvider(Supplier<TimeoutOptions> timeoutOptionsSupplier, LongSupplier defaultTimeoutNsSupplier) { LettuceAssert.notNull(timeoutOptionsSupplier, "TimeoutOptionsSupplier must not be null"); LettuceAssert.notNull(defaultTimeoutNsSupplier, "Default TimeoutSupplier must not be null"); this.timeoutOptionsSupplier = timeoutOptionsSupplier; this.defaultTimeoutSupplier = defaultTimeoutNsSupplier; } /** * Returns the timeout in {@link TimeUnit#NANOSECONDS} for {@link RedisCommand}. * * @param command the command. * @return timeout in {@link TimeUnit#NANOSECONDS}. */ public long getTimeoutNs(RedisCommand<?, ?, ?> command) {<FILL_FUNCTION_BODY>} static class State { final boolean applyDefaultTimeout; final TimeoutOptions.TimeoutSource timeoutSource; State(TimeoutOptions timeoutOptions) { this.timeoutSource = timeoutOptions.getSource(); if (timeoutSource == null || !timeoutOptions.isTimeoutCommands() || timeoutOptions.isApplyConnectionTimeout()) { this.applyDefaultTimeout = true; } else { this.applyDefaultTimeout = false; } } } }
long timeoutNs = -1; State state = this.state; if (state == null) { state = this.state = new State(timeoutOptionsSupplier.get()); } if (!state.applyDefaultTimeout) { timeoutNs = state.timeoutSource.getTimeUnit().toNanos(state.timeoutSource.getTimeout(command)); } return timeoutNs >= 0 ? timeoutNs : defaultTimeoutSupplier.getAsLong();
459
122
581
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/masterreplica/AsyncConnections.java
AsyncConnections
asMono
class AsyncConnections { private final Map<RedisURI, CompletableFuture<StatefulRedisConnection<String, String>>> connections = new TreeMap<>( ReplicaUtils.RedisURIComparator.INSTANCE); private final List<RedisNodeDescription> nodeList; AsyncConnections(List<RedisNodeDescription> nodeList) { this.nodeList = nodeList; } /** * Add a connection for a {@link RedisURI} * * @param redisURI * @param connection */ public void addConnection(RedisURI redisURI, CompletableFuture<StatefulRedisConnection<String, String>> connection) { connections.put(redisURI, connection); } public Mono<Connections> asMono(Duration timeout, ScheduledExecutorService timeoutExecutor) {<FILL_FUNCTION_BODY>} }
Connections connections = new Connections(this.connections.size(), nodeList); for (Map.Entry<RedisURI, CompletableFuture<StatefulRedisConnection<String, String>>> entry : this.connections .entrySet()) { CompletableFuture<StatefulRedisConnection<String, String>> future = entry.getValue(); future.whenComplete((connection, throwable) -> { if (throwable != null) { connections.accept(throwable); } else { connections.accept(Tuples.of(entry.getKey(), connection)); } }); } return Mono.fromCompletionStage(connections.getOrTimeout(timeout, timeoutExecutor));
227
182
409
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/masterreplica/AutodiscoveryConnector.java
AutodiscoveryConnector
connectAsync
class AutodiscoveryConnector<K, V> implements MasterReplicaConnector<K, V> { private final RedisClient redisClient; private final RedisCodec<K, V> codec; private final RedisURI redisURI; private final Map<RedisURI, StatefulRedisConnection<?, ?>> initialConnections = new ConcurrentHashMap<>(); AutodiscoveryConnector(RedisClient redisClient, RedisCodec<K, V> codec, RedisURI redisURI) { this.redisClient = redisClient; this.codec = codec; this.redisURI = redisURI; } @Override public CompletableFuture<StatefulRedisMasterReplicaConnection<K, V>> connectAsync() {<FILL_FUNCTION_BODY>} private Mono<Tuple2<RedisURI, StatefulRedisConnection<K, V>>> getMasterConnectionAndUri(List<RedisNodeDescription> nodes, Tuple2<RedisURI, StatefulRedisConnection<K, V>> connectionTuple, RedisCodec<K, V> codec) { RedisNodeDescription node = getConnectedNode(redisURI, nodes); if (!node.getRole().isUpstream()) { RedisNodeDescription master = lookupMaster(nodes); ConnectionFuture<StatefulRedisConnection<K, V>> masterConnection = redisClient.connectAsync(codec, master.getUri()); return Mono.just(master.getUri()).zipWith(Mono.fromCompletionStage(masterConnection)) // .doOnNext(it -> { initialConnections.put(it.getT1(), it.getT2()); }); } return Mono.just(connectionTuple); } @SuppressWarnings("unchecked") private Mono<StatefulRedisMasterReplicaConnection<K, V>> initializeConnection(RedisCodec<K, V> codec, Tuple2<RedisURI, StatefulRedisConnection<K, V>> connectionAndUri) { ReplicaTopologyProvider topologyProvider = new ReplicaTopologyProvider(connectionAndUri.getT2(), connectionAndUri.getT1()); MasterReplicaTopologyRefresh refresh = new MasterReplicaTopologyRefresh(redisClient, topologyProvider); MasterReplicaConnectionProvider<K, V> connectionProvider = new MasterReplicaConnectionProvider<>(redisClient, codec, redisURI, (Map) initialConnections); Mono<List<RedisNodeDescription>> refreshFuture = refresh.getNodes(redisURI); return refreshFuture.map(nodes -> { EventRecorder.getInstance().record(new MasterReplicaTopologyChangedEvent(redisURI, nodes)); connectionProvider.setKnownNodes(nodes); MasterReplicaChannelWriter channelWriter = new MasterReplicaChannelWriter(connectionProvider, redisClient.getResources(), redisClient.getOptions()); StatefulRedisMasterReplicaConnectionImpl<K, V> connection = new StatefulRedisMasterReplicaConnectionImpl<>( channelWriter, codec, redisURI.getTimeout()); connection.setOptions(redisClient.getOptions()); return connection; }); } private static RedisNodeDescription lookupMaster(List<RedisNodeDescription> nodes) { Optional<RedisNodeDescription> first = findFirst(nodes, n -> n.getRole().isUpstream()); return first.orElseThrow(() -> new IllegalStateException("Cannot lookup master from " + nodes)); } private static RedisNodeDescription getConnectedNode(RedisURI redisURI, List<RedisNodeDescription> nodes) { Optional<RedisNodeDescription> first = findFirst(nodes, n -> equals(redisURI, n)); return first.orElseThrow( () -> new IllegalStateException("Cannot lookup node descriptor for connected node at " + redisURI)); } private static Optional<RedisNodeDescription> findFirst(List<RedisNodeDescription> nodes, Predicate<? super RedisNodeDescription> predicate) { return nodes.stream().filter(predicate).findFirst(); } private static boolean equals(RedisURI redisURI, RedisNodeDescription node) { return node.getUri().getHost().equals(redisURI.getHost()) && node.getUri().getPort() == redisURI.getPort(); } }
ConnectionFuture<StatefulRedisConnection<K, V>> initialConnection = redisClient.connectAsync(codec, redisURI); Mono<StatefulRedisMasterReplicaConnection<K, V>> connect = Mono.fromCompletionStage(initialConnection) .flatMap(nodeConnection -> { initialConnections.put(redisURI, nodeConnection); TopologyProvider topologyProvider = new ReplicaTopologyProvider(nodeConnection, redisURI); return Mono.fromCompletionStage(topologyProvider.getNodesAsync()) .flatMap(nodes -> getMasterConnectionAndUri(nodes, Tuples.of(redisURI, nodeConnection), codec)); }).flatMap(connectionAndUri -> { return initializeConnection(codec, connectionAndUri); }); return connect.onErrorResume(t -> { Mono<Void> close = Mono.empty(); for (StatefulRedisConnection<?, ?> connection : initialConnections.values()) { close = close.then(Mono.fromFuture(connection.closeAsync())); } return close.then(Mono.error(t)); }).onErrorMap(ExecutionException.class, Throwable::getCause).toFuture();
1,113
315
1,428
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/masterreplica/CompletableEventLatchSupport.java
CompletableEventLatchSupport
emit
class CompletableEventLatchSupport<T, V> { @SuppressWarnings("rawtypes") private static final AtomicIntegerFieldUpdater<CompletableEventLatchSupport> NOTIFICATIONS_UPDATER = AtomicIntegerFieldUpdater .newUpdater(CompletableEventLatchSupport.class, "notifications"); @SuppressWarnings("rawtypes") private static final AtomicIntegerFieldUpdater<CompletableEventLatchSupport> GATE_UPDATER = AtomicIntegerFieldUpdater .newUpdater(CompletableEventLatchSupport.class, "gate"); private static final int GATE_OPEN = 0; private static final int GATE_CLOSED = 1; private final int expectedCount; private final CompletableFuture<V> selfFuture = new CompletableFuture<>(); private volatile ScheduledFuture<?> timeoutScheduleFuture; // accessed via UPDATER @SuppressWarnings("unused") private volatile int notifications = 0; @SuppressWarnings("unused") private volatile int gate = GATE_OPEN; /** * Construct a new {@link CompletableEventLatchSupport} class expecting {@code expectedCount} notifications. * * @param expectedCount */ public CompletableEventLatchSupport(int expectedCount) { this.expectedCount = expectedCount; } public final int getExpectedCount() { return expectedCount; } /** * Notification callback method accepting a connection for a value. Triggers emission if the gate is open and the current * call to this method is the last expected notification. */ public final void accept(T value) { if (GATE_UPDATER.get(this) == GATE_CLOSED) { onDrop(value); return; } onAccept(value); onNotification(); } /** * Notification callback method accepting a connection error. Triggers emission if the gate is open and the current call to * this method is the last expected notification. */ public final void accept(Throwable throwable) { if (GATE_UPDATER.get(this) == GATE_CLOSED) { onDrop(throwable); return; } onError(throwable); onNotification(); } private void onNotification() { if (NOTIFICATIONS_UPDATER.incrementAndGet(this) == expectedCount) { ScheduledFuture<?> timeoutScheduleFuture = this.timeoutScheduleFuture; this.timeoutScheduleFuture = null; if (timeoutScheduleFuture != null) { timeoutScheduleFuture.cancel(false); } emit(); } } private void emit() {<FILL_FUNCTION_BODY>} // Callback hooks protected void onAccept(T value) { } protected void onError(Throwable value) { } protected void onDrop(T value) { } protected void onDrop(Throwable value) { } protected void onEmit(Emission<V> emission) { } /** * Retrieve a {@link CompletionStage} that is notified upon completion or timeout. * * @param timeout * @param timeoutExecutor * @return */ public final CompletionStage<V> getOrTimeout(Duration timeout, ScheduledExecutorService timeoutExecutor) { if (GATE_UPDATER.get(this) == GATE_OPEN && timeoutScheduleFuture == null) { this.timeoutScheduleFuture = timeoutExecutor.schedule(this::emit, timeout.toNanos(), TimeUnit.NANOSECONDS); } return selfFuture; } /** * Interface to signal emission of a value or an {@link Exception}. * * @param <T> */ public interface Emission<T> { /** * Complete emission successfully. * * @param value the actual value to emit. */ void success(T value); /** * Complete emission with an {@link Throwable exception}. * * @param exception the error to emit. */ void error(Throwable exception); } }
if (GATE_UPDATER.compareAndSet(this, GATE_OPEN, GATE_CLOSED)) { onEmit(new Emission<V>() { @Override public void success(V value) { selfFuture.complete(value); } @Override public void error(Throwable exception) { selfFuture.completeExceptionally(exception); } }); }
1,117
115
1,232
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/masterreplica/Connections.java
Connections
closeAsync
class Connections extends CompletableEventLatchSupport<Tuple2<RedisURI, StatefulRedisConnection<String, String>>, Connections> implements AsyncCloseable { private final Lock lock = new ReentrantLock(); private final Map<RedisURI, StatefulRedisConnection<String, String>> connections = new TreeMap<>( ReplicaUtils.RedisURIComparator.INSTANCE); private final List<Throwable> exceptions = new CopyOnWriteArrayList<>(); private final List<RedisNodeDescription> nodes; private volatile boolean closed = false; public Connections(int expectedConnectionCount, List<RedisNodeDescription> nodes) { super(expectedConnectionCount); this.nodes = nodes; } @Override protected void onAccept(Tuple2<RedisURI, StatefulRedisConnection<String, String>> value) { if (this.closed) { value.getT2().closeAsync(); return; } try { lock.lock(); this.connections.put(value.getT1(), value.getT2()); } finally { lock.unlock(); } } @Override protected void onError(Throwable value) { this.exceptions.add(value); } @Override protected void onDrop(Tuple2<RedisURI, StatefulRedisConnection<String, String>> value) { value.getT2().closeAsync(); } @Override protected void onDrop(Throwable value) { } @Override protected void onEmit(Emission<Connections> emission) { if (getExpectedCount() != 0 && this.connections.isEmpty() && !this.exceptions.isEmpty()) { RedisConnectionException collector = new RedisConnectionException( "Unable to establish a connection to Redis Master/Replica"); this.exceptions.forEach(collector::addSuppressed); emission.error(collector); } else { emission.success(this); } } /** * @return {@code true} if no connections present. */ public boolean isEmpty() { try { lock.lock(); return this.connections.isEmpty(); } finally { lock.unlock(); } } /* * Initiate {@code PING} on all connections and return the {@link Requests}. * @return the {@link Requests}. */ public Requests requestPing() { Set<Map.Entry<RedisURI, StatefulRedisConnection<String, String>>> entries = new LinkedHashSet<>( this.connections.entrySet()); Requests requests = new Requests(entries.size(), this.nodes); for (Map.Entry<RedisURI, StatefulRedisConnection<String, String>> entry : entries) { CommandArgs<String, String> args = new CommandArgs<>(StringCodec.ASCII).add(CommandKeyword.NODES); Command<String, String, String> command = new Command<>(CommandType.PING, new StatusOutput<>(StringCodec.ASCII), args); TimedAsyncCommand<String, String, String> timedCommand = new TimedAsyncCommand<>(command); entry.getValue().dispatch(timedCommand); requests.addRequest(entry.getKey(), timedCommand); } return requests; } /** * Close all connections. */ public CompletableFuture<Void> closeAsync() {<FILL_FUNCTION_BODY>} }
List<CompletableFuture<?>> close = new ArrayList<>(this.connections.size()); List<RedisURI> toRemove = new ArrayList<>(this.connections.size()); this.closed = true; for (Map.Entry<RedisURI, StatefulRedisConnection<String, String>> entry : this.connections.entrySet()) { toRemove.add(entry.getKey()); close.add(entry.getValue().closeAsync()); } for (RedisURI redisURI : toRemove) { this.connections.remove(redisURI); } return Futures.allOf(close);
908
165
1,073
<methods>public void <init>(int) ,public final void accept(Tuple2<io.lettuce.core.RedisURI,StatefulRedisConnection<java.lang.String,java.lang.String>>) ,public final void accept(java.lang.Throwable) ,public final int getExpectedCount() ,public final CompletionStage<io.lettuce.core.masterreplica.Connections> getOrTimeout(java.time.Duration, java.util.concurrent.ScheduledExecutorService) <variables>private static final int GATE_CLOSED,private static final int GATE_OPEN,private static final AtomicIntegerFieldUpdater<CompletableEventLatchSupport#RAW> GATE_UPDATER,private static final AtomicIntegerFieldUpdater<CompletableEventLatchSupport#RAW> NOTIFICATIONS_UPDATER,private final non-sealed int expectedCount,private volatile int gate,private volatile int notifications,private final CompletableFuture<io.lettuce.core.masterreplica.Connections> selfFuture,private volatile ScheduledFuture<?> timeoutScheduleFuture
redis_lettuce
lettuce/src/main/java/io/lettuce/core/masterreplica/MasterReplicaChannelWriter.java
MasterReplicaChannelWriter
closeAsync
class MasterReplicaChannelWriter implements RedisChannelWriter { private MasterReplicaConnectionProvider<?, ?> masterReplicaConnectionProvider; private final ClientResources clientResources; private final ClientOptions clientOptions; private final io.lettuce.core.protocol.ReadOnlyCommands.ReadOnlyPredicate readOnlyCommands; private boolean closed = false; private boolean inTransaction; MasterReplicaChannelWriter(MasterReplicaConnectionProvider<?, ?> masterReplicaConnectionProvider, ClientResources clientResources, ClientOptions clientOptions) { this.masterReplicaConnectionProvider = masterReplicaConnectionProvider; this.clientResources = clientResources; this.clientOptions = clientOptions; this.readOnlyCommands = clientOptions.getReadOnlyCommands(); } @Override @SuppressWarnings("unchecked") public <K, V, T> RedisCommand<K, V, T> write(RedisCommand<K, V, T> command) { LettuceAssert.notNull(command, "Command must not be null"); if (closed) { throw new RedisException("Connection is closed"); } if (isStartTransaction(command.getType())) { inTransaction = true; } ConnectionIntent connectionIntent = inTransaction ? ConnectionIntent.WRITE : (readOnlyCommands.isReadOnly(command) ? ConnectionIntent.READ : ConnectionIntent.WRITE); CompletableFuture<StatefulRedisConnection<K, V>> future = (CompletableFuture) masterReplicaConnectionProvider .getConnectionAsync(connectionIntent); if (isEndTransaction(command.getType())) { inTransaction = false; } if (isSuccessfullyCompleted(future)) { writeCommand(command, future.join(), null); } else { future.whenComplete((c, t) -> writeCommand(command, c, t)); } return command; } @SuppressWarnings("unchecked") private static <K, V> void writeCommand(RedisCommand<K, V, ?> command, StatefulRedisConnection<K, V> connection, Throwable throwable) { if (throwable != null) { command.completeExceptionally(throwable); return; } try { connection.dispatch(command); } catch (Exception e) { command.completeExceptionally(e); } } @Override @SuppressWarnings("unchecked") public <K, V> Collection<RedisCommand<K, V, ?>> write(Collection<? extends RedisCommand<K, V, ?>> commands) { LettuceAssert.notNull(commands, "Commands must not be null"); if (closed) { throw new RedisException("Connection is closed"); } for (RedisCommand<K, V, ?> command : commands) { if (isStartTransaction(command.getType())) { inTransaction = true; break; } } // TODO: Retain order or retain ConnectionIntent preference? // Currently: Retain order ConnectionIntent connectionIntent = inTransaction ? ConnectionIntent.WRITE : getIntent(commands); CompletableFuture<StatefulRedisConnection<K, V>> future = (CompletableFuture) masterReplicaConnectionProvider .getConnectionAsync(connectionIntent); for (RedisCommand<K, V, ?> command : commands) { if (isEndTransaction(command.getType())) { inTransaction = false; break; } } if (isSuccessfullyCompleted(future)) { writeCommands(commands, future.join(), null); } else { future.whenComplete((c, t) -> writeCommands(commands, c, t)); } return (Collection) commands; } @SuppressWarnings("unchecked") private static <K, V> void writeCommands(Collection<? extends RedisCommand<K, V, ?>> commands, StatefulRedisConnection<K, V> connection, Throwable throwable) { if (throwable != null) { commands.forEach(c -> c.completeExceptionally(throwable)); return; } try { connection.dispatch(commands); } catch (Exception e) { commands.forEach(c -> c.completeExceptionally(e)); } } /** * Optimization: Determine command intents and optimize for bulk execution preferring one node. * <p> * If there is only one ConnectionIntent, then we take the ConnectionIntent derived from the commands. If there is more than * one ConnectionIntent, then use {@link ConnectionIntent#WRITE}. * * @param commands {@link Collection} of {@link RedisCommand commands}. * @return the ConnectionIntent. */ ConnectionIntent getIntent(Collection<? extends RedisCommand<?, ?, ?>> commands) { if (commands.isEmpty()) { return ConnectionIntent.WRITE; } for (RedisCommand<?, ?, ?> command : commands) { if (!readOnlyCommands.isReadOnly(command)) { return ConnectionIntent.WRITE; } } return ConnectionIntent.READ; } @Override public void close() { closeAsync().join(); } @Override public CompletableFuture<Void> closeAsync() {<FILL_FUNCTION_BODY>} MasterReplicaConnectionProvider<?, ?> getUpstreamReplicaConnectionProvider() { return masterReplicaConnectionProvider; } @Override public void setConnectionFacade(ConnectionFacade connection) { } @Override public ClientResources getClientResources() { return clientResources; } @Override public void setAutoFlushCommands(boolean autoFlush) { masterReplicaConnectionProvider.setAutoFlushCommands(autoFlush); } @Override public void flushCommands() { masterReplicaConnectionProvider.flushCommands(); } @Override public void reset() { masterReplicaConnectionProvider.reset(); } /** * Set from which nodes data is read. The setting is used as default for read operations on this connection. See the * documentation for {@link ReadFrom} for more information. * * @param readFrom the read from setting, must not be {@code null} */ public void setReadFrom(ReadFrom readFrom) { masterReplicaConnectionProvider.setReadFrom(readFrom); } /** * Gets the {@link ReadFrom} setting for this connection. Defaults to {@link ReadFrom#UPSTREAM} if not set. * * @return the read from setting */ public ReadFrom getReadFrom() { return masterReplicaConnectionProvider.getReadFrom(); } private static boolean isSuccessfullyCompleted(CompletableFuture<?> connectFuture) { return connectFuture.isDone() && !connectFuture.isCompletedExceptionally(); } private static boolean isStartTransaction(ProtocolKeyword command) { return command.name().equals("MULTI"); } private boolean isEndTransaction(ProtocolKeyword command) { return command.name().equals("EXEC") || command.name().equals("DISCARD"); } }
if (closed) { return CompletableFuture.completedFuture(null); } closed = true; CompletableFuture<Void> future = null; if (masterReplicaConnectionProvider != null) { future = masterReplicaConnectionProvider.closeAsync(); masterReplicaConnectionProvider = null; } if (future == null) { future = CompletableFuture.completedFuture(null); } return future;
1,864
122
1,986
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/masterreplica/MasterReplicaTopologyRefresh.java
MasterReplicaTopologyRefresh
getConnections
class MasterReplicaTopologyRefresh { private static final InternalLogger logger = InternalLoggerFactory.getInstance(MasterReplicaTopologyRefresh.class); private static final StringCodec CODEC = StringCodec.UTF8; private final NodeConnectionFactory nodeConnectionFactory; private final TopologyProvider topologyProvider; private final ScheduledExecutorService eventExecutors; MasterReplicaTopologyRefresh(RedisClient client, TopologyProvider topologyProvider) { this(new RedisClientNodeConnectionFactory(client), client.getResources().eventExecutorGroup(), topologyProvider); } MasterReplicaTopologyRefresh(NodeConnectionFactory nodeConnectionFactory, ScheduledExecutorService eventExecutors, TopologyProvider topologyProvider) { this.nodeConnectionFactory = nodeConnectionFactory; this.eventExecutors = eventExecutors; this.topologyProvider = topologyProvider; } /** * Load master replica nodes. Result contains an ordered list of {@link RedisNodeDescription}s. The sort key is the latency. * Nodes with lower latency come first. * * @param seed collection of {@link RedisURI}s * @return mapping between {@link RedisURI} and {@link Partitions} */ public Mono<List<RedisNodeDescription>> getNodes(RedisURI seed) { CompletableFuture<List<RedisNodeDescription>> future = topologyProvider.getNodesAsync(); Mono<List<RedisNodeDescription>> initialNodes = Mono.fromFuture(future).doOnNext(nodes -> { applyAuthenticationCredentials(nodes, seed); }); return initialNodes.map(this::getConnections) .flatMap(asyncConnections -> asyncConnections.asMono(seed.getTimeout(), eventExecutors)) .flatMap(connections -> { Requests requests = connections.requestPing(); CompletionStage<List<RedisNodeDescription>> nodes = requests.getOrTimeout(seed.getTimeout(), eventExecutors); return Mono.fromCompletionStage(nodes).flatMap(it -> ResumeAfter.close(connections).thenEmit(it)); }); } /* * Establish connections asynchronously. */ private AsyncConnections getConnections(Iterable<RedisNodeDescription> nodes) {<FILL_FUNCTION_BODY>} private static void applyAuthenticationCredentials(List<RedisNodeDescription> nodes, RedisURI seed) { for (RedisNodeDescription node : nodes) { node.getUri().applyAuthentication(seed); } } }
List<RedisNodeDescription> nodeList = LettuceLists.newList(nodes); AsyncConnections connections = new AsyncConnections(nodeList); for (RedisNodeDescription node : nodeList) { RedisURI redisURI = node.getUri(); String message = String.format("Unable to connect to %s", redisURI); try { CompletableFuture<StatefulRedisConnection<String, String>> connectionFuture = nodeConnectionFactory .connectToNodeAsync(CODEC, redisURI); CompletableFuture<StatefulRedisConnection<String, String>> sync = new CompletableFuture<>(); connectionFuture.whenComplete((connection, throwable) -> { if (throwable != null) { if (throwable instanceof RedisConnectionException) { if (logger.isDebugEnabled()) { logger.debug(throwable.getMessage(), throwable); } else { logger.warn(throwable.getMessage()); } } else { logger.warn(message, throwable); } sync.completeExceptionally(new RedisConnectionException(message, throwable)); } else { connection.async().clientSetname("lettuce#MasterReplicaTopologyRefresh"); sync.complete(connection); } }); connections.addConnection(redisURI, sync); } catch (RuntimeException e) { logger.warn(String.format(message, redisURI), e); } } return connections;
651
381
1,032
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/masterreplica/RedisMasterReplicaNode.java
RedisMasterReplicaNode
toString
class RedisMasterReplicaNode implements RedisNodeDescription { private final RedisURI redisURI; private final Role role; RedisMasterReplicaNode(String host, int port, RedisURI seed, Role role) { this.redisURI = RedisURI.builder(seed).withHost(host).withPort(port).build(); this.role = role; } @Override public RedisURI getUri() { return redisURI; } @Override public Role getRole() { return role; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RedisMasterReplicaNode)) return false; RedisMasterReplicaNode that = (RedisMasterReplicaNode) o; if (!redisURI.equals(that.redisURI)) return false; return role == that.role; } @Override public int hashCode() { int result = redisURI.hashCode(); result = 31 * result + role.hashCode(); return result; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" [redisURI=").append(redisURI); sb.append(", role=").append(role); sb.append(']'); return sb.toString();
325
73
398
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/masterreplica/ReplicaTopologyProvider.java
ReplicaTopologyProvider
getMasterFromInfo
class ReplicaTopologyProvider implements TopologyProvider { public static final Pattern ROLE_PATTERN = Pattern.compile("^role\\:([a-z]+)$", Pattern.MULTILINE); public static final Pattern SLAVE_PATTERN = Pattern.compile("^slave(\\d+)\\:([a-zA-Z\\,\\=\\d\\.\\:\\-]+)$", Pattern.MULTILINE); public static final Pattern MASTER_HOST_PATTERN = Pattern.compile("^master_host\\:([a-zA-Z\\,\\=\\d\\.\\:\\-]+)$", Pattern.MULTILINE); public static final Pattern MASTER_PORT_PATTERN = Pattern.compile("^master_port\\:(\\d+)$", Pattern.MULTILINE); public static final Pattern IP_PATTERN = Pattern.compile("ip\\=([a-zA-Z\\d\\.\\:\\-]+)"); public static final Pattern PORT_PATTERN = Pattern.compile("port\\=([\\d]+)"); private static final InternalLogger logger = InternalLoggerFactory.getInstance(ReplicaTopologyProvider.class); private final StatefulRedisConnection<?, ?> connection; private final RedisURI redisURI; /** * Creates a new {@link ReplicaTopologyProvider}. * * @param connection must not be {@code null} * @param redisURI must not be {@code null} */ public ReplicaTopologyProvider(StatefulRedisConnection<?, ?> connection, RedisURI redisURI) { LettuceAssert.notNull(connection, "Redis Connection must not be null"); LettuceAssert.notNull(redisURI, "RedisURI must not be null"); this.connection = connection; this.redisURI = redisURI; } @Override public List<RedisNodeDescription> getNodes() { logger.debug("Performing topology lookup"); String info = connection.sync().info("replication"); try { return getNodesFromInfo(info); } catch (RuntimeException e) { throw Exceptions.bubble(e); } } @Override public CompletableFuture<List<RedisNodeDescription>> getNodesAsync() { logger.debug("Performing topology lookup"); RedisFuture<String> info = connection.async().info("replication"); try { return Mono.fromCompletionStage(info).timeout(redisURI.getTimeout()).map(this::getNodesFromInfo).toFuture(); } catch (RuntimeException e) { throw Exceptions.bubble(e); } } protected List<RedisNodeDescription> getNodesFromInfo(String info) { List<RedisNodeDescription> result = new ArrayList<>(); RedisNodeDescription currentNodeDescription = getCurrentNodeDescription(info); result.add(currentNodeDescription); if (currentNodeDescription.getRole().isUpstream()) { result.addAll(getReplicasFromInfo(info)); } else { result.add(getMasterFromInfo(info)); } return result; } private RedisNodeDescription getCurrentNodeDescription(String info) { Matcher matcher = ROLE_PATTERN.matcher(info); if (!matcher.find()) { throw new IllegalStateException("No role property in info " + info); } return getRedisNodeDescription(matcher); } private List<RedisNodeDescription> getReplicasFromInfo(String info) { List<RedisNodeDescription> replicas = new ArrayList<>(); Matcher matcher = SLAVE_PATTERN.matcher(info); while (matcher.find()) { String group = matcher.group(2); String ip = getNested(IP_PATTERN, group, 1); String port = getNested(PORT_PATTERN, group, 1); replicas.add(new RedisMasterReplicaNode(ip, Integer.parseInt(port), redisURI, RedisInstance.Role.SLAVE)); } return replicas; } private RedisNodeDescription getMasterFromInfo(String info) {<FILL_FUNCTION_BODY>} private String getNested(Pattern pattern, String string, int group) { Matcher matcher = pattern.matcher(string); if (matcher.find()) { return matcher.group(group); } throw new IllegalArgumentException("Cannot extract group " + group + " with pattern " + pattern + " from " + string); } private RedisNodeDescription getRedisNodeDescription(Matcher matcher) { String roleString = matcher.group(1); RedisInstance.Role role = null; if (RedisInstance.Role.MASTER.name().equalsIgnoreCase(roleString)) { role = RedisInstance.Role.UPSTREAM; } if (RedisInstance.Role.SLAVE.name().equalsIgnoreCase(roleString) | RedisInstance.Role.REPLICA.name().equalsIgnoreCase(roleString)) { role = RedisInstance.Role.REPLICA; } if (role == null) { throw new IllegalStateException("Cannot resolve role " + roleString + " to " + RedisInstance.Role.UPSTREAM + " or " + RedisInstance.Role.REPLICA); } return new RedisMasterReplicaNode(redisURI.getHost(), redisURI.getPort(), redisURI, role); } }
Matcher masterHostMatcher = MASTER_HOST_PATTERN.matcher(info); Matcher masterPortMatcher = MASTER_PORT_PATTERN.matcher(info); boolean foundHost = masterHostMatcher.find(); boolean foundPort = masterPortMatcher.find(); if (!foundHost || !foundPort) { throw new IllegalStateException("Cannot resolve master from info " + info); } String host = masterHostMatcher.group(1); int port = Integer.parseInt(masterPortMatcher.group(1)); return new RedisMasterReplicaNode(host, port, redisURI, RedisInstance.Role.UPSTREAM);
1,457
176
1,633
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/masterreplica/ReplicaUtils.java
ReplicaUtils
compare
class ReplicaUtils { /** * Check if properties changed. * * @param o1 the first object to be compared. * @param o2 the second object to be compared. * @return {@code true} if {@code MASTER} or {@code SLAVE} flags changed or the URIs are changed. */ static boolean isChanged(Collection<RedisNodeDescription> o1, Collection<RedisNodeDescription> o2) { if (o1.size() != o2.size()) { return true; } for (RedisNodeDescription base : o2) { if (!essentiallyEqualsTo(base, findNodeByUri(o1, base.getUri()))) { return true; } } return false; } /** * Lookup a {@link RedisNodeDescription} by {@link RedisURI}. * * @param nodes * @param lookupUri * @return the {@link RedisNodeDescription} or {@code null} */ static RedisNodeDescription findNodeByUri(Collection<RedisNodeDescription> nodes, RedisURI lookupUri) { return findNodeByHostAndPort(nodes, lookupUri.getHost(), lookupUri.getPort()); } /** * Lookup a {@link RedisNodeDescription} by {@code host} and {@code port}. * * @param nodes * @param host * @param port * @return the {@link RedisNodeDescription} or {@code null} */ static RedisNodeDescription findNodeByHostAndPort(Collection<RedisNodeDescription> nodes, String host, int port) { for (RedisNodeDescription node : nodes) { RedisURI nodeUri = node.getUri(); if (nodeUri.getHost().equals(host) && nodeUri.getPort() == port) { return node; } } return null; } /** * Check for {@code MASTER} or {@code SLAVE} roles and the URI. * * @param o1 the first object to be compared. * @param o2 the second object to be compared. * @return {@code true} if {@code MASTER} or {@code SLAVE} flags changed or the URI changed. */ static boolean essentiallyEqualsTo(RedisNodeDescription o1, RedisNodeDescription o2) { if (o2 == null) { return false; } if (o1.getRole() != o2.getRole()) { return false; } if (!o1.getUri().equals(o2.getUri())) { return false; } return true; } /** * Compare {@link RedisURI} based on their host and port representation. */ enum RedisURIComparator implements Comparator<RedisURI> { INSTANCE; @Override public int compare(RedisURI o1, RedisURI o2) {<FILL_FUNCTION_BODY>} } }
String h1 = ""; String h2 = ""; if (o1 != null) { h1 = o1.getHost() + ":" + o1.getPort(); } if (o2 != null) { h2 = o2.getHost() + ":" + o2.getPort(); } return h1.compareToIgnoreCase(h2);
774
104
878
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/masterreplica/Requests.java
Requests
onEmit
class Requests extends CompletableEventLatchSupport<Tuple2<RedisURI, TimedAsyncCommand<String, String, String>>, List<RedisNodeDescription>> { private final Map<RedisURI, TimedAsyncCommand<String, String, String>> rawViews = new TreeMap<>( ReplicaUtils.RedisURIComparator.INSTANCE); private final List<RedisNodeDescription> nodes; public Requests(int expectedCount, List<RedisNodeDescription> nodes) { super(expectedCount); this.nodes = nodes; } protected void addRequest(RedisURI redisURI, TimedAsyncCommand<String, String, String> command) { rawViews.put(redisURI, command); command.onComplete((s, throwable) -> { if (throwable != null) { accept(throwable); } else { accept(Tuples.of(redisURI, command)); } }); } @Override protected void onEmit(Emission<List<RedisNodeDescription>> emission) {<FILL_FUNCTION_BODY>} protected Set<RedisURI> nodes() { return rawViews.keySet(); } protected TimedAsyncCommand<String, String, String> getRequest(RedisURI redisURI) { return rawViews.get(redisURI); } }
List<RedisNodeDescription> result = new ArrayList<>(); Map<RedisNodeDescription, Long> latencies = new HashMap<>(); for (RedisNodeDescription node : nodes) { TimedAsyncCommand<String, String, String> future = getRequest(node.getUri()); if (future == null || !future.isDone()) { continue; } RedisNodeDescription redisNodeDescription = findNodeByUri(nodes, node.getUri()); latencies.put(redisNodeDescription, future.duration()); result.add(redisNodeDescription); } SortAction sortAction = SortAction.getSortAction(); sortAction.sort(result, new LatencyComparator(latencies)); emission.success(result);
359
197
556
<methods>public void <init>(int) ,public final void accept(Tuple2<io.lettuce.core.RedisURI,TimedAsyncCommand<java.lang.String,java.lang.String,java.lang.String>>) ,public final void accept(java.lang.Throwable) ,public final int getExpectedCount() ,public final CompletionStage<List<io.lettuce.core.models.role.RedisNodeDescription>> getOrTimeout(java.time.Duration, java.util.concurrent.ScheduledExecutorService) <variables>private static final int GATE_CLOSED,private static final int GATE_OPEN,private static final AtomicIntegerFieldUpdater<CompletableEventLatchSupport#RAW> GATE_UPDATER,private static final AtomicIntegerFieldUpdater<CompletableEventLatchSupport#RAW> NOTIFICATIONS_UPDATER,private final non-sealed int expectedCount,private volatile int gate,private volatile int notifications,private final CompletableFuture<List<io.lettuce.core.models.role.RedisNodeDescription>> selfFuture,private volatile ScheduledFuture<?> timeoutScheduleFuture
redis_lettuce
lettuce/src/main/java/io/lettuce/core/masterreplica/ResumeAfter.java
ResumeAfter
thenError
class ResumeAfter { private static final AtomicIntegerFieldUpdater<ResumeAfter> UPDATER = AtomicIntegerFieldUpdater .newUpdater(ResumeAfter.class, "closed"); private final AsyncCloseable closeable; private static final int ST_OPEN = 0; private static final int ST_CLOSED = 1; @SuppressWarnings("unused") private volatile int closed = ST_OPEN; private ResumeAfter(AsyncCloseable closeable) { this.closeable = closeable; } public static ResumeAfter close(AsyncCloseable closeable) { return new ResumeAfter(closeable); } public <T> Mono<T> thenEmit(T value) { return Mono.defer(() -> { if (firstCloseLatch()) { return Mono.fromCompletionStage(closeable.closeAsync()); } return Mono.empty(); }).then(Mono.just(value)).doFinally(s -> { if (firstCloseLatch()) { closeable.closeAsync(); } }); } public <T> Mono<T> thenError(Throwable t) {<FILL_FUNCTION_BODY>} private boolean firstCloseLatch() { return UPDATER.compareAndSet(ResumeAfter.this, ST_OPEN, ST_CLOSED); } }
return Mono.defer(() -> { if (firstCloseLatch()) { return Mono.fromCompletionStage(closeable.closeAsync()); } return Mono.empty(); }).then(Mono.<T> error(t)).doFinally(s -> { if (firstCloseLatch()) { closeable.closeAsync(); } });
379
106
485
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/masterreplica/SentinelConnector.java
SentinelConnector
getTopologyRefreshRunnable
class SentinelConnector<K, V> implements MasterReplicaConnector<K, V> { private static final InternalLogger LOG = InternalLoggerFactory.getInstance(SentinelConnector.class); private final RedisClient redisClient; private final RedisCodec<K, V> codec; private final RedisURI redisURI; SentinelConnector(RedisClient redisClient, RedisCodec<K, V> codec, RedisURI redisURI) { this.redisClient = redisClient; this.codec = codec; this.redisURI = redisURI; } @Override public CompletableFuture<StatefulRedisMasterReplicaConnection<K, V>> connectAsync() { TopologyProvider topologyProvider = new SentinelTopologyProvider(redisURI.getSentinelMasterId(), redisClient, redisURI); SentinelTopologyRefresh sentinelTopologyRefresh = new SentinelTopologyRefresh(redisClient, redisURI.getSentinelMasterId(), redisURI.getSentinels()); MasterReplicaTopologyRefresh refresh = new MasterReplicaTopologyRefresh(redisClient, topologyProvider); MasterReplicaConnectionProvider<K, V> connectionProvider = new MasterReplicaConnectionProvider<>(redisClient, codec, redisURI, Collections.emptyMap()); Runnable runnable = getTopologyRefreshRunnable(refresh, connectionProvider); return refresh.getNodes(redisURI).flatMap(nodes -> { if (nodes.isEmpty()) { return Mono.error(new RedisException(String.format("Cannot determine topology from %s", redisURI))); } return initializeConnection(codec, sentinelTopologyRefresh, connectionProvider, runnable, nodes); }).onErrorMap(ExecutionException.class, Throwable::getCause).toFuture(); } private Mono<StatefulRedisMasterReplicaConnection<K, V>> initializeConnection(RedisCodec<K, V> codec, SentinelTopologyRefresh sentinelTopologyRefresh, MasterReplicaConnectionProvider<K, V> connectionProvider, Runnable runnable, List<RedisNodeDescription> nodes) { connectionProvider.setKnownNodes(nodes); MasterReplicaChannelWriter channelWriter = new MasterReplicaChannelWriter(connectionProvider, redisClient.getResources(), redisClient.getOptions()) { @Override public CompletableFuture<Void> closeAsync() { return CompletableFuture.allOf(super.closeAsync(), sentinelTopologyRefresh.closeAsync()); } }; StatefulRedisMasterReplicaConnectionImpl<K, V> connection = new StatefulRedisMasterReplicaConnectionImpl<>( channelWriter, codec, redisURI.getTimeout()); connection.setOptions(redisClient.getOptions()); CompletionStage<Void> bind = sentinelTopologyRefresh.bind(runnable); return Mono.fromCompletionStage(bind).onErrorResume(t -> { return ResumeAfter.close(connection).thenError(t); }).then(Mono.just(connection)); } private Runnable getTopologyRefreshRunnable(MasterReplicaTopologyRefresh refresh, MasterReplicaConnectionProvider<K, V> connectionProvider) {<FILL_FUNCTION_BODY>} }
return () -> { try { LOG.debug("Refreshing topology"); refresh.getNodes(redisURI).subscribe(nodes -> { EventRecorder.getInstance().record(new MasterReplicaTopologyChangedEvent(redisURI, nodes)); if (nodes.isEmpty()) { LOG.warn("Topology refresh returned no nodes from {}", redisURI); } LOG.debug("New topology: {}", nodes); connectionProvider.setKnownNodes(nodes); }, t -> LOG.error("Error during background refresh", t)); } catch (Exception e) { LOG.error("Error during background refresh", e); } };
872
175
1,047
<no_super_class>
redis_lettuce
lettuce/src/main/java/io/lettuce/core/masterreplica/SentinelTopologyProvider.java
SentinelTopologyProvider
getNodesAsync
class SentinelTopologyProvider implements TopologyProvider { private static final InternalLogger logger = InternalLoggerFactory.getInstance(SentinelTopologyProvider.class); private final String masterId; private final RedisClient redisClient; private final RedisURI sentinelUri; private final Duration timeout; /** * Creates a new {@link SentinelTopologyProvider}. * * @param masterId must not be empty * @param redisClient must not be {@code null}. * @param sentinelUri must not be {@code null}. */ public SentinelTopologyProvider(String masterId, RedisClient redisClient, RedisURI sentinelUri) { LettuceAssert.notEmpty(masterId, "MasterId must not be empty"); LettuceAssert.notNull(redisClient, "RedisClient must not be null"); LettuceAssert.notNull(sentinelUri, "Sentinel URI must not be null"); this.masterId = masterId; this.redisClient = redisClient; this.sentinelUri = sentinelUri; this.timeout = sentinelUri.getTimeout(); } @Override public List<RedisNodeDescription> getNodes() { logger.debug("lookup topology for masterId {}", masterId); try { return getNodesAsync().get(timeout.toMillis(), TimeUnit.MILLISECONDS); } catch (Exception e) { throw Exceptions.bubble(e); } } @Override public CompletableFuture<List<RedisNodeDescription>> getNodesAsync() {<FILL_FUNCTION_BODY>} protected Mono<List<RedisNodeDescription>> getNodes(StatefulRedisSentinelConnection<String, String> connection) { RedisSentinelReactiveCommands<String, String> reactive = connection.reactive(); Mono<Tuple2<Map<String, String>, List<Map<String, String>>>> masterAndReplicas = reactive.master(masterId) .zipWith(reactive.replicas(masterId).collectList()).timeout(this.timeout).flatMap(tuple -> { return ResumeAfter.close(connection).thenEmit(tuple); }).doOnError(e -> connection.closeAsync()); return masterAndReplicas.map(tuple -> { List<RedisNodeDescription> result = new ArrayList<>(); result.add(toNode(tuple.getT1(), RedisInstance.Role.UPSTREAM)); result.addAll(tuple.getT2().stream().filter(SentinelTopologyProvider::isAvailable) .map(map -> toNode(map, RedisInstance.Role.REPLICA)).collect(Collectors.toList())); return result; }); } private static boolean isAvailable(Map<String, String> map) { String flags = map.get("flags"); if (flags != null) { if (flags.contains("s_down") || flags.contains("o_down") || flags.contains("disconnected")) { return false; } } return true; } private RedisNodeDescription toNode(Map<String, String> map, RedisInstance.Role role) { String ip = map.get("ip"); String port = map.get("port"); return new RedisMasterReplicaNode(ip, Integer.parseInt(port), sentinelUri, role); } }
logger.debug("lookup topology for masterId {}", masterId); Mono<StatefulRedisSentinelConnection<String, String>> connect = Mono .fromFuture(redisClient.connectSentinelAsync(StringCodec.UTF8, sentinelUri)); return connect.flatMap(this::getNodes).toFuture();
901
89
990
<no_super_class>