id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
14,700
google/auto
value/src/main/java/com/google/auto/value/processor/TemplateVars.java
TemplateVars.readerFromUrl
private static Reader readerFromUrl(String resourceName) throws IOException { URL resourceUrl = TemplateVars.class.getResource(resourceName); InputStream in; try { if (resourceUrl.getProtocol().equalsIgnoreCase("file")) { in = inputStreamFromFile(resourceUrl); } else if (resourceUrl.getProtocol().equalsIgnoreCase("jar")) { in = inputStreamFromJar(resourceUrl); } else { throw new AssertionError("Template fallback logic fails for: " + resourceUrl); } } catch (URISyntaxException e) { throw new IOException(e); } return new InputStreamReader(in, StandardCharsets.UTF_8); }
java
private static Reader readerFromUrl(String resourceName) throws IOException { URL resourceUrl = TemplateVars.class.getResource(resourceName); InputStream in; try { if (resourceUrl.getProtocol().equalsIgnoreCase("file")) { in = inputStreamFromFile(resourceUrl); } else if (resourceUrl.getProtocol().equalsIgnoreCase("jar")) { in = inputStreamFromJar(resourceUrl); } else { throw new AssertionError("Template fallback logic fails for: " + resourceUrl); } } catch (URISyntaxException e) { throw new IOException(e); } return new InputStreamReader(in, StandardCharsets.UTF_8); }
[ "private", "static", "Reader", "readerFromUrl", "(", "String", "resourceName", ")", "throws", "IOException", "{", "URL", "resourceUrl", "=", "TemplateVars", ".", "class", ".", "getResource", "(", "resourceName", ")", ";", "InputStream", "in", ";", "try", "{", "if", "(", "resourceUrl", ".", "getProtocol", "(", ")", ".", "equalsIgnoreCase", "(", "\"file\"", ")", ")", "{", "in", "=", "inputStreamFromFile", "(", "resourceUrl", ")", ";", "}", "else", "if", "(", "resourceUrl", ".", "getProtocol", "(", ")", ".", "equalsIgnoreCase", "(", "\"jar\"", ")", ")", "{", "in", "=", "inputStreamFromJar", "(", "resourceUrl", ")", ";", "}", "else", "{", "throw", "new", "AssertionError", "(", "\"Template fallback logic fails for: \"", "+", "resourceUrl", ")", ";", "}", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "IOException", "(", "e", ")", ";", "}", "return", "new", "InputStreamReader", "(", "in", ",", "StandardCharsets", ".", "UTF_8", ")", ";", "}" ]
through the getResourceAsStream should be a lot more efficient than reopening the jar.
[ "through", "the", "getResourceAsStream", "should", "be", "a", "lot", "more", "efficient", "than", "reopening", "the", "jar", "." ]
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/TemplateVars.java#L156-L171
14,701
google/auto
value/src/main/java/com/google/auto/value/processor/TemplateVars.java
TemplateVars.inputStreamFromFile
private static InputStream inputStreamFromFile(URL resourceUrl) throws IOException, URISyntaxException { File resourceFile = new File(resourceUrl.toURI()); return new FileInputStream(resourceFile); }
java
private static InputStream inputStreamFromFile(URL resourceUrl) throws IOException, URISyntaxException { File resourceFile = new File(resourceUrl.toURI()); return new FileInputStream(resourceFile); }
[ "private", "static", "InputStream", "inputStreamFromFile", "(", "URL", "resourceUrl", ")", "throws", "IOException", ",", "URISyntaxException", "{", "File", "resourceFile", "=", "new", "File", "(", "resourceUrl", ".", "toURI", "(", ")", ")", ";", "return", "new", "FileInputStream", "(", "resourceFile", ")", ";", "}" ]
system does run it using a jar, so we do have coverage.
[ "system", "does", "run", "it", "using", "a", "jar", "so", "we", "do", "have", "coverage", "." ]
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/TemplateVars.java#L203-L207
14,702
google/auto
common/src/main/java/com/google/auto/common/MoreElements.java
MoreElements.overrides
public static boolean overrides( ExecutableElement overrider, ExecutableElement overridden, TypeElement type, Types typeUtils) { return new ExplicitOverrides(typeUtils).overrides(overrider, overridden, type); }
java
public static boolean overrides( ExecutableElement overrider, ExecutableElement overridden, TypeElement type, Types typeUtils) { return new ExplicitOverrides(typeUtils).overrides(overrider, overridden, type); }
[ "public", "static", "boolean", "overrides", "(", "ExecutableElement", "overrider", ",", "ExecutableElement", "overridden", ",", "TypeElement", "type", ",", "Types", "typeUtils", ")", "{", "return", "new", "ExplicitOverrides", "(", "typeUtils", ")", ".", "overrides", "(", "overrider", ",", "overridden", ",", "type", ")", ";", "}" ]
Tests whether one method, as a member of a given type, overrides another method. <p>This method does the same thing as {@link Elements#overrides(ExecutableElement, ExecutableElement, TypeElement)}, but in a way that is more consistent between compilers, in particular between javac and ecj (the Eclipse compiler). @param overrider the first method, possible overrider @param overridden the second method, possibly being overridden @param type the type of which the first method is a member @return {@code true} if and only if the first method overrides the second
[ "Tests", "whether", "one", "method", "as", "a", "member", "of", "a", "given", "type", "overrides", "another", "method", "." ]
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/common/src/main/java/com/google/auto/common/MoreElements.java#L346-L352
14,703
google/auto
common/src/main/java/com/google/auto/common/MoreElements.java
MoreElements.getLocalAndInheritedMethods
private static void getLocalAndInheritedMethods( PackageElement pkg, TypeElement type, SetMultimap<String, ExecutableElement> methods) { for (TypeMirror superInterface : type.getInterfaces()) { getLocalAndInheritedMethods(pkg, MoreTypes.asTypeElement(superInterface), methods); } if (type.getSuperclass().getKind() != TypeKind.NONE) { // Visit the superclass after superinterfaces so we will always see the implementation of a // method after any interfaces that declared it. getLocalAndInheritedMethods(pkg, MoreTypes.asTypeElement(type.getSuperclass()), methods); } for (ExecutableElement method : ElementFilter.methodsIn(type.getEnclosedElements())) { if (!method.getModifiers().contains(Modifier.STATIC) && methodVisibleFromPackage(method, pkg)) { methods.put(method.getSimpleName().toString(), method); } } }
java
private static void getLocalAndInheritedMethods( PackageElement pkg, TypeElement type, SetMultimap<String, ExecutableElement> methods) { for (TypeMirror superInterface : type.getInterfaces()) { getLocalAndInheritedMethods(pkg, MoreTypes.asTypeElement(superInterface), methods); } if (type.getSuperclass().getKind() != TypeKind.NONE) { // Visit the superclass after superinterfaces so we will always see the implementation of a // method after any interfaces that declared it. getLocalAndInheritedMethods(pkg, MoreTypes.asTypeElement(type.getSuperclass()), methods); } for (ExecutableElement method : ElementFilter.methodsIn(type.getEnclosedElements())) { if (!method.getModifiers().contains(Modifier.STATIC) && methodVisibleFromPackage(method, pkg)) { methods.put(method.getSimpleName().toString(), method); } } }
[ "private", "static", "void", "getLocalAndInheritedMethods", "(", "PackageElement", "pkg", ",", "TypeElement", "type", ",", "SetMultimap", "<", "String", ",", "ExecutableElement", ">", "methods", ")", "{", "for", "(", "TypeMirror", "superInterface", ":", "type", ".", "getInterfaces", "(", ")", ")", "{", "getLocalAndInheritedMethods", "(", "pkg", ",", "MoreTypes", ".", "asTypeElement", "(", "superInterface", ")", ",", "methods", ")", ";", "}", "if", "(", "type", ".", "getSuperclass", "(", ")", ".", "getKind", "(", ")", "!=", "TypeKind", ".", "NONE", ")", "{", "// Visit the superclass after superinterfaces so we will always see the implementation of a", "// method after any interfaces that declared it.", "getLocalAndInheritedMethods", "(", "pkg", ",", "MoreTypes", ".", "asTypeElement", "(", "type", ".", "getSuperclass", "(", ")", ")", ",", "methods", ")", ";", "}", "for", "(", "ExecutableElement", "method", ":", "ElementFilter", ".", "methodsIn", "(", "type", ".", "getEnclosedElements", "(", ")", ")", ")", "{", "if", "(", "!", "method", ".", "getModifiers", "(", ")", ".", "contains", "(", "Modifier", ".", "STATIC", ")", "&&", "methodVisibleFromPackage", "(", "method", ",", "pkg", ")", ")", "{", "methods", ".", "put", "(", "method", ".", "getSimpleName", "(", ")", ".", "toString", "(", ")", ",", "method", ")", ";", "}", "}", "}" ]
always precede those in descendant types.
[ "always", "precede", "those", "in", "descendant", "types", "." ]
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/common/src/main/java/com/google/auto/common/MoreElements.java#L390-L406
14,704
google/auto
value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java
AutoAnnotationProcessor.reportError
private void reportError(Element e, String msg, Object... msgParams) { String formattedMessage = String.format(msg, msgParams); processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, formattedMessage, e); }
java
private void reportError(Element e, String msg, Object... msgParams) { String formattedMessage = String.format(msg, msgParams); processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, formattedMessage, e); }
[ "private", "void", "reportError", "(", "Element", "e", ",", "String", "msg", ",", "Object", "...", "msgParams", ")", "{", "String", "formattedMessage", "=", "String", ".", "format", "(", "msg", ",", "msgParams", ")", ";", "processingEnv", ".", "getMessager", "(", ")", ".", "printMessage", "(", "Diagnostic", ".", "Kind", ".", "ERROR", ",", "formattedMessage", ",", "e", ")", ";", "}" ]
Issue a compilation error. This method does not throw an exception, since we want to continue processing and perhaps report other errors.
[ "Issue", "a", "compilation", "error", ".", "This", "method", "does", "not", "throw", "an", "exception", "since", "we", "want", "to", "continue", "processing", "and", "perhaps", "report", "other", "errors", "." ]
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java#L85-L88
14,705
google/auto
value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java
AutoAnnotationProcessor.abortWithError
private AbortProcessingException abortWithError(String msg, Element e) { reportError(e, msg); return new AbortProcessingException(); }
java
private AbortProcessingException abortWithError(String msg, Element e) { reportError(e, msg); return new AbortProcessingException(); }
[ "private", "AbortProcessingException", "abortWithError", "(", "String", "msg", ",", "Element", "e", ")", "{", "reportError", "(", "e", ",", "msg", ")", ";", "return", "new", "AbortProcessingException", "(", ")", ";", "}" ]
Issue a compilation error and return an exception that, when thrown, will cause the processing of this class to be abandoned. This does not prevent the processing of other classes.
[ "Issue", "a", "compilation", "error", "and", "return", "an", "exception", "that", "when", "thrown", "will", "cause", "the", "processing", "of", "this", "class", "to", "be", "abandoned", ".", "This", "does", "not", "prevent", "the", "processing", "of", "other", "classes", "." ]
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java#L94-L97
14,706
google/auto
value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java
AutoAnnotationProcessor.invariableHash
private static Optional<Integer> invariableHash(AnnotationValue annotationValue) { Object value = annotationValue.getValue(); if (value instanceof String || Primitives.isWrapperType(value.getClass())) { return Optional.of(value.hashCode()); } else if (value instanceof List<?>) { @SuppressWarnings("unchecked") // by specification List<? extends AnnotationValue> list = (List<? extends AnnotationValue>) value; return invariableHash(list); } else { return Optional.empty(); } }
java
private static Optional<Integer> invariableHash(AnnotationValue annotationValue) { Object value = annotationValue.getValue(); if (value instanceof String || Primitives.isWrapperType(value.getClass())) { return Optional.of(value.hashCode()); } else if (value instanceof List<?>) { @SuppressWarnings("unchecked") // by specification List<? extends AnnotationValue> list = (List<? extends AnnotationValue>) value; return invariableHash(list); } else { return Optional.empty(); } }
[ "private", "static", "Optional", "<", "Integer", ">", "invariableHash", "(", "AnnotationValue", "annotationValue", ")", "{", "Object", "value", "=", "annotationValue", ".", "getValue", "(", ")", ";", "if", "(", "value", "instanceof", "String", "||", "Primitives", ".", "isWrapperType", "(", "value", ".", "getClass", "(", ")", ")", ")", "{", "return", "Optional", ".", "of", "(", "value", ".", "hashCode", "(", ")", ")", ";", "}", "else", "if", "(", "value", "instanceof", "List", "<", "?", ">", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "// by specification", "List", "<", "?", "extends", "AnnotationValue", ">", "list", "=", "(", "List", "<", "?", "extends", "AnnotationValue", ">", ")", "value", ";", "return", "invariableHash", "(", "list", ")", ";", "}", "else", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "}" ]
Returns the hashCode of the given AnnotationValue, if that hashCode is guaranteed to be always the same. The hashCode of a String or primitive type never changes. The hashCode of a Class or an enum constant does potentially change in different runs of the same program. The hashCode of an array doesn't change if the hashCodes of its elements don't. Although we could have a similar rule for nested annotation values, we currently don't.
[ "Returns", "the", "hashCode", "of", "the", "given", "AnnotationValue", "if", "that", "hashCode", "is", "guaranteed", "to", "be", "always", "the", "same", ".", "The", "hashCode", "of", "a", "String", "or", "primitive", "type", "never", "changes", ".", "The", "hashCode", "of", "a", "Class", "or", "an", "enum", "constant", "does", "potentially", "change", "in", "different", "runs", "of", "the", "same", "program", ".", "The", "hashCode", "of", "an", "array", "doesn", "t", "change", "if", "the", "hashCodes", "of", "its", "elements", "don", "t", ".", "Although", "we", "could", "have", "a", "similar", "rule", "for", "nested", "annotation", "values", "we", "currently", "don", "t", "." ]
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java#L198-L209
14,707
google/auto
value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java
AutoAnnotationProcessor.invariableHashes
private static ImmutableMap<String, Integer> invariableHashes( ImmutableMap<String, Member> members, ImmutableSet<String> parameters) { ImmutableMap.Builder<String, Integer> builder = ImmutableMap.builder(); for (String element : members.keySet()) { if (!parameters.contains(element)) { Member member = members.get(element); AnnotationValue annotationValue = member.method.getDefaultValue(); Optional<Integer> invariableHash = invariableHash(annotationValue); if (invariableHash.isPresent()) { builder.put(element, (element.hashCode() * 127) ^ invariableHash.get()); } } } return builder.build(); }
java
private static ImmutableMap<String, Integer> invariableHashes( ImmutableMap<String, Member> members, ImmutableSet<String> parameters) { ImmutableMap.Builder<String, Integer> builder = ImmutableMap.builder(); for (String element : members.keySet()) { if (!parameters.contains(element)) { Member member = members.get(element); AnnotationValue annotationValue = member.method.getDefaultValue(); Optional<Integer> invariableHash = invariableHash(annotationValue); if (invariableHash.isPresent()) { builder.put(element, (element.hashCode() * 127) ^ invariableHash.get()); } } } return builder.build(); }
[ "private", "static", "ImmutableMap", "<", "String", ",", "Integer", ">", "invariableHashes", "(", "ImmutableMap", "<", "String", ",", "Member", ">", "members", ",", "ImmutableSet", "<", "String", ">", "parameters", ")", "{", "ImmutableMap", ".", "Builder", "<", "String", ",", "Integer", ">", "builder", "=", "ImmutableMap", ".", "builder", "(", ")", ";", "for", "(", "String", "element", ":", "members", ".", "keySet", "(", ")", ")", "{", "if", "(", "!", "parameters", ".", "contains", "(", "element", ")", ")", "{", "Member", "member", "=", "members", ".", "get", "(", "element", ")", ";", "AnnotationValue", "annotationValue", "=", "member", ".", "method", ".", "getDefaultValue", "(", ")", ";", "Optional", "<", "Integer", ">", "invariableHash", "=", "invariableHash", "(", "annotationValue", ")", ";", "if", "(", "invariableHash", ".", "isPresent", "(", ")", ")", "{", "builder", ".", "put", "(", "element", ",", "(", "element", ".", "hashCode", "(", ")", "*", "127", ")", "^", "invariableHash", ".", "get", "(", ")", ")", ";", "}", "}", "}", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Returns a map from the names of members with invariable hashCodes to the values of those hashCodes.
[ "Returns", "a", "map", "from", "the", "names", "of", "members", "with", "invariable", "hashCodes", "to", "the", "values", "of", "those", "hashCodes", "." ]
4158a5fa71f1ef763e683b627f4d29bc04cfde9d
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java#L228-L242
14,708
micrometer-metrics/micrometer
samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/CacheSample.java
CacheSample.wordDecoder
private static DelimiterBasedFrameDecoder wordDecoder() { return new DelimiterBasedFrameDecoder(256, IntStream.of('\r', '\n', ' ', '\t', '.', ',', ';', ':', '-') .mapToObj(delim -> wrappedBuffer(new byte[] { (byte) delim })) .toArray(ByteBuf[]::new)); }
java
private static DelimiterBasedFrameDecoder wordDecoder() { return new DelimiterBasedFrameDecoder(256, IntStream.of('\r', '\n', ' ', '\t', '.', ',', ';', ':', '-') .mapToObj(delim -> wrappedBuffer(new byte[] { (byte) delim })) .toArray(ByteBuf[]::new)); }
[ "private", "static", "DelimiterBasedFrameDecoder", "wordDecoder", "(", ")", "{", "return", "new", "DelimiterBasedFrameDecoder", "(", "256", ",", "IntStream", ".", "of", "(", "'", "'", ",", "'", "'", ",", "'", "'", ",", "'", "'", ",", "'", "'", ",", "'", "'", ",", "'", "'", ",", "'", "'", ",", "'", "'", ")", ".", "mapToObj", "(", "delim", "->", "wrappedBuffer", "(", "new", "byte", "[", "]", "{", "(", "byte", ")", "delim", "}", ")", ")", ".", "toArray", "(", "ByteBuf", "[", "]", "::", "new", ")", ")", ";", "}" ]
skip things that aren't words, roughly
[ "skip", "things", "that", "aren", "t", "words", "roughly" ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/samples/micrometer-samples-core/src/main/java/io/micrometer/core/samples/CacheSample.java#L65-L70
14,709
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/HazelcastCacheMetrics.java
HazelcastCacheMetrics.monitor
public static <K, V, C extends IMap<K, V>> C monitor(MeterRegistry registry, C cache, Iterable<Tag> tags) { new HazelcastCacheMetrics(cache, tags).bindTo(registry); return cache; }
java
public static <K, V, C extends IMap<K, V>> C monitor(MeterRegistry registry, C cache, Iterable<Tag> tags) { new HazelcastCacheMetrics(cache, tags).bindTo(registry); return cache; }
[ "public", "static", "<", "K", ",", "V", ",", "C", "extends", "IMap", "<", "K", ",", "V", ">", ">", "C", "monitor", "(", "MeterRegistry", "registry", ",", "C", "cache", ",", "Iterable", "<", "Tag", ">", "tags", ")", "{", "new", "HazelcastCacheMetrics", "(", "cache", ",", "tags", ")", ".", "bindTo", "(", "registry", ")", ";", "return", "cache", ";", "}" ]
Record metrics on a Hazelcast cache. @param registry The registry to bind metrics to. @param cache The cache to instrument. @param tags Tags to apply to all recorded metrics. @param <C> The cache type. @param <K> The cache key type. @param <V> The cache value type. @return The instrumented cache, unchanged. The original cache is not wrapped or proxied in any way.
[ "Record", "metrics", "on", "a", "Hazelcast", "cache", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/HazelcastCacheMetrics.java#L62-L65
14,710
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/step/StepFunctionTimer.java
StepFunctionTimer.totalTime
public double totalTime(TimeUnit unit) { T obj2 = ref.get(); if (obj2 != null) { double prevLast = lastTime; lastTime = Math.max(TimeUtils.convert(totalTimeFunction.applyAsDouble(obj2), totalTimeFunctionUnit, baseTimeUnit()), 0); total.getCurrent().add(lastTime - prevLast); } return TimeUtils.convert(total.poll(), baseTimeUnit(), unit); }
java
public double totalTime(TimeUnit unit) { T obj2 = ref.get(); if (obj2 != null) { double prevLast = lastTime; lastTime = Math.max(TimeUtils.convert(totalTimeFunction.applyAsDouble(obj2), totalTimeFunctionUnit, baseTimeUnit()), 0); total.getCurrent().add(lastTime - prevLast); } return TimeUtils.convert(total.poll(), baseTimeUnit(), unit); }
[ "public", "double", "totalTime", "(", "TimeUnit", "unit", ")", "{", "T", "obj2", "=", "ref", ".", "get", "(", ")", ";", "if", "(", "obj2", "!=", "null", ")", "{", "double", "prevLast", "=", "lastTime", ";", "lastTime", "=", "Math", ".", "max", "(", "TimeUtils", ".", "convert", "(", "totalTimeFunction", ".", "applyAsDouble", "(", "obj2", ")", ",", "totalTimeFunctionUnit", ",", "baseTimeUnit", "(", ")", ")", ",", "0", ")", ";", "total", ".", "getCurrent", "(", ")", ".", "add", "(", "lastTime", "-", "prevLast", ")", ";", "}", "return", "TimeUtils", ".", "convert", "(", "total", ".", "poll", "(", ")", ",", "baseTimeUnit", "(", ")", ",", "unit", ")", ";", "}" ]
The total time of all occurrences of the timed event.
[ "The", "total", "time", "of", "all", "occurrences", "of", "the", "timed", "event", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/step/StepFunctionTimer.java#L75-L83
14,711
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/util/JsonUtils.java
JsonUtils.appendIndentedNewLine
private static void appendIndentedNewLine(int indentLevel, StringBuilder stringBuilder) { stringBuilder.append("\n"); for (int i = 0; i < indentLevel; i++) { // Assuming indention using 2 spaces stringBuilder.append(" "); } }
java
private static void appendIndentedNewLine(int indentLevel, StringBuilder stringBuilder) { stringBuilder.append("\n"); for (int i = 0; i < indentLevel; i++) { // Assuming indention using 2 spaces stringBuilder.append(" "); } }
[ "private", "static", "void", "appendIndentedNewLine", "(", "int", "indentLevel", ",", "StringBuilder", "stringBuilder", ")", "{", "stringBuilder", ".", "append", "(", "\"\\n\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "indentLevel", ";", "i", "++", ")", "{", "// Assuming indention using 2 spaces", "stringBuilder", ".", "append", "(", "\" \"", ")", ";", "}", "}" ]
Print a new line with indention at the beginning of the new line. @param indentLevel @param stringBuilder
[ "Print", "a", "new", "line", "with", "indention", "at", "the", "beginning", "of", "the", "new", "line", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/util/JsonUtils.java#L80-L86
14,712
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/MeterRegistry.java
MeterRegistry.register
Meter register(Meter.Id id, Meter.Type type, Iterable<Measurement> measurements) { return registerMeterIfNecessary(Meter.class, id, id2 -> newMeter(id2, type, measurements), NoopMeter::new); }
java
Meter register(Meter.Id id, Meter.Type type, Iterable<Measurement> measurements) { return registerMeterIfNecessary(Meter.class, id, id2 -> newMeter(id2, type, measurements), NoopMeter::new); }
[ "Meter", "register", "(", "Meter", ".", "Id", "id", ",", "Meter", ".", "Type", "type", ",", "Iterable", "<", "Measurement", ">", "measurements", ")", "{", "return", "registerMeterIfNecessary", "(", "Meter", ".", "class", ",", "id", ",", "id2", "->", "newMeter", "(", "id2", ",", "type", ",", "measurements", ")", ",", "NoopMeter", "::", "new", ")", ";", "}" ]
Register a custom meter type. @param id Id of the meter being registered. @param type Meter type, which may be used by naming conventions to normalize the name. @param measurements A sequence of measurements describing how to sample the meter. @return The registry.
[ "Register", "a", "custom", "meter", "type", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/MeterRegistry.java#L295-L297
14,713
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/MeterRegistry.java
MeterRegistry.gauge
@Nullable public <T> T gauge(String name, T obj, ToDoubleFunction<T> valueFunction) { return gauge(name, emptyList(), obj, valueFunction); }
java
@Nullable public <T> T gauge(String name, T obj, ToDoubleFunction<T> valueFunction) { return gauge(name, emptyList(), obj, valueFunction); }
[ "@", "Nullable", "public", "<", "T", ">", "T", "gauge", "(", "String", "name", ",", "T", "obj", ",", "ToDoubleFunction", "<", "T", ">", "valueFunction", ")", "{", "return", "gauge", "(", "name", ",", "emptyList", "(", ")", ",", "obj", ",", "valueFunction", ")", ";", "}" ]
Register a gauge that reports the value of the object. @param name Name of the gauge being registered. @param obj State object used to compute a value. @param valueFunction Function that produces an instantaneous gauge value from the state object. @param <T> The type of the state object from which the gauge value is extracted. @return The number that was passed in so the registration can be done as part of an assignment statement.
[ "Register", "a", "gauge", "that", "reports", "the", "value", "of", "the", "object", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/MeterRegistry.java#L477-L480
14,714
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/MeterRegistry.java
MeterRegistry.close
public void close() { if (closed.compareAndSet(false, true)) { synchronized (meterMapLock) { for (Meter meter : meterMap.values()) { meter.close(); } } } }
java
public void close() { if (closed.compareAndSet(false, true)) { synchronized (meterMapLock) { for (Meter meter : meterMap.values()) { meter.close(); } } } }
[ "public", "void", "close", "(", ")", "{", "if", "(", "closed", ".", "compareAndSet", "(", "false", ",", "true", ")", ")", "{", "synchronized", "(", "meterMapLock", ")", "{", "for", "(", "Meter", "meter", ":", "meterMap", ".", "values", "(", ")", ")", "{", "meter", ".", "close", "(", ")", ";", "}", "}", "}", "}" ]
Closes this registry, releasing any resources in the process. Once closed, this registry will no longer accept new meters and any publishing activity will cease.
[ "Closes", "this", "registry", "releasing", "any", "resources", "in", "the", "process", ".", "Once", "closed", "this", "registry", "will", "no", "longer", "accept", "new", "meters", "and", "any", "publishing", "activity", "will", "cease", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/MeterRegistry.java#L929-L937
14,715
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/composite/AbstractCompositeMeter.java
AbstractCompositeMeter.remove
@Deprecated public final void remove(MeterRegistry registry) { for (; ; ) { if (childrenGuard.compareAndSet(false, true)) { try { Map<MeterRegistry, T> newChildren = new IdentityHashMap<>(children); newChildren.remove(registry); this.children = newChildren; break; } finally { childrenGuard.set(false); } } } }
java
@Deprecated public final void remove(MeterRegistry registry) { for (; ; ) { if (childrenGuard.compareAndSet(false, true)) { try { Map<MeterRegistry, T> newChildren = new IdentityHashMap<>(children); newChildren.remove(registry); this.children = newChildren; break; } finally { childrenGuard.set(false); } } } }
[ "@", "Deprecated", "public", "final", "void", "remove", "(", "MeterRegistry", "registry", ")", "{", "for", "(", ";", ";", ")", "{", "if", "(", "childrenGuard", ".", "compareAndSet", "(", "false", ",", "true", ")", ")", "{", "try", "{", "Map", "<", "MeterRegistry", ",", "T", ">", "newChildren", "=", "new", "IdentityHashMap", "<>", "(", "children", ")", ";", "newChildren", ".", "remove", "(", "registry", ")", ";", "this", ".", "children", "=", "newChildren", ";", "break", ";", "}", "finally", "{", "childrenGuard", ".", "set", "(", "false", ")", ";", "}", "}", "}", "}" ]
Does nothing. New registries added to the composite are automatically reflected in each meter belonging to the composite. @param registry The registry to remove.
[ "Does", "nothing", ".", "New", "registries", "added", "to", "the", "composite", "are", "automatically", "reflected", "in", "each", "meter", "belonging", "to", "the", "composite", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/composite/AbstractCompositeMeter.java#L91-L105
14,716
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowMax.java
TimeWindowMax.record
public void record(double sample, TimeUnit timeUnit) { rotate(); final long sampleNanos = (long) TimeUtils.convert(sample, timeUnit, TimeUnit.NANOSECONDS); for (AtomicLong max : ringBuffer) { updateMax(max, sampleNanos); } }
java
public void record(double sample, TimeUnit timeUnit) { rotate(); final long sampleNanos = (long) TimeUtils.convert(sample, timeUnit, TimeUnit.NANOSECONDS); for (AtomicLong max : ringBuffer) { updateMax(max, sampleNanos); } }
[ "public", "void", "record", "(", "double", "sample", ",", "TimeUnit", "timeUnit", ")", "{", "rotate", "(", ")", ";", "final", "long", "sampleNanos", "=", "(", "long", ")", "TimeUtils", ".", "convert", "(", "sample", ",", "timeUnit", ",", "TimeUnit", ".", "NANOSECONDS", ")", ";", "for", "(", "AtomicLong", "max", ":", "ringBuffer", ")", "{", "updateMax", "(", "max", ",", "sampleNanos", ")", ";", "}", "}" ]
For use by timer implementations. @param sample The value to record. @param timeUnit The unit of time of the incoming sample.
[ "For", "use", "by", "timer", "implementations", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowMax.java#L67-L73
14,717
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowMax.java
TimeWindowMax.record
public void record(double sample) { rotate(); long sampleLong = Double.doubleToLongBits(sample); for (AtomicLong max : ringBuffer) { updateMax(max, sampleLong); } }
java
public void record(double sample) { rotate(); long sampleLong = Double.doubleToLongBits(sample); for (AtomicLong max : ringBuffer) { updateMax(max, sampleLong); } }
[ "public", "void", "record", "(", "double", "sample", ")", "{", "rotate", "(", ")", ";", "long", "sampleLong", "=", "Double", ".", "doubleToLongBits", "(", "sample", ")", ";", "for", "(", "AtomicLong", "max", ":", "ringBuffer", ")", "{", "updateMax", "(", "max", ",", "sampleLong", ")", ";", "}", "}" ]
For use by distribution summary implementations. @param sample The value to record.
[ "For", "use", "by", "distribution", "summary", "implementations", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/TimeWindowMax.java#L101-L107
14,718
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/PercentileHistogramBuckets.java
PercentileHistogramBuckets.buckets
public static NavigableSet<Long> buckets(DistributionStatisticConfig distributionStatisticConfig) { return PERCENTILE_BUCKETS.subSet(distributionStatisticConfig.getMinimumExpectedValue(), true, distributionStatisticConfig.getMaximumExpectedValue(), true); }
java
public static NavigableSet<Long> buckets(DistributionStatisticConfig distributionStatisticConfig) { return PERCENTILE_BUCKETS.subSet(distributionStatisticConfig.getMinimumExpectedValue(), true, distributionStatisticConfig.getMaximumExpectedValue(), true); }
[ "public", "static", "NavigableSet", "<", "Long", ">", "buckets", "(", "DistributionStatisticConfig", "distributionStatisticConfig", ")", "{", "return", "PERCENTILE_BUCKETS", ".", "subSet", "(", "distributionStatisticConfig", ".", "getMinimumExpectedValue", "(", ")", ",", "true", ",", "distributionStatisticConfig", ".", "getMaximumExpectedValue", "(", ")", ",", "true", ")", ";", "}" ]
Pick values from a static set of percentile buckets that yields a decent error bound on most real world timers and distribution summaries because monitoring systems like Prometheus require us to report the same buckets at every interval, regardless of where actual samples have been observed. @param distributionStatisticConfig A configuration the governs how many buckets to produce based on its minimum and maximum expected values.. @return The set of histogram buckets for use in computing aggregable percentiles.
[ "Pick", "values", "from", "a", "static", "set", "of", "percentile", "buckets", "that", "yields", "a", "decent", "error", "bound", "on", "most", "real", "world", "timers", "and", "distribution", "summaries", "because", "monitoring", "systems", "like", "Prometheus", "require", "us", "to", "report", "the", "same", "buckets", "at", "every", "interval", "regardless", "of", "where", "actual", "samples", "have", "been", "observed", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/PercentileHistogramBuckets.java#L78-L81
14,719
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/search/RequiredSearch.java
RequiredSearch.name
public RequiredSearch name(String exactName) { this.nameMatches = n -> n.equals(exactName); this.exactNameMatch = exactName; return this; }
java
public RequiredSearch name(String exactName) { this.nameMatches = n -> n.equals(exactName); this.exactNameMatch = exactName; return this; }
[ "public", "RequiredSearch", "name", "(", "String", "exactName", ")", "{", "this", ".", "nameMatches", "=", "n", "->", "n", ".", "equals", "(", "exactName", ")", ";", "this", ".", "exactNameMatch", "=", "exactName", ";", "return", "this", ";", "}" ]
Meter contains a tag with the exact name. @param exactName Name to match against. @return This search.
[ "Meter", "contains", "a", "tag", "with", "the", "exact", "name", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/search/RequiredSearch.java#L57-L61
14,720
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/EhCache2Metrics.java
EhCache2Metrics.monitor
public static Ehcache monitor(MeterRegistry registry, Ehcache cache, Iterable<Tag> tags) { new EhCache2Metrics(cache, tags).bindTo(registry); return cache; }
java
public static Ehcache monitor(MeterRegistry registry, Ehcache cache, Iterable<Tag> tags) { new EhCache2Metrics(cache, tags).bindTo(registry); return cache; }
[ "public", "static", "Ehcache", "monitor", "(", "MeterRegistry", "registry", ",", "Ehcache", "cache", ",", "Iterable", "<", "Tag", ">", "tags", ")", "{", "new", "EhCache2Metrics", "(", "cache", ",", "tags", ")", ".", "bindTo", "(", "registry", ")", ";", "return", "cache", ";", "}" ]
Record metrics on an EhCache cache. @param registry The registry to bind metrics to. @param cache The cache to instrument. @param tags Tags to apply to all recorded metrics. @return The instrumented cache, unchanged. The original cache is not wrapped or proxied in any way.
[ "Record", "metrics", "on", "an", "EhCache", "cache", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/EhCache2Metrics.java#L59-L62
14,721
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/DistributionStatisticConfig.java
DistributionStatisticConfig.merge
@Override public DistributionStatisticConfig merge(DistributionStatisticConfig parent) { return DistributionStatisticConfig.builder() .percentilesHistogram(this.percentileHistogram == null ? parent.percentileHistogram : this.percentileHistogram) .percentiles(this.percentiles == null ? parent.percentiles : this.percentiles) .sla(this.sla == null ? parent.sla : this.sla) .percentilePrecision(this.percentilePrecision == null ? parent.percentilePrecision : this.percentilePrecision) .minimumExpectedValue(this.minimumExpectedValue == null ? parent.minimumExpectedValue : this.minimumExpectedValue) .maximumExpectedValue(this.maximumExpectedValue == null ? parent.maximumExpectedValue : this.maximumExpectedValue) .expiry(this.expiry == null ? parent.expiry : this.expiry) .bufferLength(this.bufferLength == null ? parent.bufferLength : this.bufferLength) .build(); }
java
@Override public DistributionStatisticConfig merge(DistributionStatisticConfig parent) { return DistributionStatisticConfig.builder() .percentilesHistogram(this.percentileHistogram == null ? parent.percentileHistogram : this.percentileHistogram) .percentiles(this.percentiles == null ? parent.percentiles : this.percentiles) .sla(this.sla == null ? parent.sla : this.sla) .percentilePrecision(this.percentilePrecision == null ? parent.percentilePrecision : this.percentilePrecision) .minimumExpectedValue(this.minimumExpectedValue == null ? parent.minimumExpectedValue : this.minimumExpectedValue) .maximumExpectedValue(this.maximumExpectedValue == null ? parent.maximumExpectedValue : this.maximumExpectedValue) .expiry(this.expiry == null ? parent.expiry : this.expiry) .bufferLength(this.bufferLength == null ? parent.bufferLength : this.bufferLength) .build(); }
[ "@", "Override", "public", "DistributionStatisticConfig", "merge", "(", "DistributionStatisticConfig", "parent", ")", "{", "return", "DistributionStatisticConfig", ".", "builder", "(", ")", ".", "percentilesHistogram", "(", "this", ".", "percentileHistogram", "==", "null", "?", "parent", ".", "percentileHistogram", ":", "this", ".", "percentileHistogram", ")", ".", "percentiles", "(", "this", ".", "percentiles", "==", "null", "?", "parent", ".", "percentiles", ":", "this", ".", "percentiles", ")", ".", "sla", "(", "this", ".", "sla", "==", "null", "?", "parent", ".", "sla", ":", "this", ".", "sla", ")", ".", "percentilePrecision", "(", "this", ".", "percentilePrecision", "==", "null", "?", "parent", ".", "percentilePrecision", ":", "this", ".", "percentilePrecision", ")", ".", "minimumExpectedValue", "(", "this", ".", "minimumExpectedValue", "==", "null", "?", "parent", ".", "minimumExpectedValue", ":", "this", ".", "minimumExpectedValue", ")", ".", "maximumExpectedValue", "(", "this", ".", "maximumExpectedValue", "==", "null", "?", "parent", ".", "maximumExpectedValue", ":", "this", ".", "maximumExpectedValue", ")", ".", "expiry", "(", "this", ".", "expiry", "==", "null", "?", "parent", ".", "expiry", ":", "this", ".", "expiry", ")", ".", "bufferLength", "(", "this", ".", "bufferLength", "==", "null", "?", "parent", ".", "bufferLength", ":", "this", ".", "bufferLength", ")", ".", "build", "(", ")", ";", "}" ]
Merges two configurations. Any options that are non-null in this configuration take precedence. Any options that are non-null in the parent are used otherwise. @param parent The configuration to merge with. The parent takes lower precedence than this configuration. @return A new, merged, immutable configuration.
[ "Merges", "two", "configurations", ".", "Any", "options", "that", "are", "non", "-", "null", "in", "this", "configuration", "take", "precedence", ".", "Any", "options", "that", "are", "non", "-", "null", "in", "the", "parent", "are", "used", "otherwise", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/DistributionStatisticConfig.java#L82-L94
14,722
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/PostgreSQLDatabaseMetrics.java
PostgreSQLDatabaseMetrics.resettableFunctionalCounter
Double resettableFunctionalCounter(String functionalCounterKey, DoubleSupplier function) { Double result = function.getAsDouble(); Double previousResult = previousValueCacheMap.getOrDefault(functionalCounterKey, 0D); Double beforeResetValue = beforeResetValuesCacheMap.getOrDefault(functionalCounterKey, 0D); Double correctedValue = result + beforeResetValue; if (correctedValue < previousResult) { beforeResetValuesCacheMap.put(functionalCounterKey, previousResult); correctedValue = previousResult + result; } previousValueCacheMap.put(functionalCounterKey, correctedValue); return correctedValue; }
java
Double resettableFunctionalCounter(String functionalCounterKey, DoubleSupplier function) { Double result = function.getAsDouble(); Double previousResult = previousValueCacheMap.getOrDefault(functionalCounterKey, 0D); Double beforeResetValue = beforeResetValuesCacheMap.getOrDefault(functionalCounterKey, 0D); Double correctedValue = result + beforeResetValue; if (correctedValue < previousResult) { beforeResetValuesCacheMap.put(functionalCounterKey, previousResult); correctedValue = previousResult + result; } previousValueCacheMap.put(functionalCounterKey, correctedValue); return correctedValue; }
[ "Double", "resettableFunctionalCounter", "(", "String", "functionalCounterKey", ",", "DoubleSupplier", "function", ")", "{", "Double", "result", "=", "function", ".", "getAsDouble", "(", ")", ";", "Double", "previousResult", "=", "previousValueCacheMap", ".", "getOrDefault", "(", "functionalCounterKey", ",", "0D", ")", ";", "Double", "beforeResetValue", "=", "beforeResetValuesCacheMap", ".", "getOrDefault", "(", "functionalCounterKey", ",", "0D", ")", ";", "Double", "correctedValue", "=", "result", "+", "beforeResetValue", ";", "if", "(", "correctedValue", "<", "previousResult", ")", "{", "beforeResetValuesCacheMap", ".", "put", "(", "functionalCounterKey", ",", "previousResult", ")", ";", "correctedValue", "=", "previousResult", "+", "result", ";", "}", "previousValueCacheMap", ".", "put", "(", "functionalCounterKey", ",", "correctedValue", ")", ";", "return", "correctedValue", ";", "}" ]
Function that makes sure functional counter values survive pg_stat_reset calls.
[ "Function", "that", "makes", "sure", "functional", "counter", "values", "survive", "pg_stat_reset", "calls", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/PostgreSQLDatabaseMetrics.java#L265-L277
14,723
micrometer-metrics/micrometer
implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdTimer.java
StatsdTimer.max
@Override public double max(TimeUnit unit) { return TimeUtils.convert(max.poll(), TimeUnit.MILLISECONDS, unit); }
java
@Override public double max(TimeUnit unit) { return TimeUtils.convert(max.poll(), TimeUnit.MILLISECONDS, unit); }
[ "@", "Override", "public", "double", "max", "(", "TimeUnit", "unit", ")", "{", "return", "TimeUtils", ".", "convert", "(", "max", ".", "poll", "(", ")", ",", "TimeUnit", ".", "MILLISECONDS", ",", "unit", ")", ";", "}" ]
The StatsD agent will likely compute max with a different window, so the value may not match what you see here. This value is not exported to the agent, and is only for diagnostic use.
[ "The", "StatsD", "agent", "will", "likely", "compute", "max", "with", "a", "different", "window", "so", "the", "value", "may", "not", "match", "what", "you", "see", "here", ".", "This", "value", "is", "not", "exported", "to", "the", "agent", "and", "is", "only", "for", "diagnostic", "use", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/implementations/micrometer-registry-statsd/src/main/java/io/micrometer/statsd/StatsdTimer.java#L75-L78
14,724
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/Tags.java
Tags.stream
public Stream<Tag> stream() { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator(), Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.NONNULL | Spliterator.SORTED), false); }
java
public Stream<Tag> stream() { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator(), Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.NONNULL | Spliterator.SORTED), false); }
[ "public", "Stream", "<", "Tag", ">", "stream", "(", ")", "{", "return", "StreamSupport", ".", "stream", "(", "Spliterators", ".", "spliteratorUnknownSize", "(", "iterator", "(", ")", ",", "Spliterator", ".", "ORDERED", "|", "Spliterator", ".", "DISTINCT", "|", "Spliterator", ".", "NONNULL", "|", "Spliterator", ".", "SORTED", ")", ",", "false", ")", ";", "}" ]
Return a stream of the contained tags. @return a tags stream
[ "Return", "a", "stream", "of", "the", "contained", "tags", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/Tags.java#L153-L156
14,725
micrometer-metrics/micrometer
implementations/micrometer-registry-signalfx/src/main/java/io/micrometer/signalfx/SignalFxNamingConvention.java
SignalFxNamingConvention.tagValue
@Override public String tagValue(String value) { String formattedValue = StringEscapeUtils.escapeJson(delegate.tagValue(value)); return StringUtils.truncate(formattedValue, TAG_VALUE_MAX_LENGTH); }
java
@Override public String tagValue(String value) { String formattedValue = StringEscapeUtils.escapeJson(delegate.tagValue(value)); return StringUtils.truncate(formattedValue, TAG_VALUE_MAX_LENGTH); }
[ "@", "Override", "public", "String", "tagValue", "(", "String", "value", ")", "{", "String", "formattedValue", "=", "StringEscapeUtils", ".", "escapeJson", "(", "delegate", ".", "tagValue", "(", "value", ")", ")", ";", "return", "StringUtils", ".", "truncate", "(", "formattedValue", ",", "TAG_VALUE_MAX_LENGTH", ")", ";", "}" ]
Dimension value can be any non-empty UTF-8 string, with a maximum length <= 256 characters.
[ "Dimension", "value", "can", "be", "any", "non", "-", "empty", "UTF", "-", "8", "string", "with", "a", "maximum", "length", "<", "=", "256", "characters", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/implementations/micrometer-registry-signalfx/src/main/java/io/micrometer/signalfx/SignalFxNamingConvention.java#L76-L80
14,726
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/util/StringUtils.java
StringUtils.truncate
public static String truncate(String string, int maxLength) { if (string.length() > maxLength) { return string.substring(0, maxLength); } return string; }
java
public static String truncate(String string, int maxLength) { if (string.length() > maxLength) { return string.substring(0, maxLength); } return string; }
[ "public", "static", "String", "truncate", "(", "String", "string", ",", "int", "maxLength", ")", "{", "if", "(", "string", ".", "length", "(", ")", ">", "maxLength", ")", "{", "return", "string", ".", "substring", "(", "0", ",", "maxLength", ")", ";", "}", "return", "string", ";", "}" ]
Truncate the String to the max length. @param string String to truncate @param maxLength max length @return truncated String
[ "Truncate", "the", "String", "to", "the", "max", "length", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/util/StringUtils.java#L85-L90
14,727
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/binder/kafka/KafkaConsumerMetrics.java
KafkaConsumerMetrics.registerNotificationListener
private void registerNotificationListener(String type, BiConsumer<ObjectName, Tags> perObject) { NotificationListener notificationListener = (notification, handback) -> { MBeanServerNotification mbs = (MBeanServerNotification) notification; ObjectName o = mbs.getMBeanName(); perObject.accept(o, Tags.concat(tags, nameTag(o))); }; NotificationFilter filter = (NotificationFilter) notification -> { if (!MBeanServerNotification.REGISTRATION_NOTIFICATION.equals(notification.getType())) return false; ObjectName obj = ((MBeanServerNotification) notification).getMBeanName(); return obj.getDomain().equals(JMX_DOMAIN) && obj.getKeyProperty("type").equals(type); }; try { mBeanServer.addNotificationListener(MBeanServerDelegate.DELEGATE_NAME, notificationListener, filter, null); notificationListenerCleanUpRunnables.add(() -> { try { mBeanServer.removeNotificationListener(MBeanServerDelegate.DELEGATE_NAME, notificationListener); } catch (InstanceNotFoundException | ListenerNotFoundException ignored) { } }); } catch (InstanceNotFoundException e) { throw new RuntimeException("Error registering Kafka MBean listener", e); } }
java
private void registerNotificationListener(String type, BiConsumer<ObjectName, Tags> perObject) { NotificationListener notificationListener = (notification, handback) -> { MBeanServerNotification mbs = (MBeanServerNotification) notification; ObjectName o = mbs.getMBeanName(); perObject.accept(o, Tags.concat(tags, nameTag(o))); }; NotificationFilter filter = (NotificationFilter) notification -> { if (!MBeanServerNotification.REGISTRATION_NOTIFICATION.equals(notification.getType())) return false; ObjectName obj = ((MBeanServerNotification) notification).getMBeanName(); return obj.getDomain().equals(JMX_DOMAIN) && obj.getKeyProperty("type").equals(type); }; try { mBeanServer.addNotificationListener(MBeanServerDelegate.DELEGATE_NAME, notificationListener, filter, null); notificationListenerCleanUpRunnables.add(() -> { try { mBeanServer.removeNotificationListener(MBeanServerDelegate.DELEGATE_NAME, notificationListener); } catch (InstanceNotFoundException | ListenerNotFoundException ignored) { } }); } catch (InstanceNotFoundException e) { throw new RuntimeException("Error registering Kafka MBean listener", e); } }
[ "private", "void", "registerNotificationListener", "(", "String", "type", ",", "BiConsumer", "<", "ObjectName", ",", "Tags", ">", "perObject", ")", "{", "NotificationListener", "notificationListener", "=", "(", "notification", ",", "handback", ")", "->", "{", "MBeanServerNotification", "mbs", "=", "(", "MBeanServerNotification", ")", "notification", ";", "ObjectName", "o", "=", "mbs", ".", "getMBeanName", "(", ")", ";", "perObject", ".", "accept", "(", "o", ",", "Tags", ".", "concat", "(", "tags", ",", "nameTag", "(", "o", ")", ")", ")", ";", "}", ";", "NotificationFilter", "filter", "=", "(", "NotificationFilter", ")", "notification", "->", "{", "if", "(", "!", "MBeanServerNotification", ".", "REGISTRATION_NOTIFICATION", ".", "equals", "(", "notification", ".", "getType", "(", ")", ")", ")", "return", "false", ";", "ObjectName", "obj", "=", "(", "(", "MBeanServerNotification", ")", "notification", ")", ".", "getMBeanName", "(", ")", ";", "return", "obj", ".", "getDomain", "(", ")", ".", "equals", "(", "JMX_DOMAIN", ")", "&&", "obj", ".", "getKeyProperty", "(", "\"type\"", ")", ".", "equals", "(", "type", ")", ";", "}", ";", "try", "{", "mBeanServer", ".", "addNotificationListener", "(", "MBeanServerDelegate", ".", "DELEGATE_NAME", ",", "notificationListener", ",", "filter", ",", "null", ")", ";", "notificationListenerCleanUpRunnables", ".", "add", "(", "(", ")", "->", "{", "try", "{", "mBeanServer", ".", "removeNotificationListener", "(", "MBeanServerDelegate", ".", "DELEGATE_NAME", ",", "notificationListener", ")", ";", "}", "catch", "(", "InstanceNotFoundException", "|", "ListenerNotFoundException", "ignored", ")", "{", "}", "}", ")", ";", "}", "catch", "(", "InstanceNotFoundException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Error registering Kafka MBean listener\"", ",", "e", ")", ";", "}", "}" ]
This notification listener should remain indefinitely since new Kafka consumers can be added at any time. @param type The Kafka JMX type to listen for. @param perObject Metric registration handler when a new MBean is created.
[ "This", "notification", "listener", "should", "remain", "indefinitely", "since", "new", "Kafka", "consumers", "can", "be", "added", "at", "any", "time", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/kafka/KafkaConsumerMetrics.java#L253-L278
14,728
micrometer-metrics/micrometer
micrometer-spring-legacy/src/main/java/io/micrometer/spring/autoconfigure/MeterValue.java
MeterValue.getValue
public Long getValue(Meter.Type meterType) { if (meterType == Meter.Type.DISTRIBUTION_SUMMARY) { return getDistributionSummaryValue(); } if (meterType == Meter.Type.TIMER) { return getTimerValue(); } return null; }
java
public Long getValue(Meter.Type meterType) { if (meterType == Meter.Type.DISTRIBUTION_SUMMARY) { return getDistributionSummaryValue(); } if (meterType == Meter.Type.TIMER) { return getTimerValue(); } return null; }
[ "public", "Long", "getValue", "(", "Meter", ".", "Type", "meterType", ")", "{", "if", "(", "meterType", "==", "Meter", ".", "Type", ".", "DISTRIBUTION_SUMMARY", ")", "{", "return", "getDistributionSummaryValue", "(", ")", ";", "}", "if", "(", "meterType", "==", "Meter", ".", "Type", ".", "TIMER", ")", "{", "return", "getTimerValue", "(", ")", ";", "}", "return", "null", ";", "}" ]
Return the underlying value of the SLA in form suitable to apply to the given meter type. @param meterType the meter type @return the value or {@code null} if the value cannot be applied
[ "Return", "the", "underlying", "value", "of", "the", "SLA", "in", "form", "suitable", "to", "apply", "to", "the", "given", "meter", "type", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-spring-legacy/src/main/java/io/micrometer/spring/autoconfigure/MeterValue.java#L51-L59
14,729
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/HistogramGauges.java
HistogramGauges.registerWithCommonFormat
public static HistogramGauges registerWithCommonFormat(Timer timer, MeterRegistry registry) { Meter.Id id = timer.getId(); return HistogramGauges.register(timer, registry, percentile -> id.getName() + ".percentile", percentile -> Tags.concat(id.getTagsAsIterable(), "phi", DoubleFormat.decimalOrNan(percentile.percentile())), percentile -> percentile.value(timer.baseTimeUnit()), bucket -> id.getName() + ".histogram", // We look for Long.MAX_VALUE to ensure a sensible tag on our +Inf bucket bucket -> Tags.concat(id.getTagsAsIterable(), "le", bucket.bucket() != Long.MAX_VALUE ? DoubleFormat.decimalOrWhole(bucket.bucket(timer.baseTimeUnit())) : "+Inf")); }
java
public static HistogramGauges registerWithCommonFormat(Timer timer, MeterRegistry registry) { Meter.Id id = timer.getId(); return HistogramGauges.register(timer, registry, percentile -> id.getName() + ".percentile", percentile -> Tags.concat(id.getTagsAsIterable(), "phi", DoubleFormat.decimalOrNan(percentile.percentile())), percentile -> percentile.value(timer.baseTimeUnit()), bucket -> id.getName() + ".histogram", // We look for Long.MAX_VALUE to ensure a sensible tag on our +Inf bucket bucket -> Tags.concat(id.getTagsAsIterable(), "le", bucket.bucket() != Long.MAX_VALUE ? DoubleFormat.decimalOrWhole(bucket.bucket(timer.baseTimeUnit())) : "+Inf")); }
[ "public", "static", "HistogramGauges", "registerWithCommonFormat", "(", "Timer", "timer", ",", "MeterRegistry", "registry", ")", "{", "Meter", ".", "Id", "id", "=", "timer", ".", "getId", "(", ")", ";", "return", "HistogramGauges", ".", "register", "(", "timer", ",", "registry", ",", "percentile", "->", "id", ".", "getName", "(", ")", "+", "\".percentile\"", ",", "percentile", "->", "Tags", ".", "concat", "(", "id", ".", "getTagsAsIterable", "(", ")", ",", "\"phi\"", ",", "DoubleFormat", ".", "decimalOrNan", "(", "percentile", ".", "percentile", "(", ")", ")", ")", ",", "percentile", "->", "percentile", ".", "value", "(", "timer", ".", "baseTimeUnit", "(", ")", ")", ",", "bucket", "->", "id", ".", "getName", "(", ")", "+", "\".histogram\"", ",", "// We look for Long.MAX_VALUE to ensure a sensible tag on our +Inf bucket", "bucket", "->", "Tags", ".", "concat", "(", "id", ".", "getTagsAsIterable", "(", ")", ",", "\"le\"", ",", "bucket", ".", "bucket", "(", ")", "!=", "Long", ".", "MAX_VALUE", "?", "DoubleFormat", ".", "decimalOrWhole", "(", "bucket", ".", "bucket", "(", "timer", ".", "baseTimeUnit", "(", ")", ")", ")", ":", "\"+Inf\"", ")", ")", ";", "}" ]
Register a set of gauges for percentiles and histogram buckets that follow a common format when the monitoring system doesn't have an opinion about the structure of this data. @param timer the timer from which to derive gauges @param registry the registry to register the gauges @return registered {@code HistogramGauges}
[ "Register", "a", "set", "of", "gauges", "for", "percentiles", "and", "histogram", "buckets", "that", "follow", "a", "common", "format", "when", "the", "monitoring", "system", "doesn", "t", "have", "an", "opinion", "about", "the", "structure", "of", "this", "data", "." ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/distribution/HistogramGauges.java#L44-L54
14,730
micrometer-metrics/micrometer
implementations/micrometer-registry-datadog/src/main/java/io/micrometer/datadog/DatadogMeterRegistry.java
DatadogMeterRegistry.postMetricMetadata
private void postMetricMetadata(String metricName, DatadogMetricMetadata metadata) { // already posted the metadata for this metric if (verifiedMetadata.contains(metricName)) return; try { httpClient .put(config.uri() + "/api/v1/metrics/" + URLEncoder.encode(metricName, "UTF-8") + "?api_key=" + config.apiKey() + "&application_key=" + config.applicationKey()) .withJsonContent(metadata.editMetadataBody()) .send() .onSuccess(response -> verifiedMetadata.add(metricName)) .onError(response -> { if (logger.isErrorEnabled()) { String msg = response.body(); // Ignore when the response content contains "metric_name not found". // Metrics that are newly created in Datadog are not immediately available // for metadata modification. We will keep trying this request on subsequent publishes, // where it will eventually succeed. if (!msg.contains("metric_name not found")) { logger.error("failed to send metric metadata to datadog: {}", msg); } } }); } catch (Throwable e) { logger.warn("failed to send metric metadata to datadog", e); } }
java
private void postMetricMetadata(String metricName, DatadogMetricMetadata metadata) { // already posted the metadata for this metric if (verifiedMetadata.contains(metricName)) return; try { httpClient .put(config.uri() + "/api/v1/metrics/" + URLEncoder.encode(metricName, "UTF-8") + "?api_key=" + config.apiKey() + "&application_key=" + config.applicationKey()) .withJsonContent(metadata.editMetadataBody()) .send() .onSuccess(response -> verifiedMetadata.add(metricName)) .onError(response -> { if (logger.isErrorEnabled()) { String msg = response.body(); // Ignore when the response content contains "metric_name not found". // Metrics that are newly created in Datadog are not immediately available // for metadata modification. We will keep trying this request on subsequent publishes, // where it will eventually succeed. if (!msg.contains("metric_name not found")) { logger.error("failed to send metric metadata to datadog: {}", msg); } } }); } catch (Throwable e) { logger.warn("failed to send metric metadata to datadog", e); } }
[ "private", "void", "postMetricMetadata", "(", "String", "metricName", ",", "DatadogMetricMetadata", "metadata", ")", "{", "// already posted the metadata for this metric", "if", "(", "verifiedMetadata", ".", "contains", "(", "metricName", ")", ")", "return", ";", "try", "{", "httpClient", ".", "put", "(", "config", ".", "uri", "(", ")", "+", "\"/api/v1/metrics/\"", "+", "URLEncoder", ".", "encode", "(", "metricName", ",", "\"UTF-8\"", ")", "+", "\"?api_key=\"", "+", "config", ".", "apiKey", "(", ")", "+", "\"&application_key=\"", "+", "config", ".", "applicationKey", "(", ")", ")", ".", "withJsonContent", "(", "metadata", ".", "editMetadataBody", "(", ")", ")", ".", "send", "(", ")", ".", "onSuccess", "(", "response", "->", "verifiedMetadata", ".", "add", "(", "metricName", ")", ")", ".", "onError", "(", "response", "->", "{", "if", "(", "logger", ".", "isErrorEnabled", "(", ")", ")", "{", "String", "msg", "=", "response", ".", "body", "(", ")", ";", "// Ignore when the response content contains \"metric_name not found\".", "// Metrics that are newly created in Datadog are not immediately available", "// for metadata modification. We will keep trying this request on subsequent publishes,", "// where it will eventually succeed.", "if", "(", "!", "msg", ".", "contains", "(", "\"metric_name not found\"", ")", ")", "{", "logger", ".", "error", "(", "\"failed to send metric metadata to datadog: {}\"", ",", "msg", ")", ";", "}", "}", "}", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "logger", ".", "warn", "(", "\"failed to send metric metadata to datadog\"", ",", "e", ")", ";", "}", "}" ]
Set up metric metadata once per time series
[ "Set", "up", "metric", "metadata", "once", "per", "time", "series" ]
127fa3265325cc894f368312ed8890b76a055d88
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/implementations/micrometer-registry-datadog/src/main/java/io/micrometer/datadog/DatadogMeterRegistry.java#L256-L284
14,731
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/ScanCursor.java
ScanCursor.of
public static ScanCursor of(String cursor) { ScanCursor scanCursor = new ScanCursor(); scanCursor.setCursor(cursor); return scanCursor; }
java
public static ScanCursor of(String cursor) { ScanCursor scanCursor = new ScanCursor(); scanCursor.setCursor(cursor); return scanCursor; }
[ "public", "static", "ScanCursor", "of", "(", "String", "cursor", ")", "{", "ScanCursor", "scanCursor", "=", "new", "ScanCursor", "(", ")", ";", "scanCursor", ".", "setCursor", "(", "cursor", ")", ";", "return", "scanCursor", ";", "}" ]
Creates a Scan-Cursor reference. @param cursor the cursor id @return ScanCursor
[ "Creates", "a", "Scan", "-", "Cursor", "reference", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/ScanCursor.java#L95-L99
14,732
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/LettuceFutures.java
LettuceFutures.awaitOrCancel
public static <T> T awaitOrCancel(RedisFuture<T> cmd, long timeout, TimeUnit unit) { try { if (!cmd.await(timeout, unit)) { cmd.cancel(true); throw ExceptionFactory.createTimeoutException(Duration.ofNanos(unit.toNanos(timeout))); } return cmd.get(); } catch (RuntimeException e) { throw e; } catch (ExecutionException e) { if (e.getCause() instanceof RedisCommandExecutionException) { throw ExceptionFactory.createExecutionException(e.getCause().getMessage(), e.getCause()); } if (e.getCause() instanceof RedisCommandTimeoutException) { throw new RedisCommandTimeoutException(e.getCause()); } throw new RedisException(e.getCause()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RedisCommandInterruptedException(e); } catch (Exception e) { throw ExceptionFactory.createExecutionException(null, e); } }
java
public static <T> T awaitOrCancel(RedisFuture<T> cmd, long timeout, TimeUnit unit) { try { if (!cmd.await(timeout, unit)) { cmd.cancel(true); throw ExceptionFactory.createTimeoutException(Duration.ofNanos(unit.toNanos(timeout))); } return cmd.get(); } catch (RuntimeException e) { throw e; } catch (ExecutionException e) { if (e.getCause() instanceof RedisCommandExecutionException) { throw ExceptionFactory.createExecutionException(e.getCause().getMessage(), e.getCause()); } if (e.getCause() instanceof RedisCommandTimeoutException) { throw new RedisCommandTimeoutException(e.getCause()); } throw new RedisException(e.getCause()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RedisCommandInterruptedException(e); } catch (Exception e) { throw ExceptionFactory.createExecutionException(null, e); } }
[ "public", "static", "<", "T", ">", "T", "awaitOrCancel", "(", "RedisFuture", "<", "T", ">", "cmd", ",", "long", "timeout", ",", "TimeUnit", "unit", ")", "{", "try", "{", "if", "(", "!", "cmd", ".", "await", "(", "timeout", ",", "unit", ")", ")", "{", "cmd", ".", "cancel", "(", "true", ")", ";", "throw", "ExceptionFactory", ".", "createTimeoutException", "(", "Duration", ".", "ofNanos", "(", "unit", ".", "toNanos", "(", "timeout", ")", ")", ")", ";", "}", "return", "cmd", ".", "get", "(", ")", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "throw", "e", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "if", "(", "e", ".", "getCause", "(", ")", "instanceof", "RedisCommandExecutionException", ")", "{", "throw", "ExceptionFactory", ".", "createExecutionException", "(", "e", ".", "getCause", "(", ")", ".", "getMessage", "(", ")", ",", "e", ".", "getCause", "(", ")", ")", ";", "}", "if", "(", "e", ".", "getCause", "(", ")", "instanceof", "RedisCommandTimeoutException", ")", "{", "throw", "new", "RedisCommandTimeoutException", "(", "e", ".", "getCause", "(", ")", ")", ";", "}", "throw", "new", "RedisException", "(", "e", ".", "getCause", "(", ")", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "throw", "new", "RedisCommandInterruptedException", "(", "e", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "ExceptionFactory", ".", "createExecutionException", "(", "null", ",", "e", ")", ";", "}", "}" ]
Wait until futures are complete or the supplied timeout is reached. Commands are canceled if the timeout is reached but the command is not finished. @param cmd Command to wait for @param timeout Maximum time to wait for futures to complete @param unit Unit of time for the timeout @param <T> Result type @return Result of the command.
[ "Wait", "until", "futures", "are", "complete", "or", "the", "supplied", "timeout", "is", "reached", ".", "Commands", "are", "canceled", "if", "the", "timeout", "is", "reached", "but", "the", "command", "is", "not", "finished", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/LettuceFutures.java#L109-L137
14,733
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/RedisChannelHandler.java
RedisChannelHandler.registerCloseables
public void registerCloseables(final Collection<Closeable> registry, Closeable... closeables) { registry.addAll(Arrays.asList(closeables)); addListener(resource -> { for (Closeable closeable : closeables) { if (closeable == RedisChannelHandler.this) { continue; } try { if (closeable instanceof AsyncCloseable) { ((AsyncCloseable) closeable).closeAsync(); } else { closeable.close(); } } catch (IOException e) { if (debugEnabled) { logger.debug(e.toString(), e); } } } registry.removeAll(Arrays.asList(closeables)); }); }
java
public void registerCloseables(final Collection<Closeable> registry, Closeable... closeables) { registry.addAll(Arrays.asList(closeables)); addListener(resource -> { for (Closeable closeable : closeables) { if (closeable == RedisChannelHandler.this) { continue; } try { if (closeable instanceof AsyncCloseable) { ((AsyncCloseable) closeable).closeAsync(); } else { closeable.close(); } } catch (IOException e) { if (debugEnabled) { logger.debug(e.toString(), e); } } } registry.removeAll(Arrays.asList(closeables)); }); }
[ "public", "void", "registerCloseables", "(", "final", "Collection", "<", "Closeable", ">", "registry", ",", "Closeable", "...", "closeables", ")", "{", "registry", ".", "addAll", "(", "Arrays", ".", "asList", "(", "closeables", ")", ")", ";", "addListener", "(", "resource", "->", "{", "for", "(", "Closeable", "closeable", ":", "closeables", ")", "{", "if", "(", "closeable", "==", "RedisChannelHandler", ".", "this", ")", "{", "continue", ";", "}", "try", "{", "if", "(", "closeable", "instanceof", "AsyncCloseable", ")", "{", "(", "(", "AsyncCloseable", ")", "closeable", ")", ".", "closeAsync", "(", ")", ";", "}", "else", "{", "closeable", ".", "close", "(", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "if", "(", "debugEnabled", ")", "{", "logger", ".", "debug", "(", "e", ".", "toString", "(", ")", ",", "e", ")", ";", "}", "}", "}", "registry", ".", "removeAll", "(", "Arrays", ".", "asList", "(", "closeables", ")", ")", ";", "}", ")", ";", "}" ]
Register Closeable resources. Internal access only. @param registry registry of closeables @param closeables closeables to register
[ "Register", "Closeable", "resources", ".", "Internal", "access", "only", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/RedisChannelHandler.java#L225-L250
14,734
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/pubsub/StatefulRedisPubSubConnectionImpl.java
StatefulRedisPubSubConnectionImpl.resubscribe
protected List<RedisFuture<Void>> resubscribe() { 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; }
java
protected List<RedisFuture<Void>> resubscribe() { 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; }
[ "protected", "List", "<", "RedisFuture", "<", "Void", ">", ">", "resubscribe", "(", ")", "{", "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", ";", "}" ]
Re-subscribe to all previously subscribed channels and patterns. @return list of the futures of the {@literal subscribe} and {@literal psubscribe} commands.
[ "Re", "-", "subscribe", "to", "all", "previously", "subscribed", "channels", "and", "patterns", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/pubsub/StatefulRedisPubSubConnectionImpl.java#L119-L132
14,735
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/dynamic/support/ParentTypeAwareTypeInformation.java
ParentTypeAwareTypeInformation.mergeMaps
private static Map<TypeVariable<?>, Type> mergeMaps(TypeDiscoverer<?> parent, Map<TypeVariable<?>, Type> map) { Map<TypeVariable<?>, Type> typeVariableMap = new HashMap<TypeVariable<?>, Type>(); typeVariableMap.putAll(map); typeVariableMap.putAll(parent.getTypeVariableMap()); return typeVariableMap; }
java
private static Map<TypeVariable<?>, Type> mergeMaps(TypeDiscoverer<?> parent, Map<TypeVariable<?>, Type> map) { Map<TypeVariable<?>, Type> typeVariableMap = new HashMap<TypeVariable<?>, Type>(); typeVariableMap.putAll(map); typeVariableMap.putAll(parent.getTypeVariableMap()); return typeVariableMap; }
[ "private", "static", "Map", "<", "TypeVariable", "<", "?", ">", ",", "Type", ">", "mergeMaps", "(", "TypeDiscoverer", "<", "?", ">", "parent", ",", "Map", "<", "TypeVariable", "<", "?", ">", ",", "Type", ">", "map", ")", "{", "Map", "<", "TypeVariable", "<", "?", ">", ",", "Type", ">", "typeVariableMap", "=", "new", "HashMap", "<", "TypeVariable", "<", "?", ">", ",", "Type", ">", "(", ")", ";", "typeVariableMap", ".", "putAll", "(", "map", ")", ";", "typeVariableMap", ".", "putAll", "(", "parent", ".", "getTypeVariableMap", "(", ")", ")", ";", "return", "typeVariableMap", ";", "}" ]
Merges the type variable maps of the given parent with the new map. @param parent must not be {@literal null}. @param map must not be {@literal null}. @return
[ "Merges", "the", "type", "variable", "maps", "of", "the", "given", "parent", "with", "the", "new", "map", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/support/ParentTypeAwareTypeInformation.java#L51-L58
14,736
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/ClusterScanSupport.java
ClusterScanSupport.getContinuationCursor
static ScanCursor getContinuationCursor(ScanCursor scanCursor) { if (ScanCursor.INITIAL.equals(scanCursor)) { return scanCursor; } assertClusterScanCursor(scanCursor); ClusterScanCursor clusterScanCursor = (ClusterScanCursor) scanCursor; if (clusterScanCursor.isScanOnCurrentNodeFinished()) { return ScanCursor.INITIAL; } return scanCursor; }
java
static ScanCursor getContinuationCursor(ScanCursor scanCursor) { if (ScanCursor.INITIAL.equals(scanCursor)) { return scanCursor; } assertClusterScanCursor(scanCursor); ClusterScanCursor clusterScanCursor = (ClusterScanCursor) scanCursor; if (clusterScanCursor.isScanOnCurrentNodeFinished()) { return ScanCursor.INITIAL; } return scanCursor; }
[ "static", "ScanCursor", "getContinuationCursor", "(", "ScanCursor", "scanCursor", ")", "{", "if", "(", "ScanCursor", ".", "INITIAL", ".", "equals", "(", "scanCursor", ")", ")", "{", "return", "scanCursor", ";", "}", "assertClusterScanCursor", "(", "scanCursor", ")", ";", "ClusterScanCursor", "clusterScanCursor", "=", "(", "ClusterScanCursor", ")", "scanCursor", ";", "if", "(", "clusterScanCursor", ".", "isScanOnCurrentNodeFinished", "(", ")", ")", "{", "return", "ScanCursor", ".", "INITIAL", ";", "}", "return", "scanCursor", ";", "}" ]
Retrieve the cursor to continue the scan. @param scanCursor can be {@literal null}. @return
[ "Retrieve", "the", "cursor", "to", "continue", "the", "scan", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/ClusterScanSupport.java#L91-L104
14,737
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/ClusterScanSupport.java
ClusterScanSupport.getNodeIds
private static List<String> getNodeIds(StatefulRedisClusterConnection<?, ?> connection) { List<String> nodeIds = new ArrayList<>(); PartitionAccessor partitionAccessor = new PartitionAccessor(connection.getPartitions()); for (RedisClusterNode redisClusterNode : partitionAccessor.getMasters()) { if (connection.getReadFrom() != null) { List<RedisNodeDescription> readCandidates = (List) partitionAccessor.getReadCandidates(redisClusterNode); List<RedisNodeDescription> selection = connection.getReadFrom().select(new ReadFrom.Nodes() { @Override public List<RedisNodeDescription> getNodes() { return readCandidates; } @Override public Iterator<RedisNodeDescription> iterator() { return readCandidates.iterator(); } }); if (!selection.isEmpty()) { RedisClusterNode selectedNode = (RedisClusterNode) selection.get(0); nodeIds.add(selectedNode.getNodeId()); continue; } } nodeIds.add(redisClusterNode.getNodeId()); } return nodeIds; }
java
private static List<String> getNodeIds(StatefulRedisClusterConnection<?, ?> connection) { List<String> nodeIds = new ArrayList<>(); PartitionAccessor partitionAccessor = new PartitionAccessor(connection.getPartitions()); for (RedisClusterNode redisClusterNode : partitionAccessor.getMasters()) { if (connection.getReadFrom() != null) { List<RedisNodeDescription> readCandidates = (List) partitionAccessor.getReadCandidates(redisClusterNode); List<RedisNodeDescription> selection = connection.getReadFrom().select(new ReadFrom.Nodes() { @Override public List<RedisNodeDescription> getNodes() { return readCandidates; } @Override public Iterator<RedisNodeDescription> iterator() { return readCandidates.iterator(); } }); if (!selection.isEmpty()) { RedisClusterNode selectedNode = (RedisClusterNode) selection.get(0); nodeIds.add(selectedNode.getNodeId()); continue; } } nodeIds.add(redisClusterNode.getNodeId()); } return nodeIds; }
[ "private", "static", "List", "<", "String", ">", "getNodeIds", "(", "StatefulRedisClusterConnection", "<", "?", ",", "?", ">", "connection", ")", "{", "List", "<", "String", ">", "nodeIds", "=", "new", "ArrayList", "<>", "(", ")", ";", "PartitionAccessor", "partitionAccessor", "=", "new", "PartitionAccessor", "(", "connection", ".", "getPartitions", "(", ")", ")", ";", "for", "(", "RedisClusterNode", "redisClusterNode", ":", "partitionAccessor", ".", "getMasters", "(", ")", ")", "{", "if", "(", "connection", ".", "getReadFrom", "(", ")", "!=", "null", ")", "{", "List", "<", "RedisNodeDescription", ">", "readCandidates", "=", "(", "List", ")", "partitionAccessor", ".", "getReadCandidates", "(", "redisClusterNode", ")", ";", "List", "<", "RedisNodeDescription", ">", "selection", "=", "connection", ".", "getReadFrom", "(", ")", ".", "select", "(", "new", "ReadFrom", ".", "Nodes", "(", ")", "{", "@", "Override", "public", "List", "<", "RedisNodeDescription", ">", "getNodes", "(", ")", "{", "return", "readCandidates", ";", "}", "@", "Override", "public", "Iterator", "<", "RedisNodeDescription", ">", "iterator", "(", ")", "{", "return", "readCandidates", ".", "iterator", "(", ")", ";", "}", "}", ")", ";", "if", "(", "!", "selection", ".", "isEmpty", "(", ")", ")", "{", "RedisClusterNode", "selectedNode", "=", "(", "RedisClusterNode", ")", "selection", ".", "get", "(", "0", ")", ";", "nodeIds", ".", "add", "(", "selectedNode", ".", "getNodeId", "(", ")", ")", ";", "continue", ";", "}", "}", "nodeIds", ".", "add", "(", "redisClusterNode", ".", "getNodeId", "(", ")", ")", ";", "}", "return", "nodeIds", ";", "}" ]
Retrieve a list of node Ids to use for the SCAN operation. @param connection @return
[ "Retrieve", "a", "list", "of", "node", "Ids", "to", "use", "for", "the", "SCAN", "operation", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/ClusterScanSupport.java#L138-L169
14,738
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/internal/HostAndPort.java
HostAndPort.getHostAndPortFromBracketedHost
private static String[] getHostAndPortFromBracketedHost(String hostPortString) { LettuceAssert.isTrue(hostPortString.charAt(0) == '[', String.format("Bracketed host-port string must start with a bracket: %s", hostPortString)); int colonIndex = hostPortString.indexOf(':'); int closeBracketIndex = hostPortString.lastIndexOf(']'); LettuceAssert.isTrue(colonIndex > -1 && closeBracketIndex > colonIndex, String.format("Invalid bracketed host/port: %s", hostPortString)); String host = hostPortString.substring(1, closeBracketIndex); if (closeBracketIndex + 1 == hostPortString.length()) { return new String[] { host, "" }; } else { LettuceAssert.isTrue(hostPortString.charAt(closeBracketIndex + 1) == ':', "Only a colon may follow a close bracket: " + hostPortString); for (int i = closeBracketIndex + 2; i < hostPortString.length(); ++i) { LettuceAssert.isTrue(Character.isDigit(hostPortString.charAt(i)), String.format("Port must be numeric: %s", hostPortString)); } return new String[] { host, hostPortString.substring(closeBracketIndex + 2) }; } }
java
private static String[] getHostAndPortFromBracketedHost(String hostPortString) { LettuceAssert.isTrue(hostPortString.charAt(0) == '[', String.format("Bracketed host-port string must start with a bracket: %s", hostPortString)); int colonIndex = hostPortString.indexOf(':'); int closeBracketIndex = hostPortString.lastIndexOf(']'); LettuceAssert.isTrue(colonIndex > -1 && closeBracketIndex > colonIndex, String.format("Invalid bracketed host/port: %s", hostPortString)); String host = hostPortString.substring(1, closeBracketIndex); if (closeBracketIndex + 1 == hostPortString.length()) { return new String[] { host, "" }; } else { LettuceAssert.isTrue(hostPortString.charAt(closeBracketIndex + 1) == ':', "Only a colon may follow a close bracket: " + hostPortString); for (int i = closeBracketIndex + 2; i < hostPortString.length(); ++i) { LettuceAssert.isTrue(Character.isDigit(hostPortString.charAt(i)), String.format("Port must be numeric: %s", hostPortString)); } return new String[] { host, hostPortString.substring(closeBracketIndex + 2) }; } }
[ "private", "static", "String", "[", "]", "getHostAndPortFromBracketedHost", "(", "String", "hostPortString", ")", "{", "LettuceAssert", ".", "isTrue", "(", "hostPortString", ".", "charAt", "(", "0", ")", "==", "'", "'", ",", "String", ".", "format", "(", "\"Bracketed host-port string must start with a bracket: %s\"", ",", "hostPortString", ")", ")", ";", "int", "colonIndex", "=", "hostPortString", ".", "indexOf", "(", "'", "'", ")", ";", "int", "closeBracketIndex", "=", "hostPortString", ".", "lastIndexOf", "(", "'", "'", ")", ";", "LettuceAssert", ".", "isTrue", "(", "colonIndex", ">", "-", "1", "&&", "closeBracketIndex", ">", "colonIndex", ",", "String", ".", "format", "(", "\"Invalid bracketed host/port: %s\"", ",", "hostPortString", ")", ")", ";", "String", "host", "=", "hostPortString", ".", "substring", "(", "1", ",", "closeBracketIndex", ")", ";", "if", "(", "closeBracketIndex", "+", "1", "==", "hostPortString", ".", "length", "(", ")", ")", "{", "return", "new", "String", "[", "]", "{", "host", ",", "\"\"", "}", ";", "}", "else", "{", "LettuceAssert", ".", "isTrue", "(", "hostPortString", ".", "charAt", "(", "closeBracketIndex", "+", "1", ")", "==", "'", "'", ",", "\"Only a colon may follow a close bracket: \"", "+", "hostPortString", ")", ";", "for", "(", "int", "i", "=", "closeBracketIndex", "+", "2", ";", "i", "<", "hostPortString", ".", "length", "(", ")", ";", "++", "i", ")", "{", "LettuceAssert", ".", "isTrue", "(", "Character", ".", "isDigit", "(", "hostPortString", ".", "charAt", "(", "i", ")", ")", ",", "String", ".", "format", "(", "\"Port must be numeric: %s\"", ",", "hostPortString", ")", ")", ";", "}", "return", "new", "String", "[", "]", "{", "host", ",", "hostPortString", ".", "substring", "(", "closeBracketIndex", "+", "2", ")", "}", ";", "}", "}" ]
Parses a bracketed host-port string, throwing IllegalArgumentException if parsing fails. @param hostPortString the full bracketed host-port specification. Post might not be specified. @return an array with 2 strings: host and port, in that order. @throws IllegalArgumentException if parsing the bracketed host-port string fails.
[ "Parses", "a", "bracketed", "host", "-", "port", "string", "throwing", "IllegalArgumentException", "if", "parsing", "fails", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/internal/HostAndPort.java#L187-L211
14,739
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/Value.java
Value.getValueOrElseThrow
public <X extends Throwable> V getValueOrElseThrow(Supplier<? extends X> exceptionSupplier) throws X { LettuceAssert.notNull(exceptionSupplier, "Supplier function must not be null"); if (hasValue()) { return value; } throw exceptionSupplier.get(); }
java
public <X extends Throwable> V getValueOrElseThrow(Supplier<? extends X> exceptionSupplier) throws X { LettuceAssert.notNull(exceptionSupplier, "Supplier function must not be null"); if (hasValue()) { return value; } throw exceptionSupplier.get(); }
[ "public", "<", "X", "extends", "Throwable", ">", "V", "getValueOrElseThrow", "(", "Supplier", "<", "?", "extends", "X", ">", "exceptionSupplier", ")", "throws", "X", "{", "LettuceAssert", ".", "notNull", "(", "exceptionSupplier", ",", "\"Supplier function must not be null\"", ")", ";", "if", "(", "hasValue", "(", ")", ")", "{", "return", "value", ";", "}", "throw", "exceptionSupplier", ".", "get", "(", ")", ";", "}" ]
Return the contained value, if present, otherwise throw an exception to be created by the provided supplier. @param <X> Type of the exception to be thrown @param exceptionSupplier The supplier which will return the exception to be thrown, must not be {@literal null}. @return the present value @throws X if there is no value present
[ "Return", "the", "contained", "value", "if", "present", "otherwise", "throw", "an", "exception", "to", "be", "created", "by", "the", "provided", "supplier", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/Value.java#L212-L221
14,740
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/masterslave/MasterSlaveUtils.java
MasterSlaveUtils.isChanged
static boolean isChanged(Collection<RedisNodeDescription> o1, Collection<RedisNodeDescription> o2) { if (o1.size() != o2.size()) { return true; } for (RedisNodeDescription base : o2) { if (!essentiallyEqualsTo(base, findNodeByUri(o1, base.getUri()))) { return true; } } return false; }
java
static boolean isChanged(Collection<RedisNodeDescription> o1, Collection<RedisNodeDescription> o2) { if (o1.size() != o2.size()) { return true; } for (RedisNodeDescription base : o2) { if (!essentiallyEqualsTo(base, findNodeByUri(o1, base.getUri()))) { return true; } } return false; }
[ "static", "boolean", "isChanged", "(", "Collection", "<", "RedisNodeDescription", ">", "o1", ",", "Collection", "<", "RedisNodeDescription", ">", "o2", ")", "{", "if", "(", "o1", ".", "size", "(", ")", "!=", "o2", ".", "size", "(", ")", ")", "{", "return", "true", ";", "}", "for", "(", "RedisNodeDescription", "base", ":", "o2", ")", "{", "if", "(", "!", "essentiallyEqualsTo", "(", "base", ",", "findNodeByUri", "(", "o1", ",", "base", ".", "getUri", "(", ")", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if properties changed. @param o1 the first object to be compared. @param o2 the second object to be compared. @return {@literal true} if {@code MASTER} or {@code SLAVE} flags changed or the URIs are changed.
[ "Check", "if", "properties", "changed", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/masterslave/MasterSlaveUtils.java#L38-L51
14,741
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/masterslave/SentinelTopologyRefresh.java
SentinelTopologyRefresh.potentiallyConnectSentinels
private List<ConnectionFuture<StatefulRedisPubSubConnection<String, String>>> potentiallyConnectSentinels() { List<ConnectionFuture<StatefulRedisPubSubConnection<String, String>>> connectionFutures = new ArrayList<>(); for (RedisURI sentinel : sentinels) { if (pubSubConnections.containsKey(sentinel)) { continue; } ConnectionFuture<StatefulRedisPubSubConnection<String, String>> future = redisClient.connectPubSubAsync(CODEC, sentinel); pubSubConnections.put(sentinel, future); future.whenComplete((connection, throwable) -> { if (throwable != null || closed) { pubSubConnections.remove(sentinel); } if (closed) { connection.closeAsync(); } }); connectionFutures.add(future); } return connectionFutures; }
java
private List<ConnectionFuture<StatefulRedisPubSubConnection<String, String>>> potentiallyConnectSentinels() { List<ConnectionFuture<StatefulRedisPubSubConnection<String, String>>> connectionFutures = new ArrayList<>(); for (RedisURI sentinel : sentinels) { if (pubSubConnections.containsKey(sentinel)) { continue; } ConnectionFuture<StatefulRedisPubSubConnection<String, String>> future = redisClient.connectPubSubAsync(CODEC, sentinel); pubSubConnections.put(sentinel, future); future.whenComplete((connection, throwable) -> { if (throwable != null || closed) { pubSubConnections.remove(sentinel); } if (closed) { connection.closeAsync(); } }); connectionFutures.add(future); } return connectionFutures; }
[ "private", "List", "<", "ConnectionFuture", "<", "StatefulRedisPubSubConnection", "<", "String", ",", "String", ">", ">", ">", "potentiallyConnectSentinels", "(", ")", "{", "List", "<", "ConnectionFuture", "<", "StatefulRedisPubSubConnection", "<", "String", ",", "String", ">", ">", ">", "connectionFutures", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "RedisURI", "sentinel", ":", "sentinels", ")", "{", "if", "(", "pubSubConnections", ".", "containsKey", "(", "sentinel", ")", ")", "{", "continue", ";", "}", "ConnectionFuture", "<", "StatefulRedisPubSubConnection", "<", "String", ",", "String", ">", ">", "future", "=", "redisClient", ".", "connectPubSubAsync", "(", "CODEC", ",", "sentinel", ")", ";", "pubSubConnections", ".", "put", "(", "sentinel", ",", "future", ")", ";", "future", ".", "whenComplete", "(", "(", "connection", ",", "throwable", ")", "->", "{", "if", "(", "throwable", "!=", "null", "||", "closed", ")", "{", "pubSubConnections", ".", "remove", "(", "sentinel", ")", ";", "}", "if", "(", "closed", ")", "{", "connection", ".", "closeAsync", "(", ")", ";", "}", "}", ")", ";", "connectionFutures", ".", "add", "(", "future", ")", ";", "}", "return", "connectionFutures", ";", "}" ]
Inspect whether additional Sentinel connections are required based on the which Sentinels are currently connected. @return list of futures that are notified with the connection progress.
[ "Inspect", "whether", "additional", "Sentinel", "connections", "are", "required", "based", "on", "the", "which", "Sentinels", "are", "currently", "connected", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/masterslave/SentinelTopologyRefresh.java#L174-L202
14,742
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/dynamic/ReactiveTypes.java
ReactiveTypes.getNoValueTypes
public static Collection<Class<?>> getNoValueTypes() { return REACTIVE_WRAPPERS.entrySet().stream().filter(entry -> entry.getValue().isNoValue()).map(Entry::getKey) .collect(Collectors.toList()); }
java
public static Collection<Class<?>> getNoValueTypes() { return REACTIVE_WRAPPERS.entrySet().stream().filter(entry -> entry.getValue().isNoValue()).map(Entry::getKey) .collect(Collectors.toList()); }
[ "public", "static", "Collection", "<", "Class", "<", "?", ">", ">", "getNoValueTypes", "(", ")", "{", "return", "REACTIVE_WRAPPERS", ".", "entrySet", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "entry", "->", "entry", ".", "getValue", "(", ")", ".", "isNoValue", "(", ")", ")", ".", "map", "(", "Entry", "::", "getKey", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}" ]
Returns a collection of No-Value wrapper types. @return a collection of No-Value wrapper types.
[ "Returns", "a", "collection", "of", "No", "-", "Value", "wrapper", "types", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/ReactiveTypes.java#L184-L187
14,743
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/dynamic/ReactiveTypes.java
ReactiveTypes.getSingleValueTypes
public static Collection<Class<?>> getSingleValueTypes() { return REACTIVE_WRAPPERS.entrySet().stream().filter(entry -> !entry.getValue().isMultiValue()).map(Entry::getKey) .collect(Collectors.toList()); }
java
public static Collection<Class<?>> getSingleValueTypes() { return REACTIVE_WRAPPERS.entrySet().stream().filter(entry -> !entry.getValue().isMultiValue()).map(Entry::getKey) .collect(Collectors.toList()); }
[ "public", "static", "Collection", "<", "Class", "<", "?", ">", ">", "getSingleValueTypes", "(", ")", "{", "return", "REACTIVE_WRAPPERS", ".", "entrySet", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "entry", "->", "!", "entry", ".", "getValue", "(", ")", ".", "isMultiValue", "(", ")", ")", ".", "map", "(", "Entry", "::", "getKey", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}" ]
Returns a collection of Single-Value wrapper types. @return a collection of Single-Value wrapper types.
[ "Returns", "a", "collection", "of", "Single", "-", "Value", "wrapper", "types", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/ReactiveTypes.java#L194-L197
14,744
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/CommandWrapper.java
CommandWrapper.unwrap
@SuppressWarnings("unchecked") public static <K, V, T> RedisCommand<K, V, T> unwrap(RedisCommand<K, V, T> wrapped) { RedisCommand<K, V, T> result = wrapped; while (result instanceof DecoratedCommand<?, ?, ?>) { result = ((DecoratedCommand<K, V, T>) result).getDelegate(); } return result; }
java
@SuppressWarnings("unchecked") public static <K, V, T> RedisCommand<K, V, T> unwrap(RedisCommand<K, V, T> wrapped) { RedisCommand<K, V, T> result = wrapped; while (result instanceof DecoratedCommand<?, ?, ?>) { result = ((DecoratedCommand<K, V, T>) result).getDelegate(); } return result; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "K", ",", "V", ",", "T", ">", "RedisCommand", "<", "K", ",", "V", ",", "T", ">", "unwrap", "(", "RedisCommand", "<", "K", ",", "V", ",", "T", ">", "wrapped", ")", "{", "RedisCommand", "<", "K", ",", "V", ",", "T", ">", "result", "=", "wrapped", ";", "while", "(", "result", "instanceof", "DecoratedCommand", "<", "?", ",", "?", ",", "?", ">", ")", "{", "result", "=", "(", "(", "DecoratedCommand", "<", "K", ",", "V", ",", "T", ">", ")", "result", ")", ".", "getDelegate", "(", ")", ";", "}", "return", "result", ";", "}" ]
Unwrap a wrapped command. @param wrapped @return
[ "Unwrap", "a", "wrapped", "command", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/CommandWrapper.java#L210-L219
14,745
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/dynamic/support/TypeWrapper.java
TypeWrapper.unwrap
@SuppressWarnings("unchecked") public static <T extends Type> T unwrap(T type) { Type unwrapped = type; while (unwrapped instanceof SerializableTypeProxy) { unwrapped = ((SerializableTypeProxy) type).getTypeProvider().getType(); } return (T) unwrapped; }
java
@SuppressWarnings("unchecked") public static <T extends Type> T unwrap(T type) { Type unwrapped = type; while (unwrapped instanceof SerializableTypeProxy) { unwrapped = ((SerializableTypeProxy) type).getTypeProvider().getType(); } return (T) unwrapped; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", "extends", "Type", ">", "T", "unwrap", "(", "T", "type", ")", "{", "Type", "unwrapped", "=", "type", ";", "while", "(", "unwrapped", "instanceof", "SerializableTypeProxy", ")", "{", "unwrapped", "=", "(", "(", "SerializableTypeProxy", ")", "type", ")", ".", "getTypeProvider", "(", ")", ".", "getType", "(", ")", ";", "}", "return", "(", "T", ")", "unwrapped", ";", "}" ]
Unwrap the given type, effectively returning the original non-serializable type. @param type the type to unwrap @return the original non-serializable type
[ "Unwrap", "the", "given", "type", "effectively", "returning", "the", "original", "non", "-", "serializable", "type", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/support/TypeWrapper.java#L116-L123
14,746
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/RedisURI.java
RedisURI.create
public static RedisURI create(String host, int port) { return Builder.redis(host, port).build(); }
java
public static RedisURI create(String host, int port) { return Builder.redis(host, port).build(); }
[ "public", "static", "RedisURI", "create", "(", "String", "host", ",", "int", "port", ")", "{", "return", "Builder", ".", "redis", "(", "host", ",", "port", ")", ".", "build", "(", ")", ";", "}" ]
Create a Redis URI from host and port. @param host the host @param port the port @return An instance of {@link RedisURI} containing details from the {@code host} and {@code port}.
[ "Create", "a", "Redis", "URI", "from", "host", "and", "port", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/RedisURI.java#L236-L238
14,747
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/RedisURI.java
RedisURI.create
public static RedisURI create(String uri) { LettuceAssert.notEmpty(uri, "URI must not be empty"); return create(URI.create(uri)); }
java
public static RedisURI create(String uri) { LettuceAssert.notEmpty(uri, "URI must not be empty"); return create(URI.create(uri)); }
[ "public", "static", "RedisURI", "create", "(", "String", "uri", ")", "{", "LettuceAssert", ".", "notEmpty", "(", "uri", ",", "\"URI must not be empty\"", ")", ";", "return", "create", "(", "URI", ".", "create", "(", "uri", ")", ")", ";", "}" ]
Create a Redis URI from an URI string. The uri must follow conventions of {@link java.net.URI} @param uri The URI string. @return An instance of {@link RedisURI} containing details from the URI.
[ "Create", "a", "Redis", "URI", "from", "an", "URI", "string", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/RedisURI.java#L248-L251
14,748
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/RedisURI.java
RedisURI.setPassword
public void setPassword(CharSequence password) { LettuceAssert.notNull(password, "Password must not be null"); this.password = password.toString().toCharArray(); }
java
public void setPassword(CharSequence password) { LettuceAssert.notNull(password, "Password must not be null"); this.password = password.toString().toCharArray(); }
[ "public", "void", "setPassword", "(", "CharSequence", "password", ")", "{", "LettuceAssert", ".", "notNull", "(", "password", ",", "\"Password must not be null\"", ")", ";", "this", ".", "password", "=", "password", ".", "toString", "(", ")", ".", "toCharArray", "(", ")", ";", "}" ]
Sets the password. Use empty string to skip authentication. @param password the password, must not be {@literal null}. @since 5.2
[ "Sets", "the", "password", ".", "Use", "empty", "string", "to", "skip", "authentication", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/RedisURI.java#L361-L365
14,749
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/RedisURI.java
RedisURI.setPassword
public void setPassword(char[] password) { LettuceAssert.notNull(password, "Password must not be null"); this.password = Arrays.copyOf(password, password.length); }
java
public void setPassword(char[] password) { LettuceAssert.notNull(password, "Password must not be null"); this.password = Arrays.copyOf(password, password.length); }
[ "public", "void", "setPassword", "(", "char", "[", "]", "password", ")", "{", "LettuceAssert", ".", "notNull", "(", "password", ",", "\"Password must not be null\"", ")", ";", "this", ".", "password", "=", "Arrays", ".", "copyOf", "(", "password", ",", "password", ".", "length", ")", ";", "}" ]
Sets the password. Use empty char array to skip authentication. @param password the password, must not be {@literal null}. @since 4.4
[ "Sets", "the", "password", ".", "Use", "empty", "char", "array", "to", "skip", "authentication", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/RedisURI.java#L373-L377
14,750
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/RedisURI.java
RedisURI.setTimeout
public void setTimeout(Duration timeout) { LettuceAssert.notNull(timeout, "Timeout must not be null"); LettuceAssert.isTrue(!timeout.isNegative(), "Timeout must be greater or equal 0"); this.timeout = timeout; }
java
public void setTimeout(Duration timeout) { LettuceAssert.notNull(timeout, "Timeout must not be null"); LettuceAssert.isTrue(!timeout.isNegative(), "Timeout must be greater or equal 0"); this.timeout = timeout; }
[ "public", "void", "setTimeout", "(", "Duration", "timeout", ")", "{", "LettuceAssert", ".", "notNull", "(", "timeout", ",", "\"Timeout must not be null\"", ")", ";", "LettuceAssert", ".", "isTrue", "(", "!", "timeout", ".", "isNegative", "(", ")", ",", "\"Timeout must be greater or equal 0\"", ")", ";", "this", ".", "timeout", "=", "timeout", ";", "}" ]
Sets the command timeout for synchronous command execution. @param timeout the command timeout for synchronous command execution. @since 5.0
[ "Sets", "the", "command", "timeout", "for", "synchronous", "command", "execution", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/RedisURI.java#L395-L401
14,751
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/RedisURI.java
RedisURI.toURI
public URI toURI() { String scheme = getScheme(); String authority = getAuthority(scheme); String queryString = getQueryString(); String uri = scheme + "://" + authority; if (!queryString.isEmpty()) { uri += "?" + queryString; } return URI.create(uri); }
java
public URI toURI() { String scheme = getScheme(); String authority = getAuthority(scheme); String queryString = getQueryString(); String uri = scheme + "://" + authority; if (!queryString.isEmpty()) { uri += "?" + queryString; } return URI.create(uri); }
[ "public", "URI", "toURI", "(", ")", "{", "String", "scheme", "=", "getScheme", "(", ")", ";", "String", "authority", "=", "getAuthority", "(", "scheme", ")", ";", "String", "queryString", "=", "getQueryString", "(", ")", ";", "String", "uri", "=", "scheme", "+", "\"://\"", "+", "authority", ";", "if", "(", "!", "queryString", ".", "isEmpty", "(", ")", ")", "{", "uri", "+=", "\"?\"", "+", "queryString", ";", "}", "return", "URI", ".", "create", "(", "uri", ")", ";", "}" ]
Creates an URI based on the RedisURI. @return URI based on the RedisURI
[ "Creates", "an", "URI", "based", "on", "the", "RedisURI", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/RedisURI.java#L511-L522
14,752
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/dynamic/support/ResolvableType.java
ResolvableType.isUnresolvableTypeVariable
private boolean isUnresolvableTypeVariable() { if (this.type instanceof TypeVariable) { if (this.variableResolver == null) { return true; } TypeVariable<?> variable = (TypeVariable<?>) this.type; ResolvableType resolved = this.variableResolver.resolveVariable(variable); if (resolved == null || resolved.isUnresolvableTypeVariable()) { return true; } } return false; }
java
private boolean isUnresolvableTypeVariable() { if (this.type instanceof TypeVariable) { if (this.variableResolver == null) { return true; } TypeVariable<?> variable = (TypeVariable<?>) this.type; ResolvableType resolved = this.variableResolver.resolveVariable(variable); if (resolved == null || resolved.isUnresolvableTypeVariable()) { return true; } } return false; }
[ "private", "boolean", "isUnresolvableTypeVariable", "(", ")", "{", "if", "(", "this", ".", "type", "instanceof", "TypeVariable", ")", "{", "if", "(", "this", ".", "variableResolver", "==", "null", ")", "{", "return", "true", ";", "}", "TypeVariable", "<", "?", ">", "variable", "=", "(", "TypeVariable", "<", "?", ">", ")", "this", ".", "type", ";", "ResolvableType", "resolved", "=", "this", ".", "variableResolver", ".", "resolveVariable", "(", "variable", ")", ";", "if", "(", "resolved", "==", "null", "||", "resolved", ".", "isUnresolvableTypeVariable", "(", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determine whether the underlying type is a type variable that cannot be resolved through the associated variable resolver.
[ "Determine", "whether", "the", "underlying", "type", "is", "a", "type", "variable", "that", "cannot", "be", "resolved", "through", "the", "associated", "variable", "resolver", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/support/ResolvableType.java#L456-L468
14,753
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/RedisClusterClient.java
RedisClusterClient.connectClusterPubSubAsync
private <K, V> CompletableFuture<StatefulRedisClusterPubSubConnection<K, V>> connectClusterPubSubAsync( RedisCodec<K, V> codec) { if (partitions == null) { return Futures.failed(new IllegalStateException( "Partitions not initialized. Initialize via RedisClusterClient.getPartitions().")); } activateTopologyRefreshIfNeeded(); logger.debug("connectClusterPubSub(" + initialUris + ")"); Mono<SocketAddress> socketAddressSupplier = getSocketAddressSupplier(TopologyComparators::sortByClientCount); PubSubClusterEndpoint<K, V> endpoint = new PubSubClusterEndpoint<K, V>(clientOptions, clientResources); RedisChannelWriter writer = endpoint; if (CommandExpiryWriter.isSupported(clientOptions)) { writer = new CommandExpiryWriter(writer, clientOptions, clientResources); } ClusterDistributionChannelWriter clusterWriter = new ClusterDistributionChannelWriter(clientOptions, writer, clusterTopologyRefreshScheduler); StatefulRedisClusterPubSubConnectionImpl<K, V> connection = new StatefulRedisClusterPubSubConnectionImpl<>(endpoint, clusterWriter, codec, timeout); ClusterPubSubConnectionProvider<K, V> pooledClusterConnectionProvider = new ClusterPubSubConnectionProvider<>(this, clusterWriter, codec, connection.getUpstreamListener(), clusterTopologyRefreshScheduler); clusterWriter.setClusterConnectionProvider(pooledClusterConnectionProvider); connection.setPartitions(partitions); Supplier<CommandHandler> commandHandlerSupplier = () -> new PubSubCommandHandler<>(clientOptions, clientResources, codec, endpoint); Mono<StatefulRedisClusterPubSubConnectionImpl<K, V>> connectionMono = Mono.defer(() -> connect(socketAddressSupplier, codec, endpoint, connection, commandHandlerSupplier)); for (int i = 1; i < getConnectionAttempts(); i++) { connectionMono = connectionMono.onErrorResume(t -> connect(socketAddressSupplier, codec, endpoint, connection, commandHandlerSupplier)); } return connectionMono .flatMap(c -> c.reactive().command().collectList() // .map(CommandDetailParser::parse) // .doOnNext(detail -> c.setState(new RedisState(detail))) .doOnError(e -> c.setState(new RedisState(Collections.emptyList()))).then(Mono.just(c)) .onErrorResume(RedisCommandExecutionException.class, e -> Mono.just(c))) .doOnNext( c -> connection.registerCloseables(closeableResources, clusterWriter, pooledClusterConnectionProvider)) .map(it -> (StatefulRedisClusterPubSubConnection<K, V>) it).toFuture(); }
java
private <K, V> CompletableFuture<StatefulRedisClusterPubSubConnection<K, V>> connectClusterPubSubAsync( RedisCodec<K, V> codec) { if (partitions == null) { return Futures.failed(new IllegalStateException( "Partitions not initialized. Initialize via RedisClusterClient.getPartitions().")); } activateTopologyRefreshIfNeeded(); logger.debug("connectClusterPubSub(" + initialUris + ")"); Mono<SocketAddress> socketAddressSupplier = getSocketAddressSupplier(TopologyComparators::sortByClientCount); PubSubClusterEndpoint<K, V> endpoint = new PubSubClusterEndpoint<K, V>(clientOptions, clientResources); RedisChannelWriter writer = endpoint; if (CommandExpiryWriter.isSupported(clientOptions)) { writer = new CommandExpiryWriter(writer, clientOptions, clientResources); } ClusterDistributionChannelWriter clusterWriter = new ClusterDistributionChannelWriter(clientOptions, writer, clusterTopologyRefreshScheduler); StatefulRedisClusterPubSubConnectionImpl<K, V> connection = new StatefulRedisClusterPubSubConnectionImpl<>(endpoint, clusterWriter, codec, timeout); ClusterPubSubConnectionProvider<K, V> pooledClusterConnectionProvider = new ClusterPubSubConnectionProvider<>(this, clusterWriter, codec, connection.getUpstreamListener(), clusterTopologyRefreshScheduler); clusterWriter.setClusterConnectionProvider(pooledClusterConnectionProvider); connection.setPartitions(partitions); Supplier<CommandHandler> commandHandlerSupplier = () -> new PubSubCommandHandler<>(clientOptions, clientResources, codec, endpoint); Mono<StatefulRedisClusterPubSubConnectionImpl<K, V>> connectionMono = Mono.defer(() -> connect(socketAddressSupplier, codec, endpoint, connection, commandHandlerSupplier)); for (int i = 1; i < getConnectionAttempts(); i++) { connectionMono = connectionMono.onErrorResume(t -> connect(socketAddressSupplier, codec, endpoint, connection, commandHandlerSupplier)); } return connectionMono .flatMap(c -> c.reactive().command().collectList() // .map(CommandDetailParser::parse) // .doOnNext(detail -> c.setState(new RedisState(detail))) .doOnError(e -> c.setState(new RedisState(Collections.emptyList()))).then(Mono.just(c)) .onErrorResume(RedisCommandExecutionException.class, e -> Mono.just(c))) .doOnNext( c -> connection.registerCloseables(closeableResources, clusterWriter, pooledClusterConnectionProvider)) .map(it -> (StatefulRedisClusterPubSubConnection<K, V>) it).toFuture(); }
[ "private", "<", "K", ",", "V", ">", "CompletableFuture", "<", "StatefulRedisClusterPubSubConnection", "<", "K", ",", "V", ">", ">", "connectClusterPubSubAsync", "(", "RedisCodec", "<", "K", ",", "V", ">", "codec", ")", "{", "if", "(", "partitions", "==", "null", ")", "{", "return", "Futures", ".", "failed", "(", "new", "IllegalStateException", "(", "\"Partitions not initialized. Initialize via RedisClusterClient.getPartitions().\"", ")", ")", ";", "}", "activateTopologyRefreshIfNeeded", "(", ")", ";", "logger", ".", "debug", "(", "\"connectClusterPubSub(\"", "+", "initialUris", "+", "\")\"", ")", ";", "Mono", "<", "SocketAddress", ">", "socketAddressSupplier", "=", "getSocketAddressSupplier", "(", "TopologyComparators", "::", "sortByClientCount", ")", ";", "PubSubClusterEndpoint", "<", "K", ",", "V", ">", "endpoint", "=", "new", "PubSubClusterEndpoint", "<", "K", ",", "V", ">", "(", "clientOptions", ",", "clientResources", ")", ";", "RedisChannelWriter", "writer", "=", "endpoint", ";", "if", "(", "CommandExpiryWriter", ".", "isSupported", "(", "clientOptions", ")", ")", "{", "writer", "=", "new", "CommandExpiryWriter", "(", "writer", ",", "clientOptions", ",", "clientResources", ")", ";", "}", "ClusterDistributionChannelWriter", "clusterWriter", "=", "new", "ClusterDistributionChannelWriter", "(", "clientOptions", ",", "writer", ",", "clusterTopologyRefreshScheduler", ")", ";", "StatefulRedisClusterPubSubConnectionImpl", "<", "K", ",", "V", ">", "connection", "=", "new", "StatefulRedisClusterPubSubConnectionImpl", "<>", "(", "endpoint", ",", "clusterWriter", ",", "codec", ",", "timeout", ")", ";", "ClusterPubSubConnectionProvider", "<", "K", ",", "V", ">", "pooledClusterConnectionProvider", "=", "new", "ClusterPubSubConnectionProvider", "<>", "(", "this", ",", "clusterWriter", ",", "codec", ",", "connection", ".", "getUpstreamListener", "(", ")", ",", "clusterTopologyRefreshScheduler", ")", ";", "clusterWriter", ".", "setClusterConnectionProvider", "(", "pooledClusterConnectionProvider", ")", ";", "connection", ".", "setPartitions", "(", "partitions", ")", ";", "Supplier", "<", "CommandHandler", ">", "commandHandlerSupplier", "=", "(", ")", "->", "new", "PubSubCommandHandler", "<>", "(", "clientOptions", ",", "clientResources", ",", "codec", ",", "endpoint", ")", ";", "Mono", "<", "StatefulRedisClusterPubSubConnectionImpl", "<", "K", ",", "V", ">", ">", "connectionMono", "=", "Mono", ".", "defer", "(", "(", ")", "->", "connect", "(", "socketAddressSupplier", ",", "codec", ",", "endpoint", ",", "connection", ",", "commandHandlerSupplier", ")", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "getConnectionAttempts", "(", ")", ";", "i", "++", ")", "{", "connectionMono", "=", "connectionMono", ".", "onErrorResume", "(", "t", "->", "connect", "(", "socketAddressSupplier", ",", "codec", ",", "endpoint", ",", "connection", ",", "commandHandlerSupplier", ")", ")", ";", "}", "return", "connectionMono", ".", "flatMap", "(", "c", "->", "c", ".", "reactive", "(", ")", ".", "command", "(", ")", ".", "collectList", "(", ")", "//", ".", "map", "(", "CommandDetailParser", "::", "parse", ")", "//", ".", "doOnNext", "(", "detail", "->", "c", ".", "setState", "(", "new", "RedisState", "(", "detail", ")", ")", ")", ".", "doOnError", "(", "e", "->", "c", ".", "setState", "(", "new", "RedisState", "(", "Collections", ".", "emptyList", "(", ")", ")", ")", ")", ".", "then", "(", "Mono", ".", "just", "(", "c", ")", ")", ".", "onErrorResume", "(", "RedisCommandExecutionException", ".", "class", ",", "e", "->", "Mono", ".", "just", "(", "c", ")", ")", ")", ".", "doOnNext", "(", "c", "->", "connection", ".", "registerCloseables", "(", "closeableResources", ",", "clusterWriter", ",", "pooledClusterConnectionProvider", ")", ")", ".", "map", "(", "it", "->", "(", "StatefulRedisClusterPubSubConnection", "<", "K", ",", "V", ">", ")", "it", ")", ".", "toFuture", "(", ")", ";", "}" ]
Create a clustered connection with command distributor. @param codec Use this codec to encode/decode keys and values, must not be {@literal null} @param <K> Key type @param <V> Value type @return a new connection
[ "Create", "a", "clustered", "connection", "with", "command", "distributor", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/RedisClusterClient.java#L632-L685
14,754
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/RedisClusterClient.java
RedisClusterClient.reloadPartitions
public void reloadPartitions() { if (partitions == null) { initializePartitions(); partitions.updateCache(); } else { Partitions loadedPartitions = loadPartitions(); if (TopologyComparators.isChanged(getPartitions(), loadedPartitions)) { logger.debug("Using a new cluster topology"); List<RedisClusterNode> before = new ArrayList<RedisClusterNode>(getPartitions()); List<RedisClusterNode> after = new ArrayList<RedisClusterNode>(loadedPartitions); getResources().eventBus().publish(new ClusterTopologyChangedEvent(before, after)); } this.partitions.reload(loadedPartitions.getPartitions()); } updatePartitionsInConnections(); }
java
public void reloadPartitions() { if (partitions == null) { initializePartitions(); partitions.updateCache(); } else { Partitions loadedPartitions = loadPartitions(); if (TopologyComparators.isChanged(getPartitions(), loadedPartitions)) { logger.debug("Using a new cluster topology"); List<RedisClusterNode> before = new ArrayList<RedisClusterNode>(getPartitions()); List<RedisClusterNode> after = new ArrayList<RedisClusterNode>(loadedPartitions); getResources().eventBus().publish(new ClusterTopologyChangedEvent(before, after)); } this.partitions.reload(loadedPartitions.getPartitions()); } updatePartitionsInConnections(); }
[ "public", "void", "reloadPartitions", "(", ")", "{", "if", "(", "partitions", "==", "null", ")", "{", "initializePartitions", "(", ")", ";", "partitions", ".", "updateCache", "(", ")", ";", "}", "else", "{", "Partitions", "loadedPartitions", "=", "loadPartitions", "(", ")", ";", "if", "(", "TopologyComparators", ".", "isChanged", "(", "getPartitions", "(", ")", ",", "loadedPartitions", ")", ")", "{", "logger", ".", "debug", "(", "\"Using a new cluster topology\"", ")", ";", "List", "<", "RedisClusterNode", ">", "before", "=", "new", "ArrayList", "<", "RedisClusterNode", ">", "(", "getPartitions", "(", ")", ")", ";", "List", "<", "RedisClusterNode", ">", "after", "=", "new", "ArrayList", "<", "RedisClusterNode", ">", "(", "loadedPartitions", ")", ";", "getResources", "(", ")", ".", "eventBus", "(", ")", ".", "publish", "(", "new", "ClusterTopologyChangedEvent", "(", "before", ",", "after", ")", ")", ";", "}", "this", ".", "partitions", ".", "reload", "(", "loadedPartitions", ".", "getPartitions", "(", ")", ")", ";", "}", "updatePartitionsInConnections", "(", ")", ";", "}" ]
Reload partitions and re-initialize the distribution table.
[ "Reload", "partitions", "and", "re", "-", "initialize", "the", "distribution", "table", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/RedisClusterClient.java#L783-L805
14,755
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/dynamic/RedisCommandFactory.java
RedisCommandFactory.getCommands
public <T extends Commands> T getCommands(Class<T> commandInterface) { LettuceAssert.notNull(commandInterface, "Redis Command Interface must not be null"); RedisCommandsMetadata metadata = new DefaultRedisCommandsMetadata(commandInterface); InvocationProxyFactory factory = new InvocationProxyFactory(); factory.addInterface(commandInterface); BatchAwareCommandLookupStrategy lookupStrategy = new BatchAwareCommandLookupStrategy( new CompositeCommandLookupStrategy(), metadata); factory.addInterceptor(new DefaultMethodInvokingInterceptor()); factory.addInterceptor(new CommandFactoryExecutorMethodInterceptor(metadata, lookupStrategy)); return factory.createProxy(commandInterface.getClassLoader()); }
java
public <T extends Commands> T getCommands(Class<T> commandInterface) { LettuceAssert.notNull(commandInterface, "Redis Command Interface must not be null"); RedisCommandsMetadata metadata = new DefaultRedisCommandsMetadata(commandInterface); InvocationProxyFactory factory = new InvocationProxyFactory(); factory.addInterface(commandInterface); BatchAwareCommandLookupStrategy lookupStrategy = new BatchAwareCommandLookupStrategy( new CompositeCommandLookupStrategy(), metadata); factory.addInterceptor(new DefaultMethodInvokingInterceptor()); factory.addInterceptor(new CommandFactoryExecutorMethodInterceptor(metadata, lookupStrategy)); return factory.createProxy(commandInterface.getClassLoader()); }
[ "public", "<", "T", "extends", "Commands", ">", "T", "getCommands", "(", "Class", "<", "T", ">", "commandInterface", ")", "{", "LettuceAssert", ".", "notNull", "(", "commandInterface", ",", "\"Redis Command Interface must not be null\"", ")", ";", "RedisCommandsMetadata", "metadata", "=", "new", "DefaultRedisCommandsMetadata", "(", "commandInterface", ")", ";", "InvocationProxyFactory", "factory", "=", "new", "InvocationProxyFactory", "(", ")", ";", "factory", ".", "addInterface", "(", "commandInterface", ")", ";", "BatchAwareCommandLookupStrategy", "lookupStrategy", "=", "new", "BatchAwareCommandLookupStrategy", "(", "new", "CompositeCommandLookupStrategy", "(", ")", ",", "metadata", ")", ";", "factory", ".", "addInterceptor", "(", "new", "DefaultMethodInvokingInterceptor", "(", ")", ")", ";", "factory", ".", "addInterceptor", "(", "new", "CommandFactoryExecutorMethodInterceptor", "(", "metadata", ",", "lookupStrategy", ")", ")", ";", "return", "factory", ".", "createProxy", "(", "commandInterface", ".", "getClassLoader", "(", ")", ")", ";", "}" ]
Returns a Redis Commands interface instance for the given interface. @param commandInterface must not be {@literal null}. @param <T> command interface type. @return the implemented Redis Commands interface.
[ "Returns", "a", "Redis", "Commands", "interface", "instance", "for", "the", "given", "interface", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/RedisCommandFactory.java#L179-L195
14,756
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/KqueueProvider.java
KqueueProvider.checkForKqueueLibrary
static void checkForKqueueLibrary() { 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."); }
java
static void checkForKqueueLibrary() { 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."); }
[ "static", "void", "checkForKqueueLibrary", "(", ")", "{", "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.\"", ")", ";", "}" ]
Check whether the kqueue library is available on the class path. @throws IllegalStateException if the {@literal netty-transport-native-kqueue} library is not available
[ "Check", "whether", "the", "kqueue", "library", "is", "available", "on", "the", "class", "path", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/KqueueProvider.java#L87-L95
14,757
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/models/role/RoleParser.java
RoleParser.parse
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: return parseMaster(roleOutput); case SLAVE: return parseReplica(roleOutput); case SENTINEL: return parseSentinel(roleOutput); } return null; }
java
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: return parseMaster(roleOutput); case SLAVE: return parseReplica(roleOutput); case SENTINEL: return parseSentinel(roleOutput); } return null; }
[ "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", ":", "return", "parseMaster", "(", "roleOutput", ")", ";", "case", "SLAVE", ":", "return", "parseReplica", "(", "roleOutput", ")", ";", "case", "SENTINEL", ":", "return", "parseSentinel", "(", "roleOutput", ")", ";", "}", "return", "null", ";", "}" ]
Parse the output of the Redis ROLE command and convert to a RedisInstance. @param roleOutput output of the Redis ROLE command. @return RedisInstance
[ "Parse", "the", "output", "of", "the", "Redis", "ROLE", "command", "and", "convert", "to", "a", "RedisInstance", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/models/role/RoleParser.java#L65-L85
14,758
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/LettuceStrings.java
LettuceStrings.digest
public static String digest(ByteBuffer script) { try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(script); return new String(Base16.encode(md.digest(), false)); } catch (NoSuchAlgorithmException e) { throw new RedisException("JVM does not support SHA1"); } }
java
public static String digest(ByteBuffer script) { try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(script); return new String(Base16.encode(md.digest(), false)); } catch (NoSuchAlgorithmException e) { throw new RedisException("JVM does not support SHA1"); } }
[ "public", "static", "String", "digest", "(", "ByteBuffer", "script", ")", "{", "try", "{", "MessageDigest", "md", "=", "MessageDigest", ".", "getInstance", "(", "\"SHA1\"", ")", ";", "md", ".", "update", "(", "script", ")", ";", "return", "new", "String", "(", "Base16", ".", "encode", "(", "md", ".", "digest", "(", ")", ",", "false", ")", ")", ";", "}", "catch", "(", "NoSuchAlgorithmException", "e", ")", "{", "throw", "new", "RedisException", "(", "\"JVM does not support SHA1\"", ")", ";", "}", "}" ]
Create SHA1 digest from Lua script. @param script the script @return the Base16 encoded SHA1 value
[ "Create", "SHA1", "digest", "from", "Lua", "script", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/LettuceStrings.java#L113-L121
14,759
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/masterslave/MasterSlaveConnectionProvider.java
MasterSlaveConnectionProvider.setAutoFlushCommands
public void setAutoFlushCommands(boolean autoFlush) { synchronized (stateLock) { this.autoFlushCommands = autoFlush; connectionProvider.forEach(connection -> connection.setAutoFlushCommands(autoFlush)); } }
java
public void setAutoFlushCommands(boolean autoFlush) { synchronized (stateLock) { this.autoFlushCommands = autoFlush; connectionProvider.forEach(connection -> connection.setAutoFlushCommands(autoFlush)); } }
[ "public", "void", "setAutoFlushCommands", "(", "boolean", "autoFlush", ")", "{", "synchronized", "(", "stateLock", ")", "{", "this", ".", "autoFlushCommands", "=", "autoFlush", ";", "connectionProvider", ".", "forEach", "(", "connection", "->", "connection", ".", "setAutoFlushCommands", "(", "autoFlush", ")", ")", ";", "}", "}" ]
Disable or enable auto-flush behavior for all connections. @param autoFlush state of autoFlush. @see StatefulConnection#setAutoFlushCommands(boolean)
[ "Disable", "or", "enable", "auto", "-", "flush", "behavior", "for", "all", "connections", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/masterslave/MasterSlaveConnectionProvider.java#L254-L260
14,760
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/SlotHash.java
SlotHash.getSlot
public static int getSlot(ByteBuffer key) { int limit = key.limit(); int position = key.position(); int start = indexOf(key, SUBKEY_START); if (start != -1) { int end = indexOf(key, start + 1, SUBKEY_END); if (end != -1 && end != start + 1) { key.position(start + 1).limit(end); } } try { if (key.hasArray()) { return CRC16.crc16(key.array(), key.position(), key.limit() - key.position()) % SLOT_COUNT; } return CRC16.crc16(key) % SLOT_COUNT; } finally { key.position(position).limit(limit); } }
java
public static int getSlot(ByteBuffer key) { int limit = key.limit(); int position = key.position(); int start = indexOf(key, SUBKEY_START); if (start != -1) { int end = indexOf(key, start + 1, SUBKEY_END); if (end != -1 && end != start + 1) { key.position(start + 1).limit(end); } } try { if (key.hasArray()) { return CRC16.crc16(key.array(), key.position(), key.limit() - key.position()) % SLOT_COUNT; } return CRC16.crc16(key) % SLOT_COUNT; } finally { key.position(position).limit(limit); } }
[ "public", "static", "int", "getSlot", "(", "ByteBuffer", "key", ")", "{", "int", "limit", "=", "key", ".", "limit", "(", ")", ";", "int", "position", "=", "key", ".", "position", "(", ")", ";", "int", "start", "=", "indexOf", "(", "key", ",", "SUBKEY_START", ")", ";", "if", "(", "start", "!=", "-", "1", ")", "{", "int", "end", "=", "indexOf", "(", "key", ",", "start", "+", "1", ",", "SUBKEY_END", ")", ";", "if", "(", "end", "!=", "-", "1", "&&", "end", "!=", "start", "+", "1", ")", "{", "key", ".", "position", "(", "start", "+", "1", ")", ".", "limit", "(", "end", ")", ";", "}", "}", "try", "{", "if", "(", "key", ".", "hasArray", "(", ")", ")", "{", "return", "CRC16", ".", "crc16", "(", "key", ".", "array", "(", ")", ",", "key", ".", "position", "(", ")", ",", "key", ".", "limit", "(", ")", "-", "key", ".", "position", "(", ")", ")", "%", "SLOT_COUNT", ";", "}", "return", "CRC16", ".", "crc16", "(", "key", ")", "%", "SLOT_COUNT", ";", "}", "finally", "{", "key", ".", "position", "(", "position", ")", ".", "limit", "(", "limit", ")", ";", "}", "}" ]
Calculate the slot from the given key. @param key the key @return slot
[ "Calculate", "the", "slot", "from", "the", "given", "key", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/SlotHash.java#L77-L98
14,761
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/SlotHash.java
SlotHash.partition
static <K, V> Map<Integer, List<K>> partition(RedisCodec<K, V> codec, Iterable<K> keys) { Map<Integer, List<K>> partitioned = new HashMap<>(); for (K key : keys) { int slot = getSlot(codec.encodeKey(key)); if (!partitioned.containsKey(slot)) { partitioned.put(slot, new ArrayList<>()); } Collection<K> list = partitioned.get(slot); list.add(key); } return partitioned; }
java
static <K, V> Map<Integer, List<K>> partition(RedisCodec<K, V> codec, Iterable<K> keys) { Map<Integer, List<K>> partitioned = new HashMap<>(); for (K key : keys) { int slot = getSlot(codec.encodeKey(key)); if (!partitioned.containsKey(slot)) { partitioned.put(slot, new ArrayList<>()); } Collection<K> list = partitioned.get(slot); list.add(key); } return partitioned; }
[ "static", "<", "K", ",", "V", ">", "Map", "<", "Integer", ",", "List", "<", "K", ">", ">", "partition", "(", "RedisCodec", "<", "K", ",", "V", ">", "codec", ",", "Iterable", "<", "K", ">", "keys", ")", "{", "Map", "<", "Integer", ",", "List", "<", "K", ">", ">", "partitioned", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "K", "key", ":", "keys", ")", "{", "int", "slot", "=", "getSlot", "(", "codec", ".", "encodeKey", "(", "key", ")", ")", ";", "if", "(", "!", "partitioned", ".", "containsKey", "(", "slot", ")", ")", "{", "partitioned", ".", "put", "(", "slot", ",", "new", "ArrayList", "<>", "(", ")", ")", ";", "}", "Collection", "<", "K", ">", "list", "=", "partitioned", ".", "get", "(", "slot", ")", ";", "list", ".", "add", "(", "key", ")", ";", "}", "return", "partitioned", ";", "}" ]
Partition keys by slot-hash. The resulting map honors order of the keys. @param codec codec to encode the key @param keys iterable of keys @param <K> Key type. @param <V> Value type. @result map between slot-hash and an ordered list of keys.
[ "Partition", "keys", "by", "slot", "-", "hash", ".", "The", "resulting", "map", "honors", "order", "of", "the", "keys", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/SlotHash.java#L126-L138
14,762
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/SlotHash.java
SlotHash.getSlots
static <K> Map<K, Integer> getSlots(Map<Integer, ? extends Iterable<K>> partitioned) { Map<K, Integer> result = new HashMap<>(); for (Map.Entry<Integer, ? extends Iterable<K>> entry : partitioned.entrySet()) { for (K key : entry.getValue()) { result.put(key, entry.getKey()); } } return result; }
java
static <K> Map<K, Integer> getSlots(Map<Integer, ? extends Iterable<K>> partitioned) { Map<K, Integer> result = new HashMap<>(); for (Map.Entry<Integer, ? extends Iterable<K>> entry : partitioned.entrySet()) { for (K key : entry.getValue()) { result.put(key, entry.getKey()); } } return result; }
[ "static", "<", "K", ">", "Map", "<", "K", ",", "Integer", ">", "getSlots", "(", "Map", "<", "Integer", ",", "?", "extends", "Iterable", "<", "K", ">", ">", "partitioned", ")", "{", "Map", "<", "K", ",", "Integer", ">", "result", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "Integer", ",", "?", "extends", "Iterable", "<", "K", ">", ">", "entry", ":", "partitioned", ".", "entrySet", "(", ")", ")", "{", "for", "(", "K", "key", ":", "entry", ".", "getValue", "(", ")", ")", "{", "result", ".", "put", "(", "key", ",", "entry", ".", "getKey", "(", ")", ")", ";", "}", "}", "return", "result", ";", "}" ]
Create mapping between the Key and hash slot. @param partitioned map partitioned by slothash and keys @param <K>
[ "Create", "mapping", "between", "the", "Key", "and", "hash", "slot", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/SlotHash.java#L146-L156
14,763
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/dynamic/DeclaredCommandMethod.java
DeclaredCommandMethod.getAnnotation
@Override public <A extends Annotation> A getAnnotation(Class<A> annotationClass) { return method.getAnnotation(annotationClass); }
java
@Override public <A extends Annotation> A getAnnotation(Class<A> annotationClass) { return method.getAnnotation(annotationClass); }
[ "@", "Override", "public", "<", "A", "extends", "Annotation", ">", "A", "getAnnotation", "(", "Class", "<", "A", ">", "annotationClass", ")", "{", "return", "method", ".", "getAnnotation", "(", "annotationClass", ")", ";", "}" ]
Lookup a method annotation. @param annotationClass the annotation class. @return the annotation object or {@literal null} if not found.
[ "Lookup", "a", "method", "annotation", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/DeclaredCommandMethod.java#L142-L145
14,764
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/codec/StringCodec.java
StringCodec.encodeAndAllocateBuffer
private ByteBuffer encodeAndAllocateBuffer(String key) { if (key == null) { return ByteBuffer.wrap(EMPTY); } CharsetEncoder encoder = CharsetUtil.encoder(charset); ByteBuffer buffer = ByteBuffer.allocate((int) (encoder.maxBytesPerChar() * key.length())); ByteBuf byteBuf = Unpooled.wrappedBuffer(buffer); byteBuf.clear(); encode(key, byteBuf); buffer.limit(byteBuf.writerIndex()); return buffer; }
java
private ByteBuffer encodeAndAllocateBuffer(String key) { if (key == null) { return ByteBuffer.wrap(EMPTY); } CharsetEncoder encoder = CharsetUtil.encoder(charset); ByteBuffer buffer = ByteBuffer.allocate((int) (encoder.maxBytesPerChar() * key.length())); ByteBuf byteBuf = Unpooled.wrappedBuffer(buffer); byteBuf.clear(); encode(key, byteBuf); buffer.limit(byteBuf.writerIndex()); return buffer; }
[ "private", "ByteBuffer", "encodeAndAllocateBuffer", "(", "String", "key", ")", "{", "if", "(", "key", "==", "null", ")", "{", "return", "ByteBuffer", ".", "wrap", "(", "EMPTY", ")", ";", "}", "CharsetEncoder", "encoder", "=", "CharsetUtil", ".", "encoder", "(", "charset", ")", ";", "ByteBuffer", "buffer", "=", "ByteBuffer", ".", "allocate", "(", "(", "int", ")", "(", "encoder", ".", "maxBytesPerChar", "(", ")", "*", "key", ".", "length", "(", ")", ")", ")", ";", "ByteBuf", "byteBuf", "=", "Unpooled", ".", "wrappedBuffer", "(", "buffer", ")", ";", "byteBuf", ".", "clear", "(", ")", ";", "encode", "(", "key", ",", "byteBuf", ")", ";", "buffer", ".", "limit", "(", "byteBuf", ".", "writerIndex", "(", ")", ")", ";", "return", "buffer", ";", "}" ]
Compatibility implementation. @param key @return
[ "Compatibility", "implementation", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/codec/StringCodec.java#L163-L177
14,765
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/models/partitions/Partitions.java
Partitions.updateCache
public void updateCache() { synchronized (partitions) { if (partitions.isEmpty()) { this.slotCache = EMPTY; this.nodeReadView = Collections.emptyList(); return; } RedisClusterNode[] slotCache = new RedisClusterNode[SlotHash.SLOT_COUNT]; List<RedisClusterNode> readView = new ArrayList<>(partitions.size()); for (RedisClusterNode partition : partitions) { readView.add(partition); for (Integer integer : partition.getSlots()) { slotCache[integer.intValue()] = partition; } } this.slotCache = slotCache; this.nodeReadView = Collections.unmodifiableCollection(readView); } }
java
public void updateCache() { synchronized (partitions) { if (partitions.isEmpty()) { this.slotCache = EMPTY; this.nodeReadView = Collections.emptyList(); return; } RedisClusterNode[] slotCache = new RedisClusterNode[SlotHash.SLOT_COUNT]; List<RedisClusterNode> readView = new ArrayList<>(partitions.size()); for (RedisClusterNode partition : partitions) { readView.add(partition); for (Integer integer : partition.getSlots()) { slotCache[integer.intValue()] = partition; } } this.slotCache = slotCache; this.nodeReadView = Collections.unmodifiableCollection(readView); } }
[ "public", "void", "updateCache", "(", ")", "{", "synchronized", "(", "partitions", ")", "{", "if", "(", "partitions", ".", "isEmpty", "(", ")", ")", "{", "this", ".", "slotCache", "=", "EMPTY", ";", "this", ".", "nodeReadView", "=", "Collections", ".", "emptyList", "(", ")", ";", "return", ";", "}", "RedisClusterNode", "[", "]", "slotCache", "=", "new", "RedisClusterNode", "[", "SlotHash", ".", "SLOT_COUNT", "]", ";", "List", "<", "RedisClusterNode", ">", "readView", "=", "new", "ArrayList", "<>", "(", "partitions", ".", "size", "(", ")", ")", ";", "for", "(", "RedisClusterNode", "partition", ":", "partitions", ")", "{", "readView", ".", "add", "(", "partition", ")", ";", "for", "(", "Integer", "integer", ":", "partition", ".", "getSlots", "(", ")", ")", "{", "slotCache", "[", "integer", ".", "intValue", "(", ")", "]", "=", "partition", ";", "}", "}", "this", ".", "slotCache", "=", "slotCache", ";", "this", ".", "nodeReadView", "=", "Collections", ".", "unmodifiableCollection", "(", "readView", ")", ";", "}", "}" ]
Update the partition cache. Updates are necessary after the partition details have changed.
[ "Update", "the", "partition", "cache", ".", "Updates", "are", "necessary", "after", "the", "partition", "details", "have", "changed", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/models/partitions/Partitions.java#L145-L169
14,766
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/models/partitions/Partitions.java
Partitions.reload
public void reload(List<RedisClusterNode> partitions) { LettuceAssert.noNullElements(partitions, "Partitions must not contain null elements"); synchronized (this.partitions) { this.partitions.clear(); this.partitions.addAll(partitions); updateCache(); } }
java
public void reload(List<RedisClusterNode> partitions) { LettuceAssert.noNullElements(partitions, "Partitions must not contain null elements"); synchronized (this.partitions) { this.partitions.clear(); this.partitions.addAll(partitions); updateCache(); } }
[ "public", "void", "reload", "(", "List", "<", "RedisClusterNode", ">", "partitions", ")", "{", "LettuceAssert", ".", "noNullElements", "(", "partitions", ",", "\"Partitions must not contain null elements\"", ")", ";", "synchronized", "(", "this", ".", "partitions", ")", "{", "this", ".", "partitions", ".", "clear", "(", ")", ";", "this", ".", "partitions", ".", "addAll", "(", "partitions", ")", ";", "updateCache", "(", ")", ";", "}", "}" ]
Update partitions and rebuild slot cache. @param partitions list of new partitions
[ "Update", "partitions", "and", "rebuild", "slot", "cache", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/models/partitions/Partitions.java#L233-L242
14,767
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/CommandArgsAccessor.java
CommandArgsAccessor.encodeFirstKey
@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; }
java
@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; }
[ "@", "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 encoded key for cluster command routing. @param commandArgs must not be null. @return the first encoded key or {@literal null}.
[ "Get", "the", "first", "encoded", "key", "for", "cluster", "command", "routing", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/CommandArgsAccessor.java#L39-L50
14,768
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/CommandArgs.java
CommandArgs.addKey
public CommandArgs<K, V> addKey(K key) { singularArguments.add(KeyArgument.of(key, codec)); return this; }
java
public CommandArgs<K, V> addKey(K key) { singularArguments.add(KeyArgument.of(key, codec)); return this; }
[ "public", "CommandArgs", "<", "K", ",", "V", ">", "addKey", "(", "K", "key", ")", "{", "singularArguments", ".", "add", "(", "KeyArgument", ".", "of", "(", "key", ",", "codec", ")", ")", ";", "return", "this", ";", "}" ]
Adds a key argument. @param key the key @return the command args.
[ "Adds", "a", "key", "argument", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/CommandArgs.java#L79-L83
14,769
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/CommandArgs.java
CommandArgs.addKeys
public CommandArgs<K, V> addKeys(Iterable<K> keys) { LettuceAssert.notNull(keys, "Keys must not be null"); for (K key : keys) { addKey(key); } return this; }
java
public CommandArgs<K, V> addKeys(Iterable<K> keys) { LettuceAssert.notNull(keys, "Keys must not be null"); for (K key : keys) { addKey(key); } return this; }
[ "public", "CommandArgs", "<", "K", ",", "V", ">", "addKeys", "(", "Iterable", "<", "K", ">", "keys", ")", "{", "LettuceAssert", ".", "notNull", "(", "keys", ",", "\"Keys must not be null\"", ")", ";", "for", "(", "K", "key", ":", "keys", ")", "{", "addKey", "(", "key", ")", ";", "}", "return", "this", ";", "}" ]
Add multiple key arguments. @param keys must not be {@literal null}. @return the command args.
[ "Add", "multiple", "key", "arguments", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/CommandArgs.java#L91-L99
14,770
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/CommandArgs.java
CommandArgs.addValue
public CommandArgs<K, V> addValue(V value) { singularArguments.add(ValueArgument.of(value, codec)); return this; }
java
public CommandArgs<K, V> addValue(V value) { singularArguments.add(ValueArgument.of(value, codec)); return this; }
[ "public", "CommandArgs", "<", "K", ",", "V", ">", "addValue", "(", "V", "value", ")", "{", "singularArguments", ".", "add", "(", "ValueArgument", ".", "of", "(", "value", ",", "codec", ")", ")", ";", "return", "this", ";", "}" ]
Add a value argument. @param value the value @return the command args.
[ "Add", "a", "value", "argument", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/CommandArgs.java#L124-L128
14,771
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/CommandArgs.java
CommandArgs.addValues
public CommandArgs<K, V> addValues(Iterable<V> values) { LettuceAssert.notNull(values, "Values must not be null"); for (V value : values) { addValue(value); } return this; }
java
public CommandArgs<K, V> addValues(Iterable<V> values) { LettuceAssert.notNull(values, "Values must not be null"); for (V value : values) { addValue(value); } return this; }
[ "public", "CommandArgs", "<", "K", ",", "V", ">", "addValues", "(", "Iterable", "<", "V", ">", "values", ")", "{", "LettuceAssert", ".", "notNull", "(", "values", ",", "\"Values must not be null\"", ")", ";", "for", "(", "V", "value", ":", "values", ")", "{", "addValue", "(", "value", ")", ";", "}", "return", "this", ";", "}" ]
Add multiple value arguments. @param values must not be {@literal null}. @return the command args.
[ "Add", "multiple", "value", "arguments", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/CommandArgs.java#L136-L144
14,772
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/CommandArgs.java
CommandArgs.add
public CommandArgs<K, V> add(String s) { singularArguments.add(StringArgument.of(s)); return this; }
java
public CommandArgs<K, V> add(String s) { singularArguments.add(StringArgument.of(s)); return this; }
[ "public", "CommandArgs", "<", "K", ",", "V", ">", "add", "(", "String", "s", ")", "{", "singularArguments", ".", "add", "(", "StringArgument", ".", "of", "(", "s", ")", ")", ";", "return", "this", ";", "}" ]
Add a string argument. The argument is represented as bulk string. @param s the string. @return the command args.
[ "Add", "a", "string", "argument", ".", "The", "argument", "is", "represented", "as", "bulk", "string", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/CommandArgs.java#L186-L190
14,773
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/CommandArgs.java
CommandArgs.add
public CommandArgs<K, V> add(char[] cs) { singularArguments.add(CharArrayArgument.of(cs)); return this; }
java
public CommandArgs<K, V> add(char[] cs) { singularArguments.add(CharArrayArgument.of(cs)); return this; }
[ "public", "CommandArgs", "<", "K", ",", "V", ">", "add", "(", "char", "[", "]", "cs", ")", "{", "singularArguments", ".", "add", "(", "CharArrayArgument", ".", "of", "(", "cs", ")", ")", ";", "return", "this", ";", "}" ]
Add a string as char-array. The argument is represented as bulk string. @param cs the string. @return the command args.
[ "Add", "a", "string", "as", "char", "-", "array", ".", "The", "argument", "is", "represented", "as", "bulk", "string", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/CommandArgs.java#L198-L202
14,774
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/CommandArgs.java
CommandArgs.add
public CommandArgs<K, V> add(double n) { singularArguments.add(DoubleArgument.of(n)); return this; }
java
public CommandArgs<K, V> add(double n) { singularArguments.add(DoubleArgument.of(n)); return this; }
[ "public", "CommandArgs", "<", "K", ",", "V", ">", "add", "(", "double", "n", ")", "{", "singularArguments", ".", "add", "(", "DoubleArgument", ".", "of", "(", "n", ")", ")", ";", "return", "this", ";", "}" ]
Add a double argument. @param n the double argument. @return the command args.
[ "Add", "a", "double", "argument", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/CommandArgs.java#L222-L226
14,775
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/CommandArgs.java
CommandArgs.add
public CommandArgs<K, V> add(byte[] value) { singularArguments.add(BytesArgument.of(value)); return this; }
java
public CommandArgs<K, V> add(byte[] value) { singularArguments.add(BytesArgument.of(value)); return this; }
[ "public", "CommandArgs", "<", "K", ",", "V", ">", "add", "(", "byte", "[", "]", "value", ")", "{", "singularArguments", ".", "add", "(", "BytesArgument", ".", "of", "(", "value", ")", ")", ";", "return", "this", ";", "}" ]
Add a byte-array argument. The argument is represented as bulk string. @param value the byte-array. @return the command args.
[ "Add", "a", "byte", "-", "array", "argument", ".", "The", "argument", "is", "represented", "as", "bulk", "string", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/CommandArgs.java#L234-L238
14,776
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/codec/Base16.java
Base16.encode
public static char[] encode(byte[] src, boolean upper) { char[] table = upper ? Base16.upper : Base16.lower; char[] dst = new char[src.length * 2]; for (int si = 0, di = 0; si < src.length; si++) { byte b = src[si]; dst[di++] = table[(b & 0xf0) >>> 4]; dst[di++] = table[(b & 0x0f)]; } return dst; }
java
public static char[] encode(byte[] src, boolean upper) { char[] table = upper ? Base16.upper : Base16.lower; char[] dst = new char[src.length * 2]; for (int si = 0, di = 0; si < src.length; si++) { byte b = src[si]; dst[di++] = table[(b & 0xf0) >>> 4]; dst[di++] = table[(b & 0x0f)]; } return dst; }
[ "public", "static", "char", "[", "]", "encode", "(", "byte", "[", "]", "src", ",", "boolean", "upper", ")", "{", "char", "[", "]", "table", "=", "upper", "?", "Base16", ".", "upper", ":", "Base16", ".", "lower", ";", "char", "[", "]", "dst", "=", "new", "char", "[", "src", ".", "length", "*", "2", "]", ";", "for", "(", "int", "si", "=", "0", ",", "di", "=", "0", ";", "si", "<", "src", ".", "length", ";", "si", "++", ")", "{", "byte", "b", "=", "src", "[", "si", "]", ";", "dst", "[", "di", "++", "]", "=", "table", "[", "(", "b", "&", "0xf0", ")", ">>>", "4", "]", ";", "dst", "[", "di", "++", "]", "=", "table", "[", "(", "b", "&", "0x0f", ")", "]", ";", "}", "return", "dst", ";", "}" ]
Encode bytes to base16 chars. @param src Bytes to encode. @param upper Use upper or lowercase chars. @return Encoded chars.
[ "Encode", "bytes", "to", "base16", "chars", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/codec/Base16.java#L51-L62
14,777
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/topology/TopologyComparators.java
TopologyComparators.sortByUri
public static List<RedisClusterNode> sortByUri(Iterable<RedisClusterNode> clusterNodes) { LettuceAssert.notNull(clusterNodes, "Cluster nodes must not be null"); List<RedisClusterNode> ordered = LettuceLists.newList(clusterNodes); ordered.sort((o1, o2) -> RedisURIComparator.INSTANCE.compare(o1.getUri(), o2.getUri())); return ordered; }
java
public static List<RedisClusterNode> sortByUri(Iterable<RedisClusterNode> clusterNodes) { LettuceAssert.notNull(clusterNodes, "Cluster nodes must not be null"); List<RedisClusterNode> ordered = LettuceLists.newList(clusterNodes); ordered.sort((o1, o2) -> RedisURIComparator.INSTANCE.compare(o1.getUri(), o2.getUri())); return ordered; }
[ "public", "static", "List", "<", "RedisClusterNode", ">", "sortByUri", "(", "Iterable", "<", "RedisClusterNode", ">", "clusterNodes", ")", "{", "LettuceAssert", ".", "notNull", "(", "clusterNodes", ",", "\"Cluster nodes must not be null\"", ")", ";", "List", "<", "RedisClusterNode", ">", "ordered", "=", "LettuceLists", ".", "newList", "(", "clusterNodes", ")", ";", "ordered", ".", "sort", "(", "(", "o1", ",", "o2", ")", "->", "RedisURIComparator", ".", "INSTANCE", ".", "compare", "(", "o1", ".", "getUri", "(", ")", ",", "o2", ".", "getUri", "(", ")", ")", ")", ";", "return", "ordered", ";", "}" ]
Sort partitions by RedisURI. @param clusterNodes @return List containing {@link RedisClusterNode}s ordered by {@link RedisURI}
[ "Sort", "partitions", "by", "RedisURI", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/topology/TopologyComparators.java#L77-L84
14,778
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/topology/TopologyComparators.java
TopologyComparators.sortByClientCount
public static List<RedisClusterNode> sortByClientCount(Iterable<RedisClusterNode> clusterNodes) { LettuceAssert.notNull(clusterNodes, "Cluster nodes must not be null"); List<RedisClusterNode> ordered = LettuceLists.newList(clusterNodes); ordered.sort(ClientCountComparator.INSTANCE); return ordered; }
java
public static List<RedisClusterNode> sortByClientCount(Iterable<RedisClusterNode> clusterNodes) { LettuceAssert.notNull(clusterNodes, "Cluster nodes must not be null"); List<RedisClusterNode> ordered = LettuceLists.newList(clusterNodes); ordered.sort(ClientCountComparator.INSTANCE); return ordered; }
[ "public", "static", "List", "<", "RedisClusterNode", ">", "sortByClientCount", "(", "Iterable", "<", "RedisClusterNode", ">", "clusterNodes", ")", "{", "LettuceAssert", ".", "notNull", "(", "clusterNodes", ",", "\"Cluster nodes must not be null\"", ")", ";", "List", "<", "RedisClusterNode", ">", "ordered", "=", "LettuceLists", ".", "newList", "(", "clusterNodes", ")", ";", "ordered", ".", "sort", "(", "ClientCountComparator", ".", "INSTANCE", ")", ";", "return", "ordered", ";", "}" ]
Sort partitions by client count. @param clusterNodes @return List containing {@link RedisClusterNode}s ordered by client count
[ "Sort", "partitions", "by", "client", "count", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/topology/TopologyComparators.java#L92-L99
14,779
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/topology/TopologyComparators.java
TopologyComparators.sortByLatency
public static List<RedisClusterNode> sortByLatency(Iterable<RedisClusterNode> clusterNodes) { List<RedisClusterNode> ordered = LettuceLists.newList(clusterNodes); ordered.sort(LatencyComparator.INSTANCE); return ordered; }
java
public static List<RedisClusterNode> sortByLatency(Iterable<RedisClusterNode> clusterNodes) { List<RedisClusterNode> ordered = LettuceLists.newList(clusterNodes); ordered.sort(LatencyComparator.INSTANCE); return ordered; }
[ "public", "static", "List", "<", "RedisClusterNode", ">", "sortByLatency", "(", "Iterable", "<", "RedisClusterNode", ">", "clusterNodes", ")", "{", "List", "<", "RedisClusterNode", ">", "ordered", "=", "LettuceLists", ".", "newList", "(", "clusterNodes", ")", ";", "ordered", ".", "sort", "(", "LatencyComparator", ".", "INSTANCE", ")", ";", "return", "ordered", ";", "}" ]
Sort partitions by latency. @param clusterNodes @return List containing {@link RedisClusterNode}s ordered by latency
[ "Sort", "partitions", "by", "latency", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/topology/TopologyComparators.java#L107-L112
14,780
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/topology/TopologyComparators.java
TopologyComparators.isChanged
public static boolean isChanged(Partitions o1, Partitions o2) { if (o1.size() != o2.size()) { return true; } for (RedisClusterNode base : o2) { if (!essentiallyEqualsTo(base, o1.getPartitionByNodeId(base.getNodeId()))) { return true; } } return false; }
java
public static boolean isChanged(Partitions o1, Partitions o2) { if (o1.size() != o2.size()) { return true; } for (RedisClusterNode base : o2) { if (!essentiallyEqualsTo(base, o1.getPartitionByNodeId(base.getNodeId()))) { return true; } } return false; }
[ "public", "static", "boolean", "isChanged", "(", "Partitions", "o1", ",", "Partitions", "o2", ")", "{", "if", "(", "o1", ".", "size", "(", ")", "!=", "o2", ".", "size", "(", ")", ")", "{", "return", "true", ";", "}", "for", "(", "RedisClusterNode", "base", ":", "o2", ")", "{", "if", "(", "!", "essentiallyEqualsTo", "(", "base", ",", "o1", ".", "getPartitionByNodeId", "(", "base", ".", "getNodeId", "(", ")", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if properties changed which are essential for cluster operations. @param o1 the first object to be compared. @param o2 the second object to be compared. @return {@literal true} if {@code MASTER} or {@code SLAVE} flags changed or the responsible slots changed.
[ "Check", "if", "properties", "changed", "which", "are", "essential", "for", "cluster", "operations", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/topology/TopologyComparators.java#L121-L134
14,781
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/dynamic/support/ClassTypeInformation.java
ClassTypeInformation.getTypeVariableMap
private static Map<TypeVariable<?>, Type> getTypeVariableMap(Class<?> type) { return getTypeVariableMap(type, new HashSet<Type>()); }
java
private static Map<TypeVariable<?>, Type> getTypeVariableMap(Class<?> type) { return getTypeVariableMap(type, new HashSet<Type>()); }
[ "private", "static", "Map", "<", "TypeVariable", "<", "?", ">", ",", "Type", ">", "getTypeVariableMap", "(", "Class", "<", "?", ">", "type", ")", "{", "return", "getTypeVariableMap", "(", "type", ",", "new", "HashSet", "<", "Type", ">", "(", ")", ")", ";", "}" ]
Little helper to allow us to create a generified map, actually just to satisfy the compiler. @param type must not be {@literal null}. @return
[ "Little", "helper", "to", "allow", "us", "to", "create", "a", "generified", "map", "actually", "just", "to", "satisfy", "the", "compiler", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/support/ClassTypeInformation.java#L132-L134
14,782
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/topology/NodeTopologyViews.java
NodeTopologyViews.getClusterNodes
public Set<RedisURI> getClusterNodes() { Set<RedisURI> result = new HashSet<>(); Map<String, RedisURI> knownUris = new HashMap<>(); for (NodeTopologyView view : views) { knownUris.put(view.getNodeId(), view.getRedisURI()); } for (NodeTopologyView view : views) { for (RedisClusterNode redisClusterNode : view.getPartitions()) { if (knownUris.containsKey(redisClusterNode.getNodeId())) { result.add(knownUris.get(redisClusterNode.getNodeId())); } else { result.add(redisClusterNode.getUri()); } } } return result; }
java
public Set<RedisURI> getClusterNodes() { Set<RedisURI> result = new HashSet<>(); Map<String, RedisURI> knownUris = new HashMap<>(); for (NodeTopologyView view : views) { knownUris.put(view.getNodeId(), view.getRedisURI()); } for (NodeTopologyView view : views) { for (RedisClusterNode redisClusterNode : view.getPartitions()) { if (knownUris.containsKey(redisClusterNode.getNodeId())) { result.add(knownUris.get(redisClusterNode.getNodeId())); } else { result.add(redisClusterNode.getUri()); } } } return result; }
[ "public", "Set", "<", "RedisURI", ">", "getClusterNodes", "(", ")", "{", "Set", "<", "RedisURI", ">", "result", "=", "new", "HashSet", "<>", "(", ")", ";", "Map", "<", "String", ",", "RedisURI", ">", "knownUris", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "NodeTopologyView", "view", ":", "views", ")", "{", "knownUris", ".", "put", "(", "view", ".", "getNodeId", "(", ")", ",", "view", ".", "getRedisURI", "(", ")", ")", ";", "}", "for", "(", "NodeTopologyView", "view", ":", "views", ")", "{", "for", "(", "RedisClusterNode", "redisClusterNode", ":", "view", ".", "getPartitions", "(", ")", ")", "{", "if", "(", "knownUris", ".", "containsKey", "(", "redisClusterNode", ".", "getNodeId", "(", ")", ")", ")", "{", "result", ".", "add", "(", "knownUris", ".", "get", "(", "redisClusterNode", ".", "getNodeId", "(", ")", ")", ")", ";", "}", "else", "{", "result", ".", "add", "(", "redisClusterNode", ".", "getUri", "(", ")", ")", ";", "}", "}", "}", "return", "result", ";", "}" ]
Return cluster node URI's using the topology query sources and partitions. @return
[ "Return", "cluster", "node", "URI", "s", "using", "the", "topology", "query", "sources", "and", "partitions", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/topology/NodeTopologyViews.java#L40-L60
14,783
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/CommandHandler.java
CommandHandler.consumeResponse
private boolean consumeResponse(ByteBuf buffer) { PristineFallbackCommand command = this.fallbackCommand; if (command == null || !command.isDone()) { if (debugEnabled) { logger.debug("{} Consuming response using FallbackCommand", logPrefix()); } if (command == null) { command = new PristineFallbackCommand(); this.fallbackCommand = command; } if (!decode(buffer, command.getOutput())) { return false; } if (isProtectedMode(command)) { onProtectedMode(command.getOutput().getError()); } } return true; }
java
private boolean consumeResponse(ByteBuf buffer) { PristineFallbackCommand command = this.fallbackCommand; if (command == null || !command.isDone()) { if (debugEnabled) { logger.debug("{} Consuming response using FallbackCommand", logPrefix()); } if (command == null) { command = new PristineFallbackCommand(); this.fallbackCommand = command; } if (!decode(buffer, command.getOutput())) { return false; } if (isProtectedMode(command)) { onProtectedMode(command.getOutput().getError()); } } return true; }
[ "private", "boolean", "consumeResponse", "(", "ByteBuf", "buffer", ")", "{", "PristineFallbackCommand", "command", "=", "this", ".", "fallbackCommand", ";", "if", "(", "command", "==", "null", "||", "!", "command", ".", "isDone", "(", ")", ")", "{", "if", "(", "debugEnabled", ")", "{", "logger", ".", "debug", "(", "\"{} Consuming response using FallbackCommand\"", ",", "logPrefix", "(", ")", ")", ";", "}", "if", "(", "command", "==", "null", ")", "{", "command", "=", "new", "PristineFallbackCommand", "(", ")", ";", "this", ".", "fallbackCommand", "=", "command", ";", "}", "if", "(", "!", "decode", "(", "buffer", ",", "command", ".", "getOutput", "(", ")", ")", ")", "{", "return", "false", ";", "}", "if", "(", "isProtectedMode", "(", "command", ")", ")", "{", "onProtectedMode", "(", "command", ".", "getOutput", "(", ")", ".", "getError", "(", ")", ")", ";", "}", "}", "return", "true", ";", "}" ]
Consume a response without having a command on the stack. @param buffer @return {@literal true} if the buffer decode was successful. {@literal false} if the buffer was not decoded.
[ "Consume", "a", "response", "without", "having", "a", "command", "on", "the", "stack", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/CommandHandler.java#L723-L748
14,784
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/CommandHandler.java
CommandHandler.discardReadBytesIfNecessary
private void discardReadBytesIfNecessary(ByteBuf buffer) { float usedRatio = (float) buffer.readerIndex() / buffer.capacity(); if (usedRatio >= discardReadBytesRatio && buffer.refCnt() != 0) { buffer.discardReadBytes(); } }
java
private void discardReadBytesIfNecessary(ByteBuf buffer) { float usedRatio = (float) buffer.readerIndex() / buffer.capacity(); if (usedRatio >= discardReadBytesRatio && buffer.refCnt() != 0) { buffer.discardReadBytes(); } }
[ "private", "void", "discardReadBytesIfNecessary", "(", "ByteBuf", "buffer", ")", "{", "float", "usedRatio", "=", "(", "float", ")", "buffer", ".", "readerIndex", "(", ")", "/", "buffer", ".", "capacity", "(", ")", ";", "if", "(", "usedRatio", ">=", "discardReadBytesRatio", "&&", "buffer", ".", "refCnt", "(", ")", "!=", "0", ")", "{", "buffer", ".", "discardReadBytes", "(", ")", ";", "}", "}" ]
Try to discard read bytes when buffer usage reach a higher usage ratio. @param buffer
[ "Try", "to", "discard", "read", "bytes", "when", "buffer", "usage", "reach", "a", "higher", "usage", "ratio", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/CommandHandler.java#L851-L858
14,785
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/RedisStateMachine.java
RedisStateMachine.add
private void add(State[] stack, State state) { if (stackElements != 0) { System.arraycopy(stack, 0, stack, 1, stackElements); } stack[0] = state; stackElements++; }
java
private void add(State[] stack, State state) { if (stackElements != 0) { System.arraycopy(stack, 0, stack, 1, stackElements); } stack[0] = state; stackElements++; }
[ "private", "void", "add", "(", "State", "[", "]", "stack", ",", "State", "state", ")", "{", "if", "(", "stackElements", "!=", "0", ")", "{", "System", ".", "arraycopy", "(", "stack", ",", "0", ",", "stack", ",", "1", ",", "stackElements", ")", ";", "}", "stack", "[", "0", "]", "=", "state", ";", "stackElements", "++", ";", "}" ]
Add a state as tail element. This method shifts the whole stack if the stack is not empty. @param stack @param state
[ "Add", "a", "state", "as", "tail", "element", ".", "This", "method", "shifts", "the", "whole", "stack", "if", "the", "stack", "is", "not", "empty", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/RedisStateMachine.java#L321-L329
14,786
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/EpollProvider.java
EpollProvider.checkForEpollLibrary
static void checkForEpollLibrary() { 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."); }
java
static void checkForEpollLibrary() { 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."); }
[ "static", "void", "checkForEpollLibrary", "(", ")", "{", "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.\"", ")", ";", "}" ]
Check whether the Epoll library is available on the class path. @throws IllegalStateException if the {@literal netty-transport-native-epoll} library is not available
[ "Check", "whether", "the", "Epoll", "library", "is", "available", "on", "the", "class", "path", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/EpollProvider.java#L85-L93
14,787
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/AbstractRedisClient.java
AbstractRedisClient.connectionBuilder
protected void connectionBuilder(Mono<SocketAddress> socketAddressSupplier, ConnectionBuilder connectionBuilder, RedisURI redisURI) { Bootstrap redisBootstrap = new Bootstrap(); redisBootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024); redisBootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024); redisBootstrap.option(ChannelOption.ALLOCATOR, BUF_ALLOCATOR); SocketOptions socketOptions = getOptions().getSocketOptions(); redisBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.toIntExact(socketOptions.getConnectTimeout().toMillis())); if (LettuceStrings.isEmpty(redisURI.getSocket())) { redisBootstrap.option(ChannelOption.SO_KEEPALIVE, socketOptions.isKeepAlive()); redisBootstrap.option(ChannelOption.TCP_NODELAY, socketOptions.isTcpNoDelay()); } connectionBuilder.timeout(redisURI.getTimeout()); connectionBuilder.password(redisURI.getPassword()); connectionBuilder.bootstrap(redisBootstrap); connectionBuilder.channelGroup(channels).connectionEvents(connectionEvents).timer(timer); connectionBuilder.socketAddressSupplier(socketAddressSupplier); }
java
protected void connectionBuilder(Mono<SocketAddress> socketAddressSupplier, ConnectionBuilder connectionBuilder, RedisURI redisURI) { Bootstrap redisBootstrap = new Bootstrap(); redisBootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024); redisBootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024); redisBootstrap.option(ChannelOption.ALLOCATOR, BUF_ALLOCATOR); SocketOptions socketOptions = getOptions().getSocketOptions(); redisBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.toIntExact(socketOptions.getConnectTimeout().toMillis())); if (LettuceStrings.isEmpty(redisURI.getSocket())) { redisBootstrap.option(ChannelOption.SO_KEEPALIVE, socketOptions.isKeepAlive()); redisBootstrap.option(ChannelOption.TCP_NODELAY, socketOptions.isTcpNoDelay()); } connectionBuilder.timeout(redisURI.getTimeout()); connectionBuilder.password(redisURI.getPassword()); connectionBuilder.bootstrap(redisBootstrap); connectionBuilder.channelGroup(channels).connectionEvents(connectionEvents).timer(timer); connectionBuilder.socketAddressSupplier(socketAddressSupplier); }
[ "protected", "void", "connectionBuilder", "(", "Mono", "<", "SocketAddress", ">", "socketAddressSupplier", ",", "ConnectionBuilder", "connectionBuilder", ",", "RedisURI", "redisURI", ")", "{", "Bootstrap", "redisBootstrap", "=", "new", "Bootstrap", "(", ")", ";", "redisBootstrap", ".", "option", "(", "ChannelOption", ".", "WRITE_BUFFER_HIGH_WATER_MARK", ",", "32", "*", "1024", ")", ";", "redisBootstrap", ".", "option", "(", "ChannelOption", ".", "WRITE_BUFFER_LOW_WATER_MARK", ",", "8", "*", "1024", ")", ";", "redisBootstrap", ".", "option", "(", "ChannelOption", ".", "ALLOCATOR", ",", "BUF_ALLOCATOR", ")", ";", "SocketOptions", "socketOptions", "=", "getOptions", "(", ")", ".", "getSocketOptions", "(", ")", ";", "redisBootstrap", ".", "option", "(", "ChannelOption", ".", "CONNECT_TIMEOUT_MILLIS", ",", "Math", ".", "toIntExact", "(", "socketOptions", ".", "getConnectTimeout", "(", ")", ".", "toMillis", "(", ")", ")", ")", ";", "if", "(", "LettuceStrings", ".", "isEmpty", "(", "redisURI", ".", "getSocket", "(", ")", ")", ")", "{", "redisBootstrap", ".", "option", "(", "ChannelOption", ".", "SO_KEEPALIVE", ",", "socketOptions", ".", "isKeepAlive", "(", ")", ")", ";", "redisBootstrap", ".", "option", "(", "ChannelOption", ".", "TCP_NODELAY", ",", "socketOptions", ".", "isTcpNoDelay", "(", ")", ")", ";", "}", "connectionBuilder", ".", "timeout", "(", "redisURI", ".", "getTimeout", "(", ")", ")", ";", "connectionBuilder", ".", "password", "(", "redisURI", ".", "getPassword", "(", ")", ")", ";", "connectionBuilder", ".", "bootstrap", "(", "redisBootstrap", ")", ";", "connectionBuilder", ".", "channelGroup", "(", "channels", ")", ".", "connectionEvents", "(", "connectionEvents", ")", ".", "timer", "(", "timer", ")", ";", "connectionBuilder", ".", "socketAddressSupplier", "(", "socketAddressSupplier", ")", ";", "}" ]
Populate connection builder with necessary resources. @param socketAddressSupplier address supplier for initial connect and re-connect @param connectionBuilder connection builder to configure the connection @param redisURI URI of the Redis instance
[ "Populate", "connection", "builder", "with", "necessary", "resources", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/AbstractRedisClient.java#L143-L167
14,788
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/DefaultEndpoint.java
DefaultEndpoint.reset
@Override public void reset() { if (debugEnabled) { logger.debug("{} reset()", logPrefix()); } if (channel != null) { channel.pipeline().fireUserEventTriggered(new ConnectionEvents.Reset()); } cancelBufferedCommands("Reset"); }
java
@Override public void reset() { if (debugEnabled) { logger.debug("{} reset()", logPrefix()); } if (channel != null) { channel.pipeline().fireUserEventTriggered(new ConnectionEvents.Reset()); } cancelBufferedCommands("Reset"); }
[ "@", "Override", "public", "void", "reset", "(", ")", "{", "if", "(", "debugEnabled", ")", "{", "logger", ".", "debug", "(", "\"{} reset()\"", ",", "logPrefix", "(", ")", ")", ";", "}", "if", "(", "channel", "!=", "null", ")", "{", "channel", ".", "pipeline", "(", ")", ".", "fireUserEventTriggered", "(", "new", "ConnectionEvents", ".", "Reset", "(", ")", ")", ";", "}", "cancelBufferedCommands", "(", "\"Reset\"", ")", ";", "}" ]
Reset the writer state. Queued commands will be canceled and the internal state will be reset. This is useful when the internal state machine gets out of sync with the connection.
[ "Reset", "the", "writer", "state", ".", "Queued", "commands", "will", "be", "canceled", "and", "the", "internal", "state", "will", "be", "reset", ".", "This", "is", "useful", "when", "the", "internal", "state", "machine", "gets", "out", "of", "sync", "with", "the", "connection", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/DefaultEndpoint.java#L537-L548
14,789
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/DefaultEndpoint.java
DefaultEndpoint.initialState
public void initialState() { commandBuffer.clear(); Channel currentChannel = this.channel; if (currentChannel != null) { ChannelFuture close = currentChannel.close(); if (currentChannel.isOpen()) { close.syncUninterruptibly(); } } }
java
public void initialState() { commandBuffer.clear(); Channel currentChannel = this.channel; if (currentChannel != null) { ChannelFuture close = currentChannel.close(); if (currentChannel.isOpen()) { close.syncUninterruptibly(); } } }
[ "public", "void", "initialState", "(", ")", "{", "commandBuffer", ".", "clear", "(", ")", ";", "Channel", "currentChannel", "=", "this", ".", "channel", ";", "if", "(", "currentChannel", "!=", "null", ")", "{", "ChannelFuture", "close", "=", "currentChannel", ".", "close", "(", ")", ";", "if", "(", "currentChannel", ".", "isOpen", "(", ")", ")", "{", "close", ".", "syncUninterruptibly", "(", ")", ";", "}", "}", "}" ]
Reset the command-handler to the initial not-connected state.
[ "Reset", "the", "command", "-", "handler", "to", "the", "initial", "not", "-", "connected", "state", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/DefaultEndpoint.java#L553-L565
14,790
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/protocol/DefaultEndpoint.java
DefaultEndpoint.drainCommands
private static List<RedisCommand<?, ?, ?>> drainCommands(Queue<? extends RedisCommand<?, ?, ?>> source) { List<RedisCommand<?, ?, ?>> target = new ArrayList<>(source.size()); RedisCommand<?, ?, ?> cmd; while ((cmd = source.poll()) != null) { if (!cmd.isDone()) { target.add(cmd); } } return target; }
java
private static List<RedisCommand<?, ?, ?>> drainCommands(Queue<? extends RedisCommand<?, ?, ?>> source) { List<RedisCommand<?, ?, ?>> target = new ArrayList<>(source.size()); RedisCommand<?, ?, ?> cmd; while ((cmd = source.poll()) != null) { if (!cmd.isDone()) { target.add(cmd); } } return target; }
[ "private", "static", "List", "<", "RedisCommand", "<", "?", ",", "?", ",", "?", ">", ">", "drainCommands", "(", "Queue", "<", "?", "extends", "RedisCommand", "<", "?", ",", "?", ",", "?", ">", ">", "source", ")", "{", "List", "<", "RedisCommand", "<", "?", ",", "?", ",", "?", ">", ">", "target", "=", "new", "ArrayList", "<>", "(", "source", ".", "size", "(", ")", ")", ";", "RedisCommand", "<", "?", ",", "?", ",", "?", ">", "cmd", ";", "while", "(", "(", "cmd", "=", "source", ".", "poll", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "!", "cmd", ".", "isDone", "(", ")", ")", "{", "target", ".", "add", "(", "cmd", ")", ";", "}", "}", "return", "target", ";", "}" ]
Drain commands from a queue and return only active commands. @param source the source queue. @return List of commands.
[ "Drain", "commands", "from", "a", "queue", "and", "return", "only", "active", "commands", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/protocol/DefaultEndpoint.java#L653-L666
14,791
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/Operators.java
Operators.addCap
static long addCap(long a, long b) { long res = a + b; if (res < 0L) { return Long.MAX_VALUE; } return res; }
java
static long addCap(long a, long b) { long res = a + b; if (res < 0L) { return Long.MAX_VALUE; } return res; }
[ "static", "long", "addCap", "(", "long", "a", ",", "long", "b", ")", "{", "long", "res", "=", "a", "+", "b", ";", "if", "(", "res", "<", "0L", ")", "{", "return", "Long", ".", "MAX_VALUE", ";", "}", "return", "res", ";", "}" ]
Cap an addition to Long.MAX_VALUE @param a left operand @param b right operand @return Addition result or Long.MAX_VALUE if overflow
[ "Cap", "an", "addition", "to", "Long", ".", "MAX_VALUE" ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/Operators.java#L101-L108
14,792
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/Operators.java
Operators.request
public static <T> boolean request(AtomicLongFieldUpdater<T> updater, T instance, long toAdd) { if (validate(toAdd)) { addCap(updater, instance, toAdd); return true; } return false; }
java
public static <T> boolean request(AtomicLongFieldUpdater<T> updater, T instance, long toAdd) { if (validate(toAdd)) { addCap(updater, instance, toAdd); return true; } return false; }
[ "public", "static", "<", "T", ">", "boolean", "request", "(", "AtomicLongFieldUpdater", "<", "T", ">", "updater", ",", "T", "instance", ",", "long", "toAdd", ")", "{", "if", "(", "validate", "(", "toAdd", ")", ")", "{", "addCap", "(", "updater", ",", "instance", ",", "toAdd", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Concurrent addition bound to Long.MAX_VALUE. Any concurrent write will "happen before" this operation. @param <T> the parent instance type @param updater current field updater @param instance current instance to update @param toAdd delta to add @return {@literal true} if the operation succeeded. @since 5.0.1
[ "Concurrent", "addition", "bound", "to", "Long", ".", "MAX_VALUE", ".", "Any", "concurrent", "write", "will", "happen", "before", "this", "operation", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/Operators.java#L120-L129
14,793
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/masterslave/CompletableEventLatchSupport.java
CompletableEventLatchSupport.accept
public final void accept(T value) { if (GATE_UPDATER.get(this) == GATE_CLOSED) { onDrop(value); return; } onAccept(value); onNotification(); }
java
public final void accept(T value) { if (GATE_UPDATER.get(this) == GATE_CLOSED) { onDrop(value); return; } onAccept(value); onNotification(); }
[ "public", "final", "void", "accept", "(", "T", "value", ")", "{", "if", "(", "GATE_UPDATER", ".", "get", "(", "this", ")", "==", "GATE_CLOSED", ")", "{", "onDrop", "(", "value", ")", ";", "return", ";", "}", "onAccept", "(", "value", ")", ";", "onNotification", "(", ")", ";", "}" ]
Notification callback method accepting a connection for a value. Triggers emission if the gate is open and the current call to this method is the last expected notification.
[ "Notification", "callback", "method", "accepting", "a", "connection", "for", "a", "value", ".", "Triggers", "emission", "if", "the", "gate", "is", "open", "and", "the", "current", "call", "to", "this", "method", "is", "the", "last", "expected", "notification", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/masterslave/CompletableEventLatchSupport.java#L74-L83
14,794
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/masterslave/CompletableEventLatchSupport.java
CompletableEventLatchSupport.accept
public final void accept(Throwable throwable) { if (GATE_UPDATER.get(this) == GATE_CLOSED) { onDrop(throwable); return; } onError(throwable); onNotification(); }
java
public final void accept(Throwable throwable) { if (GATE_UPDATER.get(this) == GATE_CLOSED) { onDrop(throwable); return; } onError(throwable); onNotification(); }
[ "public", "final", "void", "accept", "(", "Throwable", "throwable", ")", "{", "if", "(", "GATE_UPDATER", ".", "get", "(", "this", ")", "==", "GATE_CLOSED", ")", "{", "onDrop", "(", "throwable", ")", ";", "return", ";", "}", "onError", "(", "throwable", ")", ";", "onNotification", "(", ")", ";", "}" ]
Notification callback method accepting a connection error. Triggers emission if the gate is open and the current call to this method is the last expected notification.
[ "Notification", "callback", "method", "accepting", "a", "connection", "error", ".", "Triggers", "emission", "if", "the", "gate", "is", "open", "and", "the", "current", "call", "to", "this", "method", "is", "the", "last", "expected", "notification", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/masterslave/CompletableEventLatchSupport.java#L89-L98
14,795
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/internal/AsyncConnectionProvider.java
AsyncConnectionProvider.close
@SuppressWarnings("unchecked") public CompletableFuture<Void> close() { this.closed = true; List<CompletableFuture<Void>> futures = new ArrayList<>(); forEach((connectionKey, closeable) -> { futures.add(closeable.closeAsync()); connections.remove(connectionKey); }); return Futures.allOf(futures); }
java
@SuppressWarnings("unchecked") public CompletableFuture<Void> close() { this.closed = true; List<CompletableFuture<Void>> futures = new ArrayList<>(); forEach((connectionKey, closeable) -> { futures.add(closeable.closeAsync()); connections.remove(connectionKey); }); return Futures.allOf(futures); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "CompletableFuture", "<", "Void", ">", "close", "(", ")", "{", "this", ".", "closed", "=", "true", ";", "List", "<", "CompletableFuture", "<", "Void", ">", ">", "futures", "=", "new", "ArrayList", "<>", "(", ")", ";", "forEach", "(", "(", "connectionKey", ",", "closeable", ")", "->", "{", "futures", ".", "add", "(", "closeable", ".", "closeAsync", "(", ")", ")", ";", "connections", ".", "remove", "(", "connectionKey", ")", ";", "}", ")", ";", "return", "Futures", ".", "allOf", "(", "futures", ")", ";", "}" ]
Close all connections. Pending connections are closed using future chaining.
[ "Close", "all", "connections", ".", "Pending", "connections", "are", "closed", "using", "future", "chaining", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/internal/AsyncConnectionProvider.java#L152-L166
14,796
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/internal/AsyncConnectionProvider.java
AsyncConnectionProvider.forEach
public void forEach(Consumer<? super T> action) { connections.values().forEach(sync -> sync.doWithConnection(action)); }
java
public void forEach(Consumer<? super T> action) { connections.values().forEach(sync -> sync.doWithConnection(action)); }
[ "public", "void", "forEach", "(", "Consumer", "<", "?", "super", "T", ">", "action", ")", "{", "connections", ".", "values", "(", ")", ".", "forEach", "(", "sync", "->", "sync", ".", "doWithConnection", "(", "action", ")", ")", ";", "}" ]
Execute an action for all established and pending connections. @param action the action.
[ "Execute", "an", "action", "for", "all", "established", "and", "pending", "connections", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/internal/AsyncConnectionProvider.java#L189-L191
14,797
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/resource/DirContextDnsResolver.java
DirContextDnsResolver.resolve
@Override public InetAddress[] resolve(String host) throws UnknownHostException { if (ipStringToBytes(host) != null) { return new InetAddress[] { InetAddress.getByAddress(ipStringToBytes(host)) }; } List<InetAddress> inetAddresses = new ArrayList<>(); try { resolve(host, inetAddresses); } catch (NamingException e) { throw new UnknownHostException(String.format("Cannot resolve %s to a hostname because of %s", host, e)); } if (inetAddresses.isEmpty()) { throw new UnknownHostException(String.format("Cannot resolve %s to a hostname", host)); } return inetAddresses.toArray(new InetAddress[inetAddresses.size()]); }
java
@Override public InetAddress[] resolve(String host) throws UnknownHostException { if (ipStringToBytes(host) != null) { return new InetAddress[] { InetAddress.getByAddress(ipStringToBytes(host)) }; } List<InetAddress> inetAddresses = new ArrayList<>(); try { resolve(host, inetAddresses); } catch (NamingException e) { throw new UnknownHostException(String.format("Cannot resolve %s to a hostname because of %s", host, e)); } if (inetAddresses.isEmpty()) { throw new UnknownHostException(String.format("Cannot resolve %s to a hostname", host)); } return inetAddresses.toArray(new InetAddress[inetAddresses.size()]); }
[ "@", "Override", "public", "InetAddress", "[", "]", "resolve", "(", "String", "host", ")", "throws", "UnknownHostException", "{", "if", "(", "ipStringToBytes", "(", "host", ")", "!=", "null", ")", "{", "return", "new", "InetAddress", "[", "]", "{", "InetAddress", ".", "getByAddress", "(", "ipStringToBytes", "(", "host", ")", ")", "}", ";", "}", "List", "<", "InetAddress", ">", "inetAddresses", "=", "new", "ArrayList", "<>", "(", ")", ";", "try", "{", "resolve", "(", "host", ",", "inetAddresses", ")", ";", "}", "catch", "(", "NamingException", "e", ")", "{", "throw", "new", "UnknownHostException", "(", "String", ".", "format", "(", "\"Cannot resolve %s to a hostname because of %s\"", ",", "host", ",", "e", ")", ")", ";", "}", "if", "(", "inetAddresses", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "UnknownHostException", "(", "String", ".", "format", "(", "\"Cannot resolve %s to a hostname\"", ",", "host", ")", ")", ";", "}", "return", "inetAddresses", ".", "toArray", "(", "new", "InetAddress", "[", "inetAddresses", ".", "size", "(", ")", "]", ")", ";", "}" ]
Perform hostname to address resolution. @param host the hostname, must not be empty or {@literal null}. @return array of one or more {@link InetAddress adresses} @throws UnknownHostException
[ "Perform", "hostname", "to", "address", "resolution", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/resource/DirContextDnsResolver.java#L158-L177
14,798
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/resource/DirContextDnsResolver.java
DirContextDnsResolver.resolve
private void resolve(String hostname, List<InetAddress> inetAddresses) throws NamingException, UnknownHostException { if (preferIpv6 || (!preferIpv4 && !preferIpv6)) { inetAddresses.addAll(resolve(hostname, "AAAA")); inetAddresses.addAll(resolve(hostname, "A")); } else { inetAddresses.addAll(resolve(hostname, "A")); inetAddresses.addAll(resolve(hostname, "AAAA")); } if (inetAddresses.isEmpty()) { inetAddresses.addAll(resolveCname(hostname)); } }
java
private void resolve(String hostname, List<InetAddress> inetAddresses) throws NamingException, UnknownHostException { if (preferIpv6 || (!preferIpv4 && !preferIpv6)) { inetAddresses.addAll(resolve(hostname, "AAAA")); inetAddresses.addAll(resolve(hostname, "A")); } else { inetAddresses.addAll(resolve(hostname, "A")); inetAddresses.addAll(resolve(hostname, "AAAA")); } if (inetAddresses.isEmpty()) { inetAddresses.addAll(resolveCname(hostname)); } }
[ "private", "void", "resolve", "(", "String", "hostname", ",", "List", "<", "InetAddress", ">", "inetAddresses", ")", "throws", "NamingException", ",", "UnknownHostException", "{", "if", "(", "preferIpv6", "||", "(", "!", "preferIpv4", "&&", "!", "preferIpv6", ")", ")", "{", "inetAddresses", ".", "addAll", "(", "resolve", "(", "hostname", ",", "\"AAAA\"", ")", ")", ";", "inetAddresses", ".", "addAll", "(", "resolve", "(", "hostname", ",", "\"A\"", ")", ")", ";", "}", "else", "{", "inetAddresses", ".", "addAll", "(", "resolve", "(", "hostname", ",", "\"A\"", ")", ")", ";", "inetAddresses", ".", "addAll", "(", "resolve", "(", "hostname", ",", "\"AAAA\"", ")", ")", ";", "}", "if", "(", "inetAddresses", ".", "isEmpty", "(", ")", ")", "{", "inetAddresses", ".", "addAll", "(", "resolveCname", "(", "hostname", ")", ")", ";", "}", "}" ]
Resolve a hostname @param hostname @param inetAddresses @throws NamingException @throws UnknownHostException
[ "Resolve", "a", "hostname" ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/resource/DirContextDnsResolver.java#L187-L202
14,799
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/resource/DirContextDnsResolver.java
DirContextDnsResolver.resolve
@SuppressWarnings("rawtypes") private List<InetAddress> resolve(String hostname, String attrName) throws NamingException, UnknownHostException { Attributes attrs = context.getAttributes(hostname, new String[] { attrName }); List<InetAddress> inetAddresses = new ArrayList<>(); Attribute attr = attrs.get(attrName); if (attr != null && attr.size() > 0) { NamingEnumeration e = attr.getAll(); while (e.hasMore()) { InetAddress inetAddress = InetAddress.getByName("" + e.next()); inetAddresses.add(InetAddress.getByAddress(hostname, inetAddress.getAddress())); } } return inetAddresses; }
java
@SuppressWarnings("rawtypes") private List<InetAddress> resolve(String hostname, String attrName) throws NamingException, UnknownHostException { Attributes attrs = context.getAttributes(hostname, new String[] { attrName }); List<InetAddress> inetAddresses = new ArrayList<>(); Attribute attr = attrs.get(attrName); if (attr != null && attr.size() > 0) { NamingEnumeration e = attr.getAll(); while (e.hasMore()) { InetAddress inetAddress = InetAddress.getByName("" + e.next()); inetAddresses.add(InetAddress.getByAddress(hostname, inetAddress.getAddress())); } } return inetAddresses; }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "private", "List", "<", "InetAddress", ">", "resolve", "(", "String", "hostname", ",", "String", "attrName", ")", "throws", "NamingException", ",", "UnknownHostException", "{", "Attributes", "attrs", "=", "context", ".", "getAttributes", "(", "hostname", ",", "new", "String", "[", "]", "{", "attrName", "}", ")", ";", "List", "<", "InetAddress", ">", "inetAddresses", "=", "new", "ArrayList", "<>", "(", ")", ";", "Attribute", "attr", "=", "attrs", ".", "get", "(", "attrName", ")", ";", "if", "(", "attr", "!=", "null", "&&", "attr", ".", "size", "(", ")", ">", "0", ")", "{", "NamingEnumeration", "e", "=", "attr", ".", "getAll", "(", ")", ";", "while", "(", "e", ".", "hasMore", "(", ")", ")", "{", "InetAddress", "inetAddress", "=", "InetAddress", ".", "getByName", "(", "\"\"", "+", "e", ".", "next", "(", ")", ")", ";", "inetAddresses", ".", "add", "(", "InetAddress", ".", "getByAddress", "(", "hostname", ",", "inetAddress", ".", "getAddress", "(", ")", ")", ")", ";", "}", "}", "return", "inetAddresses", ";", "}" ]
Resolve an attribute for a hostname. @param hostname @param attrName @return @throws NamingException @throws UnknownHostException
[ "Resolve", "an", "attribute", "for", "a", "hostname", "." ]
b6de74e384dea112e3656684ca3f50cdfd6c8e0d
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/resource/DirContextDnsResolver.java#L252-L270