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/masterreplica/SentinelTopologyRefreshConnections.java
|
SentinelTopologyRefreshConnections
|
onEmit
|
class SentinelTopologyRefreshConnections extends
CompletableEventLatchSupport<StatefulRedisPubSubConnection<String, String>, SentinelTopologyRefreshConnections> {
private final List<Throwable> exceptions = new CopyOnWriteArrayList<>();
private final AtomicInteger success = new AtomicInteger();
/**
* Construct a new {@link CompletableEventLatchSupport} class expecting {@code expectedCount} notifications.
*
* @param expectedCount
*/
public SentinelTopologyRefreshConnections(int expectedCount) {
super(expectedCount);
}
@Override
protected void onAccept(StatefulRedisPubSubConnection<String, String> value) {
success.incrementAndGet();
}
@Override
protected void onError(Throwable value) {
exceptions.add(value);
}
@Override
protected void onEmit(Emission<SentinelTopologyRefreshConnections> emission) {<FILL_FUNCTION_BODY>}
}
|
if (success.get() == 0) {
RedisException exception = new RedisException("Cannot attach to Redis Sentinel for topology refresh");
exceptions.forEach(exception::addSuppressed);
emission.error(exception);
} else {
emission.success(this);
}
| 259
| 77
| 336
|
<methods>public void <init>(int) ,public final void accept(StatefulRedisPubSubConnection<java.lang.String,java.lang.String>) ,public final void accept(java.lang.Throwable) ,public final int getExpectedCount() ,public final CompletionStage<io.lettuce.core.masterreplica.SentinelTopologyRefreshConnections> 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.SentinelTopologyRefreshConnections> selfFuture,private volatile ScheduledFuture<?> timeoutScheduleFuture
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/masterreplica/StaticMasterReplicaConnector.java
|
StaticMasterReplicaConnector
|
initializeConnection
|
class StaticMasterReplicaConnector<K, V> implements MasterReplicaConnector<K, V> {
private final RedisClient redisClient;
private final RedisCodec<K, V> codec;
private final Iterable<RedisURI> redisURIs;
StaticMasterReplicaConnector(RedisClient redisClient, RedisCodec<K, V> codec, Iterable<RedisURI> redisURIs) {
this.redisClient = redisClient;
this.codec = codec;
this.redisURIs = redisURIs;
}
@Override
public CompletableFuture<StatefulRedisMasterReplicaConnection<K, V>> connectAsync() {
Map<RedisURI, StatefulRedisConnection<K, V>> initialConnections = new HashMap<>();
TopologyProvider topologyProvider = new StaticMasterReplicaTopologyProvider(redisClient, redisURIs);
RedisURI seedNode = redisURIs.iterator().next();
MasterReplicaTopologyRefresh refresh = new MasterReplicaTopologyRefresh(redisClient, topologyProvider);
MasterReplicaConnectionProvider<K, V> connectionProvider = new MasterReplicaConnectionProvider<>(redisClient, codec,
seedNode, initialConnections);
return refresh.getNodes(seedNode).flatMap(nodes -> {
EventRecorder.getInstance().record(new MasterReplicaTopologyChangedEvent(seedNode, nodes));
if (nodes.isEmpty()) {
return Mono.error(new RedisException(String.format("Cannot determine topology from %s", redisURIs)));
}
return initializeConnection(codec, seedNode, connectionProvider, nodes);
}).onErrorMap(ExecutionException.class, Throwable::getCause).toFuture();
}
private Mono<StatefulRedisMasterReplicaConnection<K, V>> initializeConnection(RedisCodec<K, V> codec, RedisURI seedNode,
MasterReplicaConnectionProvider<K, V> connectionProvider, List<RedisNodeDescription> nodes) {<FILL_FUNCTION_BODY>}
}
|
connectionProvider.setKnownNodes(nodes);
MasterReplicaChannelWriter channelWriter = new MasterReplicaChannelWriter(connectionProvider, redisClient.getResources(), redisClient.getOptions());
StatefulRedisMasterReplicaConnectionImpl<K, V> connection = new StatefulRedisMasterReplicaConnectionImpl<>(
channelWriter, codec, seedNode.getTimeout());
connection.setOptions(redisClient.getOptions());
return Mono.just(connection);
| 534
| 121
| 655
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/masterreplica/StaticMasterReplicaTopologyProvider.java
|
StaticMasterReplicaTopologyProvider
|
getNodesAsync
|
class StaticMasterReplicaTopologyProvider implements TopologyProvider {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(StaticMasterReplicaTopologyProvider.class);
private final RedisClient redisClient;
private final Iterable<RedisURI> redisURIs;
public StaticMasterReplicaTopologyProvider(RedisClient redisClient, Iterable<RedisURI> redisURIs) {
LettuceAssert.notNull(redisClient, "RedisClient must not be null");
LettuceAssert.notNull(redisURIs, "RedisURIs must not be null");
LettuceAssert.notNull(redisURIs.iterator().hasNext(), "RedisURIs must not be empty");
this.redisClient = redisClient;
this.redisURIs = redisURIs;
}
@Override
@SuppressWarnings("rawtypes")
public List<RedisNodeDescription> getNodes() {
RedisURI next = redisURIs.iterator().next();
try {
return getNodesAsync().get(next.getTimeout().toMillis(), TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw Exceptions.bubble(e);
}
}
@Override
public CompletableFuture<List<RedisNodeDescription>> getNodesAsync() {<FILL_FUNCTION_BODY>}
private Mono<RedisNodeDescription> getNodeDescription(List<StatefulRedisConnection<String, String>> connections,
RedisURI uri) {
return Mono.fromCompletionStage(redisClient.connectAsync(StringCodec.UTF8, uri)) //
.onErrorResume(t -> {
logger.warn("Cannot connect to {}", uri, t);
return Mono.empty();
}) //
.doOnNext(connections::add) //
.flatMap(connection -> {
Mono<RedisNodeDescription> instance = getNodeDescription(uri, connection);
return instance.flatMap(it -> ResumeAfter.close(connection).thenEmit(it)).doFinally(s -> {
connections.remove(connection);
});
});
}
private static Mono<RedisNodeDescription> getNodeDescription(RedisURI uri,
StatefulRedisConnection<String, String> connection) {
return connection.reactive().role().collectList().map(RoleParser::parse)
.map(it -> new RedisMasterReplicaNode(uri.getHost(), uri.getPort(), uri, it.getRole()));
}
}
|
List<StatefulRedisConnection<String, String>> connections = new CopyOnWriteArrayList<>();
Flux<RedisURI> uris = Flux.fromIterable(redisURIs);
Mono<List<RedisNodeDescription>> nodes = uris.flatMap(uri -> getNodeDescription(connections, uri)).collectList()
.flatMap((nodeDescriptions) -> {
if (nodeDescriptions.isEmpty()) {
return Mono.error(new RedisConnectionException(
String.format("Failed to connect to at least one node in %s", redisURIs)));
}
return Mono.just(nodeDescriptions);
});
return nodes.toFuture();
| 653
| 180
| 833
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/masterreplica/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/masterreplica/Timeout.java
|
Timeout
|
remaining
|
class Timeout {
private final long expiresMs;
public Timeout(long timeout, TimeUnit timeUnit) {
this.expiresMs = System.currentTimeMillis() + timeUnit.toMillis(timeout);
}
public boolean isExpired() {
return expiresMs < System.currentTimeMillis();
}
public long remaining() {<FILL_FUNCTION_BODY>}
}
|
long diff = expiresMs - System.currentTimeMillis();
if (diff > 0) {
return diff;
}
return 0;
| 109
| 43
| 152
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/masterreplica/TopologyComparators.java
|
LatencyComparator
|
getSortAction
|
class LatencyComparator implements Comparator<RedisNodeDescription> {
private final Map<RedisNodeDescription, Long> latencies;
public LatencyComparator(Map<RedisNodeDescription, Long> latencies) {
this.latencies = latencies;
}
@Override
public int compare(RedisNodeDescription o1, RedisNodeDescription o2) {
Long latency1 = latencies.get(o1);
Long latency2 = latencies.get(o2);
if (latency1 != null && latency2 != null) {
return latency1.compareTo(latency2);
}
if (latency1 != null) {
return -1;
}
if (latency2 != null) {
return 1;
}
return 0;
}
}
/**
* Sort action for topology. Defaults to sort by latency. Can be set via {@code io.lettuce.core.topology.sort} system
* property.
*
* @since 4.5
*/
enum SortAction {
/**
* Sort by latency.
*/
BY_LATENCY {
@Override
void sort(List<RedisNodeDescription> nodes, Comparator<? super RedisNodeDescription> latencyComparator) {
nodes.sort(latencyComparator);
}
},
/**
* Do not sort.
*/
NONE {
@Override
void sort(List<RedisNodeDescription> nodes, Comparator<? super RedisNodeDescription> latencyComparator) {
}
},
/**
* Randomize nodes.
*/
RANDOMIZE {
@Override
void sort(List<RedisNodeDescription> nodes, Comparator<? super RedisNodeDescription> latencyComparator) {
Collections.shuffle(nodes);
}
};
abstract void sort(List<RedisNodeDescription> nodes, Comparator<? super RedisNodeDescription> latencyComparator);
/**
* @return determine {@link SortAction} and fall back to {@link SortAction#BY_LATENCY} if sort action cannot be
* resolved.
*/
static SortAction getSortAction() {<FILL_FUNCTION_BODY>
|
String sortAction = System.getProperty("io.lettuce.core.topology.sort", BY_LATENCY.name());
for (SortAction action : values()) {
if (sortAction.equalsIgnoreCase(action.name())) {
return action;
}
}
return BY_LATENCY;
| 597
| 86
| 683
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/masterslave/MasterSlave.java
|
MasterSlave
|
connect
|
class MasterSlave {
/**
* Open a new connection to a Redis Master-Slave server/servers using the supplied {@link RedisURI} and the supplied
* {@link RedisCodec codec} to encode/decode keys.
* <p>
* This {@link MasterSlave} performs auto-discovery of nodes using either Redis Sentinel or Master/Slave. A {@link RedisURI}
* can point to either a master or a replica host.
* </p>
*
* @param redisClient the Redis client.
* @param codec Use this codec to encode/decode keys and values, must not be {@code null}.
* @param redisURI the Redis server to connect to, must not be {@code null}.
* @param <K> Key type.
* @param <V> Value type.
* @return a new connection.
*/
public static <K, V> StatefulRedisMasterSlaveConnection<K, V> connect(RedisClient redisClient, RedisCodec<K, V> codec,
RedisURI redisURI) {<FILL_FUNCTION_BODY>}
/**
* Open asynchronously a new connection to a Redis Master-Slave server/servers using the supplied {@link RedisURI} and the
* supplied {@link RedisCodec codec} to encode/decode keys.
* <p>
* This {@link MasterSlave} performs auto-discovery of nodes using either Redis Sentinel or Master/Slave. A {@link RedisURI}
* can point to either a master or a replica host.
* </p>
*
* @param redisClient the Redis client.
* @param codec Use this codec to encode/decode keys and values, must not be {@code null}.
* @param redisURI the Redis server to connect to, must not be {@code null}.
* @param <K> Key type.
* @param <V> Value type.
* @return {@link CompletableFuture} that is notified once the connect is finished.
* @since
*/
public static <K, V> CompletableFuture<StatefulRedisMasterSlaveConnection<K, V>> connectAsync(RedisClient redisClient,
RedisCodec<K, V> codec, RedisURI redisURI) {
return MasterReplica.connectAsync(redisClient, codec, redisURI).thenApply(MasterSlaveConnectionWrapper::new);
}
/**
* Open a new connection to a Redis Master-Slave server/servers using the supplied {@link RedisURI} and the supplied
* {@link RedisCodec codec} to encode/decode keys.
* <p>
* This {@link MasterSlave} performs auto-discovery of nodes if the URI is a Redis Sentinel URI. Master/Slave URIs will be
* treated as static topology and no additional hosts are discovered in such case. Redis Standalone Master/Slave will
* discover the roles of the supplied {@link RedisURI URIs} and issue commands to the appropriate node.
* </p>
* <p>
* When using Redis Sentinel, ensure that {@link Iterable redisURIs} contains only a single entry as only the first URI is
* considered. {@link RedisURI} pointing to multiple Sentinels can be configured through
* {@link RedisURI.Builder#withSentinel}.
* </p>
*
* @param redisClient the Redis client.
* @param codec Use this codec to encode/decode keys and values, must not be {@code null}.
* @param redisURIs the Redis server(s) to connect to, must not be {@code null}.
* @param <K> Key type.
* @param <V> Value type.
* @return a new connection.
*/
public static <K, V> StatefulRedisMasterSlaveConnection<K, V> connect(RedisClient redisClient, RedisCodec<K, V> codec,
Iterable<RedisURI> redisURIs) {
return new MasterSlaveConnectionWrapper<>(MasterReplica.connect(redisClient, codec, redisURIs));
}
/**
* Open asynchronously a new connection to a Redis Master-Slave server/servers using the supplied {@link RedisURI} and the
* supplied {@link RedisCodec codec} to encode/decode keys.
* <p>
* This {@link MasterSlave} performs auto-discovery of nodes if the URI is a Redis Sentinel URI. Master/Slave URIs will be
* treated as static topology and no additional hosts are discovered in such case. Redis Standalone Master/Slave will
* discover the roles of the supplied {@link RedisURI URIs} and issue commands to the appropriate node.
* </p>
* <p>
* When using Redis Sentinel, ensure that {@link Iterable redisURIs} contains only a single entry as only the first URI is
* considered. {@link RedisURI} pointing to multiple Sentinels can be configured through
* {@link RedisURI.Builder#withSentinel}.
* </p>
*
* @param redisClient the Redis client.
* @param codec Use this codec to encode/decode keys and values, must not be {@code null}.
* @param redisURIs the Redis server(s) to connect to, must not be {@code null}.
* @param <K> Key type.
* @param <V> Value type.
* @return {@link CompletableFuture} that is notified once the connect is finished.
*/
public static <K, V> CompletableFuture<StatefulRedisMasterSlaveConnection<K, V>> connectAsync(RedisClient redisClient,
RedisCodec<K, V> codec, Iterable<RedisURI> redisURIs) {
return MasterReplica.connectAsync(redisClient, codec, redisURIs).thenApply(MasterSlaveConnectionWrapper::new);
}
}
|
LettuceAssert.notNull(redisClient, "RedisClient must not be null");
LettuceAssert.notNull(codec, "RedisCodec must not be null");
LettuceAssert.notNull(redisURI, "RedisURI must not be null");
return new MasterSlaveConnectionWrapper<>(MasterReplica.connect(redisClient, codec, redisURI));
| 1,503
| 101
| 1,604
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/metrics/CommandLatencyId.java
|
CommandLatencyId
|
hashCode
|
class CommandLatencyId implements Serializable, Comparable<CommandLatencyId> {
private final SocketAddress localAddress;
private final SocketAddress remoteAddress;
private final ProtocolKeyword commandType;
private final String commandName;
protected CommandLatencyId(SocketAddress localAddress, SocketAddress remoteAddress, ProtocolKeyword commandType) {
LettuceAssert.notNull(localAddress, "LocalAddress must not be null");
LettuceAssert.notNull(remoteAddress, "RemoteAddress must not be null");
LettuceAssert.notNull(commandType, "CommandType must not be null");
this.localAddress = localAddress;
this.remoteAddress = remoteAddress;
this.commandType = commandType;
this.commandName = commandType.name();
}
/**
* Create a new instance of {@link CommandLatencyId}.
*
* @param localAddress the local address
* @param remoteAddress the remote address
* @param commandType the command type
* @return a new instance of {@link CommandLatencyId}
*/
public static CommandLatencyId create(SocketAddress localAddress, SocketAddress remoteAddress,
ProtocolKeyword commandType) {
return new CommandLatencyId(localAddress, remoteAddress, commandType);
}
/**
* Returns the local address.
*
* @return the local address
*/
public SocketAddress localAddress() {
return localAddress;
}
/**
* Returns the remote address.
*
* @return the remote address
*/
public SocketAddress remoteAddress() {
return remoteAddress;
}
/**
* Returns the command type.
*
* @return the command type
*/
public ProtocolKeyword commandType() {
return commandType;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof CommandLatencyId))
return false;
CommandLatencyId that = (CommandLatencyId) o;
if (!localAddress.equals(that.localAddress))
return false;
if (!remoteAddress.equals(that.remoteAddress))
return false;
return commandName.equals(that.commandName);
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public int compareTo(CommandLatencyId o) {
if (o == null) {
return -1;
}
int remoteResult = remoteAddress.toString().compareTo(o.remoteAddress.toString());
if (remoteResult != 0) {
return remoteResult;
}
int localResult = localAddress.toString().compareTo(o.localAddress.toString());
if (localResult != 0) {
return localResult;
}
return commandName.compareTo(o.commandName);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[").append(localAddress);
sb.append(" -> ").append(remoteAddress);
sb.append(", commandType=").append(commandType);
sb.append(']');
return sb.toString();
}
}
|
int result = localAddress.hashCode();
result = 31 * result + remoteAddress.hashCode();
result = 31 * result + commandName.hashCode();
return result;
| 829
| 49
| 878
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/metrics/CommandMetrics.java
|
CommandLatency
|
toString
|
class CommandLatency {
private final long min;
private final long max;
private final Map<Double, Long> percentiles;
public CommandLatency(long min, long max, Map<Double, Long> percentiles) {
this.min = min;
this.max = max;
this.percentiles = percentiles;
}
/**
*
* @return the minimum time
*/
public long getMin() {
return min;
}
/**
*
* @return the maximum time
*/
public long getMax() {
return max;
}
/**
*
* @return percentile mapping
*/
public Map<Double, Long> getPercentiles() {
return percentiles;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder();
sb.append("[min=").append(min);
sb.append(", max=").append(max);
sb.append(", percentiles=").append(percentiles);
sb.append(']');
return sb.toString();
| 228
| 72
| 300
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/metrics/DefaultCommandLatencyCollectorOptions.java
|
Builder
|
targetPercentiles
|
class Builder implements CommandLatencyCollectorOptions.Builder {
private TimeUnit targetUnit = DEFAULT_TARGET_UNIT;
private double[] targetPercentiles = DEFAULT_TARGET_PERCENTILES;
private boolean resetLatenciesAfterEvent = DEFAULT_RESET_LATENCIES_AFTER_EVENT;
private boolean localDistinction = DEFAULT_LOCAL_DISTINCTION;
private boolean enabled = DEFAULT_ENABLED;
private boolean usePauseDetector = DEFAULT_USE_NO_PAUSE_DETECTOR;
private Builder() {
}
/**
* Disable the latency collector.
*
* @return this {@link Builder}.
*/
@Override
public Builder disable() {
this.enabled = false;
return this;
}
/**
* Enable the latency collector.
*
* @return this {@link Builder}.
* @since 5.1
*/
@Override
public Builder enable() {
this.enabled = true;
return this;
}
/**
* Use {@code LatencyUtils.SimplePauseDetector} to detect pauses. Defaults to no pause detector.
*
* @return this {@link DefaultCommandLatencyCollectorOptions.Builder}.
* @since 6.1.7
* @see org.LatencyUtils.SimplePauseDetector
*/
@Override
public Builder usePauseDetector() {
this.usePauseDetector = true;
return this;
}
/**
* Do not detect pauses. Defaults to no pause detector.
*
* @return this {@link DefaultCommandLatencyCollectorOptions.Builder}.
* @since 6.1.7
*/
@Override
public Builder useNoPauseDetector() {
this.usePauseDetector = false;
return this;
}
/**
* Set the target unit for the latencies. Defaults to {@link TimeUnit#MILLISECONDS}. See
* {@link DefaultCommandLatencyCollectorOptions#DEFAULT_TARGET_UNIT}.
*
* @param targetUnit the target unit, must not be {@code null}
* @return this {@link Builder}.
*/
@Override
public Builder targetUnit(TimeUnit targetUnit) {
LettuceAssert.notNull(targetUnit, "TargetUnit must not be null");
this.targetUnit = targetUnit;
return this;
}
/**
* Sets the emitted percentiles. Defaults to 50.0, 90.0, 95.0, 99.0, 99.9} . See
* {@link DefaultCommandLatencyCollectorOptions#DEFAULT_TARGET_PERCENTILES}.
*
* @param targetPercentiles the percentiles which should be emitted, must not be {@code null}
* @return this {@link Builder}.
*/
@Override
public Builder targetPercentiles(double[] targetPercentiles) {
LettuceAssert.notNull(targetPercentiles, "TargetPercentiles must not be null");
this.targetPercentiles = targetPercentiles;
return this;
}
/**
* Sets whether the recorded latencies should be reset once the metrics event was emitted. Defaults to {@code true}.
* See {@link DefaultCommandLatencyCollectorOptions#DEFAULT_RESET_LATENCIES_AFTER_EVENT}.
*
* @param resetLatenciesAfterEvent {@code true} if the recorded latencies should be reset once the metrics event was
* emitted
* @return this {@link Builder}.
*/
@Override
public Builder resetLatenciesAfterEvent(boolean resetLatenciesAfterEvent) {
this.resetLatenciesAfterEvent = resetLatenciesAfterEvent;
return this;
}
/**
* Enables per connection metrics tracking insead of per host/port. If {@code true}, multiple connections to the same
* host/connection point will be recorded separately which allows to inspect every connection individually. If
* {@code false}, multiple connections to the same host/connection point will be recorded together. This allows a
* consolidated view on one particular service. Defaults to {@code false}. See
* {@link DefaultCommandLatencyCollectorOptions#DEFAULT_LOCAL_DISTINCTION}.
*
* @param localDistinction {@code true} if latencies are recorded distinct on local level (per connection)
* @return this {@link Builder}.
*/
@Override
public Builder localDistinction(boolean localDistinction) {
this.localDistinction = localDistinction;
return this;
}
/**
* @return a new instance of {@link DefaultCommandLatencyCollectorOptions}.
*/
@Override
public DefaultCommandLatencyCollectorOptions build() {
return new DefaultCommandLatencyCollectorOptions(this);
}
}
@Override
public TimeUnit targetUnit() {
return targetUnit;
}
@Override
public double[] targetPercentiles() {<FILL_FUNCTION_BODY>
|
double[] result = new double[targetPercentiles.length];
System.arraycopy(targetPercentiles, 0, result, 0, targetPercentiles.length);
return result;
| 1,269
| 51
| 1,320
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/metrics/MicrometerCommandLatencyRecorder.java
|
MicrometerCommandLatencyRecorder
|
recordCommandLatency
|
class MicrometerCommandLatencyRecorder implements CommandLatencyRecorder {
static final String LABEL_COMMAND = "command";
static final String LABEL_LOCAL = "local";
static final String LABEL_REMOTE = "remote";
static final String METRIC_COMPLETION = "lettuce.command.completion";
static final String METRIC_FIRST_RESPONSE = "lettuce.command.firstresponse";
private final MeterRegistry meterRegistry;
private final MicrometerOptions options;
private final Map<CommandLatencyId, Timer> completionTimers = new ConcurrentHashMap<>();
private final Map<CommandLatencyId, Timer> firstResponseTimers = new ConcurrentHashMap<>();
/**
* Create a new {@link MicrometerCommandLatencyRecorder} instance given {@link MeterRegistry} and {@link MicrometerOptions}.
*
* @param meterRegistry
* @param options
*/
public MicrometerCommandLatencyRecorder(MeterRegistry meterRegistry, MicrometerOptions options) {
LettuceAssert.notNull(meterRegistry, "MeterRegistry must not be null");
LettuceAssert.notNull(options, "MicrometerOptions must not be null");
this.meterRegistry = meterRegistry;
this.options = options;
}
@Override
public void recordCommandLatency(SocketAddress local, SocketAddress remote, RedisCommand<?, ?, ?> redisCommand,
long firstResponseLatency, long completionLatency) {<FILL_FUNCTION_BODY>}
@Override
public void recordCommandLatency(SocketAddress local, SocketAddress remote, ProtocolKeyword commandType,
long firstResponseLatency, long completionLatency) {
if (!isEnabled()) {
return;
}
CommandLatencyId commandLatencyId = createId(local, remote, commandType);
Timer firstResponseTimer = firstResponseTimers.computeIfAbsent(commandLatencyId, this::firstResponseTimer);
firstResponseTimer.record(firstResponseLatency, TimeUnit.NANOSECONDS);
Timer completionTimer = completionTimers.computeIfAbsent(commandLatencyId, this::completionTimer);
completionTimer.record(completionLatency, TimeUnit.NANOSECONDS);
}
@Override
public boolean isEnabled() {
return options.isEnabled();
}
private boolean isCommandEnabled(RedisCommand<?, ?, ?> redisCommand) {
return options.getMetricsFilter().test(redisCommand);
}
private CommandLatencyId createId(SocketAddress local, SocketAddress remote, ProtocolKeyword commandType) {
return CommandLatencyId.create(options.localDistinction() ? local : LocalAddress.ANY, remote, commandType);
}
protected Timer completionTimer(CommandLatencyId commandLatencyId) {
Timer.Builder timer = Timer.builder(METRIC_COMPLETION)
.description("Latency between command send and command completion (complete response received")
.tag(LABEL_COMMAND, commandLatencyId.commandType().name())
.tag(LABEL_LOCAL, commandLatencyId.localAddress().toString())
.tag(LABEL_REMOTE, commandLatencyId.remoteAddress().toString()).tags(options.tags());
if (options.isHistogram()) {
timer.publishPercentileHistogram().publishPercentiles(options.targetPercentiles())
.minimumExpectedValue(options.minLatency()).maximumExpectedValue(options.maxLatency());
}
return timer.register(meterRegistry);
}
protected Timer firstResponseTimer(CommandLatencyId commandLatencyId) {
Timer.Builder timer = Timer.builder(METRIC_FIRST_RESPONSE)
.description("Latency between command send and first response (first response received)")
.tag(LABEL_COMMAND, commandLatencyId.commandType().name())
.tag(LABEL_LOCAL, commandLatencyId.localAddress().toString())
.tag(LABEL_REMOTE, commandLatencyId.remoteAddress().toString()).tags(options.tags());
if (options.isHistogram()) {
timer.publishPercentileHistogram().publishPercentiles(options.targetPercentiles())
.minimumExpectedValue(options.minLatency()).maximumExpectedValue(options.maxLatency());
}
return timer.register(meterRegistry);
}
}
|
if (isEnabled() && isCommandEnabled(redisCommand)) {
recordCommandLatency(local, remote, redisCommand.getType(), firstResponseLatency, completionLatency);
}
| 1,152
| 51
| 1,203
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/metrics/MicrometerOptions.java
|
Builder
|
metricsFilter
|
class Builder {
private boolean enabled = DEFAULT_ENABLED;
private boolean histogram = DEFAULT_HISTOGRAM;
private boolean localDistinction = DEFAULT_LOCAL_DISTINCTION;
private Predicate<RedisCommand<?, ?, ?>> metricsFilter = command -> true;
private Duration maxLatency = DEFAULT_MAX_LATENCY;
private Duration minLatency = DEFAULT_MIN_LATENCY;
private Tags tags = Tags.empty();
private double[] targetPercentiles = DEFAULT_TARGET_PERCENTILES;
private Builder() {
}
/**
* Disable the latency collector.
*
* @return this {@link Builder}.
*/
public Builder disable() {
this.enabled = false;
return this;
}
/**
* Enable the latency collector.
*
* @return this {@link Builder}.
*/
public Builder enable() {
this.enabled = true;
return this;
}
/**
* Enable histogram buckets used to generate aggregable percentile approximations in monitoring systems that have query
* facilities to do so.
*
* @param histogram {@code true} if histogram buckets are recorded
* @return this {@link Builder}.
*/
public Builder histogram(boolean histogram) {
this.histogram = histogram;
return this;
}
/**
* Enables per connection metrics tracking insead of per host/port. If {@code true}, multiple connections to the same
* host/connection point will be recorded separately which allows to inspect every connection individually. If
* {@code false}, multiple connections to the same host/connection point will be recorded together. This allows a
* consolidated view on one particular service. Defaults to {@code false}. See
* {@link MicrometerOptions#DEFAULT_LOCAL_DISTINCTION}.
*
* Warning: Enabling this could potentially cause a label cardinality explosion in the remote metric system and should
* be used with caution.
*
* @param localDistinction {@code true} if latencies are recorded distinct on local level (per connection)
* @return this {@link Builder}.
*/
public Builder localDistinction(boolean localDistinction) {
this.localDistinction = localDistinction;
return this;
}
/**
* Sets which commands are enabled for latency recording. Defaults to an empty list, which means all commands will be
* recorded. Configuring enabled commands overwrites {@link #metricsFilter(Predicate)}.
*
* @param commands list of Redis commands that are enabled for latency recording, must not be {@code null}
* @return this {@link Builder}.
* @since 6.3
*/
public Builder enabledCommands(CommandType... commands) {
LettuceAssert.notNull(commands, "Commands must not be null");
if (commands.length == 0) {
return metricsFilter(command -> true);
}
Set<String> enabledCommands = new HashSet<>(commands.length);
for (CommandType enabledCommand : commands) {
enabledCommands.add(enabledCommand.name());
}
return metricsFilter(command -> enabledCommands.contains(command.getType().name()));
}
/**
* Configures a filter {@link Predicate} to filter which commands should be reported to Micrometer.
*
* @param filter the filter predicate to test commands.
* @return this {@link Builder}.
* @since 6.3
*/
public Builder metricsFilter(Predicate<RedisCommand<?, ?, ?>> filter) {<FILL_FUNCTION_BODY>}
/**
* Sets the maximum value that this timer is expected to observe. Sets an upper bound on histogram buckets that are
* shipped to monitoring systems that support aggregable percentile approximations. Only applicable when histogram is
* enabled. Defaults to {@code 5m}. See {@link MicrometerOptions#DEFAULT_MAX_LATENCY}.
*
* @param maxLatency the maximum value that this timer is expected to observe, must not be {@code null}
* @return this {@link Builder}.
*/
public Builder maxLatency(Duration maxLatency) {
LettuceAssert.notNull(maxLatency, "Max Latency must not be null");
this.maxLatency = maxLatency;
return this;
}
/**
* Sets the minimum value that this timer is expected to observe. Sets a lower bound on histogram buckets that are
* shipped to monitoring systems that support aggregable percentile approximations. Only applicable when histogram is
* enabled. Defaults to {@code 1ms}. See {@link MicrometerOptions#DEFAULT_MIN_LATENCY}.
*
* @param minLatency the minimum value that this timer is expected to observe
* @return this {@link Builder}.
*/
public Builder minLatency(Duration minLatency) {
LettuceAssert.notNull(minLatency, "Min Latency must not be null");
this.minLatency = minLatency;
return this;
}
/**
* Extra tags to add to the generated metrics. Defaults to {@code Tags.empty()}.
*
* @param tags tags to add to the metrics
* @return this {@link Builder}.
*/
public Builder tags(Tags tags) {
LettuceAssert.notNull(tags, "Tags must not be null");
this.tags = tags;
return this;
}
/**
* Sets the emitted percentiles. Defaults to {@code 0.50, 0.90, 0.95, 0.99, 0.999} for the 50th, 90th, 95th, 99th, and
* 99th percentiles. Only applicable when histogram is enabled. See
* {@link MicrometerOptions#DEFAULT_TARGET_PERCENTILES}.
*
* @param targetPercentiles the percentiles which should be emitted, must not be {@code null}
* @return this {@link Builder}.
*/
public Builder targetPercentiles(double[] targetPercentiles) {
LettuceAssert.notNull(targetPercentiles, "TargetPercentiles must not be null");
this.targetPercentiles = targetPercentiles;
return this;
}
/**
* @return a new instance of {@link MicrometerOptions}.
*/
public MicrometerOptions build() {
return new MicrometerOptions(this);
}
}
|
LettuceAssert.notNull(filter, "Metrics filter predicate must not be null");
this.metricsFilter = filter;
return this;
| 1,650
| 39
| 1,689
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/models/command/CommandDetail.java
|
CommandDetail
|
toString
|
class CommandDetail implements Serializable {
private String name;
private int arity;
private Set<Flag> flags;
private int firstKeyPosition;
private int lastKeyPosition;
private int keyStepCount;
private Set<AclCategory> aclCategories;
public CommandDetail() {
}
/**
* Constructs a {@link CommandDetail}
*
* @param name name of the command, must not be {@code null}
* @param arity command arity specification
* @param flags set of flags, must not be {@code null} but may be empty
* @param firstKeyPosition position of first key in argument list
* @param lastKeyPosition position of last key in argument list
* @param keyStepCount step count for locating repeating keys
* @deprecated since 6.1
*/
@Deprecated
public CommandDetail(String name, int arity, Set<Flag> flags, int firstKeyPosition, int lastKeyPosition, int keyStepCount) {
this(name, arity, flags, firstKeyPosition, lastKeyPosition, keyStepCount, null);
}
/**
* Constructs a {@link CommandDetail}
*
* @param name name of the command, must not be {@code null}
* @param arity command arity specification
* @param flags set of flags, must not be {@code null} but may be empty
* @param firstKeyPosition position of first key in argument list
* @param lastKeyPosition position of last key in argument list
* @param keyStepCount step count for locating repeating keys
* @param aclCategories command ACL details
* @since 6.1
*/
public CommandDetail(String name, int arity, Set<Flag> flags, int firstKeyPosition, int lastKeyPosition, int keyStepCount, Set<AclCategory> aclCategories) {
this.name = name;
this.arity = arity;
this.flags = flags;
this.firstKeyPosition = firstKeyPosition;
this.lastKeyPosition = lastKeyPosition;
this.keyStepCount = keyStepCount;
this.aclCategories = aclCategories;
}
public String getName() {
return name;
}
public int getArity() {
return arity;
}
public Set<Flag> getFlags() {
return flags;
}
public int getFirstKeyPosition() {
return firstKeyPosition;
}
public int getLastKeyPosition() {
return lastKeyPosition;
}
public int getKeyStepCount() {
return keyStepCount;
}
public void setName(String name) {
this.name = name;
}
public void setArity(int arity) {
this.arity = arity;
}
public void setFlags(Set<Flag> flags) {
this.flags = flags;
}
public void setFirstKeyPosition(int firstKeyPosition) {
this.firstKeyPosition = firstKeyPosition;
}
public void setLastKeyPosition(int lastKeyPosition) {
this.lastKeyPosition = lastKeyPosition;
}
public void setKeyStepCount(int keyStepCount) {
this.keyStepCount = keyStepCount;
}
public Set<AclCategory> getAclCategories() {
return aclCategories;
}
public void setAclCategories(Set<AclCategory> aclCategories) {
this.aclCategories = aclCategories;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public enum Flag {
/**
* command may result in modifications.
*/
WRITE,
/**
* command will never modify keys.
*/
READONLY,
/**
* reject command if currently OOM.
*/
DENYOOM,
/**
* server admin command.
*/
ADMIN,
/**
* pubsub-related command.
*/
PUBSUB,
/**
* deny this command from scripts.
*/
NOSCRIPT,
/**
* command has random results, dangerous for scripts.
*/
RANDOM,
/**
* if called from script, sort output.
*/
SORT_FOR_SCRIPT,
/**
* allow command while database is loading.
*/
LOADING,
/**
* allow command while replica has stale data.
*/
STALE,
/**
* do not show this command in MONITOR.
*/
SKIP_MONITOR,
/**
* cluster related - accept even if importing.
*/
ASKING,
/**
* command operates in constant or log(N) time. Used for latency monitoring.
*/
FAST,
/**
* keys have no pre-determined position. You must discover keys yourself.
*/
MOVABLEKEYS;
}
}
|
final StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [name='").append(name).append('\'');
sb.append(", arity=").append(arity);
sb.append(", flags=").append(flags);
sb.append(", firstKeyPosition=").append(firstKeyPosition);
sb.append(", lastKeyPosition=").append(lastKeyPosition);
sb.append(", keyStepCount=").append(keyStepCount);
sb.append(", aclCategories=").append(aclCategories);
sb.append(']');
return sb.toString();
| 1,286
| 164
| 1,450
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/models/command/CommandDetailParser.java
|
CommandDetailParser
|
parseAclCategories
|
class CommandDetailParser {
/**
* Number of array elements for a specific command.
*/
public static final int COMMAND_INFO_SIZE = 6;
@SuppressWarnings("serial")
protected static final Map<String, CommandDetail.Flag> FLAG_MAPPING;
@SuppressWarnings("serial")
protected static final Map<String, AclCategory> ACL_CATEGORY_MAPPING;
static {
Map<String, CommandDetail.Flag> flagMap = new HashMap<>();
flagMap.put("admin", CommandDetail.Flag.ADMIN);
flagMap.put("asking", CommandDetail.Flag.ASKING);
flagMap.put("denyoom", CommandDetail.Flag.DENYOOM);
flagMap.put("fast", CommandDetail.Flag.FAST);
flagMap.put("loading", CommandDetail.Flag.LOADING);
flagMap.put("noscript", CommandDetail.Flag.NOSCRIPT);
flagMap.put("movablekeys", CommandDetail.Flag.MOVABLEKEYS);
flagMap.put("pubsub", CommandDetail.Flag.PUBSUB);
flagMap.put("random", CommandDetail.Flag.RANDOM);
flagMap.put("readonly", CommandDetail.Flag.READONLY);
flagMap.put("skip_monitor", CommandDetail.Flag.SKIP_MONITOR);
flagMap.put("sort_for_script", CommandDetail.Flag.SORT_FOR_SCRIPT);
flagMap.put("stale", CommandDetail.Flag.STALE);
flagMap.put("write", CommandDetail.Flag.WRITE);
FLAG_MAPPING = Collections.unmodifiableMap(flagMap);
Map<String, AclCategory> aclCategoriesMap = new HashMap<>();
aclCategoriesMap.put("@keyspace", AclCategory.KEYSPACE);
aclCategoriesMap.put("@read", AclCategory.READ);
aclCategoriesMap.put("@write", AclCategory.WRITE);
aclCategoriesMap.put("@set", AclCategory.SET);
aclCategoriesMap.put("@sortedset", AclCategory.SORTEDSET);
aclCategoriesMap.put("@list", AclCategory.LIST);
aclCategoriesMap.put("@hash", AclCategory.HASH);
aclCategoriesMap.put("@string", AclCategory.STRING);
aclCategoriesMap.put("@bitmap", AclCategory.BITMAP);
aclCategoriesMap.put("@hyperloglog", AclCategory.HYPERLOGLOG);
aclCategoriesMap.put("@geo", AclCategory.GEO);
aclCategoriesMap.put("@stream", AclCategory.STREAM);
aclCategoriesMap.put("@pubsub", AclCategory.PUBSUB);
aclCategoriesMap.put("@admin", AclCategory.ADMIN);
aclCategoriesMap.put("@fast", AclCategory.FAST);
aclCategoriesMap.put("@slow", AclCategory.SLOW);
aclCategoriesMap.put("@blocking", AclCategory.BLOCKING);
aclCategoriesMap.put("@dangerous", AclCategory.DANGEROUS);
aclCategoriesMap.put("@connection", AclCategory.CONNECTION);
aclCategoriesMap.put("@transaction", AclCategory.TRANSACTION);
aclCategoriesMap.put("@scripting", AclCategory.SCRIPTING);
ACL_CATEGORY_MAPPING = Collections.unmodifiableMap(aclCategoriesMap);
}
private CommandDetailParser() {
}
/**
* Parse the output of the Redis COMMAND/COMMAND INFO command and convert to a list of {@link CommandDetail}.
*
* @param commandOutput the command output, must not be {@code null}
* @return RedisInstance
*/
public static List<CommandDetail> parse(List<?> commandOutput) {
LettuceAssert.notNull(commandOutput, "CommandOutput must not be null");
List<CommandDetail> result = new ArrayList<>();
for (Object o : commandOutput) {
if (!(o instanceof Collection<?>)) {
continue;
}
Collection<?> collection = (Collection<?>) o;
if (collection.size() < COMMAND_INFO_SIZE) {
continue;
}
CommandDetail commandDetail = parseCommandDetail(collection);
result.add(commandDetail);
}
return Collections.unmodifiableList(result);
}
private static CommandDetail parseCommandDetail(Collection<?> collection) {
Iterator<?> iterator = collection.iterator();
String name = (String) iterator.next();
int arity = Math.toIntExact(getLongFromIterator(iterator, 0));
Object flags = iterator.next();
int firstKey = Math.toIntExact(getLongFromIterator(iterator, 0));
int lastKey = Math.toIntExact(getLongFromIterator(iterator, 0));
int keyStepCount = Math.toIntExact(getLongFromIterator(iterator, 0));
Object categories = iterator.hasNext() ? iterator.next() : null;
Set<CommandDetail.Flag> parsedFlags = parseFlags(flags);
Set<AclCategory> parsedAclCategories = parseAclCategories(categories);
return new CommandDetail(name, arity, parsedFlags, firstKey, lastKey, keyStepCount, parsedAclCategories);
}
private static Set<CommandDetail.Flag> parseFlags(Object flags) {
Set<CommandDetail.Flag> result = new HashSet<>();
if (flags instanceof Collection<?>) {
Collection<?> collection = (Collection<?>) flags;
for (Object o : collection) {
CommandDetail.Flag flag = FLAG_MAPPING.get(o);
if (flag != null) {
result.add(flag);
}
}
}
return Collections.unmodifiableSet(result);
}
private static Set<AclCategory> parseAclCategories(Object aclCategories) {<FILL_FUNCTION_BODY>}
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;
}
}
|
Set<AclCategory> result = new HashSet<>();
if (aclCategories instanceof Collection<?>) {
Collection<?> collection = (Collection<?>) aclCategories;
for (Object o : collection) {
AclCategory aclCategory = ACL_CATEGORY_MAPPING.get(o);
if (aclCategory != null) {
result.add(aclCategory);
}
}
}
return Collections.unmodifiableSet(result);
| 1,699
| 133
| 1,832
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/models/role/RedisReplicaInstance.java
|
RedisReplicaInstance
|
toString
|
class RedisReplicaInstance implements RedisInstance, Serializable {
private ReplicationPartner upstream;
private State state;
public RedisReplicaInstance() {
}
/**
* Constructs a {@link RedisReplicaInstance}
*
* @param upstream master for the replication, must not be {@code null}
* @param state replica state, must not be {@code null}
*/
RedisReplicaInstance(ReplicationPartner upstream, State state) {
LettuceAssert.notNull(upstream, "Upstream must not be null");
LettuceAssert.notNull(state, "State must not be null");
this.upstream = upstream;
this.state = state;
}
/**
*
* @return always {@link Role#REPLICA}
*/
@Override
public Role getRole() {
return Role.REPLICA;
}
/**
*
* @return the replication origin.
*/
public ReplicationPartner getUpstream() {
return upstream;
}
/**
* @return Replica state.
*/
public State getState() {
return state;
}
public void setUpstream(ReplicationPartner upstream) {
LettuceAssert.notNull(upstream, "Master must not be null");
this.upstream = upstream;
}
public void setState(State state) {
LettuceAssert.notNull(state, "State must not be null");
this.state = state;
}
/**
* State of the Replica.
*/
public enum State {
/**
* Nothing to replicate.
*/
NONE,
/**
* unknown state.
*/
UNKNOWN,
/**
* the instance is in the handshake state.
*/
HANDSHAKE,
/**
* the instance needs to connect to its master.
*/
CONNECT,
/**
* the replica-master connection is in progress.
*/
CONNECTING,
/**
* the master and replica are trying to perform the synchronization.
*/
SYNC,
/**
* the replica is online.
*/
CONNECTED;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
final StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [master=").append(upstream);
sb.append(", state=").append(state);
sb.append(']');
return sb.toString();
| 623
| 71
| 694
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/models/role/RedisSentinelInstance.java
|
RedisSentinelInstance
|
toString
|
class RedisSentinelInstance implements RedisInstance, Serializable {
private List<String> monitoredMasters = Collections.emptyList();
public RedisSentinelInstance() {
}
/**
* Constructs a {@link RedisSentinelInstance}
*
* @param monitoredMasters list of monitored masters, must not be {@code null} but may be empty
*/
public RedisSentinelInstance(List<String> monitoredMasters) {
LettuceAssert.notNull(monitoredMasters, "List of monitoredMasters must not be null");
this.monitoredMasters = monitoredMasters;
}
/**
*
* @return always {@link io.lettuce.core.models.role.RedisInstance.Role#SENTINEL}
*/
@Override
public Role getRole() {
return Role.SENTINEL;
}
/**
*
* @return List of monitored master names.
*/
public List<String> getMonitoredMasters() {
return monitoredMasters;
}
public void setMonitoredMasters(List<String> monitoredMasters) {
LettuceAssert.notNull(monitoredMasters, "List of monitoredMasters must not be null");
this.monitoredMasters = monitoredMasters;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
final StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [monitoredMasters=").append(monitoredMasters);
sb.append(']');
return sb.toString();
| 389
| 64
| 453
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/models/role/ReplicationPartner.java
|
ReplicationPartner
|
toString
|
class ReplicationPartner implements Serializable {
private HostAndPort host;
private long replicationOffset;
public ReplicationPartner() {
}
/**
* Constructs a replication partner.
*
* @param host host information, must not be {@code null}
* @param replicationOffset the replication offset
*/
public ReplicationPartner(HostAndPort host, long replicationOffset) {
LettuceAssert.notNull(host, "Host must not be null");
this.host = host;
this.replicationOffset = replicationOffset;
}
/**
*
* @return host with port of the replication partner.
*/
public HostAndPort getHost() {
return host;
}
/**
*
* @return the replication offset.
*/
public long getReplicationOffset() {
return replicationOffset;
}
public void setHost(HostAndPort host) {
LettuceAssert.notNull(host, "Host must not be null");
this.host = host;
}
public void setReplicationOffset(long replicationOffset) {
this.replicationOffset = replicationOffset;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
final StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [host=").append(host);
sb.append(", replicationOffset=").append(replicationOffset);
sb.append(']');
return sb.toString();
| 325
| 73
| 398
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/models/role/RoleParser.java
|
RoleParser
|
getMonitoredUpstreams
|
class RoleParser {
protected static final Map<String, RedisInstance.Role> ROLE_MAPPING;
protected static final Map<String, RedisReplicaInstance.State> REPLICA_STATE_MAPPING;
static {
Map<String, RedisInstance.Role> roleMap = new HashMap<>();
roleMap.put("master", RedisInstance.Role.UPSTREAM);
roleMap.put("slave", RedisInstance.Role.REPLICA);
roleMap.put("sentinel", RedisInstance.Role.SENTINEL);
ROLE_MAPPING = Collections.unmodifiableMap(roleMap);
Map<String, RedisReplicaInstance.State> replicas = new HashMap<>();
replicas.put("connect", RedisReplicaInstance.State.CONNECT);
replicas.put("connected", RedisReplicaInstance.State.CONNECTED);
replicas.put("connecting", RedisReplicaInstance.State.CONNECTING);
replicas.put("sync", RedisReplicaInstance.State.SYNC);
replicas.put("handshake", RedisReplicaInstance.State.HANDSHAKE);
replicas.put("none", RedisReplicaInstance.State.NONE);
replicas.put("unknown", RedisReplicaInstance.State.NONE);
REPLICA_STATE_MAPPING = Collections.unmodifiableMap(replicas);
}
/**
* Utility constructor.
*/
private RoleParser() {
}
/**
* Parse the output of the Redis ROLE command and convert to a RedisInstance.
*
* @param roleOutput output of the Redis ROLE command.
* @return RedisInstance
*/
public static RedisInstance parse(List<?> roleOutput) {
LettuceAssert.isTrue(roleOutput != null && !roleOutput.isEmpty(), "Empty role output");
LettuceAssert.isTrue(roleOutput.get(0) instanceof String && ROLE_MAPPING.containsKey(roleOutput.get(0)),
() -> "First role element must be a string (any of " + ROLE_MAPPING.keySet() + ")");
RedisInstance.Role role = ROLE_MAPPING.get(roleOutput.get(0));
switch (role) {
case MASTER:
case UPSTREAM:
return parseUpstream(roleOutput);
case SLAVE:
case REPLICA:
return parseReplica(roleOutput);
case SENTINEL:
return parseSentinel(roleOutput);
}
return null;
}
private static RedisInstance parseUpstream(List<?> roleOutput) {
long replicationOffset = getUpstreamReplicationOffset(roleOutput);
List<ReplicationPartner> replicas = getUpstreamReplicaReplicationPartners(roleOutput);
RedisMasterInstance redisUpstreamInstanceRole = new RedisMasterInstance(replicationOffset,
Collections.unmodifiableList(replicas));
return redisUpstreamInstanceRole;
}
private static RedisInstance parseReplica(List<?> roleOutput) {
Iterator<?> iterator = roleOutput.iterator();
iterator.next(); // skip first element
String ip = getStringFromIterator(iterator, "");
long port = getLongFromIterator(iterator, 0);
String stateString = getStringFromIterator(iterator, null);
long replicationOffset = getLongFromIterator(iterator, 0);
ReplicationPartner master = new ReplicationPartner(HostAndPort.of(ip, Math.toIntExact(port)), replicationOffset);
RedisReplicaInstance.State state = REPLICA_STATE_MAPPING.get(stateString);
if (state == null) {
throw new IllegalStateException("Cannot resolve Replica State for \"" + stateString + "\"");
}
return new RedisReplicaInstance(master, state);
}
private static RedisInstance parseSentinel(List<?> roleOutput) {
Iterator<?> iterator = roleOutput.iterator();
iterator.next(); // skip first element
List<String> monitoredMasters = getMonitoredUpstreams(iterator);
return new RedisSentinelInstance(Collections.unmodifiableList(monitoredMasters));
}
private static List<String> getMonitoredUpstreams(Iterator<?> iterator) {<FILL_FUNCTION_BODY>}
private static List<ReplicationPartner> getUpstreamReplicaReplicationPartners(List<?> roleOutput) {
List<ReplicationPartner> replicas = new ArrayList<>();
if (roleOutput.size() > 2 && roleOutput.get(2) instanceof Collection) {
Collection<?> segments = (Collection<?>) roleOutput.get(2);
for (Object output : segments) {
if (!(output instanceof Collection<?>)) {
continue;
}
ReplicationPartner replicationPartner = getReplicationPartner((Collection<?>) output);
replicas.add(replicationPartner);
}
}
return replicas;
}
private static ReplicationPartner getReplicationPartner(Collection<?> segments) {
Iterator<?> iterator = segments.iterator();
String ip = getStringFromIterator(iterator, "");
long port = getLongFromIterator(iterator, 0);
long replicationOffset = getLongFromIterator(iterator, 0);
return new ReplicationPartner(HostAndPort.of(ip, Math.toIntExact(port)), replicationOffset);
}
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;
}
private static String getStringFromIterator(Iterator<?> iterator, String defaultValue) {
if (iterator.hasNext()) {
Object object = iterator.next();
if (object instanceof String) {
return (String) object;
}
}
return defaultValue;
}
private static long getUpstreamReplicationOffset(List<?> roleOutput) {
long replicationOffset = 0;
if (roleOutput.size() > 1 && roleOutput.get(1) instanceof Number) {
Number number = (Number) roleOutput.get(1);
replicationOffset = number.longValue();
}
return replicationOffset;
}
}
|
List<String> monitoredUpstreams = new ArrayList<>();
if (!iterator.hasNext()) {
return monitoredUpstreams;
}
Object upstreams = iterator.next();
if (!(upstreams instanceof Collection)) {
return monitoredUpstreams;
}
for (Object upstream : (Collection) upstreams) {
if (upstream instanceof String) {
monitoredUpstreams.add((String) upstream);
}
}
return monitoredUpstreams;
| 1,713
| 143
| 1,856
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/models/stream/PendingMessage.java
|
PendingMessage
|
equals
|
class PendingMessage {
private final String id;
private final String consumer;
private final long msSinceLastDelivery;
private final long redeliveryCount;
public PendingMessage(String id, String consumer, long msSinceLastDelivery, long redeliveryCount) {
this.id = id;
this.consumer = consumer;
this.msSinceLastDelivery = msSinceLastDelivery;
this.redeliveryCount = redeliveryCount;
}
public String getId() {
return id;
}
public String getConsumer() {
return consumer;
}
public long getMsSinceLastDelivery() {
return msSinceLastDelivery;
}
public Duration getSinceLastDelivery() {
return Duration.ofMillis(getMsSinceLastDelivery());
}
public long getRedeliveryCount() {
return redeliveryCount;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (consumer != null ? consumer.hashCode() : 0);
result = 31 * result + (int) (msSinceLastDelivery ^ (msSinceLastDelivery >>> 32));
result = 31 * result + (int) (redeliveryCount ^ (redeliveryCount >>> 32));
return result;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(getClass().getSimpleName());
sb.append(" [id='").append(id).append('\'');
sb.append(", consumer='").append(consumer).append('\'');
sb.append(", msSinceLastDelivery=").append(msSinceLastDelivery);
sb.append(", redeliveryCount=").append(redeliveryCount);
sb.append(']');
return sb.toString();
}
}
|
if (this == o)
return true;
if (!(o instanceof PendingMessage))
return false;
PendingMessage that = (PendingMessage) o;
if (msSinceLastDelivery != that.msSinceLastDelivery)
return false;
if (redeliveryCount != that.redeliveryCount)
return false;
if (id != null ? !id.equals(that.id) : that.id != null)
return false;
return consumer != null ? consumer.equals(that.consumer) : that.consumer == null;
| 528
| 150
| 678
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/models/stream/PendingMessages.java
|
PendingMessages
|
equals
|
class PendingMessages {
private final long count;
private final Range<String> messageIds;
private final Map<String, Long> consumerMessageCount;
public PendingMessages(long count, Range<String> messageIds, Map<String, Long> consumerMessageCount) {
this.count = count;
this.messageIds = messageIds;
this.consumerMessageCount = consumerMessageCount;
}
public long getCount() {
return count;
}
public Range<String> getMessageIds() {
return messageIds;
}
public Map<String, Long> getConsumerMessageCount() {
return consumerMessageCount;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = (int) (count ^ (count >>> 32));
result = 31 * result + (messageIds != null ? messageIds.hashCode() : 0);
result = 31 * result + (consumerMessageCount != null ? consumerMessageCount.hashCode() : 0);
return result;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer();
sb.append(getClass().getSimpleName());
sb.append(" [count=").append(count);
sb.append(", messageIds=").append(messageIds);
sb.append(", consumerMessageCount=").append(consumerMessageCount);
sb.append(']');
return sb.toString();
}
}
|
if (this == o)
return true;
if (!(o instanceof PendingMessages))
return false;
PendingMessages that = (PendingMessages) o;
if (count != that.count)
return false;
if (messageIds != null ? !messageIds.equals(that.messageIds) : that.messageIds != null)
return false;
return consumerMessageCount != null ? consumerMessageCount.equals(that.consumerMessageCount)
: that.consumerMessageCount == null;
| 398
| 134
| 532
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/models/stream/PendingParser.java
|
PendingParser
|
parseRange
|
class PendingParser {
/**
* Utility constructor.
*/
private PendingParser() {
}
/**
* Parse the output of the Redis {@literal XPENDING} command with {@link Range}.
*
* @param xpendingOutput output of the Redis {@literal XPENDING}.
* @return list of {@link PendingMessage}s.
*/
@SuppressWarnings("unchecked")
public static List<PendingMessage> parseRange(List<?> xpendingOutput) {<FILL_FUNCTION_BODY>}
/**
* Parse the output of the Redis {@literal XPENDING} reporting a summary on pending messages.
*
* @param xpendingOutput output of the Redis {@literal XPENDING}.
* @return {@link PendingMessages}.
*/
@SuppressWarnings("unchecked")
public static PendingMessages parse(List<?> xpendingOutput) {
LettuceAssert.notNull(xpendingOutput, "XPENDING output must not be null");
LettuceAssert.isTrue(xpendingOutput.size() == 4, "XPENDING output must have exactly four output elements");
Long count = (Long) xpendingOutput.get(0);
String from = (String) xpendingOutput.get(1);
String to = (String) xpendingOutput.get(2);
Range<String> messageIdRange = Range.create(from, to);
Collection<Object> consumerMessageCounts = (Collection) xpendingOutput.get(3);
Map<String, Long> counts = new LinkedHashMap<>();
for (Object element : consumerMessageCounts) {
LettuceAssert.isTrue(element instanceof List, "Consumer message counts must be a List");
List<Object> messageCount = (List) element;
counts.put((String) messageCount.get(0), (Long) messageCount.get(1));
}
return new PendingMessages(count, messageIdRange, Collections.unmodifiableMap(counts));
}
}
|
LettuceAssert.notNull(xpendingOutput, "XPENDING output must not be null");
List<PendingMessage> result = new ArrayList<>();
for (Object element : xpendingOutput) {
LettuceAssert.isTrue(element instanceof List, "Output elements must be a List");
List<Object> message = (List) element;
String messageId = (String) message.get(0);
String consumer = (String) message.get(1);
Long msSinceLastDelivery = (Long) message.get(2);
Long deliveryCount = (Long) message.get(3);
result.add(new PendingMessage(messageId, consumer, msSinceLastDelivery, deliveryCount));
}
return result;
| 520
| 192
| 712
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/BooleanListOutput.java
|
BooleanListOutput
|
multi
|
class BooleanListOutput<K, V> extends CommandOutput<K, V, List<Boolean>> implements StreamingOutput<Boolean> {
private boolean initialized;
private Subscriber<Boolean> subscriber;
public BooleanListOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyList());
setSubscriber(ListSubscriber.instance());
}
@Override
public void set(long integer) {
subscriber.onNext(output, (integer == 1) ? Boolean.TRUE : Boolean.FALSE);
}
@Override
public void multi(int count) {<FILL_FUNCTION_BODY>}
@Override
public void setSubscriber(Subscriber<Boolean> subscriber) {
LettuceAssert.notNull(subscriber, "Subscriber must not be null");
this.subscriber = subscriber;
}
@Override
public Subscriber<Boolean> getSubscriber() {
return subscriber;
}
}
|
if (!initialized) {
output = OutputFactory.newList(count);
initialized = true;
}
| 262
| 33
| 295
|
<methods>public void <init>(RedisCodec<K,V>, List<java.lang.Boolean>) ,public void complete(int) ,public List<java.lang.Boolean> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<java.lang.Boolean> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/ByteArrayOutput.java
|
ByteArrayOutput
|
set
|
class ByteArrayOutput<K, V> extends CommandOutput<K, V, byte[]> {
public ByteArrayOutput(RedisCodec<K, V> codec) {
super(codec, null);
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
}
|
if (bytes != null) {
output = new byte[bytes.remaining()];
bytes.get(output);
}
| 85
| 37
| 122
|
<methods>public void <init>(RedisCodec<K,V>, byte[]) ,public void complete(int) ,public byte[] get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected byte[] output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/ClaimedMessagesOutput.java
|
ClaimedMessagesOutput
|
set
|
class ClaimedMessagesOutput<K, V> extends CommandOutput<K, V, ClaimedMessages<K, V>> {
private final boolean justId;
private final K stream;
private String startId;
private String id;
private boolean hasId;
private K key;
private boolean hasKey;
private Map<K, V> body;
private boolean bodyReceived;
private final List<StreamMessage<K, V>> messages;
public ClaimedMessagesOutput(RedisCodec<K, V> codec, K stream, boolean justId) {
super(codec, null);
this.stream = stream;
this.messages = new ArrayList<>();
this.justId = justId;
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
@Override
public void complete(int depth) {
if (depth == 3 && bodyReceived) {
messages.add(new StreamMessage<>(stream, id, body == null ? Collections.emptyMap() : body));
bodyReceived = false;
key = null;
hasKey = false;
body = null;
id = null;
hasId = false;
}
if (depth == 2 && justId) {
messages.add(new StreamMessage<>(stream, id, null));
key = null;
hasKey = false;
body = null;
id = null;
hasId = false;
}
if (depth == 0) {
output = new ClaimedMessages<>(startId, Collections.unmodifiableList(messages));
}
}
}
|
if (startId == null) {
startId = decodeAscii(bytes);
return;
}
if (id == null) {
id = decodeAscii(bytes);
return;
}
if (justId) {
return;
}
if (!hasKey) {
bodyReceived = true;
hasKey = true;
if (bytes == null) {
return;
}
key = codec.decodeKey(bytes);
return;
}
if (body == null) {
body = new LinkedHashMap<>();
}
body.put(key, bytes == null ? null : codec.decodeValue(bytes));
key = null;
hasKey = false;
| 427
| 198
| 625
|
<methods>public void <init>(RedisCodec<K,V>, ClaimedMessages<K,V>) ,public void complete(int) ,public ClaimedMessages<K,V> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected ClaimedMessages<K,V> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/CommandOutput.java
|
CommandOutput
|
decodeAscii
|
class CommandOutput<K, V, T> {
protected final RedisCodec<K, V> codec;
protected T output;
protected String error;
/**
* Initialize a new instance that encodes and decodes keys and values using the supplied codec.
*
* @param codec Codec used to encode/decode keys and values, must not be {@code null}.
* @param output Initial value of output.
*/
public CommandOutput(RedisCodec<K, V> codec, T output) {
LettuceAssert.notNull(codec, "RedisCodec must not be null");
this.codec = codec;
this.output = output;
}
/**
* Get the command output.
*
* @return The command output.
*/
public T get() {
return output;
}
/**
* Update the command output with a sequence of bytes, or {@code null}. Concrete {@link CommandOutput} implementations must
* override this method to decode {@code bulk}/bytes response values.
*
* @param bytes The command output, or null.
*/
public void set(ByteBuffer bytes) {
throw new UnsupportedOperationException(getClass().getName() + " does not support set(ByteBuffer)");
}
/**
* Update the command output with a sequence of bytes, or {@code null} representing a simple string. Concrete
* {@link CommandOutput} implementations must override this method to decode {@code single}/bytes response values.
*
* @param bytes The command output, or null.
*/
public void setSingle(ByteBuffer bytes) {
set(bytes);
}
/**
* Update the command output with a big number. Concrete {@link CommandOutput} implementations must override this method to
* decode {@code big number} response values.
*
* @param bytes The command output, or null.
* @since 6.0/RESP 3
*/
public void setBigNumber(ByteBuffer bytes) {
set(bytes);
}
/**
* Update the command output with a 64-bit signed integer. Concrete {@link CommandOutput} implementations must override this
* method to decode {@code number} (integer) response values.
*
* @param integer The command output.
*/
public void set(long integer) {
throw new UnsupportedOperationException(getClass().getName() + " does not support set(long)");
}
/**
* Update the command output with a floating-point number. Concrete {@link CommandOutput} implementations must override this
* method to decode {@code double} response values.
*
* @param number The command output.
* @since 6.0/RESP 3
*/
public void set(double number) {
throw new UnsupportedOperationException(getClass().getName() + " does not support set(double)");
}
/**
* Update the command output with a boolean. Concrete {@link CommandOutput} implementations must override this method to
* decode {@code boolean} response values.
*
* @param value The command output.
* @since 6.0/RESP 3
*/
public void set(boolean value) {
throw new UnsupportedOperationException(getClass().getName() + " does not support set(boolean)");
}
/**
* Set command output to an error message from the server.
*
* @param error Error message.
*/
public void setError(ByteBuffer error) {
this.error = decodeAscii(error);
}
/**
* Set command output to an error message from the client.
*
* @param error Error message.
*/
public void setError(String error) {
this.error = error;
}
/**
* Check if the command resulted in an error.
*
* @return true if command resulted in an error.
*/
public boolean hasError() {
return this.error != null;
}
/**
* Get the error that occurred.
*
* @return The error.
*/
public String getError() {
return error;
}
/**
* Mark the command output complete.
*
* @param depth Remaining depth of output queue.
*
*/
public void complete(int depth) {
// nothing to do by default
}
protected String decodeAscii(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [output=").append(output);
sb.append(", error='").append(error).append('\'');
sb.append(']');
return sb.toString();
}
/**
* Mark the beginning of a multi sequence (array).
*
* @param count expected number of elements in this multi sequence.
*/
public void multi(int count) {
}
/**
* Mark the beginning of a multi sequence (array).
*
* @param count expected number of elements in this multi sequence.
* @since 6.0/RESP 3
*/
public void multiArray(int count) {
multi(count);
}
/**
* Mark the beginning of a multi sequence (push-array).
*
* @param count expected number of elements in this multi sequence.
* @since 6.0/RESP 3
*/
public void multiPush(int count) {
multi(count);
}
/**
* Mark the beginning of a multi sequence (map).
*
* @param count expected number of elements in this multi sequence.
* @since 6.0/RESP 3
*/
public void multiMap(int count) {
multi(count * 2);
}
/**
* Mark the beginning of a set.
*
* @param count expected number of elements in this multi sequence.
* @since 6.0/RESP 3
*/
public void multiSet(int count) {
multi(count);
}
}
|
if (bytes == null) {
return null;
}
char[] chars = new char[bytes.remaining()];
for (int i = 0; i < chars.length; i++) {
chars[i] = (char) bytes.get();
}
return new String(chars);
| 1,573
| 84
| 1,657
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/DefaultTransactionResult.java
|
DefaultTransactionResult
|
toString
|
class DefaultTransactionResult implements Iterable<Object>, TransactionResult {
private final boolean discarded;
private final List<Object> result;
/**
* Creates a new {@link DefaultTransactionResult}.
*
* @param discarded {@code true} if the transaction is discarded.
* @param result the transaction result, must not be {@code null}.
*/
public DefaultTransactionResult(boolean discarded, List<Object> result) {
LettuceAssert.notNull(result, "Result must not be null");
this.discarded = discarded;
this.result = result;
}
@Override
public boolean wasDiscarded() {
return discarded;
}
@Override
public Iterator<Object> iterator() {
return result.iterator();
}
@Override
public int size() {
return result.size();
}
@Override
public boolean isEmpty() {
return result.isEmpty();
}
@Override
public <T> T get(int index) {
return (T) result.get(index);
}
@Override
public Stream<Object> stream() {
return result.stream();
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [wasRolledBack=").append(discarded);
sb.append(", responses=").append(size());
sb.append(']');
return sb.toString();
| 336
| 76
| 412
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/DoubleListOutput.java
|
DoubleListOutput
|
multi
|
class DoubleListOutput<K, V> extends CommandOutput<K, V, List<Double>> {
private boolean initialized;
public DoubleListOutput(RedisCodec<K, V> codec) {
super(codec, new ArrayList<>());
}
@Override
public void set(ByteBuffer bytes) {
output.add(bytes != null ? parseDouble(decodeAscii(bytes)) : null);
}
@Override
public void set(double number) {
output.add(number);
}
@Override
public void multi(int count) {<FILL_FUNCTION_BODY>}
}
|
if (!initialized) {
output = OutputFactory.newList(count);
initialized = true;
}
| 162
| 32
| 194
|
<methods>public void <init>(RedisCodec<K,V>, List<java.lang.Double>) ,public void complete(int) ,public List<java.lang.Double> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<java.lang.Double> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/EnumSetOutput.java
|
EnumSetOutput
|
resolve
|
class EnumSetOutput<K, V, E extends Enum<E>> extends CommandOutput<K, V, Set<E>> {
private boolean initialized;
private final Class<E> enumClass;
private final UnaryOperator<String> enumValuePreprocessor;
private final Function<String, E> onUnknownValue;
/**
* Create a new {@link EnumSetOutput}.
*
* @param codec Codec used to encode/decode keys and values, must not be {@code null}.
* @param enumClass {@link Enum} type.
* @param enumValuePreprocessor pre-processor for {@link String} values before looking up the enum value.
* @param onUnknownValue fallback {@link Function} to be called when an enum value cannot be looked up.
*/
public EnumSetOutput(RedisCodec<K, V> codec, Class<E> enumClass, UnaryOperator<String> enumValuePreprocessor,
Function<String, E> onUnknownValue) {
super(codec, Collections.emptySet());
this.enumClass = enumClass;
this.enumValuePreprocessor = enumValuePreprocessor;
this.onUnknownValue = onUnknownValue;
}
@Override
public void set(ByteBuffer bytes) {
if (bytes == null) {
return;
}
E enumConstant = resolve(enumValuePreprocessor.apply(decodeAscii(bytes)));
if (enumConstant == null) {
return;
}
output.add(enumConstant);
}
@Override
public void multi(int count) {
if (!initialized) {
output = EnumSet.noneOf(enumClass);
initialized = true;
}
}
private E resolve(String value) {<FILL_FUNCTION_BODY>}
}
|
try {
return Enum.valueOf(enumClass, value);
} catch (IllegalArgumentException e) {
return onUnknownValue.apply(value);
}
| 459
| 46
| 505
|
<methods>public void <init>(RedisCodec<K,V>, Set<E>) ,public void complete(int) ,public Set<E> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected Set<E> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/GenericMapOutput.java
|
GenericMapOutput
|
set
|
class GenericMapOutput<K, V> extends CommandOutput<K, V, Map<K, Object>> {
boolean hasKey;
private K key;
public GenericMapOutput(RedisCodec<K, V> codec) {
super(codec, null);
}
@Override
public void set(ByteBuffer bytes) {
if (!hasKey) {
key = (bytes == null) ? null : codec.decodeKey(bytes);
hasKey = true;
return;
}
Object value = (bytes == null) ? null : codec.decodeValue(bytes);
output.put(key, value);
key = null;
hasKey = false;
}
@Override
public void setBigNumber(ByteBuffer bytes) {
set(bytes);
}
@Override
@SuppressWarnings("unchecked")
public void set(long integer) {<FILL_FUNCTION_BODY>}
@Override
public void set(double number) {
if (!hasKey) {
key = (K) Double.valueOf(number);
hasKey = true;
return;
}
Object value = Double.valueOf(number);
output.put(key, value);
key = null;
hasKey = false;
}
@Override
public void multi(int count) {
if (output == null) {
output = new LinkedHashMap<>(count / 2, 1);
}
}
}
|
if (!hasKey) {
key = (K) Long.valueOf(integer);
hasKey = true;
return;
}
V value = (V) Long.valueOf(integer);
output.put(key, value);
key = null;
hasKey = false;
| 388
| 79
| 467
|
<methods>public void <init>(RedisCodec<K,V>, Map<K,java.lang.Object>) ,public void complete(int) ,public Map<K,java.lang.Object> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected Map<K,java.lang.Object> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/GeoCoordinatesListOutput.java
|
GeoCoordinatesListOutput
|
multi
|
class GeoCoordinatesListOutput<K, V> extends CommandOutput<K, V, List<GeoCoordinates>>
implements StreamingOutput<GeoCoordinates> {
private Double x;
boolean hasX;
private boolean initialized;
private Subscriber<GeoCoordinates> subscriber;
public GeoCoordinatesListOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyList());
setSubscriber(ListSubscriber.instance());
}
@Override
public void set(ByteBuffer bytes) {
if (bytes == null) {
subscriber.onNext(output, null);
return;
}
double value = (bytes == null) ? 0 : parseDouble(decodeAscii(bytes));
set(value);
}
@Override
public void set(double number) {
if (!hasX) {
x = number;
hasX = true;
return;
}
subscriber.onNext(output, new GeoCoordinates(x, number));
x = null;
hasX = false;
}
@Override
public void multi(int count) {<FILL_FUNCTION_BODY>}
@Override
public void setSubscriber(Subscriber<GeoCoordinates> subscriber) {
LettuceAssert.notNull(subscriber, "Subscriber must not be null");
this.subscriber = subscriber;
}
@Override
public Subscriber<GeoCoordinates> getSubscriber() {
return subscriber;
}
}
|
if (!initialized) {
output = OutputFactory.newList(count);
initialized = true;
}
if (count == -1) {
subscriber.onNext(output, null);
}
| 414
| 59
| 473
|
<methods>public void <init>(RedisCodec<K,V>, List<io.lettuce.core.GeoCoordinates>) ,public void complete(int) ,public List<io.lettuce.core.GeoCoordinates> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<io.lettuce.core.GeoCoordinates> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/GeoCoordinatesValueListOutput.java
|
GeoCoordinatesValueListOutput
|
set
|
class GeoCoordinatesValueListOutput<K, V> extends CommandOutput<K, V, List<Value<GeoCoordinates>>>
implements StreamingOutput<Value<GeoCoordinates>> {
boolean hasX;
private Double x;
private boolean initialized;
private Subscriber<Value<GeoCoordinates>> subscriber;
public GeoCoordinatesValueListOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyList());
setSubscriber(ListSubscriber.instance());
}
@Override
public void set(ByteBuffer bytes) {
if (bytes == null) {
subscriber.onNext(output, Value.empty());
return;
}
double value = parseDouble(decodeAscii(bytes));
set(value);
}
@Override
public void set(double number) {<FILL_FUNCTION_BODY>}
@Override
public void multi(int count) {
if (!initialized) {
output = OutputFactory.newList(count / 2);
initialized = true;
}
if (count == -1) {
subscriber.onNext(output, Value.empty());
}
}
@Override
public void setSubscriber(Subscriber<Value<GeoCoordinates>> subscriber) {
LettuceAssert.notNull(subscriber, "Subscriber must not be null");
this.subscriber = subscriber;
}
@Override
public Subscriber<Value<GeoCoordinates>> getSubscriber() {
return subscriber;
}
}
|
if (!hasX) {
x = number;
hasX = true;
return;
}
subscriber.onNext(output, Value.fromNullable(new GeoCoordinates(x, number)));
x = null;
hasX = false;
| 418
| 70
| 488
|
<methods>public void <init>(RedisCodec<K,V>, List<Value<io.lettuce.core.GeoCoordinates>>) ,public void complete(int) ,public List<Value<io.lettuce.core.GeoCoordinates>> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<Value<io.lettuce.core.GeoCoordinates>> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/GeoWithinListOutput.java
|
GeoWithinListOutput
|
complete
|
class GeoWithinListOutput<K, V> extends CommandOutput<K, V, List<GeoWithin<V>>>
implements StreamingOutput<GeoWithin<V>> {
private V member;
private boolean hasMember;
private Double distance;
private boolean hasDistance;
private Long geohash;
private GeoCoordinates coordinates;
private Double x;
private boolean hasX;
private final boolean withDistance;
private final boolean withHash;
private final boolean withCoordinates;
private Subscriber<GeoWithin<V>> subscriber;
public GeoWithinListOutput(RedisCodec<K, V> codec, boolean withDistance, boolean withHash, boolean withCoordinates) {
super(codec, OutputFactory.newList(16));
this.withDistance = withDistance;
this.withHash = withHash;
this.withCoordinates = withCoordinates;
setSubscriber(ListSubscriber.instance());
}
@Override
public void set(long integer) {
if (!hasMember) {
member = (V) (Long) integer;
hasMember = true;
return;
}
if (withHash) {
geohash = integer;
}
}
@Override
public void set(ByteBuffer bytes) {
if (!hasMember) {
member = codec.decodeValue(bytes);
hasMember = true;
return;
}
double value = (bytes == null) ? 0 : parseDouble(decodeAscii(bytes));
set(value);
}
@Override
public void set(double number) {
if (withDistance) {
if (!hasDistance) {
distance = number;
hasDistance = true;
return;
}
}
if (withCoordinates) {
if (!hasX) {
x = number;
hasX = true;
return;
}
coordinates = new GeoCoordinates(x, number);
}
}
@Override
public void complete(int depth) {<FILL_FUNCTION_BODY>}
@Override
public void setSubscriber(Subscriber<GeoWithin<V>> subscriber) {
LettuceAssert.notNull(subscriber, "Subscriber must not be null");
this.subscriber = subscriber;
}
@Override
public Subscriber<GeoWithin<V>> getSubscriber() {
return subscriber;
}
}
|
if (depth == 1) {
subscriber.onNext(output, new GeoWithin<V>(member, distance, geohash, coordinates));
member = null;
hasMember = false;
distance = null;
hasDistance = false;
geohash = null;
coordinates = null;
x = null;
hasX = false;
}
| 654
| 98
| 752
|
<methods>public void <init>(RedisCodec<K,V>, List<GeoWithin<V>>) ,public void complete(int) ,public List<GeoWithin<V>> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<GeoWithin<V>> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/IntegerOutput.java
|
IntegerOutput
|
set
|
class IntegerOutput<K, V> extends CommandOutput<K, V, Long> {
public IntegerOutput(RedisCodec<K, V> codec) {
super(codec, null);
}
@Override
public void set(long integer) {
output = integer;
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
}
|
if (bytes == null) {
output = null;
} else {
// fallback for long as ByteBuffer
output = Long.parseLong(StandardCharsets.UTF_8.decode(bytes).toString());
}
| 106
| 59
| 165
|
<methods>public void <init>(RedisCodec<K,V>, java.lang.Long) ,public void complete(int) ,public java.lang.Long get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected java.lang.Long output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/KeyStreamingOutput.java
|
KeyStreamingOutput
|
set
|
class KeyStreamingOutput<K, V> extends CommandOutput<K, V, Long> {
private final KeyStreamingChannel<K> channel;
public KeyStreamingOutput(RedisCodec<K, V> codec, KeyStreamingChannel<K> channel) {
super(codec, Long.valueOf(0));
this.channel = channel;
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
}
|
channel.onKey(bytes == null ? null : codec.decodeKey(bytes));
output = output.longValue() + 1;
| 122
| 37
| 159
|
<methods>public void <init>(RedisCodec<K,V>, java.lang.Long) ,public void complete(int) ,public java.lang.Long get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected java.lang.Long output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/KeyValueListOutput.java
|
KeyValueListOutput
|
set
|
class KeyValueListOutput<K, V> extends CommandOutput<K, V, List<KeyValue<K, V>>>
implements StreamingOutput<KeyValue<K, V>> {
private boolean initialized;
private Subscriber<KeyValue<K, V>> subscriber;
private final Iterable<K> keys;
private Iterator<K> keyIterator;
private K key;
private boolean hasKey;
public KeyValueListOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyList());
setSubscriber(ListSubscriber.instance());
this.keys = null;
}
public KeyValueListOutput(RedisCodec<K, V> codec, Iterable<K> keys) {
super(codec, Collections.emptyList());
setSubscriber(ListSubscriber.instance());
this.keys = keys;
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
@Override
public void multi(int count) {
if (!initialized) {
output = OutputFactory.newList(keys == null ? count / 2 : count);
initialized = true;
}
}
@Override
public void setSubscriber(Subscriber<KeyValue<K, V>> subscriber) {
LettuceAssert.notNull(subscriber, "Subscriber must not be null");
this.subscriber = subscriber;
}
@Override
public Subscriber<KeyValue<K, V>> getSubscriber() {
return subscriber;
}
}
|
if (keys == null) {
if (!hasKey) {
key = codec.decodeKey(bytes);
hasKey = true;
return;
}
K key = this.key;
this.key = null;
this.hasKey = false;
subscriber.onNext(output, KeyValue.fromNullable(key, bytes == null ? null : codec.decodeValue(bytes)));
} else {
if (keyIterator == null) {
keyIterator = keys.iterator();
}
subscriber.onNext(output,
KeyValue.fromNullable(keyIterator.next(), bytes == null ? null : codec.decodeValue(bytes)));
}
| 420
| 175
| 595
|
<methods>public void <init>(RedisCodec<K,V>, List<KeyValue<K,V>>) ,public void complete(int) ,public List<KeyValue<K,V>> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<KeyValue<K,V>> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/KeyValueListScoredValueOutput.java
|
KeyValueListScoredValueOutput
|
set
|
class KeyValueListScoredValueOutput<K, V> extends CommandOutput<K, V, KeyValue<K, List<ScoredValue<V>>>> {
private K key;
private V value;
private double score;
private List<ScoredValue<V>> items = new ArrayList<>();
public KeyValueListScoredValueOutput(RedisCodec<K, V> codec, K defaultKey) {
super(codec, KeyValue.empty(defaultKey));
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
@Override
public void set(double number) {
if (value != null) {
score = number;
}
}
@Override
public void complete(int depth) {
if (depth == 2) {
items.add(ScoredValue.just(score, value));
value = null;
}
if (depth == 0) {
if (key != null) {
output = KeyValue.just(key, items);
}
}
}
}
|
if (bytes != null) {
if (key == null) {
key = codec.decodeKey(bytes);
return;
}
if (value == null) {
value = codec.decodeValue(bytes);
return;
}
score = parseDouble(decodeAscii(bytes));
}
| 283
| 88
| 371
|
<methods>public void <init>(RedisCodec<K,V>, KeyValue<K,List<ScoredValue<V>>>) ,public void complete(int) ,public KeyValue<K,List<ScoredValue<V>>> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected KeyValue<K,List<ScoredValue<V>>> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/KeyValueOfScoredValueOutput.java
|
KeyValueOfScoredValueOutput
|
set
|
class KeyValueOfScoredValueOutput<K, V> extends CommandOutput<K, V, KeyValue<K, ScoredValue<V>>> {
private K key;
private V value;
public KeyValueOfScoredValueOutput(RedisCodec<K, V> codec, K defaultKey) {
super(codec, KeyValue.empty(defaultKey));
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
@Override
public void set(double number) {
if (key != null && value != null) {
output = KeyValue.just(key, ScoredValue.just(number, value));
}
}
}
|
if (bytes != null) {
if (key == null) {
key = codec.decodeKey(bytes);
return;
}
if (value == null) {
value = codec.decodeValue(bytes);
return;
}
output = KeyValue.just(key, ScoredValue.just(parseDouble(decodeAscii(bytes)), value));
}
| 183
| 104
| 287
|
<methods>public void <init>(RedisCodec<K,V>, KeyValue<K,ScoredValue<V>>) ,public void complete(int) ,public KeyValue<K,ScoredValue<V>> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected KeyValue<K,ScoredValue<V>> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/KeyValueOutput.java
|
KeyValueOutput
|
set
|
class KeyValueOutput<K, V> extends CommandOutput<K, V, KeyValue<K, V>> {
private K key;
private boolean hasKey;
public KeyValueOutput(RedisCodec<K, V> codec) {
super(codec, null);
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
}
|
if (bytes != null) {
if (!hasKey) {
key = codec.decodeKey(bytes);
hasKey = true;
} else {
V value = codec.decodeValue(bytes);
output = KeyValue.fromNullable(key, value);
}
}
| 104
| 79
| 183
|
<methods>public void <init>(RedisCodec<K,V>, KeyValue<K,V>) ,public void complete(int) ,public KeyValue<K,V> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected KeyValue<K,V> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/KeyValueScanStreamingOutput.java
|
KeyValueScanStreamingOutput
|
setOutput
|
class KeyValueScanStreamingOutput<K, V> extends ScanOutput<K, V, StreamScanCursor> {
private K key;
private boolean hasKey;
private KeyValueStreamingChannel<K, V> channel;
public KeyValueScanStreamingOutput(RedisCodec<K, V> codec, KeyValueStreamingChannel<K, V> channel) {
super(codec, new StreamScanCursor());
this.channel = channel;
}
@Override
protected void setOutput(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
}
|
if (!hasKey) {
key = codec.decodeKey(bytes);
hasKey = true;
return;
}
V value = (bytes == null) ? null : codec.decodeValue(bytes);
channel.onKeyValue(key, value);
output.setCount(output.getCount() + 1);
key = null;
hasKey = false;
| 147
| 101
| 248
|
<methods>public void <init>(RedisCodec<K,V>, io.lettuce.core.StreamScanCursor) ,public void set(java.nio.ByteBuffer) <variables>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/KeyValueScoredValueOutput.java
|
KeyValueScoredValueOutput
|
set
|
class KeyValueScoredValueOutput<K, V> extends CommandOutput<K, V, KeyValue<K, ScoredValue<V>>> {
private K key;
private boolean hasKey;
private V value;
private boolean hasValue;
public KeyValueScoredValueOutput(RedisCodec<K, V> codec) {
super(codec, null);
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
@Override
public void set(double number) {
output = KeyValue.just(key, ScoredValue.just(number, value));
key = null;
hasKey = false;
value = null;
hasValue = false;
}
}
|
if (bytes == null) {
return;
}
if (!hasKey) {
key = codec.decodeKey(bytes);
hasKey = true;
return;
}
if (!hasValue) {
value = codec.decodeValue(bytes);
hasValue = true;
return;
}
double score = LettuceStrings.toDouble(decodeAscii(bytes));
set(score);
| 195
| 119
| 314
|
<methods>public void <init>(RedisCodec<K,V>, KeyValue<K,ScoredValue<V>>) ,public void complete(int) ,public KeyValue<K,ScoredValue<V>> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected KeyValue<K,ScoredValue<V>> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/KeyValueStreamingOutput.java
|
KeyValueStreamingOutput
|
set
|
class KeyValueStreamingOutput<K, V> extends CommandOutput<K, V, Long> {
private Iterable<K> keys;
private Iterator<K> keyIterator;
private K key;
private boolean hasKey;
private KeyValueStreamingChannel<K, V> channel;
public KeyValueStreamingOutput(RedisCodec<K, V> codec, KeyValueStreamingChannel<K, V> channel) {
super(codec, Long.valueOf(0));
this.channel = channel;
}
public KeyValueStreamingOutput(RedisCodec<K, V> codec, KeyValueStreamingChannel<K, V> channel, Iterable<K> keys) {
super(codec, Long.valueOf(0));
this.channel = channel;
this.keys = keys;
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
}
|
if (keys == null) {
if (!hasKey) {
key = codec.decodeKey(bytes);
hasKey = true;
return;
}
} else {
if (keyIterator == null) {
keyIterator = keys.iterator();
}
key = keyIterator.next();
}
V value = (bytes == null) ? null : codec.decodeValue(bytes);
channel.onKeyValue(key, value);
output = output.longValue() + 1;
key = null;
hasKey = false;
| 241
| 145
| 386
|
<methods>public void <init>(RedisCodec<K,V>, java.lang.Long) ,public void complete(int) ,public java.lang.Long get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected java.lang.Long output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/KeyValueValueListOutput.java
|
KeyValueValueListOutput
|
set
|
class KeyValueValueListOutput<K, V> extends CommandOutput<K, V, KeyValue<K, List<V>>> {
private K key;
private boolean hasKey;
private List<V> values = Collections.emptyList();
public KeyValueValueListOutput(RedisCodec<K, V> codec) {
super(codec, null);
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
@Override
public void multi(int count) {
values = OutputFactory.newList(count);
}
@Override
public void complete(int depth) {
if (depth == 0 && hasKey) {
output = KeyValue.just(key, values);
}
}
}
|
if (bytes != null) {
if (!hasKey) {
key = codec.decodeKey(bytes);
hasKey = true;
} else {
V value = codec.decodeValue(bytes);
values.add(value);
}
}
| 202
| 73
| 275
|
<methods>public void <init>(RedisCodec<K,V>, KeyValue<K,List<V>>) ,public void complete(int) ,public KeyValue<K,List<V>> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected KeyValue<K,List<V>> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/ListOfGenericMapsOutput.java
|
ListOfGenericMapsOutput
|
complete
|
class ListOfGenericMapsOutput<K, V> extends CommandOutput<K, V, List<Map<K, Object>>> {
private final GenericMapOutput<K, V> nested;
private int mapCount = -1;
private final List<Integer> counts = new ArrayList<>();
public ListOfGenericMapsOutput(RedisCodec<K, V> codec) {
super(codec, new ArrayList<>());
nested = new GenericMapOutput<>(codec);
}
@Override
public void set(ByteBuffer bytes) {
nested.set(bytes);
}
@Override
public void complete(int depth) {<FILL_FUNCTION_BODY>}
@Override
public void multi(int count) {
nested.multi(count);
if (mapCount == -1) {
mapCount = count;
} else {
// div 2 because of key value pair counts twice
counts.add(count / 2);
}
}
@Override
public void set(long integer) {
nested.set(integer);
}
@Override
public void set(double number) {
nested.set(number);
}
}
|
if (counts.size() > 0) {
int expectedSize = counts.get(0);
if (nested.get().size() == expectedSize) {
counts.remove(0);
output.add(new LinkedHashMap<>(nested.get()));
nested.get().clear();
}
}
| 308
| 84
| 392
|
<methods>public void <init>(RedisCodec<K,V>, List<Map<K,java.lang.Object>>) ,public void complete(int) ,public List<Map<K,java.lang.Object>> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<Map<K,java.lang.Object>> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/ListOfMapsOutput.java
|
ListOfMapsOutput
|
multi
|
class ListOfMapsOutput<K, V> extends CommandOutput<K, V, List<Map<K, V>>> {
private MapOutput<K, V> nested;
private int mapCount = -1;
private final List<Integer> counts = new ArrayList<>();
public ListOfMapsOutput(RedisCodec<K, V> codec) {
super(codec, new ArrayList<>());
nested = new MapOutput<>(codec);
}
@Override
public void set(ByteBuffer bytes) {
nested.set(bytes);
}
@Override
public void complete(int depth) {
if (!counts.isEmpty()) {
int expectedSize = counts.get(0);
if (nested.get().size() == expectedSize) {
counts.remove(0);
output.add(new LinkedHashMap<>(nested.get()));
nested.get().clear();
}
}
}
@Override
public void multi(int count) {<FILL_FUNCTION_BODY>}
@Override
public void set(long integer) {
nested.set(integer);
}
}
|
nested.multi(count);
if (mapCount == -1) {
mapCount = count;
} else {
// div 2 because of key value pair counts twice
counts.add(count / 2);
}
| 294
| 63
| 357
|
<methods>public void <init>(RedisCodec<K,V>, List<Map<K,V>>) ,public void complete(int) ,public List<Map<K,V>> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<Map<K,V>> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/MapOutput.java
|
MapOutput
|
set
|
class MapOutput<K, V> extends CommandOutput<K, V, Map<K, V>> {
private boolean initialized;
private K key;
private boolean hasKey;
public MapOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyMap());
}
@Override
public void set(ByteBuffer bytes) {
if (!hasKey) {
key = (bytes == null) ? null : codec.decodeKey(bytes);
hasKey = true;
return;
}
V value = (bytes == null) ? null : codec.decodeValue(bytes);
output.put(key, value);
key = null;
hasKey = false;
}
@Override
@SuppressWarnings("unchecked")
public void set(long integer) {
if (!hasKey) {
key = (K) Long.valueOf(integer);
hasKey = true;
return;
}
V value = (V) Long.valueOf(integer);
output.put(key, value);
key = null;
hasKey = false;
}
@Override
public void set(double number) {
if (!hasKey) {
key = (K) Double.valueOf(number);
hasKey = true;
return;
}
V value = (V) Double.valueOf(number);
output.put(key, value);
key = null;
hasKey = false;
}
@Override
public void set(boolean flag) {<FILL_FUNCTION_BODY>}
@Override
public void multi(int count) {
if (!initialized) {
output = new LinkedHashMap<>(count / 2, 1);
initialized = true;
}
}
}
|
if (!hasKey) {
key = (K) Boolean.valueOf(flag);
hasKey = true;
return;
}
V value = (V) Boolean.valueOf(flag);
output.put(key, value);
key = null;
hasKey = false;
| 472
| 79
| 551
|
<methods>public void <init>(RedisCodec<K,V>, Map<K,V>) ,public void complete(int) ,public Map<K,V> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected Map<K,V> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/MapScanOutput.java
|
MapScanOutput
|
setOutput
|
class MapScanOutput<K, V> extends ScanOutput<K, V, MapScanCursor<K, V>> {
private K key;
private boolean hasKey;
public MapScanOutput(RedisCodec<K, V> codec) {
super(codec, new MapScanCursor<K, V>());
}
@Override
protected void setOutput(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
}
|
if (!hasKey) {
key = codec.decodeKey(bytes);
hasKey = true;
return;
}
V value = (bytes == null) ? null : codec.decodeValue(bytes);
output.getMap().put(key, value);
key = null;
hasKey = false;
| 114
| 86
| 200
|
<methods>public void <init>(RedisCodec<K,V>, MapScanCursor<K,V>) ,public void set(java.nio.ByteBuffer) <variables>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/MultiOutput.java
|
MultiOutput
|
cancel
|
class MultiOutput<K, V> extends CommandOutput<K, V, TransactionResult> {
private final Queue<RedisCommand<K, V, ?>> queue;
private List<Object> responses = new ArrayList<>();
private Boolean discarded;
private Integer multi;
public MultiOutput(RedisCodec<K, V> codec) {
super(codec, null);
queue = LettuceFactories.newSpScQueue();
}
public void add(RedisCommand<K, V, ?> cmd) {
queue.add(cmd);
}
public void cancel() {<FILL_FUNCTION_BODY>}
@Override
public void set(long integer) {
RedisCommand<K, V, ?> command = queue.peek();
if (command != null && command.getOutput() != null) {
command.getOutput().set(integer);
}
}
@Override
public void setSingle(ByteBuffer bytes) {
RedisCommand<K, V, ?> command = queue.peek();
if (command != null && command.getOutput() != null) {
command.getOutput().setSingle(bytes);
}
}
@Override
public void setBigNumber(ByteBuffer bytes) {
RedisCommand<K, V, ?> command = queue.peek();
if (command != null && command.getOutput() != null) {
command.getOutput().setBigNumber(bytes);
}
}
@Override
public void set(double number) {
RedisCommand<K, V, ?> command = queue.peek();
if (command != null && command.getOutput() != null) {
command.getOutput().set(number);
}
}
@Override
public void set(ByteBuffer bytes) {
if (multi == null && bytes == null) {
discarded = true;
return;
}
RedisCommand<K, V, ?> command = queue.peek();
if (command != null && command.getOutput() != null) {
command.getOutput().set(bytes);
}
}
@Override
public void multi(int count) {
if (multi == null) {
multi = count;
}
if (discarded == null) {
discarded = count == -1;
} else {
if (!queue.isEmpty()) {
queue.peek().getOutput().multi(count);
}
}
}
@Override
public void setError(ByteBuffer error) {
if (discarded == null) {
super.setError(error);
return;
}
CommandOutput<K, V, ?> output = queue.isEmpty() ? this : queue.peek().getOutput();
output.setError(decodeAscii(error));
}
@Override
public void complete(int depth) {
if (queue.isEmpty()) {
return;
}
if (depth >= 1) {
RedisCommand<K, V, ?> cmd = queue.peek();
cmd.getOutput().complete(depth - 1);
}
if (depth == 1) {
RedisCommand<K, V, ?> cmd = queue.remove();
CommandOutput<K, V, ?> o = cmd.getOutput();
responses.add(!o.hasError() ? o.get() : ExceptionFactory.createExecutionException(o.getError()));
cmd.complete();
} else if (depth == 0 && !queue.isEmpty()) {
for (RedisCommand<K, V, ?> cmd : queue) {
cmd.complete();
}
}
}
@Override
public TransactionResult get() {
return new DefaultTransactionResult(discarded == null ? false : discarded, responses);
}
}
|
for (RedisCommand<K, V, ?> c : queue) {
c.complete();
}
| 989
| 31
| 1,020
|
<methods>public void <init>(RedisCodec<K,V>, io.lettuce.core.TransactionResult) ,public void complete(int) ,public io.lettuce.core.TransactionResult get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected io.lettuce.core.TransactionResult output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/NestedMultiOutput.java
|
NestedMultiOutput
|
set
|
class NestedMultiOutput<K, V> extends CommandOutput<K, V, List<Object>> {
private final Deque<List<Object>> stack;
private int depth;
private boolean initialized;
public NestedMultiOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyList());
stack = LettuceFactories.newSpScQueue();
depth = 0;
}
@Override
public void set(long integer) {
if (!initialized) {
output = new ArrayList<>();
}
output.add(integer);
}
@Override
public void set(double number) {
if (!initialized) {
output = new ArrayList<>();
}
output.add(number);
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
@Override
public void setSingle(ByteBuffer bytes) {
if (!initialized) {
output = new ArrayList<>();
}
output.add(bytes == null ? null : StringCodec.UTF8.decodeValue(bytes));
}
@Override
public void complete(int depth) {
if (depth > 0 && depth < this.depth) {
output = stack.pop();
this.depth--;
}
}
@Override
public void multi(int count) {
if (!initialized) {
output = OutputFactory.newList(Math.max(1, count));
initialized = true;
}
List<Object> a = OutputFactory.newList(count);
output.add(a);
stack.push(output);
output = a;
this.depth++;
}
}
|
if (!initialized) {
output = new ArrayList<>();
}
output.add(bytes == null ? null : codec.decodeValue(bytes));
| 452
| 44
| 496
|
<methods>public void <init>(RedisCodec<K,V>, List<java.lang.Object>) ,public void complete(int) ,public List<java.lang.Object> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<java.lang.Object> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/ObjectOutput.java
|
ObjectOutput
|
multiMap
|
class ObjectOutput<K, V> extends CommandOutput<K, V, Object> {
private final Deque<Object> stack;
private Object current;
private boolean hasCurrent = false;
private int depth;
private boolean initialized;
public ObjectOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyList());
stack = LettuceFactories.newSpScQueue();
depth = 0;
}
@Override
public void set(long integer) {
if (!initialized) {
output = new ArrayList<>();
}
setValue(integer);
}
@Override
public void set(double number) {
setValue(number);
}
@Override
public void setBigNumber(ByteBuffer bytes) {
setSingle(bytes);
}
@Override
public void set(boolean value) {
setValue(value);
}
@Override
public void set(ByteBuffer bytes) {
setValue(bytes == null ? null : codec.decodeValue(bytes));
}
@Override
public void setSingle(ByteBuffer bytes) {
setValue(bytes == null ? null : StringCodec.UTF8.decodeValue(bytes));
}
@SuppressWarnings("unchecked")
private void setValue(Object value) {
if (output != null) {
if (output instanceof Collection) {
((Collection<Object>) output).add(value);
} else if (output instanceof Map) {
if (!hasCurrent) {
current = value;
hasCurrent = true;
} else {
((Map<Object, Object>) output).put(current, value);
current = null;
hasCurrent = false;
}
} else {
throw new IllegalStateException(
String.format("Output %s is not a supported container type to append a response value", output));
}
} else {
output = value;
}
}
@Override
public void complete(int depth) {
if (depth > 0 && depth < this.depth) {
stack.pop();
output = stack.peek();
this.depth--;
}
}
@Override
public void multi(int count) {
if (!initialized) {
output = OutputFactory.newList(Math.max(1, count));
push(output);
initialized = true;
} else {
List<Object> list = OutputFactory.newList(count);
setValue(list);
push(list);
output = list;
}
this.depth++;
}
@Override
public void multiMap(int count) {<FILL_FUNCTION_BODY>}
private void push(Object output) {
stack.push(output);
}
}
|
if (!initialized) {
output = new LinkedHashMap<>(count);
initialized = true;
push(output);
} else {
Map<Object, Object> map = new LinkedHashMap<>(count);
setValue(map);
push(map);
output = map;
}
this.depth++;
| 730
| 90
| 820
|
<methods>public void <init>(RedisCodec<K,V>, java.lang.Object) ,public void complete(int) ,public java.lang.Object get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected java.lang.Object output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/OutputFactory.java
|
OutputFactory
|
newList
|
class OutputFactory {
static <T> List<T> newList(int capacity) {<FILL_FUNCTION_BODY>}
static <V> Set<V> newSet(int capacity) {
if (capacity < 1) {
return Collections.emptySet();
}
return new LinkedHashSet<>(capacity, 1);
}
}
|
if (capacity < 1) {
return Collections.emptyList();
}
return new ArrayList<>(Math.max(1, capacity));
| 98
| 42
| 140
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/PendingMessageListOutput.java
|
PendingMessageListOutput
|
set
|
class PendingMessageListOutput<K, V> extends CommandOutput<K, V, List<PendingMessage>>
implements StreamingOutput<PendingMessage> {
private boolean initialized;
private Subscriber<PendingMessage> subscriber;
private String messageId;
private String consumer;
private boolean hasConsumer;
private Long msSinceLastDelivery;
public PendingMessageListOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyList());
setSubscriber(ListSubscriber.instance());
}
@Override
public void set(ByteBuffer bytes) {
if (messageId == null) {
messageId = decodeAscii(bytes);
return;
}
if (!hasConsumer) {
consumer = StringCodec.UTF8.decodeKey(bytes);
hasConsumer = true;
return;
}
set(Long.parseLong(decodeAscii(bytes)));
}
@Override
public void set(long integer) {<FILL_FUNCTION_BODY>}
@Override
public void multi(int count) {
if (!initialized) {
output = OutputFactory.newList(count);
initialized = true;
}
}
@Override
public void setSubscriber(Subscriber<PendingMessage> subscriber) {
LettuceAssert.notNull(subscriber, "Subscriber must not be null");
this.subscriber = subscriber;
}
@Override
public Subscriber<PendingMessage> getSubscriber() {
return subscriber;
}
}
|
if (msSinceLastDelivery == null) {
msSinceLastDelivery = integer;
return;
}
PendingMessage message = new PendingMessage(messageId, consumer, msSinceLastDelivery, integer);
messageId = null;
consumer = null;
hasConsumer = false;
msSinceLastDelivery = null;
subscriber.onNext(output, message);
| 424
| 102
| 526
|
<methods>public void <init>(RedisCodec<K,V>, List<io.lettuce.core.models.stream.PendingMessage>) ,public void complete(int) ,public List<io.lettuce.core.models.stream.PendingMessage> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<io.lettuce.core.models.stream.PendingMessage> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/PendingMessagesOutput.java
|
PendingMessagesOutput
|
set
|
class PendingMessagesOutput<K, V> extends CommandOutput<K, V, PendingMessages> {
private Long count;
private String messageIdsFrom;
private String messageIdsTo;
private String consumer;
private boolean hasConsumer;
private final Map<String, Long> consumerMessageCount = new LinkedHashMap<>();
public PendingMessagesOutput(RedisCodec<K, V> codec) {
super(codec, null);
}
@Override
public void set(ByteBuffer bytes) {
if (messageIdsFrom == null) {
messageIdsFrom = decodeAscii(bytes);
return;
}
if (messageIdsTo == null) {
messageIdsTo = decodeAscii(bytes);
return;
}
if (!hasConsumer) {
consumer = StringCodec.UTF8.decodeKey(bytes);
hasConsumer = true;
return;
}
set(Long.parseLong(decodeAscii(bytes)));
}
@Override
public void set(long integer) {<FILL_FUNCTION_BODY>}
@Override
public void complete(int depth) {
if (depth == 0) {
Range<String> range = messageIdsFrom != null && messageIdsTo != null ? Range.create(messageIdsFrom, messageIdsTo)
: Range.unbounded();
output = new PendingMessages(count == null ? 0 : count, range, consumerMessageCount);
}
}
}
|
if (count == null) {
count = integer;
return;
}
if (hasConsumer) {
consumerMessageCount.put(consumer, integer);
consumer = null;
hasConsumer = false;
}
| 387
| 64
| 451
|
<methods>public void <init>(RedisCodec<K,V>, io.lettuce.core.models.stream.PendingMessages) ,public void complete(int) ,public io.lettuce.core.models.stream.PendingMessages get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected io.lettuce.core.models.stream.PendingMessages output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/PushOutput.java
|
PushOutput
|
getContent
|
class PushOutput<K, V> extends NestedMultiOutput<K, V> implements PushMessage {
private String type;
public PushOutput(RedisCodec<K, V> codec) {
super(codec);
}
@Override
public void set(ByteBuffer bytes) {
if (type == null) {
bytes.mark();
type = StringCodec.ASCII.decodeKey(bytes);
bytes.reset();
}
super.set(bytes);
}
@Override
public void setSingle(ByteBuffer bytes) {
if (type == null) {
set(bytes);
}
super.setSingle(bytes);
}
public String type() {
return type;
}
@Override
public String getType() {
return type();
}
@Override
public List<Object> getContent() {<FILL_FUNCTION_BODY>}
@Override
public List<Object> getContent(Function<ByteBuffer, Object> decodeFunction) {
LettuceAssert.notNull(decodeFunction, "Decode function must not be null");
List<Object> copy = new ArrayList<>();
for (Object o : get()) {
copy.add(decode(o, decodeFunction));
}
return Collections.unmodifiableList(copy);
}
private Object decode(Object toDecode, Function<ByteBuffer, Object> decodeFunction) {
if (toDecode instanceof List) {
List<Object> copy = new ArrayList<>(((List<?>) toDecode).size());
for (Object o : (List<?>) toDecode) {
copy.add(decode(o, decodeFunction));
}
return copy;
}
if (toDecode instanceof Set) {
Set<Object> copy = new LinkedHashSet<>(((Set<?>) toDecode).size());
for (Object o : (Set<?>) toDecode) {
copy.add(decode(o, decodeFunction));
}
return copy;
}
if (toDecode instanceof Map) {
Map<Object, Object> copy = new LinkedHashMap<>(((Map<?, ?>) toDecode).size());
((Map<?, ?>) toDecode).forEach((k, v) -> {
copy.put(decode(k, decodeFunction), decode(v, decodeFunction));
});
return copy;
}
if (toDecode instanceof ByteBuffer) {
ByteBuffer buffer = (ByteBuffer) toDecode;
try {
buffer.mark();
return decodeFunction.apply(buffer);
} finally {
buffer.reset();
}
}
return toDecode;
}
}
|
List<Object> copy = new ArrayList<>();
for (Object o : get()) {
if (o instanceof ByteBuffer) {
copy.add(((ByteBuffer) o).asReadOnlyBuffer());
} else {
copy.add(o);
}
}
return Collections.unmodifiableList(copy);
| 724
| 87
| 811
|
<methods>public void <init>(RedisCodec<K,V>) ,public void complete(int) ,public void multi(int) ,public void set(long) ,public void set(double) ,public void set(java.nio.ByteBuffer) ,public void setSingle(java.nio.ByteBuffer) <variables>private int depth,private boolean initialized,private final non-sealed Deque<List<java.lang.Object>> stack
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/ScanOutput.java
|
ScanOutput
|
set
|
class ScanOutput<K, V, T extends ScanCursor> extends CommandOutput<K, V, T> {
public ScanOutput(RedisCodec<K, V> codec, T cursor) {
super(codec, cursor);
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
protected abstract void setOutput(ByteBuffer bytes);
}
|
if (output.getCursor() == null) {
output.setCursor(decodeAscii(bytes));
if (LettuceStrings.isNotEmpty(output.getCursor()) && "0".equals(output.getCursor())) {
output.setFinished(true);
}
return;
}
setOutput(bytes);
| 103
| 91
| 194
|
<methods>public void <init>(RedisCodec<K,V>, T) ,public void complete(int) ,public T get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected T output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/ScoredValueListOutput.java
|
ScoredValueListOutput
|
set
|
class ScoredValueListOutput<K, V> extends CommandOutput<K, V, List<ScoredValue<V>>>
implements StreamingOutput<ScoredValue<V>> {
private boolean initialized;
private Subscriber<ScoredValue<V>> subscriber;
private V value;
private boolean hasValue;
public ScoredValueListOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyList());
setSubscriber(ListSubscriber.instance());
}
@Override
public void set(ByteBuffer bytes) {
if (!hasValue) {
value = codec.decodeValue(bytes);
hasValue = true;
return;
}
double score = LettuceStrings.toDouble(decodeAscii(bytes));
set(score);
}
@Override
public void set(double number) {<FILL_FUNCTION_BODY>}
@Override
public void multi(int count) {
if (!initialized) {
output = OutputFactory.newList(count);
initialized = true;
}
}
@Override
public void setSubscriber(Subscriber<ScoredValue<V>> subscriber) {
LettuceAssert.notNull(subscriber, "Subscriber must not be null");
this.subscriber = subscriber;
}
@Override
public Subscriber<ScoredValue<V>> getSubscriber() {
return subscriber;
}
}
|
subscriber.onNext(output, ScoredValue.just(number, value));
value = null;
hasValue = false;
| 391
| 37
| 428
|
<methods>public void <init>(RedisCodec<K,V>, List<ScoredValue<V>>) ,public void complete(int) ,public List<ScoredValue<V>> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<ScoredValue<V>> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/ScoredValueOutput.java
|
ScoredValueOutput
|
set
|
class ScoredValueOutput<K, V> extends CommandOutput<K, V, ScoredValue<V>> {
private V value;
private boolean hasValue;
public ScoredValueOutput(RedisCodec<K, V> codec) {
super(codec, ScoredValue.empty());
}
@Override
public void set(ByteBuffer bytes) {
if (bytes == null) {
return;
}
if (!hasValue) {
value = codec.decodeValue(bytes);
hasValue = true;
return;
}
double score = LettuceStrings.toDouble(decodeAscii(bytes));
set(score);
}
@Override
public void set(long integer) {
value = (V) (Long) integer;
}
@Override
public void set(double number) {<FILL_FUNCTION_BODY>}
}
|
output = ScoredValue.just(number, value);
value = null;
hasValue = false;
| 237
| 30
| 267
|
<methods>public void <init>(RedisCodec<K,V>, ScoredValue<V>) ,public void complete(int) ,public ScoredValue<V> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected ScoredValue<V> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/ScoredValueScanOutput.java
|
ScoredValueScanOutput
|
setOutput
|
class ScoredValueScanOutput<K, V> extends ScanOutput<K, V, ScoredValueScanCursor<V>> {
private V value;
private boolean hasValue;
public ScoredValueScanOutput(RedisCodec<K, V> codec) {
super(codec, new ScoredValueScanCursor<V>());
}
@Override
protected void setOutput(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
@Override
public void set(double number) {
if (hasValue) {
output.getValues().add(ScoredValue.just(number, value));
}
value = null;
hasValue = false;
}
}
|
if (!hasValue) {
value = codec.decodeValue(bytes);
hasValue = true;
return;
}
double score = LettuceStrings.toDouble(decodeAscii(bytes));
set(score);
| 179
| 66
| 245
|
<methods>public void <init>(RedisCodec<K,V>, ScoredValueScanCursor<V>) ,public void set(java.nio.ByteBuffer) <variables>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/ScoredValueScanStreamingOutput.java
|
ScoredValueScanStreamingOutput
|
set
|
class ScoredValueScanStreamingOutput<K, V> extends ScanOutput<K, V, StreamScanCursor> {
private final ScoredValueStreamingChannel<V> channel;
private V value;
private boolean hasValue;
public ScoredValueScanStreamingOutput(RedisCodec<K, V> codec, ScoredValueStreamingChannel<V> channel) {
super(codec, new StreamScanCursor());
this.channel = channel;
}
@Override
protected void setOutput(ByteBuffer bytes) {
if (!hasValue) {
value = codec.decodeValue(bytes);
hasValue = true;
return;
}
double score = LettuceStrings.toDouble(decodeAscii(bytes));
set(score);
}
@Override
public void set(double number) {<FILL_FUNCTION_BODY>}
}
|
if (hasValue) {
channel.onValue(ScoredValue.just(number, value));
}
output.setCount(output.getCount() + 1);
value = null;
hasValue = false;
| 228
| 61
| 289
|
<methods>public void <init>(RedisCodec<K,V>, io.lettuce.core.StreamScanCursor) ,public void set(java.nio.ByteBuffer) <variables>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/ScoredValueStreamingOutput.java
|
ScoredValueStreamingOutput
|
set
|
class ScoredValueStreamingOutput<K, V> extends CommandOutput<K, V, Long> {
private V value;
private boolean hasValue;
private final ScoredValueStreamingChannel<V> channel;
public ScoredValueStreamingOutput(RedisCodec<K, V> codec, ScoredValueStreamingChannel<V> channel) {
super(codec, Long.valueOf(0));
this.channel = channel;
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
@Override
public void set(double number) {
channel.onValue(ScoredValue.just(number, value));
output = output.longValue() + 1;
value = null;
hasValue = false;
}
}
|
if (!hasValue) {
value = codec.decodeValue(bytes);
hasValue = true;
return;
}
double score = LettuceStrings.toDouble(decodeAscii(bytes));
set(score);
| 206
| 66
| 272
|
<methods>public void <init>(RedisCodec<K,V>, java.lang.Long) ,public void complete(int) ,public java.lang.Long get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected java.lang.Long output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/SocketAddressOutput.java
|
SocketAddressOutput
|
set
|
class SocketAddressOutput<K, V> extends CommandOutput<K, V, SocketAddress> {
private String hostname;
private boolean hasHostname;
public SocketAddressOutput(RedisCodec<K, V> codec) {
super(codec, null);
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
}
|
if (!hasHostname) {
hostname = decodeAscii(bytes);
hasHostname = true;
return;
}
int port = Integer.parseInt(decodeAscii(bytes));
output = InetSocketAddress.createUnresolved(hostname, port);
| 105
| 77
| 182
|
<methods>public void <init>(RedisCodec<K,V>, java.net.SocketAddress) ,public void complete(int) ,public java.net.SocketAddress get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected java.net.SocketAddress output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/StreamMessageListOutput.java
|
StreamMessageListOutput
|
set
|
class StreamMessageListOutput<K, V> extends CommandOutput<K, V, List<StreamMessage<K, V>>>
implements StreamingOutput<StreamMessage<K, V>> {
private final K stream;
private boolean initialized;
private Subscriber<StreamMessage<K, V>> subscriber;
private K key;
private String id;
private Map<K, V> body;
public StreamMessageListOutput(RedisCodec<K, V> codec, K stream) {
super(codec, Collections.emptyList());
setSubscriber(ListSubscriber.instance());
this.stream = stream;
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
@Override
public void multi(int count) {
if (!initialized) {
output = OutputFactory.newList(count);
initialized = true;
}
}
@Override
public void complete(int depth) {
if (depth == 1) {
subscriber.onNext(output, new StreamMessage<>(stream, id, body));
key = null;
id = null;
body = null;
}
}
@Override
public void setSubscriber(Subscriber<StreamMessage<K, V>> subscriber) {
LettuceAssert.notNull(subscriber, "Subscriber must not be null");
this.subscriber = subscriber;
}
@Override
public Subscriber<StreamMessage<K, V>> getSubscriber() {
return subscriber;
}
}
|
if (id == null) {
id = decodeAscii(bytes);
return;
}
if (key == null) {
key = codec.decodeKey(bytes);
return;
}
if (body == null) {
body = new LinkedHashMap<>();
}
body.put(key, bytes == null ? null : codec.decodeValue(bytes));
key = null;
| 413
| 113
| 526
|
<methods>public void <init>(RedisCodec<K,V>, List<StreamMessage<K,V>>) ,public void complete(int) ,public List<StreamMessage<K,V>> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<StreamMessage<K,V>> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/StreamReadOutput.java
|
StreamReadOutput
|
set
|
class StreamReadOutput<K, V> extends CommandOutput<K, V, List<StreamMessage<K, V>>>
implements StreamingOutput<StreamMessage<K, V>> {
private boolean initialized;
private Subscriber<StreamMessage<K, V>> subscriber;
private boolean skipStreamKeyReset = false;
private K stream;
private K key;
private String id;
private Map<K, V> body;
private boolean bodyReceived = false;
public StreamReadOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyList());
setSubscriber(ListSubscriber.instance());
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
@Override
public void multi(int count) {
if (id != null && key == null && count == -1) {
bodyReceived = true;
}
if (!initialized) {
output = OutputFactory.newList(count);
initialized = true;
}
}
@Override
public void complete(int depth) {
if (depth == 3 && bodyReceived) {
subscriber.onNext(output, new StreamMessage<>(stream, id, body == null ? Collections.emptyMap() : body));
bodyReceived = false;
key = null;
body = null;
id = null;
}
// RESP2/RESP3 compat
if (depth == 2 && skipStreamKeyReset) {
skipStreamKeyReset = false;
}
if (depth == 1) {
if (skipStreamKeyReset) {
skipStreamKeyReset = false;
} else {
stream = null;
}
}
}
@Override
public void setSubscriber(Subscriber<StreamMessage<K, V>> subscriber) {
LettuceAssert.notNull(subscriber, "Subscriber must not be null");
this.subscriber = subscriber;
}
@Override
public Subscriber<StreamMessage<K, V>> getSubscriber() {
return subscriber;
}
}
|
if (stream == null) {
if (bytes == null) {
return;
}
stream = codec.decodeKey(bytes);
skipStreamKeyReset = true;
return;
}
if (id == null) {
id = decodeAscii(bytes);
return;
}
if (key == null) {
bodyReceived = true;
if (bytes == null) {
return;
}
key = codec.decodeKey(bytes);
return;
}
if (body == null) {
body = new LinkedHashMap<>();
}
body.put(key, bytes == null ? null : codec.decodeValue(bytes));
key = null;
| 560
| 194
| 754
|
<methods>public void <init>(RedisCodec<K,V>, List<StreamMessage<K,V>>) ,public void complete(int) ,public List<StreamMessage<K,V>> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<StreamMessage<K,V>> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/StringListOutput.java
|
StringListOutput
|
multi
|
class StringListOutput<K, V> extends CommandOutput<K, V, List<String>> implements StreamingOutput<String> {
private boolean initialized;
private Subscriber<String> subscriber;
public StringListOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyList());
setSubscriber(ListSubscriber.instance());
}
@Override
public void set(ByteBuffer bytes) {
if (!initialized) {
multi(1);
}
subscriber.onNext(output, bytes == null ? null : decodeAscii(bytes));
}
@Override
public void multi(int count) {<FILL_FUNCTION_BODY>}
@Override
public void setSubscriber(Subscriber<String> subscriber) {
LettuceAssert.notNull(subscriber, "Subscriber must not be null");
this.subscriber = subscriber;
}
@Override
public Subscriber<String> getSubscriber() {
return subscriber;
}
}
|
if (!initialized) {
output = OutputFactory.newList(count);
initialized = true;
}
| 281
| 33
| 314
|
<methods>public void <init>(RedisCodec<K,V>, List<java.lang.String>) ,public void complete(int) ,public List<java.lang.String> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<java.lang.String> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/StringMatchResultOutput.java
|
StringMatchResultOutput
|
buildMatchedString
|
class StringMatchResultOutput<K, V> extends CommandOutput<K, V, StringMatchResult> {
private final boolean withIdx;
private String matchString;
private int len;
private List<Long> positions;
private final List<MatchedPosition> matchedPositions = new ArrayList<>();
public StringMatchResultOutput(RedisCodec<K, V> codec, boolean withIdx) {
super(codec, null);
this.withIdx = withIdx;
}
@Override
public void set(ByteBuffer bytes) {
if (!withIdx && matchString == null) {
matchString = (String) codec.decodeKey(bytes);
}
}
@Override
public void set(long integer) {
this.len = (int) integer;
if (positions == null) {
positions = new ArrayList<>();
}
positions.add(integer);
}
@Override
public void complete(int depth) {
if (depth == 2) {
matchedPositions.add(buildMatchedString(positions));
positions = null;
}
if (depth == 0) {
output = new StringMatchResult(matchString, matchedPositions, len);
}
}
private static MatchedPosition buildMatchedString(List<Long> positions) {<FILL_FUNCTION_BODY>}
}
|
if (positions == null) {
throw new IllegalStateException("No matched positions");
}
int size = positions.size();
// not WITHMATCHLEN
long matchLen = size % 2 == 0 ? 0L : positions.get(size - 1);
return new MatchedPosition(new Position(positions.get(0), positions.get(1)),
new Position(positions.get(2), positions.get(3)), matchLen);
| 358
| 116
| 474
|
<methods>public void <init>(RedisCodec<K,V>, io.lettuce.core.StringMatchResult) ,public void complete(int) ,public io.lettuce.core.StringMatchResult get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected io.lettuce.core.StringMatchResult output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/StringValueListOutput.java
|
StringValueListOutput
|
multi
|
class StringValueListOutput<K, V> extends CommandOutput<K, V, List<Value<String>>>
implements StreamingOutput<Value<String>> {
private boolean initialized;
private Subscriber<Value<String>> subscriber;
public StringValueListOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyList());
setSubscriber(ListSubscriber.instance());
}
@Override
public void set(ByteBuffer bytes) {
subscriber.onNext(output, bytes == null ? Value.empty() : Value.fromNullable(decodeAscii(bytes)));
}
@Override
public void multi(int count) {<FILL_FUNCTION_BODY>}
@Override
public void setSubscriber(Subscriber<Value<String>> subscriber) {
LettuceAssert.notNull(subscriber, "Subscriber must not be null");
this.subscriber = subscriber;
}
@Override
public Subscriber<Value<String>> getSubscriber() {
return subscriber;
}
}
|
if (!initialized) {
output = OutputFactory.newList(count);
initialized = true;
}
| 284
| 33
| 317
|
<methods>public void <init>(RedisCodec<K,V>, List<Value<java.lang.String>>) ,public void complete(int) ,public List<Value<java.lang.String>> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<Value<java.lang.String>> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/ValueListOutput.java
|
ValueListOutput
|
multi
|
class ValueListOutput<K, V> extends CommandOutput<K, V, List<V>> implements StreamingOutput<V> {
private boolean initialized;
private Subscriber<V> subscriber;
public ValueListOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyList());
setSubscriber(ListSubscriber.instance());
}
@Override
public void set(ByteBuffer bytes) {
// RESP 3 behavior
if (bytes == null && !initialized) {
return;
}
subscriber.onNext(output, bytes == null ? null : codec.decodeValue(bytes));
}
@Override
public void multi(int count) {<FILL_FUNCTION_BODY>}
@Override
public void setSubscriber(Subscriber<V> subscriber) {
LettuceAssert.notNull(subscriber, "Subscriber must not be null");
this.subscriber = subscriber;
}
@Override
public Subscriber<V> getSubscriber() {
return subscriber;
}
}
|
if (!initialized) {
output = OutputFactory.newList(count);
initialized = true;
}
| 293
| 33
| 326
|
<methods>public void <init>(RedisCodec<K,V>, List<V>) ,public void complete(int) ,public List<V> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<V> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/ValueSetOutput.java
|
ValueSetOutput
|
set
|
class ValueSetOutput<K, V> extends CommandOutput<K, V, Set<V>> {
private boolean initialized;
public ValueSetOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptySet());
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
@Override
public void multi(int count) {
if (!initialized) {
output = OutputFactory.newSet(count);
initialized = true;
}
}
}
|
// RESP 3 behavior
if (bytes == null && !initialized) {
return;
}
output.add(bytes == null ? null : codec.decodeValue(bytes));
| 145
| 53
| 198
|
<methods>public void <init>(RedisCodec<K,V>, Set<V>) ,public void complete(int) ,public Set<V> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected Set<V> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/ValueStreamingOutput.java
|
ValueStreamingOutput
|
set
|
class ValueStreamingOutput<K, V> extends CommandOutput<K, V, Long> {
private final ValueStreamingChannel<V> channel;
public ValueStreamingOutput(RedisCodec<K, V> codec, ValueStreamingChannel<V> channel) {
super(codec, Long.valueOf(0));
this.channel = channel;
}
@Override
public void set(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
}
|
channel.onValue(bytes == null ? null : codec.decodeValue(bytes));
output = output.longValue() + 1;
| 122
| 37
| 159
|
<methods>public void <init>(RedisCodec<K,V>, java.lang.Long) ,public void complete(int) ,public java.lang.Long get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected java.lang.Long output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/output/ValueValueListOutput.java
|
ValueValueListOutput
|
multi
|
class ValueValueListOutput<K, V> extends CommandOutput<K, V, List<Value<V>>> implements StreamingOutput<Value<V>> {
private boolean initialized;
private Subscriber<Value<V>> subscriber;
public ValueValueListOutput(RedisCodec<K, V> codec) {
super(codec, Collections.emptyList());
setSubscriber(ListSubscriber.instance());
}
@Override
public void set(ByteBuffer bytes) {
subscriber.onNext(output, Value.fromNullable(bytes == null ? null : codec.decodeValue(bytes)));
}
@Override
public void set(long integer) {
subscriber.onNext(output, Value.fromNullable((V) Long.valueOf(integer)));
}
@Override
public void multi(int count) {<FILL_FUNCTION_BODY>}
@Override
public void setSubscriber(Subscriber<Value<V>> subscriber) {
LettuceAssert.notNull(subscriber, "Subscriber must not be null");
this.subscriber = subscriber;
}
@Override
public Subscriber<Value<V>> getSubscriber() {
return subscriber;
}
}
|
if (!initialized) {
output = OutputFactory.newList(count);
initialized = true;
}
| 322
| 33
| 355
|
<methods>public void <init>(RedisCodec<K,V>, List<Value<V>>) ,public void complete(int) ,public List<Value<V>> get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected List<Value<V>> output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/protocol/ActivationCommand.java
|
ActivationCommand
|
isActivationCommand
|
class ActivationCommand<K, V, T> extends CommandWrapper<K, V, T> {
public ActivationCommand(RedisCommand<K, V, T> command) {
super(command);
}
public static boolean isActivationCommand(RedisCommand<?, ?, ?> command) {<FILL_FUNCTION_BODY>}
}
|
if (command instanceof ActivationCommand) {
return true;
}
while (command instanceof CommandWrapper) {
command = ((CommandWrapper<?, ?, ?>) command).getDelegate();
if (command instanceof ActivationCommand) {
return true;
}
}
return false;
| 91
| 82
| 173
|
<methods>public void <init>(RedisCommand<K,V,T>) ,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 CommandOutput<K,V,T> getOutput() ,public io.lettuce.core.protocol.ProtocolKeyword getType() ,public int hashCode() ,public boolean isCancelled() ,public boolean isDone() ,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() ,public static RedisCommand<K,V,T> unwrap(RedisCommand<K,V,T>) ,public static R unwrap(RedisCommand<K,V,T>, Class<R>) <variables>private static final java.lang.Object[] COMPLETE,private static final java.lang.Object[] EMPTY,private static final AtomicReferenceFieldUpdater<CommandWrapper#RAW,java.lang.Object[]> ONCOMPLETE,protected final non-sealed RedisCommand<K,V,T> command,private volatile java.lang.Object[] onComplete
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/protocol/AsyncCommand.java
|
AsyncCommand
|
await
|
class AsyncCommand<K, V, T> extends CompletableFuture<T>
implements RedisCommand<K, V, T>, RedisFuture<T>, CompleteableCommand<T>, DecoratedCommand<K, V, T> {
@SuppressWarnings("rawtypes")
private static final AtomicIntegerFieldUpdater<AsyncCommand> COUNT_UPDATER = AtomicIntegerFieldUpdater
.newUpdater(AsyncCommand.class, "count");
private final RedisCommand<K, V, T> command;
// access via COUNT_UPDATER
@SuppressWarnings({ "unused" })
private volatile int count = 1;
/**
* @param command the command, must not be {@code null}.
*/
public AsyncCommand(RedisCommand<K, V, T> command) {
this(command, 1);
}
/**
* @param command the command, must not be {@code null}.
*/
protected AsyncCommand(RedisCommand<K, V, T> command, int count) {
LettuceAssert.notNull(command, "RedisCommand must not be null");
this.command = command;
this.count = count;
}
/**
* Wait up to the specified time for the command output to become available.
*
* @param timeout Maximum time to wait for a result.
* @param unit Unit of time for the timeout.
*
* @return true if the output became available.
*/
@Override
public boolean await(long timeout, TimeUnit unit) {<FILL_FUNCTION_BODY>}
/**
* Get the object that holds this command's output.
*
* @return The command output object.
*/
@Override
public CommandOutput<K, V, T> getOutput() {
return command.getOutput();
}
/**
* Mark this command complete and notify all waiting threads.
*/
@Override
public void complete() {
if (COUNT_UPDATER.decrementAndGet(this) == 0) {
completeResult();
command.complete();
}
}
protected void completeResult() {
if (command.getOutput() == null) {
complete(null);
} else if (command.getOutput().hasError()) {
doCompleteExceptionally(ExceptionFactory.createExecutionException(command.getOutput().getError()));
} else {
complete(command.getOutput().get());
}
}
@Override
public boolean completeExceptionally(Throwable ex) {
boolean result = false;
int ref = COUNT_UPDATER.get(this);
if (ref > 0 && COUNT_UPDATER.compareAndSet(this, ref, 0)) {
result = doCompleteExceptionally(ex);
}
return result;
}
private boolean doCompleteExceptionally(Throwable ex) {
command.completeExceptionally(ex);
return super.completeExceptionally(ex);
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
try {
command.cancel();
return super.cancel(mayInterruptIfRunning);
} finally {
COUNT_UPDATER.set(this, 0);
}
}
@Override
public String getError() {
return command.getOutput().getError();
}
@Override
public CommandArgs<K, V> getArgs() {
return command.getArgs();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [type=").append(getType());
sb.append(", output=").append(getOutput());
sb.append(", commandType=").append(command.getClass().getName());
sb.append(']');
return sb.toString();
}
@Override
public ProtocolKeyword getType() {
return command.getType();
}
@Override
public void cancel() {
cancel(true);
}
@Override
public void encode(ByteBuf buf) {
command.encode(buf);
}
@Override
public void setOutput(CommandOutput<K, V, T> output) {
command.setOutput(output);
}
@Override
public void onComplete(Consumer<? super T> action) {
thenAccept(action);
}
@Override
public void onComplete(BiConsumer<? super T, Throwable> action) {
whenComplete(action);
}
@Override
public RedisCommand<K, V, T> getDelegate() {
return command;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof RedisCommand)) {
return false;
}
RedisCommand<?, ?, ?> left = CommandWrapper.unwrap(command);
RedisCommand<?, ?, ?> right = CommandWrapper.unwrap((RedisCommand<?, ?, ?>) o);
return left == right;
}
@Override
public int hashCode() {
RedisCommand<?, ?, ?> toHash = CommandWrapper.unwrap(command);
return toHash != null ? toHash.hashCode() : 0;
}
}
|
try {
get(timeout, unit);
return true;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RedisCommandInterruptedException(e);
} catch (ExecutionException e) {
return true;
} catch (TimeoutException e) {
return false;
}
| 1,377
| 87
| 1,464
|
<methods>public void <init>() ,public CompletableFuture<java.lang.Void> acceptEither(CompletionStage<? extends T>, Consumer<? super T>) ,public CompletableFuture<java.lang.Void> acceptEitherAsync(CompletionStage<? extends T>, Consumer<? super T>) ,public CompletableFuture<java.lang.Void> acceptEitherAsync(CompletionStage<? extends T>, Consumer<? super T>, java.util.concurrent.Executor) ,public static transient CompletableFuture<java.lang.Void> allOf(CompletableFuture<?>[]) ,public static transient CompletableFuture<java.lang.Object> anyOf(CompletableFuture<?>[]) ,public CompletableFuture<U> applyToEither(CompletionStage<? extends T>, Function<? super T,U>) ,public CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T>, Function<? super T,U>) ,public CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T>, Function<? super T,U>, java.util.concurrent.Executor) ,public boolean cancel(boolean) ,public boolean complete(T) ,public CompletableFuture<T> completeAsync(Supplier<? extends T>) ,public CompletableFuture<T> completeAsync(Supplier<? extends T>, java.util.concurrent.Executor) ,public boolean completeExceptionally(java.lang.Throwable) ,public CompletableFuture<T> completeOnTimeout(T, long, java.util.concurrent.TimeUnit) ,public static CompletableFuture<U> completedFuture(U) ,public static CompletionStage<U> completedStage(U) ,public CompletableFuture<T> copy() ,public java.util.concurrent.Executor defaultExecutor() ,public static java.util.concurrent.Executor delayedExecutor(long, java.util.concurrent.TimeUnit) ,public static java.util.concurrent.Executor delayedExecutor(long, java.util.concurrent.TimeUnit, java.util.concurrent.Executor) ,public CompletableFuture<T> exceptionally(Function<java.lang.Throwable,? extends T>) ,public CompletableFuture<T> exceptionallyAsync(Function<java.lang.Throwable,? extends T>) ,public CompletableFuture<T> exceptionallyAsync(Function<java.lang.Throwable,? extends T>, java.util.concurrent.Executor) ,public CompletableFuture<T> exceptionallyCompose(Function<java.lang.Throwable,? extends CompletionStage<T>>) ,public CompletableFuture<T> exceptionallyComposeAsync(Function<java.lang.Throwable,? extends CompletionStage<T>>) ,public CompletableFuture<T> exceptionallyComposeAsync(Function<java.lang.Throwable,? extends CompletionStage<T>>, java.util.concurrent.Executor) ,public static CompletableFuture<U> failedFuture(java.lang.Throwable) ,public static CompletionStage<U> failedStage(java.lang.Throwable) ,public T get() throws java.lang.InterruptedException, java.util.concurrent.ExecutionException,public T get(long, java.util.concurrent.TimeUnit) throws java.lang.InterruptedException, java.util.concurrent.ExecutionException, java.util.concurrent.TimeoutException,public T getNow(T) ,public int getNumberOfDependents() ,public CompletableFuture<U> handle(BiFunction<? super T,java.lang.Throwable,? extends U>) ,public CompletableFuture<U> handleAsync(BiFunction<? super T,java.lang.Throwable,? extends U>) ,public CompletableFuture<U> handleAsync(BiFunction<? super T,java.lang.Throwable,? extends U>, java.util.concurrent.Executor) ,public boolean isCancelled() ,public boolean isCompletedExceptionally() ,public boolean isDone() ,public T join() ,public CompletionStage<T> minimalCompletionStage() ,public CompletableFuture<U> newIncompleteFuture() ,public void obtrudeException(java.lang.Throwable) ,public void obtrudeValue(T) ,public CompletableFuture<T> orTimeout(long, java.util.concurrent.TimeUnit) ,public CompletableFuture<java.lang.Void> runAfterBoth(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterBothAsync(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterBothAsync(CompletionStage<?>, java.lang.Runnable, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> runAfterEither(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterEitherAsync(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterEitherAsync(CompletionStage<?>, java.lang.Runnable, java.util.concurrent.Executor) ,public static CompletableFuture<java.lang.Void> runAsync(java.lang.Runnable) ,public static CompletableFuture<java.lang.Void> runAsync(java.lang.Runnable, java.util.concurrent.Executor) ,public static CompletableFuture<U> supplyAsync(Supplier<U>) ,public static CompletableFuture<U> supplyAsync(Supplier<U>, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> thenAccept(Consumer<? super T>) ,public CompletableFuture<java.lang.Void> thenAcceptAsync(Consumer<? super T>) ,public CompletableFuture<java.lang.Void> thenAcceptAsync(Consumer<? super T>, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> thenAcceptBoth(CompletionStage<? extends U>, BiConsumer<? super T,? super U>) ,public CompletableFuture<java.lang.Void> thenAcceptBothAsync(CompletionStage<? extends U>, BiConsumer<? super T,? super U>) ,public CompletableFuture<java.lang.Void> thenAcceptBothAsync(CompletionStage<? extends U>, BiConsumer<? super T,? super U>, java.util.concurrent.Executor) ,public CompletableFuture<U> thenApply(Function<? super T,? extends U>) ,public CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U>) ,public CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U>, java.util.concurrent.Executor) ,public CompletableFuture<V> thenCombine(CompletionStage<? extends U>, BiFunction<? super T,? super U,? extends V>) ,public CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U>, BiFunction<? super T,? super U,? extends V>) ,public CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U>, BiFunction<? super T,? super U,? extends V>, java.util.concurrent.Executor) ,public CompletableFuture<U> thenCompose(Function<? super T,? extends CompletionStage<U>>) ,public CompletableFuture<U> thenComposeAsync(Function<? super T,? extends CompletionStage<U>>) ,public CompletableFuture<U> thenComposeAsync(Function<? super T,? extends CompletionStage<U>>, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> thenRun(java.lang.Runnable) ,public CompletableFuture<java.lang.Void> thenRunAsync(java.lang.Runnable) ,public CompletableFuture<java.lang.Void> thenRunAsync(java.lang.Runnable, java.util.concurrent.Executor) ,public CompletableFuture<T> toCompletableFuture() ,public java.lang.String toString() ,public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super java.lang.Throwable>) ,public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super java.lang.Throwable>) ,public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super java.lang.Throwable>, java.util.concurrent.Executor) <variables>static final int ASYNC,private static final java.util.concurrent.Executor ASYNC_POOL,static final int NESTED,private static final java.lang.invoke.VarHandle NEXT,static final java.util.concurrent.CompletableFuture.AltResult NIL,private static final java.lang.invoke.VarHandle RESULT,private static final java.lang.invoke.VarHandle STACK,static final int SYNC,private static final boolean USE_COMMON_POOL,volatile java.lang.Object result,volatile java.util.concurrent.CompletableFuture.Completion stack
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/protocol/BaseRedisCommandBuilder.java
|
BaseRedisCommandBuilder
|
createCommand
|
class BaseRedisCommandBuilder<K, V> {
protected final RedisCodec<K, V> codec;
public BaseRedisCommandBuilder(RedisCodec<K, V> codec) {
this.codec = codec;
}
protected <T> Command<K, V, T> createCommand(CommandType type, CommandOutput<K, V, T> output) {
return createCommand(type, output, (CommandArgs<K, V>) null);
}
protected <T> Command<K, V, T> createCommand(CommandType type, CommandOutput<K, V, T> output, K key) {
CommandArgs<K, V> args = new CommandArgs<>(codec).addKey(key);
return createCommand(type, output, args);
}
protected <T> Command<K, V, T> createCommand(CommandType type, CommandOutput<K, V, T> output, K key, V value) {
CommandArgs<K, V> args = new CommandArgs<>(codec).addKey(key).addValue(value);
return createCommand(type, output, args);
}
protected <T> Command<K, V, T> createCommand(CommandType type, CommandOutput<K, V, T> output, K key, V[] values) {<FILL_FUNCTION_BODY>}
protected <T> Command<K, V, T> createCommand(CommandType type, CommandOutput<K, V, T> output, CommandArgs<K, V> args) {
return new Command<>(type, output, args);
}
@SuppressWarnings("unchecked")
protected <T> CommandOutput<K, V, T> newScriptOutput(RedisCodec<K, V> codec, ScriptOutputType type) {
switch (type) {
case BOOLEAN:
return (CommandOutput<K, V, T>) new BooleanOutput<>(codec);
case INTEGER:
return (CommandOutput<K, V, T>) new IntegerOutput<>(codec);
case STATUS:
return (CommandOutput<K, V, T>) new StatusOutput<>(codec);
case MULTI:
return (CommandOutput<K, V, T>) new NestedMultiOutput<>(codec);
case VALUE:
return (CommandOutput<K, V, T>) new ValueOutput<>(codec);
case OBJECT:
return (CommandOutput<K, V, T>) new ObjectOutput<>(codec);
default:
throw new RedisException("Unsupported script output type");
}
}
}
|
CommandArgs<K, V> args = new CommandArgs<>(codec).addKey(key).addValues(values);
return createCommand(type, output, args);
| 646
| 43
| 689
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/protocol/ChannelLogDescriptor.java
|
ChannelLogDescriptor
|
logDescriptor
|
class ChannelLogDescriptor {
static String logDescriptor(Channel channel) {<FILL_FUNCTION_BODY>}
static String getId(Channel channel) {
return String.format("0x%08x", channel.hashCode());
}
}
|
if (channel == null) {
return "unknown";
}
StringBuffer buffer = new StringBuffer(64);
buffer.append("channel=").append(getId(channel)).append(", ");
if (channel.localAddress() != null && channel.remoteAddress() != null) {
buffer.append(channel.localAddress()).append(" -> ").append(channel.remoteAddress());
} else {
buffer.append(channel);
}
if (!channel.isActive()) {
if (buffer.length() != 0) {
buffer.append(' ');
}
buffer.append("(inactive)");
}
return buffer.toString();
| 67
| 178
| 245
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/protocol/Command.java
|
Command
|
toString
|
class Command<K, V, T> implements RedisCommand<K, V, T> {
protected static final byte ST_INITIAL = 0;
protected static final byte ST_COMPLETED = 1;
protected static final byte ST_CANCELLED = 2;
private final ProtocolKeyword type;
protected CommandArgs<K, V> args;
protected CommandOutput<K, V, T> output;
protected Throwable exception;
protected volatile byte status = ST_INITIAL;
/**
* Create a new command with the supplied type.
*
* @param type Command type, must not be {@code null}.
* @param output Command output, can be {@code null}.
*/
public Command(ProtocolKeyword type, CommandOutput<K, V, T> output) {
this(type, output, null);
}
/**
* Create a new command with the supplied type and args.
*
* @param type Command type, must not be {@code null}.
* @param output Command output, can be {@code null}.
* @param args Command args, can be {@code null}
*/
public Command(ProtocolKeyword type, CommandOutput<K, V, T> output, CommandArgs<K, V> args) {
LettuceAssert.notNull(type, "Command type must not be null");
this.type = type;
this.output = output;
this.args = args;
}
/**
* Get the object that holds this command's output.
*
* @return The command output object.
*/
@Override
public CommandOutput<K, V, T> getOutput() {
return output;
}
@Override
public boolean completeExceptionally(Throwable throwable) {
if (output != null) {
output.setError(throwable.getMessage());
}
exception = throwable;
this.status = ST_COMPLETED;
return true;
}
/**
* Mark this command complete and notify all waiting threads.
*/
@Override
public void complete() {
this.status = ST_COMPLETED;
}
@Override
public void cancel() {
this.status = ST_CANCELLED;
}
/**
* Encode and write this command to the supplied buffer using the new <a href="https://redis.io/topics/protocol">Unified
* Request Protocol</a>.
*
* @param buf Buffer to write to.
*/
public void encode(ByteBuf buf) {
buf.touch("Command.encode(…)");
buf.writeByte('*');
CommandArgs.IntegerArgument.writeInteger(buf, 1 + (args != null ? args.count() : 0));
buf.writeBytes(CommandArgs.CRLF);
CommandArgs.BytesArgument.writeBytes(buf, type.getBytes());
if (args != null) {
args.encode(buf);
}
}
public String getError() {
return output.getError();
}
@Override
public CommandArgs<K, V> getArgs() {
return args;
}
/**
*
* @return the resut from the output.
*/
public T get() {
if (output != null) {
return output.get();
}
return null;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public void setOutput(CommandOutput<K, V, T> output) {
if (this.status != ST_INITIAL) {
throw new IllegalStateException("Command is completed/cancelled. Cannot set a new output");
}
this.output = output;
}
@Override
public ProtocolKeyword getType() {
return type;
}
@Override
public boolean isCancelled() {
return status == ST_CANCELLED;
}
@Override
public boolean isDone() {
return status != ST_INITIAL;
}
}
|
final StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [type=").append(type);
sb.append(", output=").append(output);
sb.append(']');
return sb.toString();
| 1,052
| 70
| 1,122
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/protocol/CommandArgsAccessor.java
|
CommandArgsAccessor
|
getStringArguments
|
class CommandArgsAccessor {
/**
* Get the first encoded key for cluster command routing.
*
* @param commandArgs must not be null.
* @return the first encoded key or {@code null}.
*/
@SuppressWarnings("unchecked")
public static <K, V> ByteBuffer encodeFirstKey(CommandArgs<K, V> commandArgs) {
for (SingularArgument singularArgument : commandArgs.singularArguments) {
if (singularArgument instanceof CommandArgs.KeyArgument) {
return commandArgs.codec.encodeKey(((CommandArgs.KeyArgument<K, V>) singularArgument).key);
}
}
return null;
}
/**
* Get the first {@link String} argument.
*
* @param commandArgs must not be null.
* @return the first {@link String} argument or {@code null}.
*/
@SuppressWarnings("unchecked")
public static <K, V> String getFirstString(CommandArgs<K, V> commandArgs) {
for (SingularArgument singularArgument : commandArgs.singularArguments) {
if (singularArgument instanceof StringArgument) {
return ((StringArgument) singularArgument).val;
}
}
return null;
}
/**
* Get the first {@code char[]}-array argument.
*
* @param commandArgs must not be null.
* @return the first {@link String} argument or {@code null}.
*/
@SuppressWarnings("unchecked")
public static <K, V> char[] getFirstCharArray(CommandArgs<K, V> commandArgs) {
for (SingularArgument singularArgument : commandArgs.singularArguments) {
if (singularArgument instanceof CharArrayArgument) {
return ((CharArrayArgument) singularArgument).val;
}
}
return null;
}
/**
* Get the all {@link String} arguments.
*
* @param commandArgs must not be null.
* @return the first {@link String} argument or {@code null}.
* @since 6.0
*/
public static <K, V> List<String> getStringArguments(CommandArgs<K, V> commandArgs) {<FILL_FUNCTION_BODY>}
/**
* Get the all {@code char[]} arguments.
*
* @param commandArgs must not be null.
* @return the first {@link String} argument or {@code null}.
* @since 6.0
*/
public static <K, V> List<char[]> getCharArrayArguments(CommandArgs<K, V> commandArgs) {
List<char[]> args = new ArrayList<>();
for (SingularArgument singularArgument : commandArgs.singularArguments) {
if (singularArgument instanceof CharArrayArgument) {
args.add(((CharArrayArgument) singularArgument).val);
}
if (singularArgument instanceof StringArgument) {
args.add(((StringArgument) singularArgument).val.toCharArray());
}
}
return args;
}
/**
* Get the first {@link Long integer} argument.
*
* @param commandArgs must not be null.
* @return the first {@link Long integer} argument or {@code null}.
*/
@SuppressWarnings("unchecked")
public static <K, V> Long getFirstInteger(CommandArgs<K, V> commandArgs) {
for (SingularArgument singularArgument : commandArgs.singularArguments) {
if (singularArgument instanceof CommandArgs.IntegerArgument) {
return ((CommandArgs.IntegerArgument) singularArgument).val;
}
}
return null;
}
}
|
List<String> args = new ArrayList<>();
for (SingularArgument singularArgument : commandArgs.singularArguments) {
if (singularArgument instanceof StringArgument) {
args.add(((StringArgument) singularArgument).val);
}
}
return args;
| 934
| 75
| 1,009
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/protocol/CommandEncoder.java
|
CommandEncoder
|
encode
|
class CommandEncoder extends MessageToByteEncoder<Object> {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(CommandEncoder.class);
private final boolean traceEnabled = logger.isTraceEnabled();
private final boolean debugEnabled = logger.isDebugEnabled();
public CommandEncoder() {
this(PlatformDependent.directBufferPreferred());
}
public CommandEncoder(boolean preferDirect) {
super(preferDirect);
}
@Override
protected ByteBuf allocateBuffer(ChannelHandlerContext ctx, Object msg, boolean preferDirect) throws Exception {
if (msg instanceof Collection) {
if (preferDirect) {
return ctx.alloc().ioBuffer(((Collection) msg).size() * 16);
} else {
return ctx.alloc().heapBuffer(((Collection) msg).size() * 16);
}
}
if (preferDirect) {
return ctx.alloc().ioBuffer();
} else {
return ctx.alloc().heapBuffer();
}
}
@Override
@SuppressWarnings("unchecked")
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
out.touch("CommandEncoder.encode(…)");
if (msg instanceof RedisCommand) {
RedisCommand<?, ?, ?> command = (RedisCommand<?, ?, ?>) msg;
encode(ctx, out, command);
}
if (msg instanceof Collection) {
Collection<RedisCommand<?, ?, ?>> commands = (Collection<RedisCommand<?, ?, ?>>) msg;
for (RedisCommand<?, ?, ?> command : commands) {
encode(ctx, out, command);
}
}
}
private void encode(ChannelHandlerContext ctx, ByteBuf out, RedisCommand<?, ?, ?> command) {<FILL_FUNCTION_BODY>}
private String logPrefix(Channel channel) {
StringBuilder buffer = new StringBuilder(64);
buffer.append('[').append(ChannelLogDescriptor.logDescriptor(channel)).append(']');
return buffer.toString();
}
}
|
try {
out.markWriterIndex();
command.encode(out);
} catch (RuntimeException e) {
out.resetWriterIndex();
command.completeExceptionally(new EncoderException(
"Cannot encode command. Please close the connection as the connection state may be out of sync.", e));
}
if (debugEnabled) {
logger.debug("{} writing command {}", logPrefix(ctx.channel()), command);
if (traceEnabled) {
logger.trace("{} Sent: {}", logPrefix(ctx.channel()), out.toString(Charset.defaultCharset()).trim());
}
}
| 545
| 155
| 700
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/protocol/CommandExpiryWriter.java
|
CommandExpiryWriter
|
potentiallyExpire
|
class CommandExpiryWriter implements RedisChannelWriter {
private final RedisChannelWriter delegate;
private final TimeoutSource source;
private final TimeUnit timeUnit;
private final ScheduledExecutorService executorService;
private final Timer timer;
private final boolean applyConnectionTimeout;
private volatile long timeout = -1;
/**
* Create a new {@link CommandExpiryWriter}.
*
* @param delegate must not be {@code null}.
* @param clientOptions must not be {@code null}.
* @param clientResources must not be {@code null}.
*/
public CommandExpiryWriter(RedisChannelWriter delegate, ClientOptions clientOptions, ClientResources clientResources) {
LettuceAssert.notNull(delegate, "RedisChannelWriter must not be null");
LettuceAssert.isTrue(isSupported(clientOptions), "Command timeout not enabled");
LettuceAssert.notNull(clientResources, "ClientResources must not be null");
TimeoutOptions timeoutOptions = clientOptions.getTimeoutOptions();
this.delegate = delegate;
this.source = timeoutOptions.getSource();
this.applyConnectionTimeout = timeoutOptions.isApplyConnectionTimeout();
this.timeUnit = source.getTimeUnit();
this.executorService = clientResources.eventExecutorGroup();
this.timer = clientResources.timer();
}
/**
* Check whether {@link ClientOptions} is configured to timeout commands.
*
* @param clientOptions must not be {@code null}.
* @return {@code true} if {@link ClientOptions} are configured to timeout commands.
*/
public static boolean isSupported(ClientOptions clientOptions) {
LettuceAssert.notNull(clientOptions, "ClientOptions must not be null");
return isSupported(clientOptions.getTimeoutOptions());
}
private static boolean isSupported(TimeoutOptions timeoutOptions) {
LettuceAssert.notNull(timeoutOptions, "TimeoutOptions must not be null");
return timeoutOptions.isTimeoutCommands();
}
@Override
public void setConnectionFacade(ConnectionFacade connectionFacade) {
delegate.setConnectionFacade(connectionFacade);
}
@Override
public ClientResources getClientResources() {
return delegate.getClientResources();
}
@Override
public void setAutoFlushCommands(boolean autoFlush) {
delegate.setAutoFlushCommands(autoFlush);
}
@Override
public <K, V, T> RedisCommand<K, V, T> write(RedisCommand<K, V, T> command) {
potentiallyExpire(command, getExecutorService());
return delegate.write(command);
}
@Override
public <K, V> Collection<RedisCommand<K, V, ?>> write(Collection<? extends RedisCommand<K, V, ?>> redisCommands) {
ScheduledExecutorService executorService = getExecutorService();
for (RedisCommand<K, V, ?> command : redisCommands) {
potentiallyExpire(command, executorService);
}
return delegate.write(redisCommands);
}
@Override
public void flushCommands() {
delegate.flushCommands();
}
@Override
public void close() {
delegate.close();
}
@Override
public CompletableFuture<Void> closeAsync() {
return delegate.closeAsync();
}
@Override
public void reset() {
delegate.reset();
}
public void setTimeout(Duration timeout) {
this.timeout = timeUnit.convert(timeout.toNanos(), TimeUnit.NANOSECONDS);
}
public RedisChannelWriter getDelegate() {
return delegate;
}
private ScheduledExecutorService getExecutorService() {
return this.executorService;
}
private void potentiallyExpire(RedisCommand<?, ?, ?> command, ScheduledExecutorService executors) {<FILL_FUNCTION_BODY>}
}
|
long timeout = applyConnectionTimeout ? this.timeout : source.getTimeout(command);
if (timeout <= 0) {
return;
}
Timeout commandTimeout = timer.newTimeout(t -> {
if (!command.isDone()) {
executors.submit(() -> command.completeExceptionally(
ExceptionFactory.createTimeoutException(Duration.ofNanos(timeUnit.toNanos(timeout)))));
}
}, timeout, timeUnit);
if (command instanceof CompleteableCommand) {
((CompleteableCommand<?>) command).onComplete((o, o2) -> commandTimeout.cancel());
}
| 1,027
| 165
| 1,192
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/protocol/LatencyMeteredCommand.java
|
LatencyMeteredCommand
|
sent
|
class LatencyMeteredCommand<K, V, T> extends CommandWrapper<K, V, T> implements WithLatency {
private long sentNs = -1;
private long firstResponseNs = -1;
private long completedNs = -1;
public LatencyMeteredCommand(RedisCommand<K, V, T> command) {
super(command);
}
@Override
public void sent(long timeNs) {<FILL_FUNCTION_BODY>}
@Override
public void firstResponse(long timeNs) {
firstResponseNs = timeNs;
}
@Override
public void completed(long timeNs) {
completedNs = timeNs;
}
@Override
public long getSent() {
return sentNs;
}
@Override
public long getFirstResponse() {
return firstResponseNs;
}
@Override
public long getCompleted() {
return completedNs;
}
}
|
sentNs = timeNs;
firstResponseNs = -1;
completedNs = -1;
| 264
| 32
| 296
|
<methods>public void <init>(RedisCommand<K,V,T>) ,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 CommandOutput<K,V,T> getOutput() ,public io.lettuce.core.protocol.ProtocolKeyword getType() ,public int hashCode() ,public boolean isCancelled() ,public boolean isDone() ,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() ,public static RedisCommand<K,V,T> unwrap(RedisCommand<K,V,T>) ,public static R unwrap(RedisCommand<K,V,T>, Class<R>) <variables>private static final java.lang.Object[] COMPLETE,private static final java.lang.Object[] EMPTY,private static final AtomicReferenceFieldUpdater<CommandWrapper#RAW,java.lang.Object[]> ONCOMPLETE,protected final non-sealed RedisCommand<K,V,T> command,private volatile java.lang.Object[] onComplete
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/protocol/RatioDecodeBufferPolicy.java
|
RatioDecodeBufferPolicy
|
discardReadBytesIfNecessary
|
class RatioDecodeBufferPolicy implements DecodeBufferPolicy {
private final float discardReadBytesRatio;
/**
* Create a new {@link RatioDecodeBufferPolicy} using {@code bufferUsageRatio}.
*
* @param bufferUsageRatio the buffer usage ratio. Must be between {@code 0} and {@code 2^31-1}, typically a value between 1
* and 10 representing 50% to 90%.
*
*/
public RatioDecodeBufferPolicy(float bufferUsageRatio) {
LettuceAssert.isTrue(bufferUsageRatio > 0 && bufferUsageRatio < Integer.MAX_VALUE,
"BufferUsageRatio must be greater than 0");
this.discardReadBytesRatio = bufferUsageRatio / (bufferUsageRatio + 1);
}
@Override
public void afterPartialDecode(ByteBuf buffer) {
discardReadBytesIfNecessary(buffer);
}
@Override
public void afterDecoding(ByteBuf buffer) {
discardReadBytesIfNecessary(buffer);
}
@Override
public void afterCommandDecoded(ByteBuf buffer) {
discardReadBytesIfNecessary(buffer);
}
private void discardReadBytesIfNecessary(ByteBuf buffer) {<FILL_FUNCTION_BODY>}
}
|
float usedRatio = (float) buffer.readerIndex() / buffer.capacity();
if (usedRatio >= discardReadBytesRatio) {
buffer.discardReadBytes();
}
| 347
| 54
| 401
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/protocol/ReconnectionHandler.java
|
ReconnectionHandler
|
reconnect0
|
class ReconnectionHandler {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(ReconnectionHandler.class);
private static final Set<Class<?>> EXECUTION_EXCEPTION_TYPES = LettuceSets.unmodifiableSet(TimeoutException.class,
CancellationException.class, RedisCommandTimeoutException.class, ConnectException.class);
private final ClientOptions clientOptions;
private final Bootstrap bootstrap;
private final Mono<SocketAddress> socketAddressSupplier;
private final ConnectionFacade connectionFacade;
private volatile CompletableFuture<Channel> currentFuture;
private volatile boolean reconnectSuspended;
ReconnectionHandler(ClientOptions clientOptions, Bootstrap bootstrap, Mono<SocketAddress> socketAddressSupplier,
Timer timer, ExecutorService reconnectWorkers, ConnectionFacade connectionFacade) {
LettuceAssert.notNull(socketAddressSupplier, "SocketAddressSupplier must not be null");
LettuceAssert.notNull(bootstrap, "Bootstrap must not be null");
LettuceAssert.notNull(timer, "Timer must not be null");
LettuceAssert.notNull(reconnectWorkers, "ExecutorService must not be null");
LettuceAssert.notNull(connectionFacade, "ConnectionFacade must not be null");
this.socketAddressSupplier = socketAddressSupplier;
this.bootstrap = bootstrap;
this.clientOptions = clientOptions;
this.connectionFacade = connectionFacade;
}
/**
* Initiate reconnect and return a {@link ChannelFuture} for synchronization. The resulting future either succeeds or fails.
* It can be {@link ChannelFuture#cancel(boolean) canceled} to interrupt reconnection and channel initialization. A failed
* {@link ChannelFuture} will close the channel.
*
* @return reconnect {@link ChannelFuture}.
*/
protected Tuple2<CompletableFuture<Channel>, CompletableFuture<SocketAddress>> reconnect() {
CompletableFuture<Channel> future = new CompletableFuture<>();
CompletableFuture<SocketAddress> address = new CompletableFuture<>();
socketAddressSupplier.subscribe(remoteAddress -> {
address.complete(remoteAddress);
if (future.isCancelled()) {
return;
}
reconnect0(future, remoteAddress);
}, ex -> {
if (!address.isDone()) {
address.completeExceptionally(ex);
}
future.completeExceptionally(ex);
});
this.currentFuture = future;
return Tuples.of(future, address);
}
private void reconnect0(CompletableFuture<Channel> result, SocketAddress remoteAddress) {<FILL_FUNCTION_BODY>}
boolean isReconnectSuspended() {
return reconnectSuspended;
}
void setReconnectSuspended(boolean reconnectSuspended) {
this.reconnectSuspended = reconnectSuspended;
}
void prepareClose() {
CompletableFuture<?> currentFuture = this.currentFuture;
if (currentFuture != null && !currentFuture.isDone()) {
currentFuture.cancel(true);
}
}
/**
* @param throwable
* @return {@code true} if {@code throwable} is an execution {@link Exception}.
*/
public static boolean isExecutionException(Throwable throwable) {
for (Class<?> type : EXECUTION_EXCEPTION_TYPES) {
if (type.isAssignableFrom(throwable.getClass())) {
return true;
}
}
return false;
}
ClientOptions getClientOptions() {
return clientOptions;
}
}
|
ChannelHandler handler = bootstrap.config().handler();
// reinitialize SslChannelInitializer if Redis - SSL connection.
if (SslConnectionBuilder.isSslChannelInitializer(handler)) {
bootstrap.handler(SslConnectionBuilder.withSocketAddress(handler, remoteAddress));
}
ChannelFuture connectFuture = bootstrap.connect(remoteAddress);
logger.debug("Reconnecting to Redis at {}", remoteAddress);
result.whenComplete((c, t) -> {
if (t instanceof CancellationException) {
connectFuture.cancel(true);
}
});
connectFuture.addListener(future -> {
if (!future.isSuccess()) {
result.completeExceptionally(future.cause());
return;
}
RedisHandshakeHandler handshakeHandler = connectFuture.channel().pipeline().get(RedisHandshakeHandler.class);
if (handshakeHandler == null) {
result.completeExceptionally(new IllegalStateException("RedisHandshakeHandler not registered"));
return;
}
handshakeHandler.channelInitialized().whenComplete((success, throwable) -> {
if (throwable != null) {
if (isExecutionException(throwable)) {
result.completeExceptionally(throwable);
return;
}
if (clientOptions.isCancelCommandsOnReconnectFailure()) {
connectionFacade.reset();
}
if (clientOptions.isSuspendReconnectOnProtocolFailure()) {
logger.error("Disabling autoReconnect due to initialization failure", throwable);
setReconnectSuspended(true);
}
result.completeExceptionally(throwable);
return;
}
if (logger.isDebugEnabled()) {
logger.info("Reconnected to {}, Channel {}", remoteAddress,
ChannelLogDescriptor.logDescriptor(connectFuture.channel()));
} else {
logger.info("Reconnected to {}", remoteAddress);
}
result.complete(connectFuture.channel());
});
});
| 945
| 524
| 1,469
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/protocol/RedisHandshakeHandler.java
|
RedisHandshakeHandler
|
channelActive
|
class RedisHandshakeHandler extends ChannelInboundHandlerAdapter {
private final ConnectionInitializer connectionInitializer;
private final ClientResources clientResources;
private final Duration initializeTimeout;
private final CompletableFuture<Void> handshakeFuture = new CompletableFuture<>();
private volatile boolean timedOut = false;
public RedisHandshakeHandler(ConnectionInitializer connectionInitializer, ClientResources clientResources,
Duration initializeTimeout) {
this.connectionInitializer = connectionInitializer;
this.clientResources = clientResources;
this.initializeTimeout = initializeTimeout;
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
Runnable timeoutGuard = () -> {
timedOut = true;
if (handshakeFuture.isDone()) {
return;
}
fail(ctx, new RedisCommandTimeoutException(
"Connection initialization timed out after " + ExceptionFactory.formatTimeout(initializeTimeout)));
};
Timeout timeoutHandle = clientResources.timer().newTimeout(t -> {
if (clientResources.eventExecutorGroup().isShuttingDown()) {
timeoutGuard.run();
return;
}
clientResources.eventExecutorGroup().submit(timeoutGuard);
}, initializeTimeout.toNanos(), TimeUnit.NANOSECONDS);
handshakeFuture.thenAccept(ignore -> {
timeoutHandle.cancel();
});
super.channelRegistered(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
if (shouldFail()) {
fail(ctx, new RedisConnectionException("Connection closed prematurely"));
}
super.channelInactive(ctx);
}
@Override
public void channelActive(ChannelHandlerContext ctx) {<FILL_FUNCTION_BODY>}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (shouldFail()) {
fail(ctx, cause);
}
super.exceptionCaught(ctx, cause);
}
/**
* Complete the handshake future successfully.
*/
protected void succeed() {
handshakeFuture.complete(null);
}
/**
* Complete the handshake future with an error and close the channel..
*/
protected void fail(ChannelHandlerContext ctx, Throwable cause) {
ctx.close().addListener(closeFuture -> {
handshakeFuture.completeExceptionally(cause);
});
}
/**
* @return future to synchronize channel initialization. Returns a new future for every reconnect.
*/
public CompletionStage<Void> channelInitialized() {
return handshakeFuture;
}
private boolean shouldFail() {
return !handshakeFuture.isDone() && !timedOut;
}
}
|
CompletionStage<Void> future = connectionInitializer.initialize(ctx.channel());
future.whenComplete((ignore, throwable) -> {
if (throwable != null) {
if (shouldFail()) {
fail(ctx, throwable);
}
} else {
ctx.fireChannelActive();
succeed();
}
});
| 740
| 99
| 839
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/protocol/SharedLock.java
|
SharedLock
|
incrementWriters
|
class SharedLock {
private static final AtomicLongFieldUpdater<SharedLock> WRITERS = AtomicLongFieldUpdater.newUpdater(SharedLock.class,
"writers");
private final Lock lock = new ReentrantLock();
private volatile long writers = 0;
private volatile Thread exclusiveLockOwner;
/**
* Wait for stateLock and increment writers. Will wait if stateLock is locked and if writer counter is negative.
*/
void incrementWriters() {<FILL_FUNCTION_BODY>}
/**
* Decrement writers without any wait.
*/
void decrementWriters() {
if (exclusiveLockOwner == Thread.currentThread()) {
return;
}
WRITERS.decrementAndGet(this);
}
/**
* Execute a {@link Runnable} guarded by an exclusive lock.
*
* @param runnable the runnable, must not be {@code null}.
*/
void doExclusive(Runnable runnable) {
LettuceAssert.notNull(runnable, "Runnable must not be null");
doExclusive(() -> {
runnable.run();
return null;
});
}
/**
* Retrieve a value produced by a {@link Supplier} guarded by an exclusive lock.
*
* @param supplier the {@link Supplier}, must not be {@code null}.
* @param <T> the return type
* @return the return value
*/
<T> T doExclusive(Supplier<T> supplier) {
LettuceAssert.notNull(supplier, "Supplier must not be null");
lock.lock();
try {
try {
lockWritersExclusive();
return supplier.get();
} finally {
unlockWritersExclusive();
}
} finally {
lock.unlock();
}
}
/**
* Wait for stateLock and no writers. Must be used in an outer {@code synchronized} block to prevent interleaving with other
* methods using writers. Sets writers to a negative value to create a lock for {@link #incrementWriters()}.
*/
private void lockWritersExclusive() {
if (exclusiveLockOwner == Thread.currentThread()) {
WRITERS.decrementAndGet(this);
return;
}
lock.lock();
try {
for (;;) {
if (WRITERS.compareAndSet(this, 0, -1)) {
exclusiveLockOwner = Thread.currentThread();
return;
}
}
} finally {
lock.unlock();
}
}
/**
* Unlock writers.
*/
private void unlockWritersExclusive() {
if (exclusiveLockOwner == Thread.currentThread()) {
if (WRITERS.incrementAndGet(this) == 0) {
exclusiveLockOwner = null;
}
}
}
}
|
if (exclusiveLockOwner == Thread.currentThread()) {
return;
}
lock.lock();
try {
for (;;) {
if (WRITERS.get(this) >= 0) {
WRITERS.incrementAndGet(this);
return;
}
}
} finally {
lock.unlock();
}
| 772
| 97
| 869
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/protocol/TracedCommand.java
|
TracedCommand
|
encode
|
class TracedCommand<K, V, T> extends CommandWrapper<K, V, T> implements TraceContextProvider {
private final TraceContext traceContext;
private Tracer.Span span;
public TracedCommand(RedisCommand<K, V, T> command, TraceContext traceContext) {
super(command);
this.traceContext = traceContext;
}
@Override
public TraceContext getTraceContext() {
return traceContext;
}
public Tracer.Span getSpan() {
return span;
}
public void setSpan(Tracer.Span span) {
this.span = span;
}
@Override
public void encode(ByteBuf buf) {<FILL_FUNCTION_BODY>}
}
|
if (span != null) {
span.annotate("redis.encode.start");
}
super.encode(buf);
if (span != null) {
span.annotate("redis.encode.end");
}
| 197
| 69
| 266
|
<methods>public void <init>(RedisCommand<K,V,T>) ,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 CommandOutput<K,V,T> getOutput() ,public io.lettuce.core.protocol.ProtocolKeyword getType() ,public int hashCode() ,public boolean isCancelled() ,public boolean isDone() ,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() ,public static RedisCommand<K,V,T> unwrap(RedisCommand<K,V,T>) ,public static R unwrap(RedisCommand<K,V,T>, Class<R>) <variables>private static final java.lang.Object[] COMPLETE,private static final java.lang.Object[] EMPTY,private static final AtomicReferenceFieldUpdater<CommandWrapper#RAW,java.lang.Object[]> ONCOMPLETE,protected final non-sealed RedisCommand<K,V,T> command,private volatile java.lang.Object[] onComplete
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/pubsub/PubSubCommandBuilder.java
|
PubSubCommandBuilder
|
pubsubShardNumsub
|
class PubSubCommandBuilder<K, V> extends BaseRedisCommandBuilder<K, V> {
static final String MUST_NOT_BE_EMPTY = "must not be empty";
PubSubCommandBuilder(RedisCodec<K, V> codec) {
super(codec);
}
Command<K, V, Long> publish(K channel, V message) {
CommandArgs<K, V> args = new PubSubCommandArgs<>(codec).addKey(channel).addValue(message);
return createCommand(PUBLISH, new IntegerOutput<>(codec), args);
}
Command<K, V, List<K>> pubsubChannels(K pattern) {
CommandArgs<K, V> args = new PubSubCommandArgs<>(codec).add(CHANNELS).addKey(pattern);
return createCommand(PUBSUB, new KeyListOutput<>(codec), args);
}
@SafeVarargs
@SuppressWarnings({ "unchecked", "rawtypes" })
final Command<K, V, Map<K, Long>> pubsubNumsub(K... channels) {
LettuceAssert.notEmpty(channels, "Channels " + MUST_NOT_BE_EMPTY);
CommandArgs<K, V> args = new PubSubCommandArgs<>(codec).add(NUMSUB).addKeys(channels);
return createCommand(PUBSUB, new MapOutput<>((RedisCodec) codec), args);
}
Command<K, V, List<K>> pubsubShardChannels(K pattern) {
CommandArgs<K, V> args = new PubSubCommandArgs<>(codec).add(SHARDCHANNELS).addKey(pattern);
return createCommand(PUBSUB, new KeyListOutput<>(codec), args);
}
@SafeVarargs
@SuppressWarnings({ "unchecked", "rawtypes" })
final Command<K, V, Map<K, Long>> pubsubShardNumsub(K... shardChannels) {<FILL_FUNCTION_BODY>}
@SafeVarargs
final Command<K, V, V> psubscribe(K... patterns) {
LettuceAssert.notEmpty(patterns, "Patterns " + MUST_NOT_BE_EMPTY);
return pubSubCommand(PSUBSCRIBE, new PubSubOutput<>(codec), patterns);
}
@SafeVarargs
final Command<K, V, V> punsubscribe(K... patterns) {
return pubSubCommand(PUNSUBSCRIBE, new PubSubOutput<>(codec), patterns);
}
@SafeVarargs
final Command<K, V, V> subscribe(K... channels) {
LettuceAssert.notEmpty(channels, "Channels " + MUST_NOT_BE_EMPTY);
return pubSubCommand(SUBSCRIBE, new PubSubOutput<>(codec), channels);
}
@SafeVarargs
final Command<K, V, V> unsubscribe(K... channels) {
return pubSubCommand(UNSUBSCRIBE, new PubSubOutput<>(codec), channels);
}
@SafeVarargs
final Command<K, V, V> ssubscribe(K... shardChannels) {
LettuceAssert.notEmpty(shardChannels, "Shard channels " + MUST_NOT_BE_EMPTY);
CommandArgs<K, V> args = new CommandArgs<>(codec).addKeys(shardChannels);
return createCommand(SSUBSCRIBE, new PubSubOutput<>(codec), args);
}
@SafeVarargs
final <T> Command<K, V, T> pubSubCommand(CommandType type, CommandOutput<K, V, T> output, K... keys) {
return new Command<>(type, output, new PubSubCommandArgs<>(codec).addKeys(keys));
}
}
|
LettuceAssert.notEmpty(shardChannels, "Shard channels " + MUST_NOT_BE_EMPTY);
CommandArgs<K, V> args = new PubSubCommandArgs<>(codec).add(SHARDNUMSUB).addKeys(shardChannels);
return createCommand(PUBSUB, new MapOutput<>((RedisCodec) codec), args);
| 972
| 98
| 1,070
|
<methods>public void <init>(RedisCodec<K,V>) <variables>protected final non-sealed RedisCodec<K,V> codec
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/pubsub/PubSubOutput.java
|
PubSubOutput
|
handleOutput
|
class PubSubOutput<K, V> extends CommandOutput<K, V, V> implements PubSubMessage<K, V> {
public enum Type {
message, pmessage, psubscribe, punsubscribe, subscribe, unsubscribe, ssubscribe;
private final static Set<String> names = new HashSet<>();
static {
for (Type value : Type.values()) {
names.add(value.name());
}
}
public static boolean isPubSubType(String name) {
return names.contains(name);
}
}
private Type type;
private K channel;
private K pattern;
private long count;
private boolean completed;
public PubSubOutput(RedisCodec<K, V> codec) {
super(codec, null);
}
public Type type() {
return type;
}
public K channel() {
return channel;
}
public K pattern() {
return pattern;
}
public long count() {
return count;
}
@Override
@SuppressWarnings({ "fallthrough", "unchecked" })
public void set(ByteBuffer bytes) {
if (bytes == null) {
return;
}
if (type == null) {
type = Type.valueOf(decodeAscii(bytes));
return;
}
handleOutput(bytes);
}
@SuppressWarnings("unchecked")
private void handleOutput(ByteBuffer bytes) {<FILL_FUNCTION_BODY>}
@Override
public void set(long integer) {
count = integer;
// count comes last in (p)(un)subscribe ack.
completed = true;
}
boolean isCompleted() {
return completed;
}
@Override
public V body() {
return output;
}
}
|
switch (type) {
case pmessage:
if (pattern == null) {
pattern = codec.decodeKey(bytes);
break;
}
case message:
if (channel == null) {
channel = codec.decodeKey(bytes);
break;
}
output = codec.decodeValue(bytes);
completed = true;
break;
case psubscribe:
case punsubscribe:
pattern = codec.decodeKey(bytes);
break;
case subscribe:
case unsubscribe:
case ssubscribe:
channel = codec.decodeKey(bytes);
break;
default:
throw new UnsupportedOperationException("Operation " + type + " not supported");
}
| 489
| 185
| 674
|
<methods>public void <init>(RedisCodec<K,V>, V) ,public void complete(int) ,public V get() ,public java.lang.String getError() ,public boolean hasError() ,public void multi(int) ,public void multiArray(int) ,public void multiMap(int) ,public void multiPush(int) ,public void multiSet(int) ,public void set(java.nio.ByteBuffer) ,public void set(long) ,public void set(double) ,public void set(boolean) ,public void setBigNumber(java.nio.ByteBuffer) ,public void setError(java.nio.ByteBuffer) ,public void setError(java.lang.String) ,public void setSingle(java.nio.ByteBuffer) ,public java.lang.String toString() <variables>protected final non-sealed RedisCodec<K,V> codec,protected java.lang.String error,protected V output
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/pubsub/RedisPubSubReactiveCommandsImpl.java
|
RedisPubSubReactiveCommandsImpl
|
observeChannels
|
class RedisPubSubReactiveCommandsImpl<K, V> extends RedisReactiveCommandsImpl<K, V>
implements RedisPubSubReactiveCommands<K, V> {
private final PubSubCommandBuilder<K, V> commandBuilder;
/**
* Initialize a new connection.
*
* @param connection the connection .
* @param codec Codec used to encode/decode keys and values.
*/
public RedisPubSubReactiveCommandsImpl(StatefulRedisPubSubConnection<K, V> connection, RedisCodec<K, V> codec) {
super(connection, codec);
this.commandBuilder = new PubSubCommandBuilder<>(codec);
}
@Override
public Flux<PatternMessage<K, V>> observePatterns() {
return observePatterns(FluxSink.OverflowStrategy.BUFFER);
}
@Override
public Flux<PatternMessage<K, V>> observePatterns(FluxSink.OverflowStrategy overflowStrategy) {
return Flux.create(sink -> {
RedisPubSubAdapter<K, V> listener = new RedisPubSubAdapter<K, V>() {
@Override
public void message(K pattern, K channel, V message) {
sink.next(new PatternMessage<>(pattern, channel, message));
}
};
StatefulRedisPubSubConnection<K, V> statefulConnection = getStatefulConnection();
statefulConnection.addListener(listener);
sink.onDispose(() -> {
statefulConnection.removeListener(listener);
});
}, overflowStrategy);
}
@Override
public Flux<ChannelMessage<K, V>> observeChannels() {
return observeChannels(FluxSink.OverflowStrategy.BUFFER);
}
@Override
public Flux<ChannelMessage<K, V>> observeChannels(FluxSink.OverflowStrategy overflowStrategy) {<FILL_FUNCTION_BODY>}
@Override
public Mono<Void> psubscribe(K... patterns) {
return createMono(() -> commandBuilder.psubscribe(patterns)).then();
}
@Override
public Mono<Void> punsubscribe(K... patterns) {
return createFlux(() -> commandBuilder.punsubscribe(patterns)).then();
}
@Override
public Mono<Void> subscribe(K... channels) {
return createFlux(() -> commandBuilder.subscribe(channels)).then();
}
@Override
public Mono<Void> unsubscribe(K... channels) {
return createFlux(() -> commandBuilder.unsubscribe(channels)).then();
}
@Override
public Mono<Long> publish(K channel, V message) {
return createMono(() -> commandBuilder.publish(channel, message));
}
@Override
public Flux<K> pubsubChannels(K channel) {
return createDissolvingFlux(() -> commandBuilder.pubsubChannels(channel));
}
@Override
public Mono<Map<K, Long>> pubsubNumsub(K... channels) {
return createMono(() -> commandBuilder.pubsubNumsub(channels));
}
@Override
public Flux<K> pubsubShardChannels(K channel) {
return createDissolvingFlux(() -> commandBuilder.pubsubShardChannels(channel));
}
@Override
public Mono<Map<K, Long>> pubsubShardNumsub(K... shardChannels) {
return createMono(() -> commandBuilder.pubsubShardNumsub(shardChannels));
}
@Override
public Mono<Void> ssubscribe(K... shardChannels) {
return createFlux(() -> commandBuilder.ssubscribe(shardChannels)).then();
}
@Override
@SuppressWarnings("unchecked")
public StatefulRedisPubSubConnection<K, V> getStatefulConnection() {
return (StatefulRedisPubSubConnection<K, V>) super.getStatefulConnection();
}
}
|
return Flux.create(sink -> {
RedisPubSubAdapter<K, V> listener = new RedisPubSubAdapter<K, V>() {
@Override
public void message(K channel, V message) {
sink.next(new ChannelMessage<>(channel, message));
}
};
StatefulRedisPubSubConnection<K, V> statefulConnection = getStatefulConnection();
statefulConnection.addListener(listener);
sink.onDispose(() -> {
statefulConnection.removeListener(listener);
});
}, overflowStrategy);
| 1,060
| 155
| 1,215
|
<methods>public void <init>(StatefulRedisConnection<K,V>, RedisCodec<K,V>) ,public StatefulRedisConnection<K,V> getStatefulConnection() <variables>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/pubsub/StatefulRedisPubSubConnectionImpl.java
|
StatefulRedisPubSubConnectionImpl
|
resubscribe
|
class StatefulRedisPubSubConnectionImpl<K, V> extends StatefulRedisConnectionImpl<K, V>
implements StatefulRedisPubSubConnection<K, V> {
private final PubSubEndpoint<K, V> endpoint;
/**
* Initialize a new connection.
*
* @param endpoint the {@link PubSubEndpoint}
* @param writer the writer used to write commands
* @param codec Codec used to encode/decode keys and values.
* @param timeout Maximum time to wait for a response.
*/
public StatefulRedisPubSubConnectionImpl(PubSubEndpoint<K, V> endpoint, RedisChannelWriter writer, RedisCodec<K, V> codec,
Duration timeout) {
super(writer, endpoint, codec, timeout);
this.endpoint = endpoint;
endpoint.setConnectionState(getConnectionState());
}
/**
* Add a new listener.
*
* @param listener Listener.
*/
@Override
public void addListener(RedisPubSubListener<K, V> listener) {
endpoint.addListener(listener);
}
/**
* Remove an existing listener.
*
* @param listener Listener.
*/
@Override
public void removeListener(RedisPubSubListener<K, V> listener) {
endpoint.removeListener(listener);
}
@Override
public RedisPubSubAsyncCommands<K, V> async() {
return (RedisPubSubAsyncCommands<K, V>) async;
}
@Override
protected RedisPubSubAsyncCommandsImpl<K, V> newRedisAsyncCommandsImpl() {
return new RedisPubSubAsyncCommandsImpl<>(this, codec);
}
@Override
public RedisPubSubCommands<K, V> sync() {
return (RedisPubSubCommands<K, V>) sync;
}
@Override
protected RedisPubSubCommands<K, V> newRedisSyncCommandsImpl() {
return syncHandler(async(), RedisPubSubCommands.class);
}
@Override
public RedisPubSubReactiveCommands<K, V> reactive() {
return (RedisPubSubReactiveCommands<K, V>) reactive;
}
@Override
protected RedisPubSubReactiveCommandsImpl<K, V> newRedisReactiveCommandsImpl() {
return new RedisPubSubReactiveCommandsImpl<>(this, codec);
}
/**
* Re-subscribe to all previously subscribed channels and patterns.
*
* @return list of the futures of the {@literal subscribe} and {@literal psubscribe} commands.
*/
protected List<RedisFuture<Void>> resubscribe() {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
private <T> T[] toArray(Collection<T> c) {
Class<T> cls = (Class<T>) c.iterator().next().getClass();
T[] array = (T[]) Array.newInstance(cls, c.size());
return c.toArray(array);
}
@Override
public void activated() {
super.activated();
for (RedisFuture<Void> command : resubscribe()) {
command.exceptionally(throwable -> {
if (throwable instanceof RedisCommandExecutionException) {
InternalLoggerFactory.getInstance(getClass()).warn("Re-subscribe failed: " + command.getError());
}
return null;
});
}
}
}
|
List<RedisFuture<Void>> result = new ArrayList<>();
if (endpoint.hasChannelSubscriptions()) {
result.add(async().subscribe(toArray(endpoint.getChannels())));
}
if (endpoint.hasPatternSubscriptions()) {
result.add(async().psubscribe(toArray(endpoint.getPatterns())));
}
return result;
| 917
| 105
| 1,022
|
<methods>public void <init>(io.lettuce.core.RedisChannelWriter, io.lettuce.core.protocol.PushHandler, RedisCodec<K,V>, java.time.Duration) ,public void addListener(io.lettuce.core.api.push.PushListener) ,public RedisAsyncCommands<K,V> async() ,public RedisCommand<K,V,T> dispatch(RedisCommand<K,V,T>) ,public Collection<RedisCommand<K,V,?>> dispatch(Collection<? extends RedisCommand<K,V,?>>) ,public RedisCodec<K,V> getCodec() ,public io.lettuce.core.ConnectionState getConnectionState() ,public boolean isMulti() ,public RedisReactiveCommands<K,V> reactive() ,public void removeListener(io.lettuce.core.api.push.PushListener) ,public void setClientName(java.lang.String) ,public RedisCommands<K,V> sync() <variables>protected final non-sealed RedisAsyncCommandsImpl<K,V> async,protected final non-sealed RedisCodec<K,V> codec,protected MultiOutput<K,V> multi,private final non-sealed io.lettuce.core.protocol.PushHandler pushHandler,protected final non-sealed RedisReactiveCommandsImpl<K,V> reactive,private final io.lettuce.core.ConnectionState state,protected final non-sealed RedisCommands<K,V> sync
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/resource/DecorrelatedJitterDelay.java
|
DecorrelatedJitterDelay
|
createDelay
|
class DecorrelatedJitterDelay extends Delay implements StatefulDelay {
private final Duration lower;
private final Duration upper;
private final long base;
private final TimeUnit targetTimeUnit;
/*
* Delays may be used by different threads, this one is volatile to prevent visibility issues
*/
private volatile long prevDelay;
DecorrelatedJitterDelay(Duration lower, Duration upper, long base, TimeUnit targetTimeUnit) {
this.lower = lower;
this.upper = upper;
this.base = base;
this.targetTimeUnit = targetTimeUnit;
reset();
}
@Override
public Duration createDelay(long attempt) {<FILL_FUNCTION_BODY>}
@Override
public void reset() {
prevDelay = 0L;
}
}
|
long value = randomBetween(base, Math.max(base, prevDelay * 3));
Duration delay = applyBounds(Duration.ofNanos(targetTimeUnit.toNanos(value)), lower, upper);
prevDelay = targetTimeUnit.convert(delay.toNanos(), TimeUnit.NANOSECONDS);
return delay;
| 211
| 90
| 301
|
<methods>public static io.lettuce.core.resource.Delay constant(java.time.Duration) ,public static io.lettuce.core.resource.Delay constant(int, java.util.concurrent.TimeUnit) ,public abstract java.time.Duration createDelay(long) ,public static Supplier<io.lettuce.core.resource.Delay> decorrelatedJitter() ,public static Supplier<io.lettuce.core.resource.Delay> decorrelatedJitter(java.time.Duration, java.time.Duration, long, java.util.concurrent.TimeUnit) ,public static Supplier<io.lettuce.core.resource.Delay> decorrelatedJitter(long, long, long, java.util.concurrent.TimeUnit) ,public static io.lettuce.core.resource.Delay equalJitter() ,public static io.lettuce.core.resource.Delay equalJitter(java.time.Duration, java.time.Duration, long, java.util.concurrent.TimeUnit) ,public static io.lettuce.core.resource.Delay equalJitter(long, long, long, java.util.concurrent.TimeUnit) ,public static io.lettuce.core.resource.Delay exponential() ,public static io.lettuce.core.resource.Delay exponential(java.time.Duration, java.time.Duration, int, java.util.concurrent.TimeUnit) ,public static io.lettuce.core.resource.Delay exponential(long, long, java.util.concurrent.TimeUnit, int) ,public static io.lettuce.core.resource.Delay fullJitter() ,public static io.lettuce.core.resource.Delay fullJitter(java.time.Duration, java.time.Duration, long, java.util.concurrent.TimeUnit) ,public static io.lettuce.core.resource.Delay fullJitter(long, long, long, java.util.concurrent.TimeUnit) <variables>private static java.time.Duration DEFAULT_LOWER_BOUND,private static int DEFAULT_POWER_OF,private static java.util.concurrent.TimeUnit DEFAULT_TIMEUNIT,private static java.time.Duration DEFAULT_UPPER_BOUND
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/resource/DirContextDnsResolver.java
|
StackPreference
|
textToNumericFormatV6
|
class StackPreference {
final boolean preferIpv4;
final boolean preferIpv6;
public StackPreference() {
boolean preferIpv4 = false;
boolean preferIpv6 = false;
if (System.getProperty(PREFER_IPV4_KEY) == null && System.getProperty(PREFER_IPV6_KEY) == null) {
preferIpv4 = false;
preferIpv6 = false;
}
if (System.getProperty(PREFER_IPV4_KEY) == null && System.getProperty(PREFER_IPV6_KEY) != null) {
preferIpv6 = Boolean.getBoolean(PREFER_IPV6_KEY);
if (!preferIpv6) {
preferIpv4 = true;
}
}
if (System.getProperty(PREFER_IPV4_KEY) != null && System.getProperty(PREFER_IPV6_KEY) == null) {
preferIpv4 = Boolean.getBoolean(PREFER_IPV4_KEY);
if (!preferIpv4) {
preferIpv6 = true;
}
}
if (System.getProperty(PREFER_IPV4_KEY) != null && System.getProperty(PREFER_IPV6_KEY) != null) {
preferIpv4 = Boolean.getBoolean(PREFER_IPV4_KEY);
preferIpv6 = Boolean.getBoolean(PREFER_IPV6_KEY);
}
this.preferIpv4 = preferIpv4;
this.preferIpv6 = preferIpv6;
}
}
private static byte[] ipStringToBytes(String ipString) {
// Make a first pass to categorize the characters in this string.
boolean hasColon = false;
boolean hasDot = false;
for (int i = 0; i < ipString.length(); i++) {
char c = ipString.charAt(i);
if (c == '.') {
hasDot = true;
} else if (c == ':') {
if (hasDot) {
return null; // Colons must not appear after dots.
}
hasColon = true;
} else if (Character.digit(c, 16) == -1) {
return null; // Everything else must be a decimal or hex digit.
}
}
// Now decide which address family to parse.
if (hasColon) {
if (hasDot) {
ipString = convertDottedQuadToHex(ipString);
if (ipString == null) {
return null;
}
}
return textToNumericFormatV6(ipString);
} else if (hasDot) {
return textToNumericFormatV4(ipString);
}
return null;
}
private static byte[] textToNumericFormatV4(String ipString) {
byte[] bytes = new byte[IPV4_PART_COUNT];
int i = 0;
try {
for (String octet : ipString.split("\\.", IPV4_PART_COUNT)) {
bytes[i++] = parseOctet(octet);
}
} catch (NumberFormatException ex) {
return null;
}
return i == IPV4_PART_COUNT ? bytes : null;
}
private static byte[] textToNumericFormatV6(String ipString) {<FILL_FUNCTION_BODY>
|
// An address can have [2..8] colons, and N colons make N+1 parts.
String[] parts = ipString.split(":", IPV6_PART_COUNT + 2);
if (parts.length < 3 || parts.length > IPV6_PART_COUNT + 1) {
return null;
}
// Disregarding the endpoints, find "::" with nothing in between.
// This indicates that a run of zeroes has been skipped.
int skipIndex = -1;
for (int i = 1; i < parts.length - 1; i++) {
if (parts[i].length() == 0) {
if (skipIndex >= 0) {
return null; // Can't have more than one ::
}
skipIndex = i;
}
}
int partsHi; // Number of parts to copy from above/before the "::"
int partsLo; // Number of parts to copy from below/after the "::"
if (skipIndex >= 0) {
// If we found a "::", then check if it also covers the endpoints.
partsHi = skipIndex;
partsLo = parts.length - skipIndex - 1;
if (parts[0].length() == 0 && --partsHi != 0) {
return null; // ^: requires ^::
}
if (parts[parts.length - 1].length() == 0 && --partsLo != 0) {
return null; // :$ requires ::$
}
} else {
// Otherwise, allocate the entire address to partsHi. The endpoints
// could still be empty, but parseHextet() will check for that.
partsHi = parts.length;
partsLo = 0;
}
// If we found a ::, then we must have skipped at least one part.
// Otherwise, we must have exactly the right number of parts.
int partsSkipped = IPV6_PART_COUNT - (partsHi + partsLo);
if (!(skipIndex >= 0 ? partsSkipped >= 1 : partsSkipped == 0)) {
return null;
}
// Now parse the hextets into a byte array.
ByteBuffer rawBytes = ByteBuffer.allocate(2 * IPV6_PART_COUNT);
try {
for (int i = 0; i < partsHi; i++) {
rawBytes.putShort(parseHextet(parts[i]));
}
for (int i = 0; i < partsSkipped; i++) {
rawBytes.putShort((short) 0);
}
for (int i = partsLo; i > 0; i--) {
rawBytes.putShort(parseHextet(parts[parts.length - i]));
}
} catch (NumberFormatException ex) {
return null;
}
return rawBytes.array();
| 920
| 709
| 1,629
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/resource/EpollProvider.java
|
EpollProvider
|
checkForEpollLibrary
|
class EpollProvider {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(EpollProvider.class);
private static final String EPOLL_ENABLED_KEY = "io.lettuce.core.epoll";
private static final boolean EPOLL_ENABLED = Boolean.parseBoolean(SystemPropertyUtil.get(EPOLL_ENABLED_KEY, "true"));
private static final boolean EPOLL_AVAILABLE;
private static final EventLoopResources EPOLL_RESOURCES;
static {
boolean availability;
try {
Class.forName("io.netty.channel.epoll.Epoll");
availability = Epoll.isAvailable();
} catch (ClassNotFoundException e) {
availability = false;
}
EPOLL_AVAILABLE = availability;
if (EPOLL_AVAILABLE) {
logger.debug("Starting with epoll library");
EPOLL_RESOURCES = new EventLoopResourcesWrapper(EpollResources.INSTANCE, EpollProvider::checkForEpollLibrary);
} else {
logger.debug("Starting without optional epoll library");
EPOLL_RESOURCES = new EventLoopResourcesWrapper(UnavailableResources.INSTANCE, EpollProvider::checkForEpollLibrary);
}
}
/**
* @return {@code true} if epoll is available.
*/
public static boolean isAvailable() {
return EPOLL_AVAILABLE && EPOLL_ENABLED;
}
/**
* Check whether the Epoll library is available on the class path.
*
* @throws IllegalStateException if the {@literal netty-transport-native-epoll} library is not available
*/
static void checkForEpollLibrary() {<FILL_FUNCTION_BODY>}
/**
* Returns the {@link EventLoopResources} for epoll-backed transport. Check availability with {@link #isAvailable()} prior
* to obtaining the resources.
*
* @return the {@link EventLoopResources}. May be unavailable.
*
* @since 6.0
*/
public static EventLoopResources getResources() {
return EPOLL_RESOURCES;
}
/**
* Apply Keep-Alive options.
*
* @since 6.1
*/
public static void applyKeepAlive(Bootstrap bootstrap, int count, Duration idle, Duration interval) {
bootstrap.option(EpollChannelOption.TCP_KEEPCNT, count);
bootstrap.option(EpollChannelOption.TCP_KEEPIDLE, Math.toIntExact(idle.getSeconds()));
bootstrap.option(EpollChannelOption.TCP_KEEPINTVL, Math.toIntExact(interval.getSeconds()));
}
/**
* Apply TcpUserTimeout options.
*/
public static void applyTcpUserTimeout(Bootstrap bootstrap, Duration timeout) {
bootstrap.option(EpollChannelOption.TCP_USER_TIMEOUT, Math.toIntExact(timeout.toMillis()));
}
/**
* {@link EventLoopResources} for available Epoll.
*/
enum EpollResources implements EventLoopResources {
INSTANCE;
@Override
public boolean matches(Class<? extends EventExecutorGroup> type) {
LettuceAssert.notNull(type, "EventLoopGroup type must not be null");
return type.equals(EpollEventLoopGroup.class);
}
@Override
public Class<? extends EventLoopGroup> eventLoopGroupClass() {
return EpollEventLoopGroup.class;
}
@Override
public EventLoopGroup newEventLoopGroup(int nThreads, ThreadFactory threadFactory) {
return new EpollEventLoopGroup(nThreads, threadFactory);
}
@Override
public Class<? extends Channel> socketChannelClass() {
return EpollSocketChannel.class;
}
@Override
public Class<? extends Channel> domainSocketChannelClass() {
return EpollDomainSocketChannel.class;
}
@Override
public Class<? extends DatagramChannel> datagramChannelClass() {
return EpollDatagramChannel.class;
}
@Override
public SocketAddress newSocketAddress(String socketPath) {
return new DomainSocketAddress(socketPath);
}
}
}
|
LettuceAssert.assertState(EPOLL_ENABLED,
String.format("epoll use is disabled via System properties (%s)", EPOLL_ENABLED_KEY));
LettuceAssert.assertState(isAvailable(),
"netty-transport-native-epoll is not available. Make sure netty-transport-native-epoll library on the class path and supported by your operating system.");
| 1,115
| 100
| 1,215
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/resource/EqualJitterDelay.java
|
EqualJitterDelay
|
createDelay
|
class EqualJitterDelay extends ExponentialDelay {
private final long base;
private final TimeUnit targetTimeUnit;
EqualJitterDelay(Duration lower, Duration upper, long base, TimeUnit targetTimeUnit) {
super(lower, upper, 2, targetTimeUnit);
this.base = base;
this.targetTimeUnit = targetTimeUnit;
}
@Override
public Duration createDelay(long attempt) {<FILL_FUNCTION_BODY>}
}
|
long value = randomBetween(0, base * calculatePowerOfTwo(attempt));
return applyBounds(Duration.ofNanos(targetTimeUnit.toNanos(value)));
| 127
| 48
| 175
|
<methods>public java.time.Duration createDelay(long) <variables>private final non-sealed java.time.Duration lower,private final non-sealed int powersOf,private final non-sealed java.util.concurrent.TimeUnit targetTimeUnit,private final non-sealed java.time.Duration upper
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/resource/ExponentialDelay.java
|
ExponentialDelay
|
calculateAlternatePower
|
class ExponentialDelay extends Delay {
private final Duration lower;
private final Duration upper;
private final int powersOf;
private final TimeUnit targetTimeUnit;
ExponentialDelay(Duration lower, Duration upper, int powersOf, TimeUnit targetTimeUnit) {
this.lower = lower;
this.upper = upper;
this.powersOf = powersOf;
this.targetTimeUnit = targetTimeUnit;
}
@Override
public Duration createDelay(long attempt) {
long delay;
if (attempt <= 0) { // safeguard against underflow
delay = 0;
} else if (powersOf == 2) {
delay = calculatePowerOfTwo(attempt);
} else {
delay = calculateAlternatePower(attempt);
}
return applyBounds(Duration.ofNanos(targetTimeUnit.toNanos(delay)));
}
/**
* Apply bounds to the given {@code delay}.
*
* @param delay the delay
* @return the delay normalized to its lower and upper bounds.
*/
protected Duration applyBounds(Duration delay) {
return applyBounds(delay, lower, upper);
}
private long calculateAlternatePower(long attempt) {<FILL_FUNCTION_BODY>}
// fastpath with bitwise operator
protected static long calculatePowerOfTwo(long attempt) {
if (attempt <= 0) { // safeguard against underflow
return 0L;
} else if (attempt >= 63) { // safeguard against overflow in the bitshift operation
return Long.MAX_VALUE - 1;
} else {
return 1L << (attempt - 1);
}
}
}
|
// round will cap at Long.MAX_VALUE and pow should prevent overflows
double step = Math.pow(powersOf, attempt - 1); // attempt > 0
return Math.round(step);
| 445
| 53
| 498
|
<methods>public static io.lettuce.core.resource.Delay constant(java.time.Duration) ,public static io.lettuce.core.resource.Delay constant(int, java.util.concurrent.TimeUnit) ,public abstract java.time.Duration createDelay(long) ,public static Supplier<io.lettuce.core.resource.Delay> decorrelatedJitter() ,public static Supplier<io.lettuce.core.resource.Delay> decorrelatedJitter(java.time.Duration, java.time.Duration, long, java.util.concurrent.TimeUnit) ,public static Supplier<io.lettuce.core.resource.Delay> decorrelatedJitter(long, long, long, java.util.concurrent.TimeUnit) ,public static io.lettuce.core.resource.Delay equalJitter() ,public static io.lettuce.core.resource.Delay equalJitter(java.time.Duration, java.time.Duration, long, java.util.concurrent.TimeUnit) ,public static io.lettuce.core.resource.Delay equalJitter(long, long, long, java.util.concurrent.TimeUnit) ,public static io.lettuce.core.resource.Delay exponential() ,public static io.lettuce.core.resource.Delay exponential(java.time.Duration, java.time.Duration, int, java.util.concurrent.TimeUnit) ,public static io.lettuce.core.resource.Delay exponential(long, long, java.util.concurrent.TimeUnit, int) ,public static io.lettuce.core.resource.Delay fullJitter() ,public static io.lettuce.core.resource.Delay fullJitter(java.time.Duration, java.time.Duration, long, java.util.concurrent.TimeUnit) ,public static io.lettuce.core.resource.Delay fullJitter(long, long, long, java.util.concurrent.TimeUnit) <variables>private static java.time.Duration DEFAULT_LOWER_BOUND,private static int DEFAULT_POWER_OF,private static java.util.concurrent.TimeUnit DEFAULT_TIMEUNIT,private static java.time.Duration DEFAULT_UPPER_BOUND
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/resource/FullJitterDelay.java
|
FullJitterDelay
|
createDelay
|
class FullJitterDelay extends ExponentialDelay {
private final Duration upper;
private final long base;
private final TimeUnit targetTimeUnit;
FullJitterDelay(Duration lower, Duration upper, long base, TimeUnit targetTimeUnit) {
super(lower, upper, 2, targetTimeUnit);
this.upper = upper;
this.base = base;
this.targetTimeUnit = targetTimeUnit;
}
@Override
public Duration createDelay(long attempt) {<FILL_FUNCTION_BODY>}
}
|
long upperTarget = targetTimeUnit.convert(upper.toNanos(), TimeUnit.NANOSECONDS);
long upperBase = base * calculatePowerOfTwo(attempt);
long temp = Math.min(upperTarget, 0 > upperBase ? upperTarget : upperBase);
long delay = temp / 2 + randomBetween(0, temp / 2);
return applyBounds(Duration.ofNanos(targetTimeUnit.toNanos(delay)));
| 142
| 118
| 260
|
<methods>public java.time.Duration createDelay(long) <variables>private final non-sealed java.time.Duration lower,private final non-sealed int powersOf,private final non-sealed java.util.concurrent.TimeUnit targetTimeUnit,private final non-sealed java.time.Duration upper
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/resource/IOUringProvider.java
|
IOUringProvider
|
matches
|
class IOUringProvider {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(IOUringProvider.class);
private static final String IOURING_ENABLED_KEY = "io.lettuce.core.iouring";
private static final boolean IOURING_ENABLED = Boolean.parseBoolean(SystemPropertyUtil.get(IOURING_ENABLED_KEY, "true"));
private static final boolean IOURING_AVAILABLE;
private static final EventLoopResources IOURING_RESOURCES;
static {
boolean availability;
try {
Class.forName("io.netty.incubator.channel.uring.IOUring");
availability = IOUring.isAvailable();
} catch (ClassNotFoundException e) {
availability = false;
}
IOURING_AVAILABLE = availability;
if (IOURING_AVAILABLE) {
logger.debug("Starting with io_uring library");
IOURING_RESOURCES = new EventLoopResourcesWrapper(IOUringResources.INSTANCE,
IOUringProvider::checkForIOUringLibrary);
} else {
logger.debug("Starting without optional io_uring library");
IOURING_RESOURCES = new EventLoopResourcesWrapper(UnavailableResources.INSTANCE,
IOUringProvider::checkForIOUringLibrary);
}
}
/**
* @return {@code true} if io_uring is available.
*/
public static boolean isAvailable() {
return IOURING_AVAILABLE && IOURING_ENABLED;
}
/**
* Check whether the io_uring library is available on the class path.
*
* @throws IllegalStateException if the {@literal netty-incubator-transport-native-io_uring} library is not available
*/
static void checkForIOUringLibrary() {
LettuceAssert.assertState(IOURING_ENABLED,
String.format("io_uring use is disabled via System properties (%s)", IOURING_ENABLED_KEY));
LettuceAssert.assertState(isAvailable(),
"netty-incubator-transport-native-io_uring is not available. Make sure netty-incubator-transport-native-io_uring library on the class path and supported by your operating system.");
}
/**
* Returns the {@link EventLoopResources} for io_uring-backed transport. Check availability with {@link #isAvailable()}
* prior to obtaining the resources.
*
* @return the {@link EventLoopResources}. May be unavailable.
*/
public static EventLoopResources getResources() {
return IOURING_RESOURCES;
}
/**
* Apply Keep-Alive options.
*
* @since 6.1
*/
public static void applyKeepAlive(Bootstrap bootstrap, int count, Duration idle, Duration interval) {
bootstrap.option(IOUringChannelOption.TCP_KEEPCNT, count);
bootstrap.option(IOUringChannelOption.TCP_KEEPIDLE, Math.toIntExact(idle.getSeconds()));
bootstrap.option(IOUringChannelOption.TCP_KEEPINTVL, Math.toIntExact(interval.getSeconds()));
}
/**
* Apply TcpUserTimeout options.
*/
public static void applyTcpUserTimeout(Bootstrap bootstrap, Duration timeout) {
bootstrap.option(IOUringChannelOption.TCP_USER_TIMEOUT, Math.toIntExact(timeout.toMillis()));
}
/**
* {@link EventLoopResources} for available io_uring.
*/
enum IOUringResources implements EventLoopResources {
INSTANCE;
@Override
public boolean matches(Class<? extends EventExecutorGroup> type) {<FILL_FUNCTION_BODY>}
@Override
public Class<? extends EventLoopGroup> eventLoopGroupClass() {
return IOUringEventLoopGroup.class;
}
@Override
public EventLoopGroup newEventLoopGroup(int nThreads, ThreadFactory threadFactory) {
return new IOUringEventLoopGroup(nThreads, threadFactory);
}
@Override
public Class<? extends Channel> socketChannelClass() {
return IOUringSocketChannel.class;
}
@Override
public Class<? extends Channel> domainSocketChannelClass() {
return IOUringSocketChannel.class;
}
@Override
public Class<? extends DatagramChannel> datagramChannelClass() {
return IOUringDatagramChannel.class;
}
@Override
public SocketAddress newSocketAddress(String socketPath) {
return new DomainSocketAddress(socketPath);
}
}
}
|
LettuceAssert.notNull(type, "EventLoopGroup type must not be null");
return type.equals(eventLoopGroupClass());
| 1,209
| 39
| 1,248
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/resource/KqueueProvider.java
|
KqueueProvider
|
checkForKqueueLibrary
|
class KqueueProvider {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(KqueueProvider.class);
private static final String KQUEUE_ENABLED_KEY = "io.lettuce.core.kqueue";
private static final boolean KQUEUE_ENABLED = Boolean.parseBoolean(SystemPropertyUtil.get(KQUEUE_ENABLED_KEY, "true"));
private static final boolean KQUEUE_AVAILABLE;
private static final EventLoopResources KQUEUE_RESOURCES;
static {
boolean availability;
try {
Class.forName("io.netty.channel.kqueue.KQueue");
availability = KQueue.isAvailable();
} catch (ClassNotFoundException e) {
availability = false;
}
KQUEUE_AVAILABLE = availability;
if (KQUEUE_AVAILABLE) {
logger.debug("Starting with kqueue library");
KQUEUE_RESOURCES = new EventLoopResourcesWrapper(KqueueResources.INSTANCE, KqueueProvider::checkForKqueueLibrary);
} else {
logger.debug("Starting without optional kqueue library");
KQUEUE_RESOURCES = new EventLoopResourcesWrapper(UnavailableResources.INSTANCE,
KqueueProvider::checkForKqueueLibrary);
}
}
/**
* @return {@code true} if kqueue is available.
*/
public static boolean isAvailable() {
return KQUEUE_AVAILABLE && KQUEUE_ENABLED;
}
/**
* Check whether the kqueue library is available on the class path.
*
* @throws IllegalStateException if the {@literal netty-transport-native-kqueue} library is not available
*/
static void checkForKqueueLibrary() {<FILL_FUNCTION_BODY>}
/**
* Returns the {@link EventLoopResources} for kqueue-backed transport. Check availability with {@link #isAvailable()} prior
* to obtaining the resources.
*
* @return the {@link EventLoopResources}. May be unavailable.
*
* @since 6.0
*/
public static EventLoopResources getResources() {
return KQUEUE_RESOURCES;
}
/**
* {@link EventLoopResources} for unavailable Kqueue.
*/
enum UnavailableKqueueResources implements EventLoopResources {
INSTANCE;
@Override
public boolean matches(Class<? extends EventExecutorGroup> type) {
checkForKqueueLibrary();
return false;
}
@Override
public Class<? extends EventLoopGroup> eventLoopGroupClass() {
checkForKqueueLibrary();
return null;
}
@Override
public EventLoopGroup newEventLoopGroup(int nThreads, ThreadFactory threadFactory) {
checkForKqueueLibrary();
return null;
}
@Override
public Class<? extends Channel> socketChannelClass() {
checkForKqueueLibrary();
return null;
}
@Override
public Class<? extends Channel> domainSocketChannelClass() {
checkForKqueueLibrary();
return null;
}
@Override
public SocketAddress newSocketAddress(String socketPath) {
checkForKqueueLibrary();
return null;
}
@Override
public Class<? extends DatagramChannel> datagramChannelClass() {
checkForKqueueLibrary();
return null;
}
}
/**
* {@link EventLoopResources} for available kqueue.
*/
enum KqueueResources implements EventLoopResources {
INSTANCE;
@Override
public boolean matches(Class<? extends EventExecutorGroup> type) {
LettuceAssert.notNull(type, "EventLoopGroup type must not be null");
return type.equals(eventLoopGroupClass());
}
@Override
public Class<? extends EventLoopGroup> eventLoopGroupClass() {
checkForKqueueLibrary();
return KQueueEventLoopGroup.class;
}
@Override
public EventLoopGroup newEventLoopGroup(int nThreads, ThreadFactory threadFactory) {
checkForKqueueLibrary();
return new KQueueEventLoopGroup(nThreads, threadFactory);
}
@Override
public Class<? extends Channel> socketChannelClass() {
checkForKqueueLibrary();
return KQueueSocketChannel.class;
}
@Override
public Class<? extends DatagramChannel> datagramChannelClass() {
checkForKqueueLibrary();
return KQueueDatagramChannel.class;
}
@Override
public Class<? extends Channel> domainSocketChannelClass() {
checkForKqueueLibrary();
return KQueueDomainSocketChannel.class;
}
@Override
public SocketAddress newSocketAddress(String socketPath) {
checkForKqueueLibrary();
return new DomainSocketAddress(socketPath);
}
}
}
|
LettuceAssert.assertState(KQUEUE_ENABLED,
String.format("kqueue use is disabled via System properties (%s)", KQUEUE_ENABLED_KEY));
LettuceAssert.assertState(isAvailable(),
"netty-transport-native-kqueue is not available. Make sure netty-transport-native-kqueue library on the class path and supported by your operating system.");
| 1,269
| 100
| 1,369
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/resource/MappingSocketAddressResolver.java
|
MappingSocketAddressResolver
|
doResolve
|
class MappingSocketAddressResolver extends SocketAddressResolver {
private final Function<HostAndPort, HostAndPort> mappingFunction;
private final DnsResolver dnsResolver;
/**
* Create a new {@link SocketAddressResolver} given {@link Function mapping function}.
*
* @param mappingFunction must not be {@code null}.
* @since 6.1
*/
private MappingSocketAddressResolver(Function<HostAndPort, HostAndPort> mappingFunction) {
this(DnsResolver.unresolved(), mappingFunction);
}
/**
* Create a new {@link SocketAddressResolver} given {@link DnsResolver} and {@link Function mapping function}.
*
* @param dnsResolver must not be {@code null}.
* @param mappingFunction must not be {@code null}.
*/
private MappingSocketAddressResolver(DnsResolver dnsResolver, Function<HostAndPort, HostAndPort> mappingFunction) {
super(dnsResolver);
LettuceAssert.notNull(mappingFunction, "Mapping function must not be null!");
this.dnsResolver = dnsResolver;
this.mappingFunction = mappingFunction;
}
/**
* Create a new {@link SocketAddressResolver} given {@link DnsResolver} and {@link Function mapping function}.
*
* @param mappingFunction must not be {@code null}.
* @return the {@link MappingSocketAddressResolver}.
* @since 6.1
*/
public static MappingSocketAddressResolver create(
Function<HostAndPort, HostAndPort> mappingFunction) {
return new MappingSocketAddressResolver(mappingFunction);
}
/**
* Create a new {@link SocketAddressResolver} given {@link DnsResolver} and {@link Function mapping function}.
*
* @param dnsResolver must not be {@code null}.
* @param mappingFunction must not be {@code null}.
* @return the {@link MappingSocketAddressResolver}.
*/
public static MappingSocketAddressResolver create(DnsResolver dnsResolver,
Function<HostAndPort, HostAndPort> mappingFunction) {
return new MappingSocketAddressResolver(dnsResolver, mappingFunction);
}
@Override
public SocketAddress resolve(RedisURI redisURI) {
if (redisURI.getSocket() != null) {
return getDomainSocketAddress(redisURI);
}
HostAndPort hostAndPort = HostAndPort.of(redisURI.getHost(), redisURI.getPort());
HostAndPort mapped = mappingFunction.apply(hostAndPort);
if (mapped == null) {
throw new IllegalStateException("Mapping function must not return null for HostAndPort");
}
try {
return doResolve(mapped);
} catch (UnknownHostException e) {
return new InetSocketAddress(redisURI.getHost(), redisURI.getPort());
}
}
private SocketAddress doResolve(HostAndPort mapped) throws UnknownHostException {<FILL_FUNCTION_BODY>}
}
|
InetAddress[] inetAddress = dnsResolver.resolve(mapped.getHostText());
if (inetAddress.length == 0) {
return InetSocketAddress.createUnresolved(mapped.getHostText(), mapped.getPort());
}
return new InetSocketAddress(inetAddress[0], mapped.getPort());
| 763
| 86
| 849
|
<methods>public static io.lettuce.core.resource.SocketAddressResolver create(io.lettuce.core.resource.DnsResolver) ,public java.net.SocketAddress resolve(io.lettuce.core.RedisURI) ,public static java.net.SocketAddress resolve(io.lettuce.core.RedisURI, io.lettuce.core.resource.DnsResolver) <variables>private final non-sealed io.lettuce.core.resource.DnsResolver dnsResolver
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/resource/PromiseAdapter.java
|
PromiseAdapter
|
toBooleanPromise
|
class PromiseAdapter {
/**
* Create a promise that emits a {@code Boolean} value on completion of the {@code future}
*
* @param future the future.
* @return Promise emitting a {@code Boolean} value. {@code true} if the {@code future} completed successfully, otherwise
* the cause wil be transported.
*/
static Promise<Boolean> toBooleanPromise(Future<?> future) {<FILL_FUNCTION_BODY>}
}
|
DefaultPromise<Boolean> result = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
if (future.isDone() || future.isCancelled()) {
if (future.isSuccess()) {
result.setSuccess(true);
} else {
result.setFailure(future.cause());
}
return result;
}
future.addListener((GenericFutureListener<Future<Object>>) f -> {
if (f.isSuccess()) {
result.setSuccess(true);
} else {
result.setFailure(f.cause());
}
});
return result;
| 121
| 158
| 279
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/resource/SocketAddressResolver.java
|
SocketAddressResolver
|
resolve
|
class SocketAddressResolver {
private final DnsResolver dnsResolver;
/**
* Create a new {@link SocketAddressResolver}.
*
* @since 6.1
*/
protected SocketAddressResolver() {
this(DnsResolver.unresolved());
}
/**
* Create a new {@link SocketAddressResolver} given {@link DnsResolver}.
*
* @param dnsResolver must not be {@code null}.
* @since 5.1
*/
protected SocketAddressResolver(DnsResolver dnsResolver) {
LettuceAssert.notNull(dnsResolver, "DnsResolver must not be null");
this.dnsResolver = dnsResolver;
}
/**
* Create a new {@link SocketAddressResolver} given {@link DnsResolver}.
*
* @param dnsResolver must not be {@code null}.
* @return the {@link SocketAddressResolver}.
* @since 5.1
*/
public static SocketAddressResolver create(DnsResolver dnsResolver) {
return new SocketAddressResolver(dnsResolver);
}
/**
* Resolve a {@link RedisURI} to a {@link SocketAddress}.
*
* @param redisURI must not be {@code null}.
* @return the resolved {@link SocketAddress}.
* @since 5.1
*/
public SocketAddress resolve(RedisURI redisURI) {<FILL_FUNCTION_BODY>}
/**
* Resolves a {@link io.lettuce.core.RedisURI} to a {@link java.net.SocketAddress}.
*
* @param redisURI must not be {@code null}.
* @param dnsResolver must not be {@code null}.
* @return the resolved {@link SocketAddress}.
*/
public static SocketAddress resolve(RedisURI redisURI, DnsResolver dnsResolver) {
if (redisURI.getSocket() != null) {
return getDomainSocketAddress(redisURI);
}
try {
InetAddress[] inetAddress = dnsResolver.resolve(redisURI.getHost());
if (inetAddress.length == 0) {
return InetSocketAddress.createUnresolved(redisURI.getHost(), redisURI.getPort());
}
return new InetSocketAddress(inetAddress[0], redisURI.getPort());
} catch (UnknownHostException e) {
return new InetSocketAddress(redisURI.getHost(), redisURI.getPort());
}
}
static SocketAddress getDomainSocketAddress(RedisURI redisURI) {
if (KqueueProvider.isAvailable() || EpollProvider.isAvailable()) {
EventLoopResources resources = KqueueProvider.isAvailable() ? KqueueProvider.getResources()
: EpollProvider.getResources();
return resources.newSocketAddress(redisURI.getSocket());
}
throw new IllegalStateException(
"No native transport available. Make sure that either netty's epoll or kqueue library is on the class path and supported by your operating system.");
}
}
|
LettuceAssert.notNull(redisURI, "RedisURI must not be null");
return resolve(redisURI, dnsResolver);
| 793
| 41
| 834
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/resource/Transports.java
|
NativeTransports
|
assertDomainSocketAvailable
|
class NativeTransports {
static EventLoopResources RESOURCES = KqueueProvider.isAvailable() ? KqueueProvider.getResources()
: IOUringProvider.isAvailable() ? IOUringProvider.getResources() : EpollProvider.getResources();
/**
* @return {@code true} if a native transport is available.
*/
static boolean isAvailable() {
return EpollProvider.isAvailable() || KqueueProvider.isAvailable() || IOUringProvider.isAvailable();
}
/**
* @return {@code true} if a native transport for domain sockets is available.
*/
public static boolean isDomainSocketSupported() {
return EpollProvider.isAvailable() || KqueueProvider.isAvailable();
}
/**
* @return the native transport socket {@link Channel} class.
*/
static Class<? extends Channel> socketChannelClass() {
return RESOURCES.socketChannelClass();
}
/**
* @return the native transport socket {@link DatagramChannel} class.
*/
static Class<? extends DatagramChannel> datagramChannelClass() {
return RESOURCES.datagramChannelClass();
}
/**
* @return the native transport domain socket {@link Channel} class.
*/
public static Class<? extends Channel> domainSocketChannelClass() {
assertDomainSocketAvailable();
return EpollProvider.isAvailable() && IOUringProvider.isAvailable()
? EpollProvider.getResources().domainSocketChannelClass()
: RESOURCES.domainSocketChannelClass();
}
/**
* @return the native transport {@link EventLoopGroup} class. Defaults to TCP sockets. See
* {@link #eventLoopGroupClass(boolean)} to request a specific EventLoopGroup for Domain Socket usage.
*/
public static Class<? extends EventLoopGroup> eventLoopGroupClass() {
return eventLoopGroupClass(false);
}
/**
* @return the native transport {@link EventLoopGroup} class.
* @param domainSocket {@code true} to indicate Unix Domain Socket usage, {@code false} otherwise.
* @since 6.3.3
*/
public static Class<? extends EventLoopGroup> eventLoopGroupClass(boolean domainSocket) {
return domainSocket && EpollProvider.isAvailable() && IOUringProvider.isAvailable()
? EpollProvider.getResources().eventLoopGroupClass()
: RESOURCES.eventLoopGroupClass();
}
public static void assertDomainSocketAvailable() {<FILL_FUNCTION_BODY>}
}
|
LettuceAssert.assertState(NativeTransports.isDomainSocketSupported(),
"A unix domain socket connection requires epoll or kqueue and neither is available");
| 641
| 44
| 685
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/sentinel/RedisSentinelAsyncCommandsImpl.java
|
RedisSentinelAsyncCommandsImpl
|
dispatch
|
class RedisSentinelAsyncCommandsImpl<K, V> implements RedisSentinelAsyncCommands<K, V> {
private final SentinelCommandBuilder<K, V> commandBuilder;
private final StatefulConnection<K, V> connection;
public RedisSentinelAsyncCommandsImpl(StatefulConnection<K, V> connection, RedisCodec<K, V> codec) {
this.connection = connection;
commandBuilder = new SentinelCommandBuilder<K, V>(codec);
}
@Override
public RedisFuture<SocketAddress> getMasterAddrByName(K key) {
return dispatch(commandBuilder.getMasterAddrByKey(key));
}
@Override
public RedisFuture<List<Map<K, V>>> masters() {
return dispatch(commandBuilder.masters());
}
@Override
public RedisFuture<Map<K, V>> master(K key) {
return dispatch(commandBuilder.master(key));
}
@Override
public RedisFuture<List<Map<K, V>>> slaves(K key) {
return dispatch(commandBuilder.slaves(key));
}
@Override
public RedisFuture<List<Map<K, V>>> replicas(K key) {
return dispatch(commandBuilder.replicas(key));
}
@Override
public RedisFuture<Long> reset(K key) {
return dispatch(commandBuilder.reset(key));
}
@Override
public RedisFuture<String> failover(K key) {
return dispatch(commandBuilder.failover(key));
}
@Override
public RedisFuture<String> monitor(K key, String ip, int port, int quorum) {
return dispatch(commandBuilder.monitor(key, ip, port, quorum));
}
@Override
public RedisFuture<String> set(K key, String option, V value) {
return dispatch(commandBuilder.set(key, option, value));
}
@Override
public RedisFuture<String> remove(K key) {
return dispatch(commandBuilder.remove(key));
}
@Override
public RedisFuture<String> ping() {
return dispatch(commandBuilder.ping());
}
@Override
public RedisFuture<K> clientGetname() {
return dispatch(commandBuilder.clientGetname());
}
@Override
public RedisFuture<String> clientSetname(K name) {
return dispatch(commandBuilder.clientSetname(name));
}
@Override
public RedisFuture<String> clientSetinfo(String key, String value) {
return dispatch(commandBuilder.clientSetinfo(key, value));
}
@Override
public RedisFuture<String> clientKill(String addr) {
return dispatch(commandBuilder.clientKill(addr));
}
@Override
public RedisFuture<Long> clientKill(KillArgs killArgs) {
return dispatch(commandBuilder.clientKill(killArgs));
}
@Override
public RedisFuture<String> clientPause(long timeout) {
return dispatch(commandBuilder.clientPause(timeout));
}
@Override
public RedisFuture<String> clientList() {
return dispatch(commandBuilder.clientList());
}
@Override
public RedisFuture<String> clientList(ClientListArgs clientListArgs) {
return dispatch(commandBuilder.clientList(clientListArgs));
}
@Override
public RedisFuture<String> clientInfo() {
return dispatch(commandBuilder.clientInfo());
}
@Override
public RedisFuture<String> info() {
return dispatch(commandBuilder.info());
}
@Override
public RedisFuture<String> info(String section) {
return dispatch(commandBuilder.info(section));
}
@Override
public <T> RedisFuture<T> dispatch(ProtocolKeyword type, CommandOutput<K, V, T> output) {
LettuceAssert.notNull(type, "Command type must not be null");
LettuceAssert.notNull(output, "CommandOutput type must not be null");
return dispatch(new AsyncCommand<>(new Command<>(type, output)));
}
@Override
public <T> RedisFuture<T> dispatch(ProtocolKeyword type, CommandOutput<K, V, T> output, CommandArgs<K, V> args) {
LettuceAssert.notNull(type, "Command type must not be null");
LettuceAssert.notNull(output, "CommandOutput type must not be null");
LettuceAssert.notNull(args, "CommandArgs type must not be null");
return dispatch(new AsyncCommand<>(new Command<>(type, output, args)));
}
public <T> AsyncCommand<K, V, T> dispatch(RedisCommand<K, V, T> cmd) {<FILL_FUNCTION_BODY>}
public void close() {
connection.close();
}
@Override
public boolean isOpen() {
return connection.isOpen();
}
@Override
public StatefulRedisSentinelConnection<K, V> getStatefulConnection() {
return (StatefulRedisSentinelConnection<K, V>) connection;
}
}
|
AsyncCommand<K, V, T> asyncCommand = new AsyncCommand<>(cmd);
RedisCommand<K, V, T> dispatched = connection.dispatch(asyncCommand);
if (dispatched instanceof AsyncCommand) {
return (AsyncCommand<K, V, T>) dispatched;
}
return asyncCommand;
| 1,353
| 90
| 1,443
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.